code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
/* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o 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.db4o.internal.ids;
import com.db4o.*;
import com.db4o.ext.*;
import com.db4o.foundation.*;
import com.db4o.internal.*;
import com.db4o.internal.freespace.*;
import com.db4o.internal.slots.*;
/**
* @exclude
*/
public class InMemoryIdSystem implements StackableIdSystem {
private final LocalObjectContainer _container;
private IdSlotTree _ids;
private Slot _slot;
private final SequentialIdGenerator _idGenerator;
private int _childId;
/**
* for testing purposes only.
*/
public InMemoryIdSystem(LocalObjectContainer container, final int maxValidId){
_container = container;
_idGenerator = new SequentialIdGenerator(new Function4<Integer, Integer>() {
public Integer apply(Integer start) {
return findFreeId(start, maxValidId);
}
}, _container.handlers().lowestValidId(), maxValidId);
}
public InMemoryIdSystem(LocalObjectContainer container){
this(container, Integer.MAX_VALUE);
readThis();
}
private void readThis() {
SystemData systemData = _container.systemData();
_slot = systemData.idSystemSlot();
if(! Slot.isNull(_slot)){
ByteArrayBuffer buffer = _container.readBufferBySlot(_slot);
_childId = buffer.readInt();
_idGenerator.read(buffer);
_ids = (IdSlotTree) new TreeReader(buffer, new IdSlotTree(0, null)).read();
}
}
public void close() {
// do nothing
}
public void commit(Visitable<SlotChange> slotChanges, FreespaceCommitter freespaceCommitter) {
Slot oldSlot = _slot;
Slot reservedSlot = allocateSlot(false, estimatedSlotLength(estimateMappingCount(slotChanges)));
// No more operations against the FreespaceManager.
// Time to free old slots.
freespaceCommitter.commit();
slotChanges.accept(new Visitor4<SlotChange>() {
public void visit(SlotChange slotChange) {
if(! slotChange.slotModified()){
return;
}
if(slotChange.removeId()){
_ids = (IdSlotTree) Tree.removeLike(_ids, new TreeInt(slotChange._key));
return;
}
if(DTrace.enabled){
DTrace.SLOT_COMMITTED.logLength(slotChange._key, slotChange.newSlot());
}
_ids = Tree.add(_ids, new IdSlotTree(slotChange._key, slotChange.newSlot()));
}
});
writeThis(reservedSlot);
freeSlot(oldSlot);
}
private Slot allocateSlot(boolean appendToFile, int slotLength) {
if(! appendToFile){
Slot slot = _container.freespaceManager().allocateSafeSlot(slotLength);
if(slot != null){
return slot;
}
}
return _container.appendBytes(slotLength);
}
private int estimateMappingCount(Visitable<SlotChange> slotChanges) {
final IntByRef count = new IntByRef();
count.value = _ids == null ? 0 :_ids.size();
slotChanges.accept(new Visitor4<SlotChange>() {
public void visit(SlotChange slotChange) {
if(! slotChange.slotModified() || slotChange.removeId()){
return;
}
count.value++;
}
});
return count.value;
}
private void writeThis(Slot reservedSlot) {
// We need a little dance here to keep filling free slots
// with X bytes. The FreespaceManager would do it immediately
// upon the free call, but then our CrashSimulatingTestCase
// fails because we have the Xses in the file before flushing.
Slot xByteSlot = null;
if(Debug4.xbytes){
xByteSlot = _slot;
}
int slotLength = slotLength();
if (reservedSlot.length() >= slotLength){
_slot = reservedSlot;
reservedSlot = null;
} else{
if(Debug4.xbytes){
_container.freespaceManager().slotFreed(reservedSlot);
}
_slot = allocateSlot(true, slotLength);
}
ByteArrayBuffer buffer = new ByteArrayBuffer(_slot.length());
buffer.writeInt(_childId);
_idGenerator.write(buffer);
TreeInt.write(buffer, _ids);
_container.writeBytes(buffer, _slot.address(), 0);
_container.systemData().idSystemSlot(_slot);
Runnable commitHook = _container.commitHook();
_container.syncFiles(commitHook);
freeSlot(reservedSlot);
if(Debug4.xbytes){
if(! Slot.isNull(xByteSlot)){
_container.freespaceManager().slotFreed(xByteSlot);
}
}
}
private void freeSlot(Slot slot) {
if(Slot.isNull(slot)){
return;
}
FreespaceManager freespaceManager = _container.freespaceManager();
if(freespaceManager == null){
return;
}
freespaceManager.freeSafeSlot(slot);
}
private int slotLength() {
return TreeInt.marshalledLength(_ids) + _idGenerator.marshalledLength() + Const4.ID_LENGTH;
}
private int estimatedSlotLength(int estimatedCount) {
IdSlotTree template = _ids;
if(template == null){
template = new IdSlotTree(0, new Slot(0, 0));
}
return template.marshalledLength(estimatedCount) + _idGenerator.marshalledLength() + Const4.ID_LENGTH;
}
public Slot committedSlot(int id) {
IdSlotTree idSlotMapping = (IdSlotTree) Tree.find(_ids, new TreeInt(id));
if(idSlotMapping == null){
throw new InvalidIDException(id);
}
return idSlotMapping.slot();
}
public void completeInterruptedTransaction(int address,
int length) {
// do nothing
}
public int newId() {
int id = _idGenerator.newId();
_ids = Tree.add(_ids, new IdSlotTree(id, Slot.ZERO));
return id;
}
private int findFreeId(final int start, final int end) {
if(_ids == null){
return start;
}
final IntByRef lastId = new IntByRef();
final IntByRef freeId = new IntByRef();
Tree.traverse(_ids, new TreeInt(start), new CancellableVisitor4<TreeInt>() {
public boolean visit(TreeInt node) {
int id = node._key;
if(lastId.value == 0){
if( id > start){
freeId.value = start;
return false;
}
lastId.value = id;
return true;
}
if(id > lastId.value + 1){
freeId.value = lastId.value + 1;
return false;
}
lastId.value = id;
return true;
}
});
if(freeId.value > 0){
return freeId.value;
}
if(lastId.value < end){
return Math.max(start, lastId.value + 1);
}
return 0;
}
public void returnUnusedIds(Visitable<Integer> visitable) {
visitable.accept(new Visitor4<Integer>() {
public void visit(Integer obj) {
_ids = (IdSlotTree) Tree.removeLike(_ids, new TreeInt(obj));
}
});
}
public int childId() {
return _childId;
}
public void childId(int id) {
_childId = id;
}
public void traverseOwnSlots(Procedure4<Pair<Integer, Slot>> block) {
block.apply(Pair.of(0, _slot));
}
}
| xionghuiCoder/db4o | src/main/java/com/db4o/internal/ids/InMemoryIdSystem.java | Java | agpl-3.0 | 7,011 |
package io.hops.hopsworks.common.dao.jobs.description;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class YarnAppUrlsDTO implements Serializable {
String name;
String url;
public YarnAppUrlsDTO() {
}
public YarnAppUrlsDTO(String name, String url) {
this.name = name;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| FilotasSiskos/hopsworks | hopsworks-common/src/main/java/io/hops/hopsworks/common/dao/jobs/description/YarnAppUrlsDTO.java | Java | agpl-3.0 | 591 |
/*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2019 Asqatasun.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa22;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.rules.rgaa22.test.Rgaa22RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 2.3 of the referential RGAA 2.2.
*
* @author jkowalczyk
*/
public class Rgaa22Rule02031Test extends Rgaa22RuleImplementationTestCase {
/**
* Default constructor
*/
public Rgaa22Rule02031Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.asqatasun.rules.rgaa22.Rgaa22Rule02031");
}
@Override
protected void setUpWebResourceMap() {
// getWebResourceMap().put("Rgaa22.Test.2.3-1Passed-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule02031/RGAA22.Test.2.3-1Passed-01.html"));
// getWebResourceMap().put("Rgaa22.Test.2.3-2Failed-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule02031/RGAA22.Test.2.3-2Failed-01.html"));
// getWebResourceMap().put("Rgaa22.Test.2.3-3NMI-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule02031/RGAA22.Test.2.3-3NMI-01.html"));
// getWebResourceMap().put("Rgaa22.Test.2.3-4NA-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule02031/RGAA22.Test.2.3-4NA-01.html"));
getWebResourceMap().put("Rgaa22.Test.2.3-5NT-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "rgaa22/Rgaa22Rule02031/RGAA22.Test.2.3-5NT-01.html"));
}
@Override
protected void setProcess() {
// assertEquals(TestSolution.PASSED,
// processPageTest("Rgaa22.Test.2.3-1Passed-01").getValue());
// assertEquals(TestSolution.FAILED,
// processPageTest("Rgaa22.Test.2.3-2Failed-01").getValue());
// assertEquals(TestSolution.NEED_MORE_INFO,
// processPageTest("Rgaa22.Test.2.3-3NMI-01").getValue());
// assertEquals(TestSolution.NOT_APPLICABLE,
// processPageTest("Rgaa22.Test.2.3-4NA-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
processPageTest("Rgaa22.Test.2.3-5NT-01").getValue());
}
@Override
protected void setConsolidate() {
// assertEquals(TestSolution.PASSED,
// consolidate("Rgaa22.Test.2.3-1Passed-01").getValue());
// assertEquals(TestSolution.FAILED,
// consolidate("Rgaa22.Test.2.3-2Failed-01").getValue());
// assertEquals(TestSolution.NEED_MORE_INFO,
// consolidate("Rgaa22.Test.2.3-3NMI-01").getValue());
// assertEquals(TestSolution.NOT_APPLICABLE,
// consolidate("Rgaa22.Test.2.3-4NA-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
consolidate("Rgaa22.Test.2.3-5NT-01").getValue());
}
}
| dzc34/Asqatasun | rules/rules-rgaa2.2/src/test/java/org/asqatasun/rules/rgaa22/Rgaa22Rule02031Test.java | Java | agpl-3.0 | 3,926 |
package org.bimserver.utils;
public interface BasicUnit {
}
| opensourceBIM/BIMserver | PluginBase/src/org/bimserver/utils/BasicUnit.java | Java | agpl-3.0 | 67 |
/*
* Copyright (C) 2021 Grakn Labs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package grakn.core.concurrent.actor;
import javax.annotation.concurrent.ThreadSafe;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
@ThreadSafe
public class ActorExecutorGroup {
private final ActorExecutor[] executors;
private final AtomicInteger nextIndex;
public ActorExecutorGroup(int size, ThreadFactory threadFactory) {
this(size, threadFactory, System::currentTimeMillis);
}
public ActorExecutorGroup(int size, ThreadFactory threadFactory, Supplier<Long> clock) {
executors = new ActorExecutor[size];
for (int i = 0; i < size; i++) executors[i] = new ActorExecutor(threadFactory, clock);
nextIndex = new AtomicInteger(0);
}
ActorExecutor nextExecutor() {
return executors[nextIndexAndIncrement()];
}
public void await() throws InterruptedException {
for (int i = 0; i < executors.length; i++) {
executors[i].await();
}
}
public void stop() throws InterruptedException {
for (int i = 0; i < executors.length; i++) {
executors[i].stop();
}
}
private int nextIndexAndIncrement() {
return nextIndex.getAndUpdate(index -> (index + 1) % executors.length);
}
}
| graknlabs/grakn | concurrent/actor/ActorExecutorGroup.java | Java | agpl-3.0 | 2,022 |
/**
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of the GPL, you may
* redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS")
* applications as described in Silverpeas's FLOSS exception. You should have received a copy of the
* text describing the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.form.fieldType;
import org.silverpeas.core.admin.OrganisationControllerFactory;
import com.silverpeas.form.AbstractField;
import com.silverpeas.form.Field;
import com.silverpeas.form.FormException;
import com.silverpeas.util.StringUtil;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.webactiv.beans.admin.UserDetail;
/**
* A UserField stores a user reference.
*
* @see Field
* @see com.silverpeas.form.FieldDisplayer
*/
public class UserField extends AbstractField {
private static final long serialVersionUID = -861888647155176647L;
/**
* The text field type name.
*/
static public final String TYPE = "user";
/**
* Returns the type name.
*/
@Override
public String getTypeName() {
return TYPE;
}
/**
* The no parameters constructor
*/
public UserField() {
}
/**
* Returns the user id referenced by this field.
*/
public String getUserId() {
return userId;
}
/**
* Set the userd id referenced by this field.
*/
public void setUserId(String userId) {
SilverTrace.info("form", "UserField.setUserId",
"root.MSG_GEN_ENTER_METHOD", "userId = " + userId);
this.userId = userId;
}
/**
* Returns true if the value is read only.
*/
public boolean isReadOnly() {
return false;
}
/**
* Returns the string value of this field : aka the user name.
*/
@Override
public String getValue() {
String theUserId = getUserId();
SilverTrace.info("form", "UserField.getValue", "root.MSG_GEN_PARAM_VALUE",
"userId = " + theUserId);
if (!StringUtil.isDefined(theUserId)) {
return theUserId;
}
UserDetail user = OrganisationControllerFactory.getOrganisationController().getUserDetail(
getUserId());
if (user == null) {
return "user(" + getUserId() + ")";
}
return user.getDisplayedName();
}
/**
* Returns the local value of this field. There is no local format for a user field, so the
* language parameter is unused.
*/
@Override
public String getValue(String language) {
return getValue();
}
/**
* Does nothing since a user reference can't be computed from a user name.
*/
@Override
public void setValue(String value) throws FormException {
}
/**
* Does nothing since a user reference can't be computed from a user name.
*/
@Override
public void setValue(String value, String language) throws FormException {
}
/**
* Always returns false since a user reference can't be computed from a user name.
*/
@Override
public boolean acceptValue(String value) {
return false;
}
/**
* Always returns false since a user reference can't be computed from a user name.
*/
@Override
public boolean acceptValue(String value, String language) {
return false;
}
/**
* Returns the User referenced by this field.
*/
@Override
public Object getObjectValue() {
if (getUserId() == null) {
return null;
}
return OrganisationControllerFactory.getOrganisationController().getUserDetail(getUserId());
}
/**
* Set user referenced by this field.
*/
@Override
public void setObjectValue(Object value) throws FormException {
if (value instanceof UserDetail) {
setUserId(((UserDetail) value).getId());
} else if (value == null) {
setUserId("");
} else {
throw new FormException("UserField.setObjectValue",
"form.EXP_NOT_AN_USER");
}
}
/**
* Returns true if the value is a String and this field isn't read only.
*/
@Override
public boolean acceptObjectValue(Object value) {
if (value instanceof UserDetail) {
return !isReadOnly();
} else {
return false;
}
}
/**
* Returns this field value as a normalized String : a user id
*/
@Override
public String getStringValue() {
return getUserId();
}
/**
* Set this field value from a normalized String : a user id
*/
@Override
public void setStringValue(String value) {
SilverTrace.info("form", "UserField.setStringValue",
"root.MSG_GEN_ENTER_METHOD", "value = " + value);
setUserId(value);
}
/**
* Returns true if this field isn't read only.
*/
@Override
public boolean acceptStringValue(String value) {
return !isReadOnly();
}
/**
* Returns true if this field is not set.
*/
@Override
public boolean isNull() {
return (getUserId() == null);
}
/**
* Set to null this field.
*
* @throw FormException when the field is mandatory.
* @throw FormException when the field is read only.
*/
@Override
public void setNull() throws FormException {
setUserId(null);
}
/**
* Tests equality between this field and the specified field.
*/
@Override
public boolean equals(Object o) {
String s = getUserId();
if (s == null) {
s = "";
}
if (o instanceof UserField) {
String t = ((UserField) o).getUserId();
if (t == null) {
t = "";
}
return s.equals(t);
} else {
return false;
}
}
/**
* Compares this field with the specified field.
*/
@Override
public int compareTo(Object o) {
String s = getValue();
if (s == null) {
s = "";
}
if (o instanceof UserField) {
String t = ((UserField) o).getValue();
if (t == null) {
t = "";
}
if (s.equals(t)) {
s = getUserId();
if (s == null) {
s = "";
}
t = ((UserField) o).getUserId();
if (t == null) {
t = "";
}
}
return s.compareTo(t);
} else {
return -1;
}
}
@Override
public int hashCode() {
String s = getUserId();
return ("" + s).hashCode();
}
/**
* The referenced userId.
*/
private String userId = null;
}
| CecileBONIN/Silverpeas-Core | lib-core/src/main/java/com/silverpeas/form/fieldType/UserField.java | Java | agpl-3.0 | 7,007 |
/**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.nioneo.store;
public interface ChainStore<R extends Abstract64BitRecord>
{
Iterable<R> chain( long firstId );
R nextRecordInChainOrNull( R prev );
void linkChain( R prev, R next );
} | thobe/neo4j-admin-store | src/main/java/org/neo4j/kernel/impl/nioneo/store/ChainStore.java | Java | agpl-3.0 | 1,042 |
package gccc;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class TaskFileHandler {
public static List<Task> getTasks(File folder) throws InterruptedException {
List<Task> tasks=new ArrayList<>();
for (File child: folder.listFiles()) {
if (!child.isDirectory())
continue;
Task task=getTask(child);
if (task!=null)
tasks.add(task);
}
return tasks;
}
public static Task getTask(File folder) throws InterruptedException {
try {
File infoFile=new File(folder, "task.inf");
if (!infoFile.exists()) {
System.out.println("Cannot find task.inf in "+folder.getAbsolutePath());
return null;
}
Properties properties = new Properties();
try (InputStream input=new FileInputStream(infoFile)) {
properties.load(input);
String name=folder.getName();
String displayName=properties.getProperty("displayname", name);
long maxtimems=Tools.getLong(properties, "maxtimems", 1000);
List<Test> tests=new ArrayList<>();
for (int i=1; ; i++) {
File testInput=new File(folder, "input"+i+".txt");
File testOutput=new File(folder, "output"+i+".txt");
if (!testInput.exists() || !testOutput.exists())
break;
try {
tests.add(new TestNumbers(Tools.readFile(testInput), Tools.readFile(testOutput), i));
}
catch (Throwable error) {
Tools.checkError(error);
System.out.println("Cannot read test "+i+" for task "+name);
error.printStackTrace();
}
}
return new Task(name, displayName, (int)maxtimems, tests);
}
}
catch (Throwable error) {
Tools.checkError(error);
System.out.println("Cannot read task from folder "+folder.getAbsolutePath());
error.printStackTrace();
return null;
}
}
}
| tailcalled/GCCodeCompetition | GCCC/src/gccc/TaskFileHandler.java | Java | agpl-3.0 | 1,853 |
package io.hops.hopsworks.dela.util;
import io.hops.hopsworks.common.dao.dataset.Dataset;
import io.hops.hopsworks.common.dao.hdfs.inode.Inode;
import io.hops.hopsworks.common.dao.hdfs.inode.InodeFacade;
import io.hops.hopsworks.common.dao.project.Project;
import io.hops.hopsworks.common.dao.project.ProjectFacade;
import io.hops.hopsworks.common.util.Settings;
import java.io.File;
public class DatasetHelper {
public static String getOwningDatasetPath(Dataset dataset, InodeFacade inodeFacade, ProjectFacade projectFacade) {
Project owningProject = getOwningProject(dataset, inodeFacade, projectFacade);
String path = Settings.getProjectPath(owningProject.getName()) + File.separator + dataset.getName();
return path;
}
public static String getDatasetPath(Project project, Dataset dataset) {
String path = Settings.getProjectPath(project.getName()) + File.separator + dataset.getName();
return path;
}
public static Project getOwningProject(Dataset ds, InodeFacade inodeFacade, ProjectFacade projectFacade) {
// If the dataset is not a shared one, just return the project
if (!ds.isShared()) {
return ds.getProject();
}
// Get the owning project based on the dataset inode
Inode projectInode = inodeFacade.findParent(ds.getInode());
return projectFacade.findByName(projectInode.getInodePK().getName());
}
}
| FilotasSiskos/hopsworks | hopsworks-dela/src/main/java/io/hops/hopsworks/dela/util/DatasetHelper.java | Java | agpl-3.0 | 1,379 |
package cn.crap.dto;
public class CategoryDto {
private String category;
private String md5Category;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getMd5Category() {
return md5Category;
}
public void setMd5Category(String md5Category) {
this.md5Category = md5Category;
}
}
| EhsanTang/ApiManager | api/src/main/java/cn/crap/dto/CategoryDto.java | Java | agpl-3.0 | 380 |
/**
* Copyright (C) 2001-2017 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.filesystem;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.UserError;
import com.rapidminer.operator.ports.DummyPortPairExtender;
import com.rapidminer.operator.ports.PortPairExtender;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeFile;
import com.rapidminer.parameter.ParameterTypeString;
import java.io.File;
import java.util.List;
/**
* This operator renames the selected file. If the file doesn't exist, an exception is thrown.
*
* @author Philipp Kersting
*/
public class RenameFileOperator extends Operator {
/**
* The constant PARAMETER_FILE.
*/
public static final String PARAMETER_FILE = "file";
/**
* The constant PARAMETER_NEW_NAME.
*/
public static final String PARAMETER_NEW_NAME = "new_name";
private PortPairExtender dummyPorts = new DummyPortPairExtender("through", getInputPorts(), getOutputPorts());
/**
* Instantiates a new Rename file operator.
*
* @param description the description
*/
public RenameFileOperator(OperatorDescription description) {
super(description);
dummyPorts.start();
getTransformer().addRule(dummyPorts.makePassThroughRule());
}
@Override
public List<ParameterType> getParameterTypes() {
List<ParameterType> types = super.getParameterTypes();
types.add(new ParameterTypeFile(PARAMETER_FILE, "The file to rename.", "*", false, false));
types.add(new ParameterTypeString(PARAMETER_NEW_NAME, "The new filename.", false));
return types;
}
@Override
public void doWork() throws OperatorException {
String fileName = getParameterAsString(PARAMETER_FILE);
File file = new File(fileName);
File newFile = new File(file.getParentFile(), getParameterAsString(PARAMETER_NEW_NAME));
if (file.exists() && !newFile.exists()) {
file.renameTo(newFile);
} else if (!file.exists()) {
throw new UserError(this, "301", file);
} else if (newFile.exists()) {
throw new UserError(this, "rename_file.exists", file, newFile.getName());
}
dummyPorts.passDataThrough();
}
}
| cm-is-dog/rapidminer-studio-core | src/main/java/com/rapidminer/operator/filesystem/RenameFileOperator.java | Java | agpl-3.0 | 3,129 |
package com.liferay.infinity.ownership.util;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.infinity.util.InfinityUserUtil;
import org.infinity.util.InfrastructureUtil;
import com.liferay.infinity.ownership.struts.form.AlphabeticListForm;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
public class Util {
public static boolean checkIfUserIsAdmin(String remoteUserId) {
try {
User user = UserLocalServiceUtil.getUserById(Long
.parseLong(remoteUserId));
List<Role> roles = user.getRoles();
for (int i = 0; i < roles.size(); i++) {
if (roles.get(i).getName().indexOf("Administrator") >= 0) {
return true;
}
}
} catch (Exception err) {
}
return false;
}
public static boolean checkIfUserIsSurvey(String remoteUserId) {
try {
User user = UserLocalServiceUtil.getUserById(Long
.parseLong(remoteUserId));
List<Role> roles = user.getRoles();
for (int i = 0; i < roles.size(); i++) {
if (roles.get(i).getName().indexOf("Survey") >= 0) {
return true;
}
}
} catch (Exception err) {
}
return false;
}
public static void setUserTypeVariable(HttpServletRequest request){
String remoteUserId = request.getRemoteUser();
String userType="Guest";
if (remoteUserId!= null){
if (checkIfUserIsAdmin(remoteUserId)){
userType="Admin";
}else{
try {
if (InfinityUserUtil.isOwner(new Integer(remoteUserId))){
userType="Owner";
}else{
userType="End User";
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
request.getSession().setAttribute("UserType", userType);
}
public static void prepareInfrastructureList(HttpServletRequest request) throws Exception{
String remoteUserId = request.getRemoteUser();
System.out.println("remoteUserId:"+remoteUserId);
setUserTypeVariable(request);
List infras = null;
boolean admin = false;
boolean survey = false;
if (remoteUserId!=null){
admin = Util.checkIfUserIsAdmin(remoteUserId);
survey =Util.checkIfUserIsSurvey(remoteUserId);
if (admin){
infras = InfrastructureUtil.getfInfrastructureItems();
} else {
if (survey){
infras = InfrastructureUtil.getInfrastructuresBySurvey(new Integer(remoteUserId));
survey = true;
}else{
infras = InfrastructureUtil.getInfrastructuresByOwner(new Integer(remoteUserId));
survey=true;
}
}
}
AlphabeticListForm aForm=new AlphabeticListForm();
aForm.setList(infras);
request.setAttribute("alphabeticListForm", aForm);
request.setAttribute("infrastructures", infras);
request.setAttribute("admin", admin);
request.setAttribute("survey", survey);
}
}
| SmartInfrastructures/xipi | portlets/OwnerShipPortlet-portlet/docroot/WEB-INF/src/com/liferay/infinity/ownership/util/Util.java | Java | agpl-3.0 | 2,909 |
/**
* Copyright (C) 2001-2020 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.preprocessing.filter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.Statistics;
import com.rapidminer.example.table.NominalMapping;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorVersion;
import com.rapidminer.operator.ProcessSetupError.Severity;
import com.rapidminer.operator.UserError;
import com.rapidminer.operator.annotation.ResourceConsumptionEstimator;
import com.rapidminer.operator.ports.metadata.AttributeMetaData;
import com.rapidminer.operator.ports.metadata.ExampleSetMetaData;
import com.rapidminer.operator.ports.metadata.MDInteger;
import com.rapidminer.operator.ports.metadata.SimpleMetaDataError;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeDateFormat;
import com.rapidminer.parameter.ParameterTypeString;
import com.rapidminer.parameter.UndefinedParameterError;
import com.rapidminer.parameter.conditions.ParameterCondition;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.OperatorResourceConsumptionHandler;
/**
* Replaces missing values in examples. If a value is missing, it is replaced by one of the
* functions "minimum", "maximum", "average", and "none",
* which is applied to the non missing attribute values of the example set. "none" means,
* that the value is not replaced. The function can be selected using the parameter list
* <code>columns</code>. If an attribute's name appears in this list as a key, the value is used as
* the function name. If the attribute's name is not in the list, the function specified by the
* <code>default</code> parameter is used. For nominal attributes the mode is used for the average,
* i.e. the nominal value which occurs most often in the data. For nominal attributes and
* replacement type zero the first nominal value defined for this attribute is used. The
* replenishment "value" indicates that the user defined parameter should be used for the
* replacement.
*
* @author Ingo Mierswa, Simon Fischer, Marius Helf
*/
public class MissingValueReplenishment extends ValueReplenishment {
/**
* The parameter name for "This value is used for some of the replenishment types."
*/
public static final String PARAMETER_REPLENISHMENT_VALUE = "replenishment_value";
private static final int NONE = 0;
private static final int MINIMUM = 1;
private static final int MAXIMUM = 2;
private static final int AVERAGE = 3;
private static final int ZERO = 4;
private static final int VALUE = 5;
private static final String[] REPLENISHMENT_NAMES = { "none", "minimum", "maximum", "average", "zero", "value" };
public static final OperatorVersion VERSION_BEFORE_ROUND_ON_INTEGER_ATTRIBUTES = new OperatorVersion(5, 2, 0);
public MissingValueReplenishment(OperatorDescription description) {
super(description);
}
/*
* (non-Javadoc)
*
* @see com.rapidminer.operator.Operator#getIncompatibleVersionChanges()
*/
@Override
public OperatorVersion[] getIncompatibleVersionChanges() {
OperatorVersion[] oldIncompatibleVersionChanges = super.getIncompatibleVersionChanges();
OperatorVersion[] newIncompatibleVersionChanges = new OperatorVersion[oldIncompatibleVersionChanges.length + 1];
for (int i = 0; i < oldIncompatibleVersionChanges.length; ++i) {
newIncompatibleVersionChanges[i] = oldIncompatibleVersionChanges[i];
}
newIncompatibleVersionChanges[newIncompatibleVersionChanges.length - 1] = VERSION_BEFORE_ROUND_ON_INTEGER_ATTRIBUTES;
return newIncompatibleVersionChanges;
}
private static boolean doesReplenishmentSupportValueType(int replenishment, int valueType) {
if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(valueType, Ontology.NOMINAL)) {
// don't support MINIMUM, MAXIMUM, ZERO for NOMINAL attributes
switch (replenishment) {
case MINIMUM:
case MAXIMUM:
case ZERO:
return false;
}
} else if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(valueType, Ontology.DATE_TIME)) {
// don't support AVERAGE for DATE_TIME attributes
switch (replenishment) {
case AVERAGE:
return false;
}
}
return true;
}
@Override
protected void checkSelectedSubsetMetaData(ExampleSetMetaData subsetMetaData) {
super.checkSelectedSubsetMetaData(subsetMetaData);
int replenishment;
try {
replenishment = getParameterAsInt(PARAMETER_DEFAULT);
} catch (UndefinedParameterError e) {
// should never happen
return;
}
Set<AttributeMetaData> unsupportedAttributes = new HashSet<AttributeMetaData>();
for (AttributeMetaData amd : subsetMetaData.getAllAttributes()) {
if (!doesReplenishmentSupportValueType(replenishment, amd.getValueType())) {
unsupportedAttributes.add(amd);
}
}
if (!unsupportedAttributes.isEmpty()) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (AttributeMetaData amd : unsupportedAttributes) {
if (!first) {
builder.append(", ");
} else {
first = false;
}
builder.append("\"");
builder.append(amd.getName());
builder.append("\"");
}
getExampleSetInputPort().addError(
new SimpleMetaDataError(Severity.WARNING, getExampleSetInputPort(),
"missing_value_replenishment.value_type_not_supported_by_replenishment",
REPLENISHMENT_NAMES[replenishment], builder.toString()));
}
}
@Override
protected Collection<AttributeMetaData> modifyAttributeMetaData(ExampleSetMetaData emd, AttributeMetaData amd)
throws UndefinedParameterError {
if (doesReplenishmentSupportValueType(getParameterAsInt(PARAMETER_DEFAULT), amd.getValueType())) {
amd.setNumberOfMissingValues(new MDInteger(0));
}
return Collections.singletonList(amd);
}
@Override
protected int[] getFilterValueTypes() {
return new int[] { Ontology.VALUE_TYPE };
}
@Override
public String[] getFunctionNames() {
return REPLENISHMENT_NAMES;
}
@Override
public int getDefaultFunction() {
return AVERAGE;
}
@Override
public int getDefaultColumnFunction() {
return AVERAGE;
}
@Override
public double getReplacedValue() {
return Double.NaN;
}
@Override
public double getReplenishmentValue(int functionIndex, ExampleSet exampleSet, Attribute attribute) throws UserError {
if (!doesReplenishmentSupportValueType(functionIndex, attribute.getValueType())) {
logWarning("function \"" + REPLENISHMENT_NAMES[functionIndex] + "\" does not support attribute \""
+ attribute.getName() + "\" of type \""
+ Ontology.ATTRIBUTE_VALUE_TYPE.mapIndex(attribute.getValueType())
+ "\". Ignoring missing values of this attribute.");
return Double.NaN;
}
// no need to check for incompatibe valueTypes/functions, since we already did that above
switch (functionIndex) {
case NONE:
return Double.NaN;
case MINIMUM:
final double min = exampleSet.getStatistics(attribute, Statistics.MINIMUM);
return min;
case MAXIMUM:
final double max = exampleSet.getStatistics(attribute, Statistics.MAXIMUM);
return max;
case AVERAGE:
if (attribute.isNominal()) {
final double mode = exampleSet.getStatistics(attribute, Statistics.MODE);
return mode;
} else {
double average = exampleSet.getStatistics(attribute, Statistics.AVERAGE);
average = getProperlyRoundedValue(attribute, average);
return average;
}
case ZERO:
return 0.0d;
case VALUE:
String valueString = getParameterAsString(PARAMETER_REPLENISHMENT_VALUE);
if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.DATE_TIME)) {
String formatString = null;
if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.DATE)) {
formatString = ParameterTypeDateFormat.DATE_FORMAT_MM_DD_YYYY;
} else if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.TIME)) {
formatString = "hh.mm a";
} else if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.DATE_TIME)) {
formatString = "MM/dd/yyyy hh.mm a";
}
SimpleDateFormat dateFormat = new SimpleDateFormat(formatString, Locale.US);
try {
Date date = dateFormat.parse(valueString);
return date.getTime();
} catch (ParseException e) {
throw new UserError(this, 218, PARAMETER_REPLENISHMENT_VALUE, valueString);
}
} else if (attribute.isNominal()) {
int categoryValue = attribute.getMapping().getIndex(valueString);
if (categoryValue < 0) {
if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.BINOMINAL)) {
if (attribute.getMapping().size() < 2) {
// clone mapping if possible to add additional value
attribute.setMapping((NominalMapping) attribute.getMapping().clone());
}
return attribute.getMapping().mapString(valueString);
} else {
// attribute#setMapping clones the input parameter for polynomial attributes
attribute.setMapping(attribute.getMapping());
return attribute.getMapping().mapString(valueString);
}
} else {
return categoryValue;
}
} else { // any numerical type
try {
double value = Double.parseDouble(valueString);
if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.INTEGER)
&& !getCompatibilityLevel().isAtMost(VERSION_BEFORE_ROUND_ON_INTEGER_ATTRIBUTES)) {
if (value != Math.round(value)) {
throw new UserError(this, 225, PARAMETER_REPLENISHMENT_VALUE, valueString);
}
}
return value;
} catch (NumberFormatException e) {
throw new UserError(this, 211, PARAMETER_REPLENISHMENT_VALUE, valueString);
}
}
default:
throw new RuntimeException("Illegal value functionIndex: " + functionIndex);
}
}
/**
* @param attribute
* @param average2
* @return
*/
private double getProperlyRoundedValue(Attribute attribute, double value) {
if (getCompatibilityLevel().isAtMost(VERSION_BEFORE_ROUND_ON_INTEGER_ATTRIBUTES)) {
return value;
} else {
if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.INTEGER)) {
return Math.round(value);
} else {
return value;
}
}
}
@Override
public List<ParameterType> getParameterTypes() {
List<ParameterType> types = super.getParameterTypes();
ParameterTypeString type = new ParameterTypeString(PARAMETER_REPLENISHMENT_VALUE,
"This value is used for some of the replenishment types.", true, false);
type.registerDependencyCondition(new ParameterCondition(this, PARAMETER_DEFAULT, true) {
@Override
public boolean isConditionFullfilled() {
// check if any of the options is set to value
try {
if (getParameterAsInt(PARAMETER_DEFAULT) == VALUE) {
return true;
}
List<String[]> pairs = getParameterList(PARAMETER_COLUMNS);
if (pairs != null) {
for (String[] pair : pairs) {
if (pair[1].equals("value") || pair[1].equals("" + VALUE)) {
return true;
}
}
}
} catch (UndefinedParameterError e) {
}
return false;
}
});
types.add(type);
return types;
}
@Override
public boolean writesIntoExistingData() {
// the model takes care of materialization
return false;
}
@Override
public ResourceConsumptionEstimator getResourceConsumptionEstimator() {
return OperatorResourceConsumptionHandler.getResourceConsumptionEstimator(getInputPort(),
MissingValueReplenishment.class, attributeSelector);
}
}
| rapidminer/rapidminer-studio | src/main/java/com/rapidminer/operator/preprocessing/filter/MissingValueReplenishment.java | Java | agpl-3.0 | 12,960 |
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2015 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.types;
import org.w3c.dom.Element;
import com.kaltura.client.KalturaParams;
import com.kaltura.client.KalturaApiException;
import java.util.ArrayList;
import com.kaltura.client.utils.ParseUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
* @date Mon, 10 Aug 15 02:02:11 -0400
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaThumbAssetListResponse extends KalturaListResponse {
public ArrayList<KalturaThumbAsset> objects;
public KalturaThumbAssetListResponse() {
}
public KalturaThumbAssetListResponse(Element node) throws KalturaApiException {
super(node);
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node aNode = childNodes.item(i);
String nodeName = aNode.getNodeName();
if (nodeName.equals("objects")) {
this.objects = ParseUtils.parseArray(KalturaThumbAsset.class, aNode);
continue;
}
}
}
public KalturaParams toParams() {
KalturaParams kparams = super.toParams();
kparams.add("objectType", "KalturaThumbAssetListResponse");
return kparams;
}
}
| moskiteau/KalturaGeneratedAPIClientsJava | src/com/kaltura/client/types/KalturaThumbAssetListResponse.java | Java | agpl-3.0 | 2,705 |
package org.mcphoton.plugin;
import java.io.File;
import org.slf4j.Logger;
/**
* A plugin that may be loaded and unloaded.
* <h1>Dependency format</h1>
* Each string defines a dependency like this: <code>dependency:versionRequirement</code><br />
* The version requirement describes the version of the dependency that is needed by this plugin. It
* has two
* parts: a condition, and a version number.
* <h2>Conditions</h2>
* The following conditions may be used:
* <ul>
* <li><code>==</code> strictly equal</li>
* <li><code>!=</code> not equal</li>
* <li><code>~=</code> compatible</li>
* <li>{@code >=} greater than or equal to</li>
* <li>{@code > } strictly greater than</li>
* <li>{@code <=} less than or equal to</li>
* <li>{@code < } strictly less than</li>
* </ul>
* <h2>Version number</h2>
* This system is based on <a href="http://semver.org/">Semantic Versioning</a>. A version number
* consists of 3 integers (major, minor and patch number), separated by a dot, like for example
* "1.3.15". You can use less than 3 numbers, in which case any missing number will be replaced
* by a zero. For example, "1.3" is the same as "1.3.0".<br />
* You may also add a supplementary char sequence to the end of the version number, prefixed by an
* hyphen (minus sign). For example: "1.2.1-alpha"
* <h2>Wildcard requirements with '*'</h2>
* The character '*' replaces an integer. It allows for any version at its position.<br />
* For example, "== 1.2.*" allows any version that starts with "1.2", like "1.2.0", "1.2.21", etc.
* And "== 1.*.3" allows for any version that has a major version of 1 and a patch version of 3,
* like "1.0.3", "1.17.3", etc.<br />
* <b>The wildcard may only be used with a "strictly equal" or "non equal" condition.</b>
* <h2>Minimum requirements with '+'</h2>
* The character '+' goes to the end of an integer. It allows for any version that is greater or
* equal to the specified one.<br />
* For example, "== 1.2.3+" allow any version that has a major of 1, a minor of 2 and a patch
* greater or equal to 3, like "1.2.3" and "1.2.14". And "== 1.2+.3" allows for any version that
* has a major of 1, a minor greater or equal to 2 and a patch of 3, like "1.2.3" and "1.25.3".
* <br />
* <b>The + may only be used with a "strictly equal" or "non equal" condition.</b>
* <h2>Compatible condition</h2>
* The "compatible" condition allows for any version that is compatible to the specified one
* according to the semantic versioning. There are two cases:
* <ul>
* <li>The major version is 0: in that case, a version is compatible with the requirement if and
* only if:
* <ul>
* <li>they have the same supplementary char sequence</li>
* <li>AND they have the same minor version number</li>
* <li>AND the patch version number is greater than or equal to the required one</li>
* </ul>
* </li>
* <li>The major version isn't 0: in that case, a version is compatible with the requirement if and
* only if:
* <ul>
* <li>they have the same supplementary char sequence</li>
* <li>AND they have the same major version number</li>
* <li>AND the minor version is greater than or equal to the required one</li>
* <li>AND, if the minor version is equal to the required one, the patch version is greater than or
* equal to the required one</li>
* </ul>
* </li>
* </ul>
*/
public interface Plugin {
/**
* @return the plugin's name.
*/
String getName();
/**
* @return the plugin's author(s).
*/
String getAuthor();
/**
* @return the plugin's version. The version should follow the principles of
* <a href="http://semver.org/">Semantic versioning</a>.
*/
String getVersion();
/**
* @return the plugin's required dependencies. If there is no dependancy it doesn't return null
* but an empty
* array instead.
*
* @see Plugin the dependency format
*/
String[] getRequiredDependencies();
/**
* @return the plugin's optional dependencies. If there is no dependancy it doesn't return null
* but an
* empty array instead.
*
* @see Plugin the dependency format
*/
String[] getOptionalDependencies();
/**
* @return the directory that this plugin may use to store files.
*/
File getDirectory();
/**
* @return the plugin's main config file.
*/
File getConfigFile();
/**
* @return the plugin's logger.
*/
Logger getLogger();
/**
* Called when the plugin is loaded.
*/
void onLoad();
/**
* Called when the plugin is unloaded.
*/
void onUnload();
} | DJmaxZPL4Y/Photon-Server | api/src/main/java/org/mcphoton/plugin/Plugin.java | Java | agpl-3.0 | 4,491 |
/*
Copyright 2010 Jeremie Gottero, Nicolas Bosc
This file is part of Fallen Galaxy.
Fallen Galaxy is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fallen Galaxy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Fallen Galaxy. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.fg.client.i18n;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.Messages;
public interface StaticMessages extends Messages {
// ------------------------------------------------------- CONSTANTES -- //
// --------------------------------------------------------- METHODES -- //
public String ok();
public String cancel();
public String yes();
public String no();
public String close();
public String error();
public String experience();
public String level(int level);
public String colonizationPoints(String points);
public final static StaticMessages INSTANCE = (StaticMessages) GWT.create(StaticMessages.class);
@Key("day")
public String day(int day);
public String days(int days);
@Key("base.galaxy")
public String galaxy();
@Key("base.login")
public String login();
@Key("base.login.tooltip")
public String loginToolTip();
@Key("base.password")
public String password();
@Key("base.password.tooltip")
public String passwordToolTip();
@Key("base.password.nomatch")
public String passwordNoMatch();
@Key("base.connect")
public String connect();
@Key("base.register")
public String register();
@Key("base.passwordForgotten")
public String passwordForgotten();
@Key("base.gameConnection")
public String gameConnection();
@Key("base.confirmPassword")
public String confirmPassword();
@Key("base.email")
public String email();
@Key("base.email.tooltip")
public String emailToolTip();
@Key("base.birthday")
public String birthday();
@Key("base.birthday.tooltip")
public String birthdayToolTip();
@Key("base.birthday.format")
public String birthdayFormat();
@Key("base.agreeTos")
public String agreeTos(String tos);
@Key("base.termsOfService")
public String termsOfService();
@Key("base.checkTermsOfService")
public String checkTermsOfService();
@Key("base.license")
public String license();
@Key("base.emailSent")
public String emailSent();
@Key("base.recoverPassword")
public String recoverPassword();
@Key("base.recoverPassword.help")
public String recoverPasswordHelp();
@Key("base.recoverEmailSent")
public String recoverEmailSent();
@Key("unit.k")
public String unitK();
@Key("unit.m")
public String unitM();
@Key("area.vacantSystem")
public String vacantSystem();
@Key("area.uncolonizableSystem")
public String uncolonizableSystem();
@Key("area.gate")
public String gate();
@Key("area.gate.desc")
public String gateDesc();
@Key("area.gravityWell")
public String gravityWell();
@Key("area.gravityWell.desc")
public String gravityWellDesc();
@Key("area.hyperspaceSignature")
public String hyperspaceSignature();
@Key("area.hyperspaceSignature.desc")
public String hyperspaceSignatureDesc();
@Key("area.blackhole")
public String blackhole();
@Key("area.blackhole.desc")
public String blackholeDesc();
@Key("area.wormhole")
public String wormhole();
@Key("area.wormhole.desc")
public String wormholeDesc();
@Key("area.openingWormhole")
public String openingWormhole();
@Key("area.openingWormhole.desc")
public String openingWormholeDesc();
@Key("area.pirateFleet")
public String pirateFleet();
@Key("area.asteroids")
public String asteroids();
@Key("area.asteroids.desc")
public String asteroidsDesc(String percentage);
@Key("area.asteroidsDense")
public String asteroidsDense();
@Key("area.asteroidsDense.desc")
public String asteroidsDenseDesc(String percentage);
@Key("area.asteroidsLow")
public String asteroidsLow();
@Key("area.asteroidsLow.desc")
public String asteroidsLowDesc(String percentage, String resource);
@Key("area.asteroidsAvg")
public String asteroidsAvg();
@Key("area.asteroidsAvg.desc")
public String asteroidsAvgDesc(String percentage, String resource);
@Key("area.asteroidsHigh")
public String asteroidsHigh();
@Key("area.asteroidsHigh.desc")
public String asteroidsHighDesc(String percentage, String resource);
@Key("area.asteroidsVein")
public String asteroidsVein();
@Key("area.asteroidsVein.desc")
public String asteroidsVeinDesc(String percentage, String resource);
@Key("area.asteroidsLowc")
public String asteroidsLowc();
@Key("area.asteroidsLowc.desc")
public String asteroidsLowcDesc(String percentage, String resource);
@Key("area.asteroidsMediumc")
public String asteroidsMediumc();
@Key("area.asteroidsMediumc.desc")
public String asteroidsMediumcDesc(String percentage, String resource);
@Key("area.asteroidsImportant")
public String asteroidsImportant();
@Key("area.asteroidsImportant.desc")
public String asteroidsImportantDesc(String percentage, String resource);
@Key("area.asteroidsAbondant")
public String asteroidsAbondant();
@Key("area.asteroidsAbondant.desc")
public String asteroidsAbondantDesc(String percentage, String resource);
@Key("area.asteroidsPure")
public String asteroidsPure();
@Key("area.asteroidsPure.desc")
public String asteroidsPureDesc(String percentage, String resource);
@Key("area.asteroidsConcentrate")
public String asteroidsConcentrate();
@Key("area.asteroidsConcentrate.desc")
public String asteroidsConcentrateDesc(String percentage, String resource);
@Key("area.bank")
public String bank();
@Key("area.bank.desc")
public String bankDesc();
@Key("area.lottery")
public String lottery();
@Key("area.lottery.desc")
public String lotteryDesc();
@Key("area.tradeCenter")
public String tradeCenter();
@Key("area.tradeCenter.desc")
public String tradeCenterDesc();
@Key("area.doodad.desc")
public String doodadDesc();
@Key("qualifier.several")
public String qualifier1(String qualified);
@Key("qualifier.dozen")
public String qualifier2(String qualified);
@Key("qualifier.hundreds")
public String qualifier3(String qualified);
@Key("qualifier.squadron")
public String qualifier4(String qualified);
@Key("qualifier.thousands")
public String qualifier5(String qualified);
@Key("qualifier.multitude")
public String qualifier6(String qualified);
@Key("qualifier.legion")
public String qualifier7(String qualified);
@Key("qualifier.armada")
public String qualifier8(String qualified);
@Key("qualifier.millions")
public String qualifier9(String qualified);
@Key("skill.offensiveLink")
public String offensiveLink();
@Key("skill.defensiveLink")
public String defensiveLink();
@Key("advancement.colonizationPoints")
public String advancementColonizationPoints();
@Key("advancement.buildings")
public String advancementBuildings();
@Key("advancement.tiles")
public String advancementTiles();
@Key("ability.frontLine")
public String frontLine();
@Key("ability.backLine")
public String backLine();
@Key("fleet.movement")
public String movement(String movement);
@Key("fleet.maxMovement")
public String maxMovement(String time);
@Key("fleet.enteringHyperspace.notime")
public String enteringHyperspace();
@Key("fleet.leavingHyperspace.notime")
public String leavingHyperspace();
@Key("fleet.systemCapture.notime")
public String systemCapture();
@Key("fleet.jumpReload")
public String jumpReload(String time);
@Key("fleet.enteringHyperspace")
public String enteringHyperspace(String time);
@Key("fleet.leavingHyperspace")
public String leavingHyperspace(String time);
@Key("fleet.level")
public String fleetLevel(String level, String xp);
@Key("fleet.power")
public String fleetPower(String power);
@Key("fleet.colonization")
public String colonization(String time);
@Key("fleet.systemCapture")
public String systemCapture(String time);
@Key("fleet.systemMigration")
public String systemMigration(String time);
@Key("fleet.skillLevel")
public String skillLevel(int level);
@Key("ladder.players")
public String ladderPlayers();
@Key("ladder.allies")
public String ladderAllies();
@Key("ladder.player")
public String ladderPlayer();
@Key("ladder.ally")
public String ladderAlly();
@Key("ladder.points")
public String ladderPoints();
@Key("ladder.allyOrganization")
public String ladderAllyOrganization();
@Key("ladder.allyMembers")
public String ladderAllyMembers();
@Key("ladder.noAlly")
public String ladderNoAlly();
@Key("ladder.level")
public String ladderLevel();
@Key("menu.options")
public String options();
@Key("menu.shortcut")
public String shortcut(String key);
@Key("menu.help")
public String help();
@Key("menu.forum")
public String forum();
@Key("menu.exit")
public String exit();
@Key("menu.confirmExit")
public String confirmExit();
@Key("menu.resume")
public String resume();
@Key("menu.ally")
public String ally();
@Key("menu.research")
public String research();
@Key("menu.diplomacy")
public String diplomacy();
@Key("menu.galaxyMap")
public String galaxyMap();
@Key("menu.messages")
public String messages();
@Key("menu.events")
public String events();
@Key("menu.eventsLog")
public String eventsLog();
@Key("menu.menu")
public String menu();
@Key("menu.ladder")
public String ladder();
@Key("messages.inbox")
public String inbox();
@Key("messages.sentbox")
public String sentbox();
@Key("messages.archives")
public String archives();
@Key("messages.write")
public String write();
@Key("messages.answer")
public String answer();
@Key("messages.delete")
public String delete();
@Key("messages.bookmark")
public String bookmark();
@Key("messages.title")
public String title();
@Key("messages.receiver")
public String receiver();
@Key("messages.send")
public String send();
@Key("messages.dateTimeFormat")
public String dateTimeFormat();
@Key("messages.dateFormat")
public String dateFormat();
@Key("messages.timeFormat")
public String timeFormat();
@Key("messages.msgSent")
public String msgSent();
@Key("messages.confirmDel")
public String confirmDel();
@Key("battle.previousRound")
public String previousRound();
@Key("battle.nextRound")
public String nextRound();
@Key("battle.replayRound")
public String replayRound();
@Key("battle.title")
public String battleTitle();
@Key("battle.start.label")
public String battleStartLabel();
@Key("battle.start.message")
public String battleStartMessage();
@Key("battle.round.label")
public String battleRoundLabel(int round);
@Key("battle.round.message")
public String battleRoundMessage(int round);
@Key("battle.end.label")
public String battleEndLabel();
@Key("battle.end.message")
public String battleEndMessage();
@Key("battle.retreat.message")
public String battleRetreatMessage();
@Key("battle.miss")
public String miss();
@Key("battle.criticalHit")
public String criticalHitShot();
@Key("battle.dodged")
public String dodged();
@Key("battle.phased")
public String phased();
@Key("ship.targets")
public String shipTargets(String classes);
@Key("product1.desc")
public String product1Desc(String bonus);
@Key("product2.desc")
public String product2Desc(String bonus);
@Key("product3.desc")
public String product3Desc(String bonus);
@Key("product4.desc")
public String product4Desc(String bonus);
@Key("product5.desc")
public String product5Desc(String bonus);
@Key("product6.desc")
public String product6Desc(String bonus);
@Key("galaxy.search")
public String search();
@Key("galaxy.areaMap")
public String areaMap(String areaName);
@Key("galaxy.unknownSector")
public String unknownSector();
@Key("galaxy.unknownArea")
public String unknownArea();
@Key("galaxy.coordinates")
public String coordinates(String value);
@Key("build.level")
public String buildLevel(int level);
@Key("research.allow")
public String researchAllow();
@Key("research.technology")
public String technology();
@Key("research.building")
public String building();
@Key("research.ability")
public String ability();
@Key("research.finished")
public String researchFinished();
@Key("research.length")
public String researchLength(String length);
@Key("swap.transfer")
public String transfer();
@Key("swap.transferLimit")
public String transferLimit();
@Key("swap.transferLimit.help")
public String transferLimitHelp();
@Key("swap.power")
public String swapPower();
@Key("swap.power.value")
public String swapPower(String power);
@Key("swap.power.help")
public String swapPowerHelp();
@Key("swap.lockPower.help")
public String swapLockPowerHelp();
@Key("swap.payload")
public String payload();
@Key("swap.payload.help")
public String payloadHelp();
public String premium();
@Key("options.grid")
public String optionGrid();
@Key("options.proxy")
public String optionProxy();
@Key("options.proxy.help")
public String optionProxyHelp();
@Key("options.brightness")
public String optionBrightness();
@Key("options.chat")
public String optionChat();
@Key("options.censorship")
public String optionCensorship();
@Key("options.censorship.help")
public String optionCensorshipHelp();
@Key("options.fleetsSkin")
public String optionFleetsSkin();
@Key("options.fleetsName")
public String optionFleetsName();
@Key("options.fleetsName.help")
public String optionFleetsNameHelp();
@Key("options.password")
public String optionPassword();
@Key("options.change")
public String optionChange();
@Key("options.theme")
public String optionTheme();
@Key("options.theme.help")
public String optionThemeHelp();
@Key("options.generalVolume")
public String optionGeneralVolume();
@Key("options.musicVolume")
public String optionMusicVolume();
@Key("options.soundVolume")
public String optionSoundVolume();
@Key("options.graphicsQuality")
public String optionGraphicsQuality();
@Key("options.graphicsQuality.help")
public String optionGraphicsQualityHelp();
@Key("options.graphicsQuality.low")
public String optionGraphicsQualityLow();
@Key("options.graphicsQuality.average")
public String optionGraphicsQualityAverage();
@Key("options.graphicsQuality.high")
public String optionGraphicsQualityHigh();
@Key("options.graphicsQuality.max")
public String optionGraphicsQualityMax();
}
| Orichievac/FallenGalaxy | src-client/fr/fg/client/i18n/StaticMessages.java | Java | agpl-3.0 | 14,876 |
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.types;
import com.google.gson.JsonObject;
import com.kaltura.client.Params;
import com.kaltura.client.utils.GsonParser;
import com.kaltura.client.utils.request.MultiRequestBuilder;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
@MultiRequestBuilder.Tokenizer(SystemPartnerFilter.Tokenizer.class)
public class SystemPartnerFilter extends PartnerFilter {
public interface Tokenizer extends PartnerFilter.Tokenizer {
String partnerParentIdEqual();
String partnerParentIdIn();
}
private Integer partnerParentIdEqual;
private String partnerParentIdIn;
// partnerParentIdEqual:
public Integer getPartnerParentIdEqual(){
return this.partnerParentIdEqual;
}
public void setPartnerParentIdEqual(Integer partnerParentIdEqual){
this.partnerParentIdEqual = partnerParentIdEqual;
}
public void partnerParentIdEqual(String multirequestToken){
setToken("partnerParentIdEqual", multirequestToken);
}
// partnerParentIdIn:
public String getPartnerParentIdIn(){
return this.partnerParentIdIn;
}
public void setPartnerParentIdIn(String partnerParentIdIn){
this.partnerParentIdIn = partnerParentIdIn;
}
public void partnerParentIdIn(String multirequestToken){
setToken("partnerParentIdIn", multirequestToken);
}
public SystemPartnerFilter() {
super();
}
public SystemPartnerFilter(JsonObject jsonObject) throws APIException {
super(jsonObject);
if(jsonObject == null) return;
// set members values:
partnerParentIdEqual = GsonParser.parseInt(jsonObject.get("partnerParentIdEqual"));
partnerParentIdIn = GsonParser.parseString(jsonObject.get("partnerParentIdIn"));
}
public Params toParams() {
Params kparams = super.toParams();
kparams.add("objectType", "KalturaSystemPartnerFilter");
kparams.add("partnerParentIdEqual", this.partnerParentIdEqual);
kparams.add("partnerParentIdIn", this.partnerParentIdIn);
return kparams;
}
}
| kaltura/KalturaGeneratedAPIClientsJava | src/main/java/com/kaltura/client/types/SystemPartnerFilter.java | Java | agpl-3.0 | 3,387 |
/**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.transaction.xaframework;
import java.io.IOException;
public class IllegalLogFormatException extends IOException
{
public IllegalLogFormatException( long expected, long was )
{
super( "Invalid log format version found, expected " + expected + " but was " + was +
". To be able to upgrade from an older log format version there must have " +
"been a clean shutdown of the database" );
}
}
| neo4j-attic/graphdb | kernel/src/main/java/org/neo4j/kernel/impl/transaction/xaframework/IllegalLogFormatException.java | Java | agpl-3.0 | 1,288 |
package cs.lang.scobol.dfa;
import cs.lang.scobol.Language;
import cs.lang.DFAState;
import cs.lang.scobol.Alphabet;
import cs.lang.DFATools;
public class PERF extends DFAState<Language.DFAState, Language.LexicalUnit, Character>{
public PERF(){
super(Language.LexicalUnit.IDENTIFIER);
transition.put('o', Language.DFAState.PERFO);
DFATools.fill(transition, Alphabet.IDENTIFIER, Language.DFAState.IDENTIFIER_4);
}
}
| aureooms-ulb-2010-2015/2013-2014-infof403-project | 1/more/src/cs/lang/scobol/dfa/PERF.java | Java | agpl-3.0 | 426 |
package org.bimserver.database.queries;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.bimserver.BimserverDatabaseException;
import org.bimserver.database.DatabaseSession;
import org.bimserver.database.OidCounters;
import org.bimserver.database.actions.AbstractDownloadDatabaseAction;
import org.bimserver.emf.PackageMetaData;
import org.bimserver.models.store.ConcreteRevision;
import org.bimserver.shared.QueryContext;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
public class ConcreteRevisionStackFrame extends StackFrame {
private final QueryObjectProvider queryObjectProvider;
private final PackageMetaData packageMetaData;
private final QueryContext queryContext;
// TODO make not static (use factory somewhere), and check concurrency
private static final Map<Long, OidCounters> reusableQueryContexts = new HashMap<>();
public ConcreteRevisionStackFrame(QueryObjectProvider queryObjectProvider, ConcreteRevision concreteRevision, long roid) {
this.queryObjectProvider = queryObjectProvider;
int highestStopId = AbstractDownloadDatabaseAction.findHighestStopRid(concreteRevision.getProject(), concreteRevision);
packageMetaData = queryObjectProvider.getMetaDataManager().getPackageMetaData(concreteRevision.getProject().getSchema());
queryContext = new QueryContext(queryObjectProvider.getDatabaseSession(), packageMetaData, concreteRevision.getProject().getId(), concreteRevision.getId(), roid, concreteRevision.getOid(), highestStopId);
if (concreteRevision.getOidCounters() != null) {
synchronized (getClass()) {
if (reusableQueryContexts.containsKey(concreteRevision.getOid())) {
queryContext.setOidCounters(reusableQueryContexts.get(concreteRevision.getOid()));
} else {
try {
OidCounters updateOidCounters = updateOidCounters(concreteRevision, queryObjectProvider.getDatabaseSession());
queryContext.setOidCounters(updateOidCounters);
reusableQueryContexts.put(concreteRevision.getOid(), updateOidCounters);
} catch (BimserverDatabaseException e) {
e.printStackTrace();
}
}
}
}
}
public static void clearCache(long croid) {
reusableQueryContexts.remove(croid);
}
private OidCounters updateOidCounters(ConcreteRevision subRevision, DatabaseSession databaseSession) throws BimserverDatabaseException {
if (subRevision.getOidCounters() != null) {
return new OidCounters(databaseSession, subRevision.getOidCounters());
}
return null;
}
@Override
public boolean process() throws BimserverDatabaseException, JsonParseException, JsonMappingException, IOException {
queryObjectProvider.push(new QueryStackFrame(queryObjectProvider, queryContext));
return true;
}
} | opensourceBIM/BIMserver | BimServer/src/org/bimserver/database/queries/ConcreteRevisionStackFrame.java | Java | agpl-3.0 | 3,704 |
/*
This file is part of PH-Tree:
A multi-dimensional indexing and storage structure.
Copyright (C) 2011-2015
Eidgenössische Technische Hochschule Zürich (ETH Zurich)
Institute for Information Systems
GlobIS Group
Bogdan Vancea, Tilmann Zaeschke
[email protected] or [email protected]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ch.ethz.globis.distindex.concurrency.dummies;
public class NodeWithLock<T> implements Node<T> {
}
| tzaeschke/distributed-phtree | shared/src/main/java/ch/ethz/globis/distindex/concurrency/dummies/NodeWithLock.java | Java | agpl-3.0 | 1,030 |
package org.opencps.api.controller;
import java.net.HttpURLConnection;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.opencps.api.v21.dossiersync.model.DossierSyncV21ResultsModel;
import org.opencps.exception.model.ExceptionModel;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.service.ServiceContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@Path("/dossiersyncs")
@Api(value = "/dossiersyncs", tags = "dossiersyncs")
public interface DossierSyncManagement {
// @GET
// @Path("/server/{serverNo}")
// @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
// @ApiOperation(value = "Get the list of Dossiers that need to sync in queue", response = DossierSyncResultsModel.class)
// @ApiResponses(value = {
// @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the list of DossierSyncs", response = DossierSyncResultsModel.class),
// @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
// @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
// @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
//
// public Response getDossierSyncs(@Context HttpServletRequest request, @Context HttpHeaders header,
// @Context Company company, @Context Locale locale, @Context User user,
// @Context ServiceContext serviceContext, @PathParam("serverNo") String serverNo);
//
// @GET
// @Path("/{id}/sending")
// @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
// @ApiOperation(value = "Sending a DossierSync have to sync", response = DossierSyncSendingModel.class)
// @ApiResponses(value = {
// @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "The DossierSync has been synchronized", response = DossierSyncSendingModel.class),
// @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
// @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
// @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
//
// public Response sendDossierSync(@Context HttpServletRequest request, @Context HttpHeaders header,
// @Context Company company, @Context Locale locale, @Context User user,
// @Context ServiceContext serviceContext, @PathParam("id") long id);
//
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Get a DossierSync of dossier", response = DossierSyncV21ResultsModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "The DossierSync has been synchronized", response = DossierSyncV21ResultsModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response getDossierSyncsByApplicant(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext, @QueryParam("action") String action,
@QueryParam("start") Integer start, @QueryParam("end") Integer end);
}
| VietOpenCPS/opencps-v2 | modules/backend-api-rest/src/main/java/org/opencps/api/controller/DossierSyncManagement.java | Java | agpl-3.0 | 4,025 |
/**
* Copyright (C) 2009-2014 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cn.dlb.bim.models.ifc4.impl;
import org.eclipse.emf.ecore.EClass;
import cn.dlb.bim.models.ifc4.Ifc4Package;
import cn.dlb.bim.models.ifc4.IfcActor;
import cn.dlb.bim.models.ifc4.IfcActorRole;
import cn.dlb.bim.models.ifc4.IfcRelAssignsToActor;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Ifc Rel Assigns To Actor</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link cn.dlb.bim.models.ifc4.impl.IfcRelAssignsToActorImpl#getRelatingActor <em>Relating Actor</em>}</li>
* <li>{@link cn.dlb.bim.models.ifc4.impl.IfcRelAssignsToActorImpl#getActingRole <em>Acting Role</em>}</li>
* </ul>
*
* @generated
*/
public class IfcRelAssignsToActorImpl extends IfcRelAssignsImpl implements IfcRelAssignsToActor {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IfcRelAssignsToActorImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Ifc4Package.Literals.IFC_REL_ASSIGNS_TO_ACTOR;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IfcActor getRelatingActor() {
return (IfcActor) eGet(Ifc4Package.Literals.IFC_REL_ASSIGNS_TO_ACTOR__RELATING_ACTOR, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setRelatingActor(IfcActor newRelatingActor) {
eSet(Ifc4Package.Literals.IFC_REL_ASSIGNS_TO_ACTOR__RELATING_ACTOR, newRelatingActor);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IfcActorRole getActingRole() {
return (IfcActorRole) eGet(Ifc4Package.Literals.IFC_REL_ASSIGNS_TO_ACTOR__ACTING_ROLE, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setActingRole(IfcActorRole newActingRole) {
eSet(Ifc4Package.Literals.IFC_REL_ASSIGNS_TO_ACTOR__ACTING_ROLE, newActingRole);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unsetActingRole() {
eUnset(Ifc4Package.Literals.IFC_REL_ASSIGNS_TO_ACTOR__ACTING_ROLE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetActingRole() {
return eIsSet(Ifc4Package.Literals.IFC_REL_ASSIGNS_TO_ACTOR__ACTING_ROLE);
}
} //IfcRelAssignsToActorImpl
| shenan4321/BIMplatform | generated/cn/dlb/bim/models/ifc4/impl/IfcRelAssignsToActorImpl.java | Java | agpl-3.0 | 3,157 |
/*
* Encog(tm) Core v3.2 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2013 Heaton Research, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package syncleus.dann.data.language;
public class SimpleParser {
private final String line;
private int currentPosition;
private int marked;
public SimpleParser(final String line) {
this.line = line;
}
public int remaining() {
return Math.max(this.line.length() - this.currentPosition, 0);
}
public boolean parseThroughComma() {
eatWhiteSpace();
if (!eol()) {
if (peek() == ',') {
advance();
return true;
}
}
return false;
}
public boolean isIdentifier() {
if (eol())
return false;
return Character.isLetterOrDigit(peek()) || peek() == '_';
}
public char peek() {
if (eol())
return 0;
else if (currentPosition >= this.line.length())
return 0;
else
return this.line.charAt(this.currentPosition);
}
public void advance() {
if (currentPosition < this.line.length()) {
currentPosition++;
}
}
public boolean isWhiteSpace() {
return " \t\n\r".indexOf(peek()) != -1;
}
public boolean eol() {
return (this.currentPosition >= this.line.length());
}
public void eatWhiteSpace() {
while (!eol() && isWhiteSpace())
advance();
}
public char readChar() {
if (eol())
return 0;
final char ch = peek();
advance();
return ch;
}
public String readToWhiteSpace() {
final StringBuilder result = new StringBuilder();
while (!isWhiteSpace() && !eol()) {
result.append(readChar());
}
return result.toString();
}
public boolean lookAhead(final String str, final boolean ignoreCase) {
if (remaining() < str.length())
return false;
for (int i = 0; i < str.length(); i++) {
char c1 = str.charAt(i);
char c2 = this.line.charAt(this.currentPosition + i);
if (ignoreCase) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
}
if (c1 != c2)
return false;
}
return true;
}
public void advance(final int p) {
this.currentPosition = Math
.min(line.length(), this.currentPosition + p);
}
public void mark() {
this.marked = this.currentPosition;
}
public void reset() {
this.currentPosition = this.marked;
}
public String readQuotedString() {
if (peek() != '\"')
return "";
final StringBuilder result = new StringBuilder();
advance();
while (peek() != '\"' && !this.eol()) {
result.append(readChar());
}
advance();
return result.toString();
}
public String readToChars(final String chs) {
final StringBuilder result = new StringBuilder();
while (chs.indexOf(this.peek()) == -1 && !eol()) {
result.append(readChar());
}
return result.toString();
}
public String getLine() {
return this.line;
}
public boolean lookAhead(final String c) {
return lookAhead(c, false);
}
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
result.append("[Parser: ");
result.append(this.line.substring(this.currentPosition));
result.append(']');
return result.toString();
}
}
| automenta/java_dann | src/syncleus/dann/data/language/SimpleParser.java | Java | agpl-3.0 | 4,462 |
package org.freya.similarity;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.freya.util.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import uk.ac.shef.wit.simmetrics.similaritymetrics.AbstractStringMetric;
import uk.ac.shef.wit.simmetrics.similaritymetrics.MongeElkan;
@Component
public class SimilarityCalculator {
static Log logger = LogFactory.getLog(SimilarityCalculator.class);
AbstractStringMetric metrics = new MongeElkan();
AbstractStringMetric soundex =
new uk.ac.shef.wit.simmetrics.similaritymetrics.Soundex();
/* shall the wordnet be used or not */
boolean useWordnet = true;
@Autowired WordnetInvoker wordnetInvoker;
/**
* compare the two strings
*
* @param text
* @param niceLabel
* @return
*/
public double findSimilarity(String text, String niceLabel) {
float simBtwStrings = 0;
float soundexSim = 0;
int maxNumberOfSynonyms = 3;
// first find synonym of poc and compare to suggestion
Set<String> synonyms =
wordnetInvoker.getSynonyms(text, maxNumberOfSynonyms);
int numberOfSynonyms = 0;
float synonymSim = 0;
for (String syn : synonyms) {
float tmpSim = metrics.getSimilarity(syn, niceLabel);
synonymSim = synonymSim + tmpSim;
logger.debug("sim(" + niceLabel + ",(synonym)" + syn + ")= " + tmpSim);
numberOfSynonyms++;
}
if (numberOfSynonyms > 0) synonymSim = synonymSim / numberOfSynonyms;
// then find synonym of suggestion and compare to poc
Set<String> synonyms2 =
wordnetInvoker.getSynonyms(niceLabel, numberOfSynonyms);
int numberOfSynonyms2 = 0;
float synonymSim2 = 0;
for (String syn : synonyms2) {
float tmpSim = metrics.getSimilarity(syn, text);
synonymSim2 = synonymSim2 + tmpSim;
logger.debug("sim(" + text + ",(synonym)" + syn + ")= " + tmpSim);
numberOfSynonyms2++;
}
if (numberOfSynonyms2 > 0) synonymSim2 = synonymSim2 / numberOfSynonyms2;
simBtwStrings = metrics.getSimilarity(text, niceLabel);
soundexSim = soundex.getSimilarity(text, niceLabel);
double totalSimilarity =
NumberUtils.roundTwoDecimals(0.45 * simBtwStrings + 0.15
* (soundexSim) + 0.2 * synonymSim + 0.2 * synonymSim2);
logger.debug("TotalSim(" + niceLabel + "," + text + ")=" + totalSimilarity
+ "(" + " MongeElkan:" + simBtwStrings + " Soundex:" + soundexSim
+ " Wordnet:" + synonymSim + "+" + synonymSim2 + ")");
return totalSimilarity;
}
/**
* compare the two strings using MongeElkan and Soundex
*
* @param text
* @param niceLabel
* @return
*/
public double findStringSimilarity(String text, String niceLabel, String similarityTypeName) {
float simBtwStrings = 0;
float soundexSim = 0;
simBtwStrings = metrics.getSimilarity(text, niceLabel);
soundexSim = soundex.getSimilarity(text, niceLabel);
double totalSimilarity =
NumberUtils.roundTwoDecimals(0.45 * simBtwStrings + 0.15
* (soundexSim));
logger.debug("TotalSim(" + niceLabel + "," + text + ")=" + totalSimilarity
+ "(" + " MongeElkan:" + simBtwStrings + " Soundex:" + soundexSim
);
return totalSimilarity;
}
}
| danicadamljanovic/freya | freya/freya-annotate/src/main/java/org/freya/similarity/SimilarityCalculator.java | Java | agpl-3.0 | 3,764 |
package roart.component.model;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import roart.result.model.ResultMeta;
public class MLCCIData extends ComponentMLData {
public MLCCIData(ComponentData componentparam) {
super(componentparam);
}
/*
public void setDatesAndOffset(int daysafterzero, Integer offset, String aDate) throws ParseException {
this.offset = setDates(daysafterzero, offset, aDate);
}
*/
}
| rroart/stockstat | iclij/iclij-common/iclij-componentdata/src/main/java/roart/component/model/MLCCIData.java | Java | agpl-3.0 | 486 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* 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.restcomm.protocols.ss7.scheduler;
/**
*
* @author oifa yulian
*/
public class IntConcurrentHashMap<E> {
private IntConcurrentLinkedList<E>[] lists = new IntConcurrentLinkedList[16];
public IntConcurrentHashMap() {
for (int i = 0; i < 16; i++)
lists[i] = new IntConcurrentLinkedList<E>();
}
public boolean contains(int key) {
return lists[getHash(key)].contains(key);
}
public boolean add(E value, int key) {
if (value == null)
return false;
lists[getHash(key)].add(value, key);
return true;
}
public boolean offer(E value, int key) {
if (value == null)
return false;
lists[getHash(key)].offer(value, key);
return true;
}
public E get(int key) {
return lists[getHash(key)].get(key);
}
public E remove(int key) {
return lists[getHash(key)].remove(key);
}
private int getHash(int key) {
// 4 bits allows 16 values
// use bits 1,2 and 6,7
return key & 0x3 + (key >> 3) & 0xC;
}
}
| RestComm/jss7 | scheduler/src/main/java/org/restcomm/protocols/ss7/scheduler/IntConcurrentHashMap.java | Java | agpl-3.0 | 2,105 |
/*
* ClientEvent.java
*
* Copyright (C) 2009-15 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.server.remote;
import com.google.gwt.core.client.JavaScriptObject;
class ClientEvent extends JavaScriptObject
{
public static final String Busy = "busy";
public static final String ConsolePrompt = "console_prompt";
public static final String ConsoleOutput = "console_output" ;
public static final String ConsoleError = "console_error";
public static final String ConsoleWritePrompt = "console_write_prompt";
public static final String ConsoleWriteInput = "console_write_input";
public static final String ShowErrorMessage = "show_error_message";
public static final String ShowHelp = "show_help" ;
public static final String BrowseUrl = "browse_url";
public static final String ShowEditor = "show_editor";
public static final String ChooseFile = "choose_file";
public static final String AbendWarning = "abend_warning";
public static final String Quit = "quit";
public static final String Suicide = "suicide";
public static final String FileChanged = "file_changed";
public static final String WorkingDirChanged = "working_dir_changed";
public static final String PlotsStateChanged = "plots_state_changed";
public static final String ViewData = "view_data";
public static final String PackageStatusChanged = "package_status_changed";
public static final String PackageStateChanged = "package_state_changed";
public static final String Locator = "locator";
public static final String ConsoleResetHistory = "console_reset_history";
public static final String SessionSerialization = "session_serialization";
public static final String HistoryEntriesAdded = "history_entries_added";
public static final String QuotaStatus = "quota_status";
public static final String FileEdit = "file_edit";
public static final String ShowContent = "show_content";
public static final String ShowData = "show_data";
public static final String AsyncCompletion = "async_completion";
public static final String SaveActionChanged = "save_action_changed";
public static final String ShowWarningBar = "show_warning_bar";
public static final String OpenProjectError = "open_project_error";
public static final String VcsRefresh = "vcs_refresh";
public static final String AskPass = "ask_pass";
public static final String ConsoleProcessOutput = "console_process_output";
public static final String ConsoleProcessExit = "console_process_exit";
public static final String ListChanged = "list_changed";
public static final String UiPrefsChanged = "ui_prefs_changed";
public static final String HandleUnsavedChanges = "handle_unsaved_changes";
public static final String PosixShellOutput = "posix_shell_output";
public static final String PosixShellExit = "posix_shell_exit";
public static final String ConsoleProcessPrompt = "console_process_prompt";
public static final String ConsoleProcessCreated = "console_process_created";
public static final String HTMLPreviewStartedEvent = "html_preview_started_event";
public static final String HTMLPreviewOutputEvent = "html_preview_output_event";
public static final String HTMLPreviewCompletedEvent = "html_preview_completed_event";
public static final String CompilePdfStartedEvent = "compile_pdf_started_event";
public static final String CompilePdfOutputEvent = "compile_pdf_output_event";
public static final String CompilePdfErrorsEvent = "compile_pdf_errors_event";
public static final String CompilePdfCompletedEvent = "compile_pdf_completed_event";
public static final String SynctexEditFile = "synctex_edit_file";
public static final String FindResult = "find_result";
public static final String FindOperationEnded = "find_operation_ended";
public static final String RPubsUploadStatus = "rpubs_upload_status";
public static final String BuildStarted = "build_started";
public static final String BuildOutput = "build_output";
public static final String BuildCompleted = "build_completed";
public static final String BuildErrors = "build_errors";
public static final String DirectoryNavigate = "directory_navigate";
public static final String DeferredInitCompleted = "deferred_init_completed";
public static final String PlotsZoomSizeChanged = "plots_zoom_size_changed";
public static final String SourceCppStarted = "source_cpp_started";
public static final String SourceCppCompleted = "source_cpp_completed";
public static final String LoadedPackageUpdates = "loaded_package_updates";
public static final String ActivatePane = "activate_pane";
public static final String ShowPresentationPane = "show_presentation_pane";
public static final String EnvironmentRefresh = "environment_refresh";
public static final String ContextDepthChanged = "context_depth_changed";
public static final String EnvironmentAssigned = "environment_assigned";
public static final String EnvironmentRemoved = "environment_removed";
public static final String BrowserLineChanged = "browser_line_changed";
public static final String PackageLoaded = "package_loaded";
public static final String PackageUnloaded = "package_unloaded";
public static final String PresentationPaneRequestCompleted = "presentation_pane_request_completed";
public static final String UnhandledError = "unhandled_error";
public static final String ErrorHandlerChanged = "error_handler_changed";
public static final String ViewerNavigate = "viewer_navigate";
public static final String UpdateCheck = "update_check";
public static final String SourceExtendedTypeDetected = "source_extended_type_detected";
public static final String ShinyViewer = "shiny_viewer";
public static final String DebugSourceCompleted = "debug_source_completed";
public static final String RmdRenderStarted = "rmd_render_started";
public static final String RmdRenderOutput = "rmd_render_output";
public static final String RmdRenderCompleted = "rmd_render_completed";
public static final String RmdTemplateDiscovered = "rmd_template_discovered";
public static final String RmdTemplateDiscoveryCompleted = "rmd_template_discovery_completed";
public static final String RmdShinyDocStarted = "rmd_shiny_doc_started";
public static final String RSConnectDeploymentOutput = "rsconnect_deployment_output";
public static final String RSConnectDeploymentCompleted = "rsconnect_deployment_completed";
public static final String RSConnectDeploymentFailed = "rsconnect_deployment_failed";
public static final String UserPrompt = "user_prompt";
public static final String InstallRtools = "install_r_tools";
public static final String InstallShiny = "install_shiny";
public static final String SuspendAndRestart = "suspend_and_restart";
public static final String PackratRestoreNeeded = "packrat_restore_needed";
public static final String DataViewChanged = "data_view_changed";
public static final String ViewFunction = "view_function";
public static final String MarkersChanged = "markers_changed";
public static final String EnableRStudioConnect = "enable_rstudio_connect";
public static final String UpdateGutterMarkers = "update_gutter_markers";
public static final String SnippetsChanged = "snippets_changed";
public static final String JumpToFunction = "jump_to_function";
public static final String CollabEditStarted = "collab_edit_started";
public static final String SessionCountChanged = "session_count_changed";
public static final String CollabEditEnded = "collab_edit_ended";
public static final String ProjectUsersChanged = "project_users_changed";
public static final String RVersionsChanged = "r_versions_changed";
public static final String ShinyGadgetDialog = "shiny_gadget_dialog";
public static final String RmdParamsReady = "rmd_params_ready";
public static final String RegisterUserCommand = "register_user_command";
public static final String SendToConsole = "send_to_console";
public static final String UserFollowStarted = "user_follow_started";
public static final String UserFollowEnded = "user_follow_ended";
public static final String ProjectAccessRevoked = "project_access_revoked";
public static final String CollabEditSaved = "collab_edit_saved";
public static final String AddinRegistryUpdated = "addin_registry_updated";
public static final String ChunkOutput = "chunk_output";
public static final String ChunkOutputFinished = "chunk_output_finished";
public static final String RprofStarted = "rprof_started";
public static final String RprofStopped = "rprof_stopped";
public static final String RprofCreated = "rprof_created";
public static final String EditorCommand = "editor_command";
public static final String PreviewRmd = "preview_rmd";
public static final String WebsiteFileSaved = "website_file_saved";
public static final String ChunkPlotRefreshed = "chunk_plot_refreshed";
public static final String ChunkPlotRefreshFinished = "chunk_plot_refresh_finished";
public static final String ReloadWithLastChanceSave = "reload_with_last_chance_save";
public static final String ConnectionUpdated = "connection_updated";
public static final String EnableConnections = "enable_connections";
public static final String ConnectionListChanged = "connection_list_changed";
public static final String ActiveConnectionsChanged = "active_connections_changed";
public static final String ConnectionOpened = "connection_opened";
public static final String NotebookRangeExecuted = "notebook_range_executed";
public static final String ChunkExecStateChanged = "chunk_exec_state_changed";
protected ClientEvent()
{
}
public final native int getId() /*-{
return this.id;
}-*/;
public final native String getType() /*-{
return this.type;
}-*/;
public final native <T> T getData() /*-{
return this.data;
}-*/;
}
| jrnold/rstudio | src/gwt/src/org/rstudio/studio/client/server/remote/ClientEvent.java | Java | agpl-3.0 | 10,554 |
/*
* This file is part of Bitsquare.
*
* Bitsquare is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bitsquare is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
*/
package io.bitsquare.trade;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.bitsquare.app.Log;
import io.bitsquare.app.Version;
import io.bitsquare.arbitration.Arbitrator;
import io.bitsquare.arbitration.ArbitratorManager;
import io.bitsquare.btc.TradeWalletService;
import io.bitsquare.btc.WalletService;
import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.common.taskrunner.Model;
import io.bitsquare.crypto.DecryptedMsgWithPubKey;
import io.bitsquare.filter.FilterManager;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService;
import io.bitsquare.storage.Storage;
import io.bitsquare.trade.offer.Offer;
import io.bitsquare.trade.offer.OpenOfferManager;
import io.bitsquare.trade.protocol.trade.ProcessModel;
import io.bitsquare.trade.protocol.trade.TradeProtocol;
import io.bitsquare.user.User;
import javafx.beans.property.*;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence;
import org.bitcoinj.utils.ExchangeRate;
import org.bitcoinj.utils.Fiat;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Holds all data which are relevant to the trade, but not those which are only needed in the trade process as shared data between tasks. Those data are
* stored in the task model.
*/
public abstract class Trade implements Tradable, Model {
// That object is saved to disc. We need to take care of changes to not break deserialization.
private static final long serialVersionUID = Version.LOCAL_DB_VERSION;
private static final Logger log = LoggerFactory.getLogger(Trade.class);
public enum State {
PREPARATION(Phase.PREPARATION),
TAKER_FEE_PAID(Phase.TAKER_FEE_PAID),
OFFERER_SENT_PUBLISH_DEPOSIT_TX_REQUEST(Phase.DEPOSIT_REQUESTED),
TAKER_PUBLISHED_DEPOSIT_TX(Phase.DEPOSIT_PAID),
DEPOSIT_SEEN_IN_NETWORK(Phase.DEPOSIT_PAID), // triggered by balance update, used only in error cases
TAKER_SENT_DEPOSIT_TX_PUBLISHED_MSG(Phase.DEPOSIT_PAID),
OFFERER_RECEIVED_DEPOSIT_TX_PUBLISHED_MSG(Phase.DEPOSIT_PAID),
DEPOSIT_CONFIRMED_IN_BLOCK_CHAIN(Phase.DEPOSIT_PAID),
BUYER_CONFIRMED_FIAT_PAYMENT_INITIATED(Phase.FIAT_SENT),
BUYER_SENT_FIAT_PAYMENT_INITIATED_MSG(Phase.FIAT_SENT),
SELLER_RECEIVED_FIAT_PAYMENT_INITIATED_MSG(Phase.FIAT_SENT),
SELLER_CONFIRMED_FIAT_PAYMENT_RECEIPT(Phase.FIAT_RECEIVED),
SELLER_SENT_FIAT_PAYMENT_RECEIPT_MSG(Phase.FIAT_RECEIVED),
BUYER_RECEIVED_FIAT_PAYMENT_RECEIPT_MSG(Phase.FIAT_RECEIVED),
BUYER_COMMITTED_PAYOUT_TX(Phase.PAYOUT_PAID), //TODO needed?
BUYER_STARTED_SEND_PAYOUT_TX(Phase.PAYOUT_PAID), // not from the success/arrived handler!
SELLER_RECEIVED_AND_COMMITTED_PAYOUT_TX(Phase.PAYOUT_PAID),
PAYOUT_BROAD_CASTED(Phase.PAYOUT_PAID),
WITHDRAW_COMPLETED(Phase.WITHDRAWN);
public Phase getPhase() {
return phase;
}
private final Phase phase;
State(Phase phase) {
this.phase = phase;
}
}
public enum Phase {
PREPARATION,
TAKER_FEE_PAID,
DEPOSIT_REQUESTED,
DEPOSIT_PAID,
FIAT_SENT,
FIAT_RECEIVED,
PAYOUT_PAID,
WITHDRAWN,
DISPUTE
}
public enum DisputeState {
NONE,
DISPUTE_REQUESTED,
DISPUTE_STARTED_BY_PEER,
DISPUTE_CLOSED
}
public enum TradePeriodState {
NORMAL,
HALF_REACHED,
TRADE_PERIOD_OVER
}
///////////////////////////////////////////////////////////////////////////////////////////
// Fields
///////////////////////////////////////////////////////////////////////////////////////////
// Transient/Immutable
transient private ObjectProperty<State> stateProperty;
transient private ObjectProperty<DisputeState> disputeStateProperty;
transient private ObjectProperty<TradePeriodState> tradePeriodStateProperty;
// Trades are saved in the TradeList
@Nullable
transient private Storage<? extends TradableList> storage;
transient protected TradeProtocol tradeProtocol;
transient private Date maxTradePeriodDate, halfTradePeriodDate;
// Immutable
private final Offer offer;
private final ProcessModel processModel;
// Mutable
private DecryptedMsgWithPubKey decryptedMsgWithPubKey;
private Date takeOfferDate;
private Coin tradeAmount;
private long tradePrice;
private NodeAddress tradingPeerNodeAddress;
@Nullable
private String takeOfferFeeTxId;
protected State state;
private DisputeState disputeState = DisputeState.NONE;
private TradePeriodState tradePeriodState = TradePeriodState.NORMAL;
private Transaction depositTx;
private Contract contract;
private String contractAsJson;
private byte[] contractHash;
private String takerContractSignature;
private String offererContractSignature;
private Transaction payoutTx;
private long lockTimeAsBlockHeight;
private NodeAddress arbitratorNodeAddress;
private byte[] arbitratorBtcPubKey;
private String takerPaymentAccountId;
private String errorMessage;
transient private StringProperty errorMessageProperty;
transient private ObjectProperty<Coin> tradeAmountProperty;
transient private ObjectProperty<Fiat> tradeVolumeProperty;
transient private Set<DecryptedMsgWithPubKey> mailboxMessageSet = new HashSet<>();
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor, initialization
///////////////////////////////////////////////////////////////////////////////////////////
// offerer
protected Trade(Offer offer, Storage<? extends TradableList> storage) {
this.offer = offer;
this.storage = storage;
this.takeOfferDate = new Date();
processModel = new ProcessModel();
tradeVolumeProperty = new SimpleObjectProperty<>();
tradeAmountProperty = new SimpleObjectProperty<>();
errorMessageProperty = new SimpleStringProperty();
initStates();
initStateProperties();
}
// taker
protected Trade(Offer offer, Coin tradeAmount, long tradePrice, NodeAddress tradingPeerNodeAddress,
Storage<? extends TradableList> storage) {
this(offer, storage);
this.tradeAmount = tradeAmount;
this.tradePrice = tradePrice;
this.tradingPeerNodeAddress = tradingPeerNodeAddress;
tradeAmountProperty.set(tradeAmount);
tradeVolumeProperty.set(getTradeVolume());
this.takeOfferDate = new Date();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
in.defaultReadObject();
initStateProperties();
initAmountProperty();
errorMessageProperty = new SimpleStringProperty(errorMessage);
mailboxMessageSet = new HashSet<>();
} catch (Throwable t) {
log.warn("Cannot be deserialized." + t.getMessage());
}
}
public void init(P2PService p2PService,
WalletService walletService,
TradeWalletService tradeWalletService,
ArbitratorManager arbitratorManager,
TradeManager tradeManager,
OpenOfferManager openOfferManager,
User user,
FilterManager filterManager,
KeyRing keyRing,
boolean useSavingsWallet,
Coin fundsNeededForTrade) {
Log.traceCall();
processModel.onAllServicesInitialized(offer,
tradeManager,
openOfferManager,
p2PService,
walletService,
tradeWalletService,
arbitratorManager,
user,
filterManager,
keyRing,
useSavingsWallet,
fundsNeededForTrade);
createProtocol();
log.trace("init: decryptedMsgWithPubKey = " + decryptedMsgWithPubKey);
if (decryptedMsgWithPubKey != null && !mailboxMessageSet.contains(decryptedMsgWithPubKey)) {
mailboxMessageSet.add(decryptedMsgWithPubKey);
tradeProtocol.applyMailboxMessage(decryptedMsgWithPubKey, this);
}
}
protected void initStateProperties() {
stateProperty = new SimpleObjectProperty<>(state);
disputeStateProperty = new SimpleObjectProperty<>(disputeState);
tradePeriodStateProperty = new SimpleObjectProperty<>(tradePeriodState);
}
protected void initAmountProperty() {
tradeAmountProperty = new SimpleObjectProperty<>();
tradeVolumeProperty = new SimpleObjectProperty<>();
if (tradeAmount != null) {
tradeAmountProperty.set(tradeAmount);
tradeVolumeProperty.set(getTradeVolume());
}
}
///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
// The deserialized tx has not actual confidence data, so we need to get the fresh one from the wallet.
public void updateDepositTxFromWallet() {
if (depositTx != null)
setDepositTx(processModel.getTradeWalletService().getWalletTx(depositTx.getHash()));
}
public void setDepositTx(Transaction tx) {
log.debug("setDepositTx " + tx);
this.depositTx = tx;
setupConfidenceListener();
persist();
}
@Nullable
public Transaction getDepositTx() {
return depositTx;
}
public void setMailboxMessage(DecryptedMsgWithPubKey decryptedMsgWithPubKey) {
log.trace("setMailboxMessage decryptedMsgWithPubKey=" + decryptedMsgWithPubKey);
this.decryptedMsgWithPubKey = decryptedMsgWithPubKey;
if (tradeProtocol != null && decryptedMsgWithPubKey != null && !mailboxMessageSet.contains(decryptedMsgWithPubKey)) {
mailboxMessageSet.add(decryptedMsgWithPubKey);
tradeProtocol.applyMailboxMessage(decryptedMsgWithPubKey, this);
}
}
public DecryptedMsgWithPubKey getMailboxMessage() {
return decryptedMsgWithPubKey;
}
public void setStorage(Storage<? extends TradableList> storage) {
this.storage = storage;
}
///////////////////////////////////////////////////////////////////////////////////////////
// States
///////////////////////////////////////////////////////////////////////////////////////////
public void setState(State state) {
log.info("Trade.setState: " + state);
boolean changed = this.state != state;
this.state = state;
stateProperty.set(state);
if (changed)
persist();
}
public void setDisputeState(DisputeState disputeState) {
Log.traceCall("disputeState=" + disputeState + "\n\ttrade=" + this);
boolean changed = this.disputeState != disputeState;
this.disputeState = disputeState;
disputeStateProperty.set(disputeState);
if (changed)
persist();
}
public DisputeState getDisputeState() {
return disputeState;
}
public void setTradePeriodState(TradePeriodState tradePeriodState) {
boolean changed = this.tradePeriodState != tradePeriodState;
this.tradePeriodState = tradePeriodState;
tradePeriodStateProperty.set(tradePeriodState);
if (changed)
persist();
}
public TradePeriodState getTradePeriodState() {
return tradePeriodState;
}
public boolean isTakerFeePaid() {
return state.getPhase() != null && state.getPhase().ordinal() >= Phase.TAKER_FEE_PAID.ordinal();
}
public boolean isDepositPaid() {
return state.getPhase() != null && state.getPhase().ordinal() >= Phase.DEPOSIT_PAID.ordinal();
}
public State getState() {
return state;
}
///////////////////////////////////////////////////////////////////////////////////////////
// Model implementation
///////////////////////////////////////////////////////////////////////////////////////////
// Get called from taskRunner after each completed task
@Override
public void persist() {
if (storage != null)
storage.queueUpForSave();
}
@Override
public void onComplete() {
persist();
}
///////////////////////////////////////////////////////////////////////////////////////////
// Getter only
///////////////////////////////////////////////////////////////////////////////////////////
public String getId() {
return offer.getId();
}
public String getShortId() {
return offer.getShortId();
}
public Offer getOffer() {
return offer;
}
abstract public Coin getPayoutAmount();
public ProcessModel getProcessModel() {
return processModel;
}
@Nullable
public Fiat getTradeVolume() {
if (tradeAmount != null && getTradePrice() != null)
return new ExchangeRate(getTradePrice()).coinToFiat(tradeAmount);
else
return null;
}
@Nullable
public Date getMaxTradePeriodDate() {
if (maxTradePeriodDate == null && takeOfferDate != null)
maxTradePeriodDate = new Date(takeOfferDate.getTime() + getOffer().getPaymentMethod().getMaxTradePeriod());
return maxTradePeriodDate;
}
@Nullable
public Date getHalfTradePeriodDate() {
if (halfTradePeriodDate == null && takeOfferDate != null)
halfTradePeriodDate = new Date(takeOfferDate.getTime() + getOffer().getPaymentMethod().getMaxTradePeriod() / 2);
return halfTradePeriodDate;
}
public ReadOnlyObjectProperty<? extends State> stateProperty() {
return stateProperty;
}
public ReadOnlyObjectProperty<Coin> tradeAmountProperty() {
return tradeAmountProperty;
}
public ReadOnlyObjectProperty<Fiat> tradeVolumeProperty() {
return tradeVolumeProperty;
}
public ReadOnlyObjectProperty<DisputeState> disputeStateProperty() {
return disputeStateProperty;
}
public ReadOnlyObjectProperty<TradePeriodState> getTradePeriodStateProperty() {
return tradePeriodStateProperty;
}
///////////////////////////////////////////////////////////////////////////////////////////
// Getter/Setter for Mutable objects
///////////////////////////////////////////////////////////////////////////////////////////
public Date getDate() {
return takeOfferDate;
}
public void setTradingPeerNodeAddress(NodeAddress tradingPeerNodeAddress) {
if (tradingPeerNodeAddress == null)
log.error("tradingPeerAddress=null");
else
this.tradingPeerNodeAddress = tradingPeerNodeAddress;
}
@Nullable
public NodeAddress getTradingPeerNodeAddress() {
return tradingPeerNodeAddress;
}
public void setTradeAmount(Coin tradeAmount) {
this.tradeAmount = tradeAmount;
tradeAmountProperty.set(tradeAmount);
tradeVolumeProperty.set(getTradeVolume());
}
public void setTradePrice(long tradePrice) {
this.tradePrice = tradePrice;
}
public Fiat getTradePrice() {
return Fiat.valueOf(offer.getCurrencyCode(), tradePrice);
}
@Nullable
public Coin getTradeAmount() {
return tradeAmount;
}
public void setLockTimeAsBlockHeight(long lockTimeAsBlockHeight) {
this.lockTimeAsBlockHeight = lockTimeAsBlockHeight;
}
public long getLockTimeAsBlockHeight() {
return lockTimeAsBlockHeight;
}
public void setTakerContractSignature(String takerSignature) {
this.takerContractSignature = takerSignature;
}
@Nullable
public String getTakerContractSignature() {
return takerContractSignature;
}
public void setOffererContractSignature(String offererContractSignature) {
this.offererContractSignature = offererContractSignature;
}
@Nullable
public String getOffererContractSignature() {
return offererContractSignature;
}
public void setContractAsJson(String contractAsJson) {
this.contractAsJson = contractAsJson;
}
@Nullable
public String getContractAsJson() {
return contractAsJson;
}
public void setContract(Contract contract) {
this.contract = contract;
}
@Nullable
public Contract getContract() {
return contract;
}
public void setPayoutTx(Transaction payoutTx) {
this.payoutTx = payoutTx;
}
// Not used now, but will be used in some reporting UI
@Nullable
public Transaction getPayoutTx() {
return payoutTx;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
errorMessageProperty.set(errorMessage);
}
public ReadOnlyStringProperty errorMessageProperty() {
return errorMessageProperty;
}
public NodeAddress getArbitratorNodeAddress() {
return arbitratorNodeAddress;
}
public void applyArbitratorNodeAddress(NodeAddress arbitratorNodeAddress) {
this.arbitratorNodeAddress = arbitratorNodeAddress;
Arbitrator arbitrator = processModel.getUser().getAcceptedArbitratorByAddress(arbitratorNodeAddress);
checkNotNull(arbitrator, "arbitrator must not be null");
arbitratorBtcPubKey = arbitrator.getBtcPubKey();
}
public byte[] getArbitratorPubKey() {
// Prior to v0.4.8.4 we did not store the arbitratorBtcPubKey in the trade object so we need to support the
// previously used version as well and request the arbitrator from the user object (but that caused sometimes a bug when
// the client did not get delivered an arbitrator from the P2P network).
if (arbitratorBtcPubKey == null) {
Arbitrator arbitrator = processModel.getUser().getAcceptedArbitratorByAddress(arbitratorNodeAddress);
checkNotNull(arbitrator, "arbitrator must not be null");
arbitratorBtcPubKey = arbitrator.getBtcPubKey();
}
checkNotNull(arbitratorBtcPubKey, "ArbitratorPubKey must not be null");
return arbitratorBtcPubKey;
}
public String getTakerPaymentAccountId() {
return takerPaymentAccountId;
}
public void setTakerPaymentAccountId(String takerPaymentAccountId) {
this.takerPaymentAccountId = takerPaymentAccountId;
}
public void setContractHash(byte[] contractHash) {
this.contractHash = contractHash;
}
public byte[] getContractHash() {
return contractHash;
}
public void setTakeOfferFeeTxId(String takeOfferFeeTxId) {
this.takeOfferFeeTxId = takeOfferFeeTxId;
}
@org.jetbrains.annotations.Nullable
public String getTakeOfferFeeTxId() {
return takeOfferFeeTxId;
}
///////////////////////////////////////////////////////////////////////////////////////////
// Private
///////////////////////////////////////////////////////////////////////////////////////////
private void setupConfidenceListener() {
log.debug("setupConfidenceListener");
if (depositTx != null) {
TransactionConfidence transactionConfidence = depositTx.getConfidence();
log.debug("transactionConfidence " + transactionConfidence.getDepthInBlocks());
if (transactionConfidence.getDepthInBlocks() > 0) {
setConfirmedState();
} else {
ListenableFuture<TransactionConfidence> future = transactionConfidence.getDepthFuture(1);
Futures.addCallback(future, new FutureCallback<TransactionConfidence>() {
@Override
public void onSuccess(TransactionConfidence result) {
log.debug("transactionConfidence " + transactionConfidence.getDepthInBlocks());
log.debug("state " + state);
setConfirmedState();
}
@Override
public void onFailure(@NotNull Throwable t) {
t.printStackTrace();
log.error(t.getMessage());
Throwables.propagate(t);
}
});
}
} else {
log.error("depositTx == null. That must not happen.");
}
}
abstract protected void createProtocol();
private void setConfirmedState() {
// we oly apply the state if we are not already further in the process
if (state.ordinal() < State.DEPOSIT_CONFIRMED_IN_BLOCK_CHAIN.ordinal())
setState(State.DEPOSIT_CONFIRMED_IN_BLOCK_CHAIN);
}
abstract protected void initStates();
@Override
public String toString() {
return "Trade{" +
"\n\ttradeAmount=" + tradeAmount +
"\n\ttradingPeerNodeAddress=" + tradingPeerNodeAddress +
"\n\ttradeVolume=" + tradeVolumeProperty.get() +
"\n\toffer=" + offer +
"\n\tprocessModel=" + processModel +
"\n\tdecryptedMsgWithPubKey=" + decryptedMsgWithPubKey +
"\n\ttakeOfferDate=" + takeOfferDate +
"\n\tstate=" + state +
"\n\tdisputeState=" + disputeState +
"\n\ttradePeriodState=" + tradePeriodState +
"\n\tdepositTx=" + depositTx +
"\n\ttakeOfferFeeTxId=" + takeOfferFeeTxId +
"\n\tcontract=" + contract +
"\n\ttakerContractSignature.hashCode()='" + (takerContractSignature != null ? takerContractSignature.hashCode() : "") + '\'' +
"\n\toffererContractSignature.hashCode()='" + (offererContractSignature != null ? offererContractSignature.hashCode() : "") + '\'' +
"\n\tpayoutTx=" + payoutTx +
"\n\tlockTimeAsBlockHeight=" + lockTimeAsBlockHeight +
"\n\tarbitratorNodeAddress=" + arbitratorNodeAddress +
"\n\ttakerPaymentAccountId='" + takerPaymentAccountId + '\'' +
"\n\terrorMessage='" + errorMessage + '\'' +
'}';
}
} | haiqu/bitsquare | core/src/main/java/io/bitsquare/trade/Trade.java | Java | agpl-3.0 | 23,684 |
// ----------> GENERATED FILE - DON'T TOUCH! <----------
// generator: ilarkesto.mda.legacy.generator.GwtServiceCallGenerator
package scrum.client.search;
import java.util.*;
@com.google.gwt.user.client.rpc.RemoteServiceRelativePath("scrum")
public class SearchServiceCall
extends ilarkesto.gwt.client.AServiceCall<scrum.client.DataTransferObject> {
private static scrum.client.ScrumServiceAsync service;
java.lang.String text;
public SearchServiceCall(java.lang.String text) {
this.text = text;
}
@Override
protected void onExecute(int conversationNumber, com.google.gwt.user.client.rpc.AsyncCallback<scrum.client.DataTransferObject> callback) {
if (service==null) {
service = (scrum.client.ScrumServiceAsync) com.google.gwt.core.client.GWT.create(scrum.client.ScrumService.class);
initializeService(service, "scrum");
}
service.search(conversationNumber, text, callback);
}
@Override
public String toString() {
return "search";
}
} | Kunagi/kunagi | src/generated/java/scrum/client/search/SearchServiceCall.java | Java | agpl-3.0 | 1,068 |
/*
* Copyright © 2017 Logistimo.
*
* This file is part of Logistimo.
*
* Logistimo software is a mobile & web platform for supply chain management and remote temperature monitoring in
* low-resource settings, made available under the terms of the GNU Affero General Public License (AGPL).
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
* Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
* You can be released from the requirements of the license by purchasing a commercial license. To know more about
* the commercial license, please contact us at [email protected]
*/
package com.logistimo.db;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import play.db.jpa.JPA;
@Entity
@Table(name = "daily_stats_device_errors")
public class DailyStatsDeviceError {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
public Long id;
@Column(name = "error_code", nullable = false)
public String errorCode;
@Column(name = "count", nullable = false)
public int count;
@Column(name = "time", nullable = false)
public int time;
@ManyToOne
public DailyStatsDO daily_stats;
public static List<DailyStatsDeviceError> getDailyStatsDeviceErrors(DailyStatsDO dailyStatsDO) {
return JPA.em().createQuery("from DailyStatsDeviceError where daily_stats = ?1",
DailyStatsDeviceError.class)
.setParameter(1, dailyStatsDO)
.getResultList();
}
public void save() {
JPA.em().persist(this);
}
}
| logistimo/asset-monitoring-service | app/com/logistimo/db/DailyStatsDeviceError.java | Java | agpl-3.0 | 2,267 |
/*
* Copyright (C) 2000 - 2021 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "https://www.silverpeas.org/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.webapi.pdc;
import org.silverpeas.core.admin.user.model.UserDetail;
import org.silverpeas.core.annotation.WebService;
import org.silverpeas.core.pdc.pdc.model.AxisValueCriterion;
import org.silverpeas.core.pdc.pdc.model.UsedAxis;
import org.silverpeas.core.personalization.UserPreferences;
import org.silverpeas.core.web.rs.RESTWebService;
import org.silverpeas.core.web.rs.annotation.Authenticated;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import java.util.List;
import static org.silverpeas.core.util.logging.SilverLogger.getLogger;
import static org.silverpeas.core.webapi.pdc.PdcEntity.*;
/**
* A REST Web resource that represents the classification plan (named PdC) filtered by some
* criteria.
*
* For a description of the PdC, see the documentation on {@link PdcResource}.
*/
@WebService
@Path(FilteredPdcResource.PATH)
@Authenticated
public class FilteredPdcResource extends RESTWebService {
static final String PATH = "pdc/filter";
@Inject
private PdcServiceProvider pdcServiceProvider;
@Override
protected String getResourceBasePath() {
return PATH;
}
/**
* Gets a PdC containing only the axis and the axis's value that were used in the classification
* of the contents in Silverpeas. The Pdc can be restricted by the workspace and by the component
* to which the classified contents belong. As the filtered PdC is for a search, only the
* component instances configured as searchable are taken into account.
*
* The PdC that is sent back contains only the axis and, with each of them, the values to which
* the contents in Silverpeas are classified. The classified contents to take into account can be
* restricted by the workspace or by the application to which they belong, and by a set of axis'
* values with which they have to be classified. The version of the returned PdC indicates, for
* each axis's value, the count of contents that are classified with this value. According to the
* query parameters, it can contain also the secondary axis of the PdC. The PdC is sent back in
* JSON. If the user isn't authenticated, a 401 HTTP code is returned. If a problem occurs when
* processing the request, a 503 HTTP code is returned.
*
* @param workspaceId optionally the unique identifier of the workspace in which the classified
* contents are published.
* @param componentIds optionally the unique identifier of the component to which the classified
* contents belong.
* @param withSecondaryAxis optionally a boolean flag indicating whether the secondary PdC axis
* should be taken into account.
* @param axisValues optionally a set of axis' values on which the contents to take into account
* have to be classified. A value is defined by the identifier of the axis it belongs to and by
* its path from the root value in this axis, the two fields separated by a ':' character.
*
* @return a web entity representing the PdC filtered by the contents that are classified on it.
* The entity is serialized in JSON.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("used")
public PdcEntity getPdcFilteredByClassifiedContents(@QueryParam("workspaceId") String workspaceId,
@QueryParam("componentId") List<String> componentIds,
@QueryParam("withSecondaryAxis") boolean withSecondaryAxis,
@QueryParam("values") String axisValues) {
PdcFilterCriteria criteria = new PdcFilterCriteria().
onWorkspace(workspaceId).
onComponentInstances(componentIds).
onSecondaryAxisInclusion(withSecondaryAxis).
onUser(UserDetail.from(getUser()));
setAxisValues(criteria, axisValues);
try {
List<UsedAxis> axis = pdcServiceProvider().getAxisUsedInClassificationsByCriteria(criteria);
UserPreferences userPreferences = getUserPreferences();
return aPdcEntityWithUsedAxis(
withAxis(axis),
inLanguage(userPreferences.getLanguage()),
atURI(getUri().getRequestUri()),
withThesaurusAccordingTo(userPreferences));
} catch (Exception ex) {
getLogger(this).error(ex.getMessage(), ex);
throw new WebApplicationException(ex, Status.SERVICE_UNAVAILABLE);
}
}
@Override
public String getComponentId() {
return null;
}
private PdcServiceProvider pdcServiceProvider() {
return pdcServiceProvider;
}
private void setAxisValues(PdcFilterCriteria criteria, String axisValues) {
List<AxisValueCriterion> axisValuesCriteria = AxisValueCriterion.fromFlattenedAxisValues(
axisValues);
criteria.onAxisValues(axisValuesCriteria);
}
private UserThesaurusHolder withThesaurusAccordingTo(UserPreferences userPreferences) {
UserThesaurusHolder thesaurus = NoThesaurus;
if (userPreferences.isThesaurusEnabled()) {
thesaurus = pdcServiceProvider().getThesaurusOfUser(UserDetail.from(getUser()));
}
return thesaurus;
}
}
| SilverDav/Silverpeas-Core | core-web/src/main/java/org/silverpeas/core/webapi/pdc/FilteredPdcResource.java | Java | agpl-3.0 | 6,289 |
// vim: sw=4 et tw=72 com=srO\:/**,mb\:*,ex\:*/,srO\:/*,mb\:*,ex\:*/,b\:TRANS,\://,b\:#,\:%,\:XCOMM,n\:>,fb\:-
/*
@(#) $RCSfile: BaseRootPkg.java,v $ $Name: $($Revision: 1.1.2.2 $) $Date: 2011-02-07 07:27:20 $ <p>
Copyright © 2008-2009 Monavacon Limited <a href="http://www.monavacon.com/"><http://www.monavacon.com/></a>. <br>
Copyright © 2001-2008 OpenSS7 Corporation <a href="http://www.openss7.com/"><http://www.openss7.com/></a>. <br>
Copyright © 1997-2001 Brian F. G. Bidulock <a href="mailto:[email protected]"><[email protected]></a>. <p>
All Rights Reserved. <p>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, version 3 of the license. <p>
This program is distributed in the hope that it will be useful, but <b>WITHOUT
ANY WARRANTY</b>; without even the implied warranty of <b>MERCHANTABILITY</b>
or <b>FITNESS FOR A PARTICULAR PURPOSE</b>. See the GNU Affero General Public
License for more details. <p>
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see
<a href="http://www.gnu.org/licenses/"><http://www.gnu.org/licenses/></a>,
or write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
02139, USA. <p>
<em>U.S. GOVERNMENT RESTRICTED RIGHTS</em>. If you are licensing this
Software on behalf of the U.S. Government ("Government"), the following
provisions apply to you. If the Software is supplied by the Department of
Defense ("DoD"), it is classified as "Commercial Computer Software" under
paragraph 252.227-7014 of the DoD Supplement to the Federal Acquisition
Regulations ("DFARS") (or any successor regulations) and the Government is
acquiring only the license rights granted herein (the license rights
customarily provided to non-Government users). If the Software is supplied to
any unit or agency of the Government other than DoD, it is classified as
"Restricted Computer Software" and the Government's rights in the Software are
defined in paragraph 52.227-19 of the Federal Acquisition Regulations ("FAR")
(or any successor regulations) or, in the cases of NASA, in paragraph
18.52.227-86 of the NASA Supplement to the FAR (or any successor regulations). <p>
Commercial licensing and support of this software is available from OpenSS7
Corporation at a fee. See
<a href="http://www.openss7.com/">http://www.openss7.com/</a> <p>
Last Modified $Date: 2011-02-07 07:27:20 $ by $Author: brian $
*/
// vim: sw=4 et tw=72 com=srO\:/**,mb\:*,ex\:*/,srO\:/*,mb\:*,ex\:*/,b\:TRANS,\://,b\:#,\:%,\:XCOMM,n\:>,fb\:-
/*
Overview Package Class Tree Index Help
JAIN^TM MEGACO API (RELEASE) - Version 1.0 - 22 December 2003
PREV CLASSNEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR |
METHOD
_________________________________________________________________
javax.megaco.pkg
Class BaseRootPkg
java.lang.Object
|
+--javax.megaco.pkg.MegacoPkg
|
+--javax.megaco.pkg.BaseRootPkg.BaseRootPkg
All Implemented Interfaces:
None
Direct Known Subclasses:
None
_________________________________________________________________
public class BaseRootPkg
extends MegacoPkg
The MEGACO Base Root inherits all methods of the Package, but
overrides the getPkgId and getPkgName to define packageid
corresponding to the Base Root Package. This class also overrides the
getExtendedPkgIds to define that there are no packages that this
package extends.
_________________________________________________________________
Constructor Summary
BaseRootPkg()
Constructs a MEGACO Base Root Package.
Method Summary
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait
Methods inherited from class javax.megaco.pkg. MegacoPkg
getPkgId, getPkgName, getExtendedPkgIds
Constructor Detail
BaseRootPkg
public BaseRootPkg()
Constructs a derived class of Base Root Package that extends
the Package
Method Detail
getPkgId
public final int getPkgId()
This method return the package Id of the MEGACO package for
which the object is created. For Base ROOT Package constant
value BASE_ROOT_PACKAGE shall be returned.
Returns:
Constant value BASE_ROOT_PACKAGE indicating Base ROOT
Package.
_________________________________________________________________
getExtendedPkgIds
public final int[] getExtendedPkgIds()
This method gets the package ids of all the package which the
package had directly or indirectly extended. Package ids are
defined in PkgConsts.
Returns:
Since this packge extends no other package, this shall
return a NULL value.
_________________________________________________________________
_________________________________________________________________
Overview Package Class Tree Index Help
JAIN^TM MEGACO API (RELEASE) - Version 1.0 - 22 December 2003
PREV CLASSNEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR |
METHOD
_________________________________________________________________
Copyright (C) 2001 Hughes Software Systems
HUGHES SOFTWARE SYSTEMS and JAIN JSPA SIGNATORIES PROPRIETARY
This document contains proprietary information that shall be
distributed, routed or made available only within Hughes Software
Systems and JAIN JSPA Signatory Companies, except with written
permission of Hughes Software Systems
_________________________________________________
22 December 2003
If you have any comments or queries, please mail them to
[email protected]
*/
| 0x7678/openss7 | src/java/javax/megaco/pkg/BaseRootPkg/BaseRootPkg.java | Java | agpl-3.0 | 6,109 |
/* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o 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.db4o.foundation;
public class CompositeIterable4 implements Iterable4 {
private final Iterable4 _iterables;
public CompositeIterable4(Iterable4 iterables) {
_iterables = iterables;
}
public Iterator4 iterator() {
return new CompositeIterator4(_iterables.iterator()) {
protected Iterator4 nextIterator(Object current) {
return ((Iterable4)current).iterator();
}
};
}
}
| xionghuiCoder/db4o | src/main/java/com/db4o/foundation/CompositeIterable4.java | Java | agpl-3.0 | 1,086 |
package com.databazoo.devmodeler.conn;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.databazoo.devmodeler.gui.DesignGUI;
/**
* Forward + revers engineering setup for MariaDB
*
* @author bobus
*/
public class ConnectionMaria extends ConnectionMy {
private static final List<String> STORAGE_ENGINES = new ArrayList<>(Arrays.asList("InnoDB", "XtraDB", "MyISAM", "Aria", "TokuDB", "MEMORY", "ARCHIVE", "Cassandra", "CONNECT", "SphinxSE", "Spider", "ScaleDB"));
public ConnectionMaria (String name, String host, String user, String pass) {
super(name, host, user, pass);
}
public ConnectionMaria (String name, String host, String user, String pass, int type) {
super(name, host, user, pass, type);
}
@Override
public String getTypeName(){
return "MariaDB";
}
@Override
public String[] getStorageEngines(){
return ConnectionMaria.STORAGE_ENGINES.toArray(new String[0]);
}
@Override
public String getDefaultStorageEngine(){
return "XtraDB";
}
@Override
public void loadEnvironment() throws DBCommException {
// load available storage engines
int log = DesignGUI.getInfoPanel().write("Loading server environment...");
Query q = new Query("SHOW ENGINES", getDefaultDB()).run();
while(q.next()){
if(!ConnectionMaria.STORAGE_ENGINES.contains(q.getString("ENGINE"))) {
ConnectionMaria.STORAGE_ENGINES.add(q.getString("ENGINE"));
}
}
q.close();
q.log(log);
}
}
| databazoo/dev-modeler | devmodeler/src/main/java/com/databazoo/devmodeler/conn/ConnectionMaria.java | Java | agpl-3.0 | 1,454 |
package es.igosoftware.dmvc.testing;
import java.util.ArrayList;
import java.util.List;
import es.igosoftware.dmvc.model.GDModel;
import es.igosoftware.dmvc.model.GDProperty;
import es.igosoftware.dmvc.model.IDProperty;
public class GDCustomer
extends
GDModel
implements
IDCustomer {
private final String _name;
public GDCustomer(final String name) {
_name = name;
}
@Override
public String getName() {
return _name;
}
@Override
public String toString() {
return "GDCustomer [name=" + _name + "]";
}
@Override
protected List<IDProperty> defaultProperties() {
final List<IDProperty> result = new ArrayList<IDProperty>();
result.add(new GDProperty(this, "name", false));
return result;
}
}
| AsherBond/MondocosmOS | glob3/dmvc/es/igosoftware/dmvc/testing/GDCustomer.java | Java | agpl-3.0 | 818 |
/**
* Copyright (C) 2001-2017 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.new_plotter.configuration;
import com.rapidminer.gui.new_plotter.listener.events.LineFormatChangeEvent;
import com.rapidminer.gui.new_plotter.utility.DataStructureUtils;
import com.rapidminer.tools.I18N;
import java.awt.BasicStroke;
import java.awt.Color;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* @author Marius Helf
*/
public class LineFormat implements Cloneable {
private static class StrokeFactory {
static public BasicStroke getSolidStroke() {
return new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
}
static public BasicStroke getDottedStroke() {
return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 1f, 1f }, 0.0f);
}
static public BasicStroke getShortDashedStroke() {
return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 4f, 2f }, 0.0f);
}
static public BasicStroke getLongDashedStroke() {
return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 7f, 3f }, 0.0f);
}
static public BasicStroke getDashDotStroke() {
return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 6f, 2f, 1f, 2f },
0.0f);
}
static public BasicStroke getStripedStroke() {
return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 0.2f, 0.2f }, 0.0f);
}
}
public enum LineStyle {
NONE(null, I18N.getGUILabel("plotter.linestyle.NONE.label")), SOLID(StrokeFactory.getSolidStroke(), I18N
.getGUILabel("plotter.linestyle.SOLID.label")), DOTS(StrokeFactory.getDottedStroke(), I18N
.getGUILabel("plotter.linestyle.DOTS.label")), SHORT_DASHES(StrokeFactory.getShortDashedStroke(), I18N
.getGUILabel("plotter.linestyle.SHORT_DASHES.label")), LONG_DASHES(StrokeFactory.getLongDashedStroke(), I18N
.getGUILabel("plotter.linestyle.LONG_DASHES.label")), DASH_DOT(StrokeFactory.getDashDotStroke(), I18N
.getGUILabel("plotter.linestyle.DASH_DOT.label")), STRIPES(StrokeFactory.getStripedStroke(), I18N
.getGUILabel("plotter.linestyle.STRIPES.label"));
private final BasicStroke stroke;
private final String name;
public BasicStroke getStroke() {
return stroke;
}
public String getName() {
return name;
}
private LineStyle(BasicStroke stroke, String name) {
this.stroke = stroke;
this.name = name;
}
}
private List<WeakReference<LineFormatListener>> listeners = new LinkedList<WeakReference<LineFormatListener>>();
private LineStyle style = LineStyle.NONE; // dashed, solid...
private Color color = Color.GRAY;
private float width = 1.0f;
public LineStyle getStyle() {
return style;
}
public void setStyle(LineStyle style) {
if (style != this.style) {
this.style = style;
fireStyleChanged();
}
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
if (color == null ? this.color != null : !color.equals(this.color)) {
this.color = color;
fireColorChanged();
}
}
public float getWidth() {
return width;
}
public void setWidth(float width) {
if (width != this.width) {
this.width = width;
fireWidthChanged();
}
}
private void fireWidthChanged() {
fireLineFormatChanged(new LineFormatChangeEvent(this, width));
}
private void fireColorChanged() {
fireLineFormatChanged(new LineFormatChangeEvent(this, color));
}
private void fireStyleChanged() {
fireLineFormatChanged(new LineFormatChangeEvent(this, style));
}
private void fireLineFormatChanged(LineFormatChangeEvent e) {
Iterator<WeakReference<LineFormatListener>> it = listeners.iterator();
while (it.hasNext()) {
LineFormatListener l = it.next().get();
if (l != null) {
l.lineFormatChanged(e);
} else {
it.remove();
}
}
}
@Override
public LineFormat clone() {
LineFormat clone = new LineFormat();
clone.color = new Color(color.getRGB(), true);
clone.style = style;
clone.width = width;
return clone;
}
public BasicStroke getStroke() {
BasicStroke stroke = style.getStroke();
if (stroke != null) {
float[] scaledDashArray = getScaledDashArray();
BasicStroke scaledStroke = new BasicStroke(this.getWidth(), stroke.getEndCap(), stroke.getLineJoin(),
stroke.getMiterLimit(), scaledDashArray, stroke.getDashPhase());
return scaledStroke;
} else {
return null;
}
}
float[] getScaledDashArray() {
BasicStroke stroke = getStyle().getStroke();
if (stroke == null) {
return null;
}
float[] dashArray = stroke.getDashArray();
float[] scaledDashArray;
if (dashArray != null) {
float scalingFactor = getWidth();
if (scalingFactor <= 0) {
scalingFactor = 1;
}
if (scalingFactor != 1) {
scaledDashArray = DataStructureUtils.cloneAndMultiplyArray(dashArray, scalingFactor);
} else {
scaledDashArray = dashArray;
}
} else {
scaledDashArray = dashArray;
}
return scaledDashArray;
}
public void addLineFormatListener(LineFormatListener l) {
listeners.add(new WeakReference<LineFormatListener>(l));
}
public void removeLineFormatListener(LineFormatListener l) {
Iterator<WeakReference<LineFormatListener>> it = listeners.iterator();
while (it.hasNext()) {
LineFormatListener listener = it.next().get();
if (l != null) {
if (listener != null && listener.equals(l)) {
it.remove();
}
} else {
it.remove();
}
}
}
}
| boob-sbcm/3838438 | src/main/java/com/rapidminer/gui/new_plotter/configuration/LineFormat.java | Java | agpl-3.0 | 6,556 |
/**
* Copyright (C) 2001-2019 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.ports.metadata;
import com.rapidminer.example.Attributes;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.operator.ModelApplier;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.OperatorCreationException;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.ProcessSetupError.Severity;
import com.rapidminer.operator.ports.InputPort;
import com.rapidminer.operator.ports.quickfix.ChangeAttributeRoleQuickFix;
import com.rapidminer.operator.ports.quickfix.OperatorInsertionQuickFix;
import com.rapidminer.operator.ports.quickfix.QuickFix;
import com.rapidminer.operator.preprocessing.IdTagging;
import com.rapidminer.parameter.UndefinedParameterError;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.OperatorService;
import java.util.LinkedList;
import java.util.List;
/**
* @author Simon Fischer
*/
public class ExampleSetPrecondition extends AbstractPrecondition {
private final String[] requiredSpecials;
private final int allowedValueTypes;
private final String[] ignoreForTypeCheck;
private final int allowedSpecialsValueType;
private final String[] requiredAttributes;
private boolean optional = false;
public ExampleSetPrecondition(InputPort inputPort) {
this(inputPort, Ontology.ATTRIBUTE_VALUE, (String[]) null);
}
public ExampleSetPrecondition(InputPort inputPort, int allowedValueTypesForRegularAttributes, String... requiredSpecials) {
this(inputPort, new String[0], allowedValueTypesForRegularAttributes, new String[0], Ontology.ATTRIBUTE_VALUE,
requiredSpecials);
}
public ExampleSetPrecondition(InputPort inputPort, String[] requiredAttributeNames, int allowedValueTypesForRegular,
String... requiredSpecials) {
this(inputPort, requiredAttributeNames, allowedValueTypesForRegular, new String[0], Ontology.ATTRIBUTE_VALUE,
requiredSpecials);
}
public ExampleSetPrecondition(InputPort inputPort, String requiredSpecials, int allowedValueTypForSpecial) {
this(inputPort, new String[0], Ontology.ATTRIBUTE_VALUE, new String[0], allowedValueTypForSpecial, requiredSpecials);
}
public ExampleSetPrecondition(InputPort inputPort, String[] requiredAttributeNames, int allowedValueTypesForRegular,
String[] ignoreForTypeCheck, int allowedValueTypesForSpecial, String... requiredSpecials) {
super(inputPort);
this.allowedValueTypes = allowedValueTypesForRegular;
this.requiredSpecials = requiredSpecials;
this.requiredAttributes = requiredAttributeNames;
this.allowedSpecialsValueType = allowedValueTypesForSpecial;
this.ignoreForTypeCheck = ignoreForTypeCheck;
}
public void setOptional(boolean optional) {
this.optional = optional;
}
@Override
public void assumeSatisfied() {
getInputPort().receiveMD(new ExampleSetMetaData());
}
@Override
public void check(MetaData metaData) {
final InputPort inputPort = getInputPort();
if (metaData == null) {
if (!optional) {
inputPort.addError(new InputMissingMetaDataError(inputPort, ExampleSet.class, null));
} else {
return;
}
} else {
if (metaData instanceof ExampleSetMetaData) {
ExampleSetMetaData emd = (ExampleSetMetaData) metaData;
// checking attribute names
for (String attributeName : requiredAttributes) {
MetaDataInfo attInfo = emd.containsAttributeName(attributeName);
if (attInfo == MetaDataInfo.NO) {
createError(Severity.WARNING, "missing_attribute", attributeName);
}
}
// checking allowed types
if ((allowedValueTypes != Ontology.ATTRIBUTE_VALUE) && (allowedValueTypes != -1)) {
for (AttributeMetaData amd : emd.getAllAttributes()) {
if (amd.isSpecial()) {
continue;
}
// check if name is in ignore list
for (String name : ignoreForTypeCheck) {
if (name.equals(amd.getName())) {
continue;
}
}
// otherwise do check
if (!Ontology.ATTRIBUTE_VALUE_TYPE.isA(amd.getValueType(), allowedValueTypes)) {
createError(Severity.ERROR, "regular_type_mismatch",
new Object[] { Ontology.ATTRIBUTE_VALUE_TYPE.mapIndex(allowedValueTypes) });
break;
}
}
}
// checking required special attribute roles
if (requiredSpecials != null) {
for (String name : requiredSpecials) {
MetaDataInfo has = emd.hasSpecial(name);
switch (has) {
case NO:
List<QuickFix> fixes = new LinkedList<QuickFix>();
// ID-Tagging
if (name.equals(Attributes.ID_NAME)) {
OperatorDescription[] ods = OperatorService.getOperatorDescriptions(IdTagging.class);
fixes.add(new OperatorInsertionQuickFix("insert_id_tagging",
new Object[] { ods.length > 0 ? ods[0].getName() : "" },
10, inputPort) {
@Override
public Operator createOperator() throws OperatorCreationException {
return OperatorService.createOperator(IdTagging.class);
}
});
}
// Prediction
if (name.equals(Attributes.PREDICTION_NAME)) {
OperatorDescription[] ods = OperatorService.getOperatorDescriptions(ModelApplier.class);
if (ods.length > 0) {
fixes.add(new OperatorInsertionQuickFix("insert_model_applier",
new Object[] { ods[0].getName() }, 10, inputPort, 1, 0) {
@Override
public Operator createOperator() throws OperatorCreationException {
return OperatorService.createOperator(ModelApplier.class);
}
});
}
}
// General Attribute Role Change
fixes.add(new ChangeAttributeRoleQuickFix(inputPort, name, "change_attribute_role", name));
if (fixes.size() > 0) {
inputPort.addError(new SimpleMetaDataError(Severity.ERROR, inputPort, fixes,
"exampleset.missing_role", name));
} else {
createError(Severity.ERROR, "special_missing", new Object[] { name });
}
break;
case UNKNOWN:
createError(Severity.WARNING, "special_unknown", new Object[] { name });
break;
case YES:
// checking type
AttributeMetaData amd = emd.getSpecial(name);
if (amd == null) {
// TODO: This can happen for confidence. Then, hasSpecial
// returns YES, but getSpecial(confidence) returns null
break;
}
if (!Ontology.ATTRIBUTE_VALUE_TYPE.isA(amd.getValueType(), allowedSpecialsValueType)) {
createError(Severity.ERROR, "special_attribute_has_wrong_type", amd.getName(), name,
Ontology.ATTRIBUTE_VALUE_TYPE.mapIndex(allowedSpecialsValueType));
}
break;
}
}
}
try {
makeAdditionalChecks(emd);
} catch (UndefinedParameterError e) {
}
} else {
inputPort.addError(new MetaDataUnderspecifiedError(inputPort));
}
}
}
/**
* Can be implemented by subclasses.
*
* @throws UndefinedParameterError
*/
public void makeAdditionalChecks(ExampleSetMetaData emd) throws UndefinedParameterError {}
@Override
public String getDescription() {
return "<em>expects:</em> ExampleSet";
}
@Override
public boolean isCompatible(MetaData input, CompatibilityLevel level) {
return null != input && ExampleSet.class.isAssignableFrom(input.getObjectClass());
}
@Override
public MetaData getExpectedMetaData() {
return new ExampleSetMetaData();
}
}
| aborg0/rapidminer-studio | src/main/java/com/rapidminer/operator/ports/metadata/ExampleSetPrecondition.java | Java | agpl-3.0 | 8,472 |
/*
@(#) $RCSfile: Result.java,v $ $Name: $($Revision: 1.1.2.1 $) $Date: 2009-06-21 11:34:39 $ <p>
Copyright © 2008-2009 Monavacon Limited <a href="http://www.monavacon.com/"><http://www.monavacon.com/></a>. <br>
Copyright © 2001-2008 OpenSS7 Corporation <a href="http://www.openss7.com/"><http://www.openss7.com/></a>. <br>
Copyright © 1997-2001 Brian F. G. Bidulock <a href="mailto:[email protected]"><[email protected]></a>. <p>
All Rights Reserved. <p>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, version 3 of the license. <p>
This program is distributed in the hope that it will be useful, but <b>WITHOUT
ANY WARRANTY</b>; without even the implied warranty of <b>MERCHANTABILITY</b>
or <b>FITNESS FOR A PARTICULAR PURPOSE</b>. See the GNU Affero General Public
License for more details. <p>
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see
<a href="http://www.gnu.org/licenses/"><http://www.gnu.org/licenses/></a>,
or write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
02139, USA. <p>
<em>U.S. GOVERNMENT RESTRICTED RIGHTS</em>. If you are licensing this
Software on behalf of the U.S. Government ("Government"), the following
provisions apply to you. If the Software is supplied by the Department of
Defense ("DoD"), it is classified as "Commercial Computer Software" under
paragraph 252.227-7014 of the DoD Supplement to the Federal Acquisition
Regulations ("DFARS") (or any successor regulations) and the Government is
acquiring only the license rights granted herein (the license rights
customarily provided to non-Government users). If the Software is supplied to
any unit or agency of the Government other than DoD, it is classified as
"Restricted Computer Software" and the Government's rights in the Software are
defined in paragraph 52.227-19 of the Federal Acquisition Regulations ("FAR")
(or any successor regulations) or, in the cases of NASA, in paragraph
18.52.227-86 of the NASA Supplement to the FAR (or any successor regulations). <p>
Commercial licensing and support of this software is available from OpenSS7
Corporation at a fee. See
<a href="http://www.openss7.com/">http://www.openss7.com/</a> <p>
Last Modified $Date: 2009-06-21 11:34:39 $ by $Author: brian $
*/
package javax.jain.protocol.ss7.map;
import javax.jain.protocol.ss7.*;
import javax.jain.*;
/**
* This parameter is used in confirmation primitives (from provider to
* user) and in response primitives (from user to provider) to convey
* result information. <p>
*
* <h4>Parameter components:</h4><ul>
* <li>status - Status code with general result information, mandatory
* component
*
* <li>errorCode - Error code is specified in case of error, mandatory
* component <ul>
*
* @author Monavacon Limited
* @version 1.2.2
*/
public class Result extends SS7Parameter {
/** Status code: undefined. */
public static final int STATUS_UNDEFINED = 0;
/** Status code: OK. */
public static final int STATUS_OK = 1;
/** Status code: user error. */
public static final int STATUS_USER_ERROR = 2;
/** Status code: provider error. */
public static final int STATUS_PROVIDER_ERROR = 3;
/** Error code: undefined. */
public static final int ERROR_CODE_UNDEFINED = 4;
/** Error code: provider error, protocol related error, Duplicated
* invoke ID. */
public static final int DUPLICATED_INVOKE_ID = 5;
/** Error code: provider error, protocol related error, Provider
* does not support the service. */
public static final int NOT_SUPPORTED_SERVICE = 6;
/** Error code: provider error, protocol related error, Wrong
* parameter. */
public static final int MISTYPED_PARAMETER = 7;
/** Error code: provider error, protocol related error, Provider
* resource limitation. */
public static final int PE_RESOURCE_LIMITATION = 8;
/** Error code: provider error, protocol related error, Provider
* initiating release. */
public static final int PE_INITIATING_RELEASE = 9;
/** Error code: provider error, protocol related error, Unexpected
* response from peer. */
public static final int UNEXPECTED_RESPONSE_FROM_PEER = 10;
/** Error code: provider error, protocol related error, Service
* compretion failure. */
public static final int SERVICE_COMPLETION_FAILURE = 11;
/** Error code: provider error, protocol related error, No response
* from peer. */
public static final int NO_RESPONSE_FROM_PEER = 12;
/** Error code: provider error, protocol related error, Invalid
* response received. */
public static final int INVALID_RESPONSE_RECEIVED = 13;
/** Error code: user error, generic error, System failure. */
public static final int SYSTEM_FAILURE = 14;
/** Error code: user error, generic error, Data missing. */
public static final int DATA_MISSING = 15;
/** Error code: user error, generic error, Unexpected data value. */
public static final int UNEXPECTED_DATA_VALUE = 16;
/** Error code: user error, generic error, User resource limitation. */
public static final int UE_RESOURCE_LIMITATION = 17;
/** Error code: user error, generic error, User initiating release. */
public static final int UE_INITIATING_RELEASE = 18;
/** Error code: user error, generic error, Facility not supported. */
public static final int FACILITY_NOT_SUPPORTED = 19;
/** Error code: user error, generic error, Incompatible terminal. */
public static final int INCOMPATIBLE_TERMINAL = 20;
/** Error code: user error, identification or numbering problem,
* Unknown subscriber. */
public static final int UNKNOWN_SUBSCRIBER = 21;
/** Error code: user error, identification or numbering problem,
* Number changed. */
public static final int NUMBER_CHANGED = 22;
/** Error code: user error, identification or numbering problem,
* Unknown MSC. */
public static final int UNKNOWN_MSC = 23;
/** Error code: user error, identification or numbering problem,
* Unidentified subscriber. */
public static final int UNIDENTIFIED_SUBSCRIBER = 24;
/** Error code: user error, identification or numbering problem,
* Unallocated roaming number. */
public static final int UNALLOCATED_ROAMING_NUMBER = 25;
/** Error code: user error, identification or numbering problem,
* Unknown equipment. */
public static final int UNKNOWN_EQUIPMENT = 26;
/** Error code: user error, identification or numbering problem,
* Unknown location area. */
public static final int UNKNOWN_LOCATION_AREA = 27;
/** Error code: user error, subscription problem, Roaming not
* allowed. */
public static final int ROAMING_NOT_ALLOWED = 28;
/** Error code: user error, subscription problem, Illegal
* subscriber. */
public static final int ILLEGAL_SUBSCRIBER = 29;
/** Error code: user error, subscription problem, Bearer service not
* provisioned. */
public static final int BEARER_SERVICE_NOT_PROVISIONED = 30;
/** Error code: user error, subscription problem, Teleservice not
* provisioned. */
public static final int TELESERVICE_NOT_PROVISIONED = 31;
/** Error code: user error, subscription problem, Illegal equipment.
* */
public static final int ILLEGAL_EQUIPMENT = 32;
/** Error code: user error, supplementary services problem, Illegal
* supplementary service operation. */
public static final int ILLEGAL_SS_OPERATION = 33;
/** Error code: user error, supplementary services problem,
* Supplementary service error status. */
public static final int SS_ERROR_STATUS = 34;
/** Error code: user error, supplementary services problem,
* Supplementary service not available. */
public static final int SS_NOT_AVAILABLE = 35;
/** Error code: user error, supplementary services problem,
* Supplementary service subscription violation. */
public static final int SS_SUBSCRIPTION_VIOLATION = 36;
/** Error code: user error, supplementary services problem,
* Supplementary service imcompatibility. */
public static final int SS_INCOMPATIBILITY = 37;
/** Error code: user error, supplementary services problem, Negative
* password check. */
public static final int NEGATIVE_PASSWORD_CHECK = 38;
/** Error code: user error, supplementary services problem, Password
* registration failure. */
public static final int PASSWORD_REGISTRATION_FAILURE = 39;
/** Error code: user error, supplementary services problem, Number
* of password attemts. */
public static final int NUMBER_OF_PASSWORD_ATTEMPTS = 40;
/** Error code: user error, supplementary services problem, USSD
* busy. */
public static final int USSD_BUSY = 41;
/** Error code: user error, supplementary services problem, Unknown
* alphabet. */
public static final int UNKNOWN_ALPHABET = 42;
/** Error code: user error, supplementary services problem, Short
* term denial of service. */
public static final int SHORT_TERM_DENIAL = 43;
/** Error code: user error, supplementary services problem, Long
* term denial of service. */
public static final int LONG_TERM_DENIAL = 44;
/** Error code: user error, Short Message delivery failure, Memory
* capacity exceeded. */
public static final int MEMORY_CAPACITY_EXCEEDED = 45;
/** Error code: user error, Short Message delivery failure, MS
* protocol error. */
public static final int MS_PROTOCOL_ERROR = 46;
/** Error code: user error, Short Message delivery failure, MS not
* equipped to handle Short Message. */
public static final int MS_NOT_EQUIPPED = 47;
/** Error code: user error, Short Message delivery failure, Unknown
* Service Centre. */
public static final int UNKNOWN_SERVICE_CENTRE = 48;
/** Error code: user error, Short Message delivery failure, Service
* Centre congestion. */
public static final int SC_CONGESTION = 49;
/** Error code: user error, Short Message delivery failure, Invalid
* Short Message Entity address. */
public static final int INVALID_SME_ADDRESS = 50;
/** Error code: user error, Short Message delivery failure,
* Subscriber is not a Service Center subscriber. */
public static final int SUBSCRIBER_IS_NOT_AN_SC_SUBSCRIBER = 51;
/** Error code: user error, Short Message delivery failure, Message
* waiting list in HLR is full. */
public static final int MESSAGE_WAITING_LIST_FULL = 52;
/** Error code: user error, Short Message delivery failure,
* Subscriber busy for Mobile Terminated SMS. */
public static final int SUBSCRIBER_BUSY_FOR_MT_SMS = 53;
/** Error code: user error, Short Message delivery failure, Absent
* subscriber. */
public static final int ABSENT_SUBSCRIBER_SM = 54;
/** Error code: user error, location services problem, Unauthorized
* requesting network. */
public static final int UNAUTHORIZED_REQUESTING_NETWORK = 55;
/** Error code: user error, location services problem, Unauthorized
* LCS client. */
public static final int UNAUTHORIZED_LCS_CLIENT = 56;
/** Error code: user error, location services problem, Unauthorized
* privacy class. */
public static final int UNAUTHORZIED_PRIVACY_CLASS = 57;
/** Error code: user error, location services problem, Unauthorized
* call, unrelated external client. */
public static final int UNAUTHORIZED_CALL_UNRELATED_EXTERNAL_CLIENT = 58;
/** Error code: user error, location services problem, Unauthorized
* call, related external client. */
public static final int UNAUTHORIZED_CALL_RELATED_EXTERNAL_CLIENT = 59;
/** Error code: user error, location services problem, Privacy
* override not applicable. */
public static final int PRIVACY_OVERRIDE_NOT_APPLICABLE = 60;
/** Error code: user error, position method failure, Congestion. */
public static final int CONGESTION = 61;
/** Error code: user error, position method failure, Insufficient
* resources. */
public static final int INSUFFICIENT_RESOURCES = 62;
/** Error code: user error, position method failure, Insufficient
* measurement data. */
public static final int INSUFFICIENT_MEASUREMENT_DATA = 63;
/** Error code: user error, position method failure, Inconsistent
* measurement data. */
public static final int INCONSISTENT_MEASUREMENT_DATA = 64;
/** Error code: user error, position method failure, Location
* procedure not completed. */
public static final int LOCATION_PROCEDURE_NOT_COMPLETED = 65;
/** Error code: user error, position method failure, Location
* procedure not supported by target MS. */
public static final int LOCATION_PROCEDURE_NOT_SUPPORTED_BY_TARGET_MS = 66;
/** Error code: user error, position method failure, Requested
* quality of service not attainable. */
public static final int QOS_NOT_ATTAINABLE = 67;
/** Error code: user error, position method failure, Unknown or
* unreachable LCS client. */
public static final int UNKNOWN_OR_UNREACHABLE_LCS_CLIENT = 68;
/** Error code: user error, errors for Any Time Interrogation,
* System failure. */
public static final int ATI_SYSTEM_FAILURE = 69;
/** Error code: user error, errors for Any Time Interrogation, ATI
* not allowed. */
public static final int ATI_NOT_ALLOWED = 70;
/** Error code: user error, errors for Any Time Interrogation, Data
* missing. */
public static final int ATI_DATA_MISSING = 71;
/** Error code: user error, errors for Any Time Interrogation,
* Unexpected data value. */
public static final int ATI_UNEXPECTED_DATA_VALUE = 72;
/** Error code: user error, errors for Any Time Interrogation,
* Unknown subscriber. */
public static final int ATI_UNKNOWN_SUBSCRIBER = 73;
/**
* Constructor setting status.
* @param status
* Status code with general result information.
* @exception SS7InvalidParamException
* Thrown if parameter(s) are invalid / out of range.
*/
public Result(int status)
throws SS7InvalidParamException {
}
/**
* Constructor setting status and errorCode.
* @param status
* Status code with general result information.
* @param errorCode
* Error code is specified in case of error.
* @exception SS7InvalidParamException
* Thrown if parameter(s) are invalid / out of range.
*/
public Result(int status, int errorCode)
throws SS7InvalidParamException {
}
/**
* Empty constructor; needed for serializable objects and beans.
*/
public Result()
throws SS7InvalidParamException {
}
/**
* Set the status.
* @param status
* Status code with general result information.
*/
public void setStatus(int status)
throws SS7InvalidParamException {
}
/**
* Get the status.
* @return
* Status code with general result information.
*/
public int getStatus() {
return 0;
}
/**
* Set the error code.
* @param errorCode
* Error code is specified in case of error.
*/
public void setErrorCode(int errorCode)
throws SS7InvalidParamException {
}
/**
* Get the error code.
* @return
* Error code is specified in case of error.
*/
public int getErrorCode() {
return 0;
}
}
// vim: sw=4 et tw=72 com=srO\:/**,mb\:*,ex\:*/,srO\:/*,mb\:*,ex\:*/,b\:TRANS,\://,b\:#,\:%,\:XCOMM,n\:>,fb\:-
| 0x7678/openss7 | src/java/javax/jain/protocol/ss7/map/Result.java | Java | agpl-3.0 | 16,062 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package uk.ac.surrey.ee.ccsr.s2w.model.iota.testing;
import com.oreilly.servlet.multipart.FilePart;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.ParamPart;
import com.oreilly.servlet.multipart.Part;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import uk.ac.surrey.ee.ccsr.s2w.config.EntityConfigParams;
import uk.ac.surrey.ee.ccsr.s2w.config.ResourceConfigParams;
import uk.ac.surrey.ee.ccsr.s2w.config.ServiceConfigParams;
import uk.ac.surrey.ee.ccsr.s2w.webui.iota.query.SDBHandler;
import uk.ac.surrey.ee.ccsr.s2w.util.Utils;
import uk.ac.surrey.ee.ccsr.s2w.config.old.Parameters;
/**
*
* @author Payam
*/
public class PublishObjectFileServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext context = getServletConfig().getServletContext();
Parameters param = new Parameters();
param.ttlFile = context.getRealPath(param.ttlFile);
//String descType = request.getParameter("desctype");
String dbType = "";
String ontoUri = "";
MultipartParser mp = new MultipartParser(request, 1 * 1024 * 50); // 500 KB
Part part;
part = mp.readNextPart();
ParamPart paramName1 = (ParamPart) part;
String descType = paramName1.getStringValue();
if (descType.equalsIgnoreCase(EntityConfigParams.objType)) {
dbType = param.dbEntityUrl;
ontoUri = param.ontoEntityURI;
} else if (descType.equalsIgnoreCase(ServiceConfigParams.objType)) {
dbType = param.dbServiceUrl;
ontoUri = param.ontoServiceURI;
} else if (descType.equalsIgnoreCase(ResourceConfigParams.objType)){
dbType = param.dbResourceUrl;
ontoUri = param.ontoResourceURI;
}else{
out.println(param.invalidRepoMsg);
return;
}
String fileValue = "";
Utils tool = new Utils();
while ((part = mp.readNextPart()) != null) {
if (part.isFile()) {
// it's a file part
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
if (fileName != null && fileName.length() > 0) {
InputStream in = filePart.getInputStream();
fileValue = tool.convertStreamToString(in);
}
}
}
SDBHandler sdbHandler = new SDBHandler();
sdbHandler.SDBStore(dbType, param.dbuser, param.dbpass, param.ttlFile, fileValue, ontoUri);
//out.println(fileValue);
out.println("<div>");
out.println("<span style= \"font-weight: bold;font-family: Calibri;font-size:medium;\"/>");
out.println("<hr>");
out.println("<br>");
out.println("RDF data is created successfully...<br>");
out.println("<br>");
out.println("Click <a href=\"/S2W/publish/ResourcePubForm.html\">here</a> to go to publish a resource;<br>");
out.println("Click <a href=\"/S2W/publish/EntityPubForm.html\">here</a> to go to publish an entity;<br>");
out.println("Click <a href=\"/S2W/query/QueryEndpoint.html\">here</a> to make a query<br>");
out.println("Click <a href=\"/S2W/map/MapOverlay.html\">here</a> to locate an object on a map;<br>");
out.println("Click <a href=\"/S2W\">here</a> to go back to the home page.<br>");
out.println("</div>");
///end of Debug data
// } catch (FileUploadException ex) {
// Logger.getLogger(PubRDFDirect.class.getName()).log(Level.SEVERE, null, ex);
// } catch (Exception e) {
// e.printStackTrace(out);
// } finally {
// out.close();
// }
// }
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(PublishObjectFileServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(PublishObjectFileServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| UniSurreyIoT/S2W | src/java/uk/ac/surrey/ee/ccsr/s2w/model/iota/testing/PublishObjectFileServlet.java | Java | agpl-3.0 | 6,368 |
package org.jvalue.commons.auth;
import org.junit.Assert;
import org.junit.Test;
public final class BasicAuthUtilsTest {
private final BasicAuthUtils utils = new BasicAuthUtils();
@Test
public void testIsPartiallySecurePassword() {
Assert.assertFalse(utils.isPartiallySecurePassword(null));
Assert.assertFalse(utils.isPartiallySecurePassword("0123456"));
Assert.assertFalse(utils.isPartiallySecurePassword("hello world"));
Assert.assertTrue(utils.isPartiallySecurePassword("hello world 42"));
}
} | jvalue/commons | auth/src/test/java/org/jvalue/commons/auth/BasicAuthUtilsTest.java | Java | agpl-3.0 | 513 |
/*
* Artcodes recognises a different marker scheme that allows the
* creation of aesthetically pleasing, even beautiful, codes.
* Copyright (C) 2013-2016 The University of Nottingham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.horizon.artcodes.activity;
import android.accounts.AccountManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.SearchView;
import androidx.core.view.GravityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.material.navigation.NavigationView;
import java.util.List;
import uk.ac.horizon.artcodes.Analytics;
import uk.ac.horizon.artcodes.Features;
import uk.ac.horizon.artcodes.R;
import uk.ac.horizon.artcodes.account.Account;
import uk.ac.horizon.artcodes.databinding.NavigationBinding;
import uk.ac.horizon.artcodes.fragment.ExperienceLibraryFragment;
import uk.ac.horizon.artcodes.fragment.ExperienceRecentFragment;
import uk.ac.horizon.artcodes.fragment.ExperienceRecommendFragment;
import uk.ac.horizon.artcodes.fragment.ExperienceSearchFragment;
import uk.ac.horizon.artcodes.fragment.ExperienceStarFragment;
import uk.ac.horizon.artcodes.fragment.FeatureListFragment;
import uk.ac.horizon.artcodes.server.LoadCallback;
public class NavigationActivity extends ArtcodeActivityBase implements
NavigationView.OnNavigationItemSelectedListener {
private static final int REQUEST_CODE_SIGN_IN = 63;
private static final int REQUEST_CODE_PICK_ACCOUNT = 67;
private static final long DRAWER_CLOSE_DELAY_MS = 250;
private static final String NAV_ITEM_ID = "navItemId";
private final Handler drawerActionHandler = new Handler();
private NavigationBinding binding;
private ActionBarDrawerToggle drawerToggle;
private MenuItem selected;
private static final String FRAGMENT_TAG = "fragment";
private static final Handler searchHandler = new Handler();
private GoogleApiClient apiClient;
@Override
public void onBackPressed() {
if (binding.drawer.isDrawerOpen(GravityCompat.START)) {
binding.drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public void onConfigurationChanged(@NonNull final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onNavigationItemSelected(@NonNull final MenuItem menuItem) {
if (menuItem.isCheckable()) {
if (selected != null) {
selected.setChecked(false);
}
selected = menuItem;
menuItem.setChecked(true);
}
drawerActionHandler.postDelayed(() -> navigate(menuItem, true), DRAWER_CLOSE_DELAY_MS);
binding.drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (item.getItemId() == R.id.home) {
return drawerToggle.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
private void updateAccounts() {
final Menu menu = binding.navigation.getMenu();
final MenuItem libraries = menu.findItem(R.id.nav_libraries);
final SubMenu subMenu = libraries.getSubMenu();
while (subMenu.size() > 0) {
subMenu.removeItem(subMenu.getItem(0).getItemId());
}
final List<Account> accounts = getServer().getAccounts();
for (int index = 0; index < accounts.size(); index++) {
final Account account = accounts.get(index);
final MenuItem menuItem = subMenu.add(R.id.navigation, index, Menu.NONE, account.getDisplayName());
if (account.getId().equals("local")) {
menuItem.setIcon(R.drawable.ic_folder_24dp);
} else {
menuItem.setIcon(R.drawable.ic_cloud_24dp);
}
menuItem.setCheckable(true);
}
final MenuItem menuItem = subMenu.add(R.id.navigation, R.id.nav_addaccount, Menu.NONE, R.string.nav_addaccount);
menuItem.setIcon(R.drawable.ic_add_24dp);
for (int i = 0, count = binding.navigation.getChildCount(); i < count; i++) {
final View child = binding.navigation.getChildAt(i);
if (child instanceof ListView) {
final ListView menuView = (ListView) child;
final HeaderViewListAdapter adapter = (HeaderViewListAdapter) menuView.getAdapter();
final BaseAdapter wrapped = (BaseAdapter) adapter.getWrappedAdapter();
wrapped.notifyDataSetChanged();
}
}
getServer().loadRecent(new LoadCallback<List<String>>() {
@Override
public void loaded(List<String> item) {
final MenuItem recent = menu.findItem(R.id.nav_recent);
if (recent != null) {
recent.setVisible(!item.isEmpty());
}
}
@Override
public void error(Throwable e) {
Analytics.trackException(e);
}
});
getServer().loadStarred(new LoadCallback<List<String>>() {
@Override
public void loaded(List<String> item) {
final MenuItem starred = menu.findItem(R.id.nav_starred);
if (starred != null) {
starred.setVisible(!item.isEmpty());
}
}
@Override
public void error(Throwable e) {
Analytics.trackException(e);
}
});
}
@Override
protected void onNewIntent(Intent intent) {
Log.i("a", "New intent " + intent);
super.onNewIntent(intent);
}
public void navigate(Fragment fragment, boolean addToBackStack) {
if (addToBackStack) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.content, fragment, FRAGMENT_TAG)
.addToBackStack(null)
.commit();
} else {
getSupportFragmentManager().beginTransaction()
.replace(R.id.content, fragment, FRAGMENT_TAG)
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu, menu);
final MenuItem searchItem = menu.findItem(R.id.search);
final SearchView searchView = (SearchView) searchItem.getActionView();
final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
private Runnable delayedAction = null;
@Override
public boolean onQueryTextSubmit(String query) {
search(query);
return true;
}
@Override
public boolean onQueryTextChange(final String newText) {
if (delayedAction != null) {
searchHandler.removeCallbacks(delayedAction);
delayedAction = null;
}
if (newText.trim().length() > 3) {
delayedAction = () -> search(newText);
searchHandler.postDelayed(delayedAction, 1000);
}
return true;
}
});
searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(final MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(final MenuItem item) {
Log.i("a", "Closed");
Fragment fragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);
if (fragment instanceof ExperienceSearchFragment) {
getSupportFragmentManager().popBackStack();
}
return true;
}
});
return true;
}
private void search(String query) {
Analytics.logSearch(query);
Fragment fragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);
if (fragment instanceof ExperienceSearchFragment) {
((ExperienceSearchFragment) fragment).search(query);
} else {
ExperienceSearchFragment experienceSearchFragment = new ExperienceSearchFragment();
experienceSearchFragment.setArguments(new Bundle());
experienceSearchFragment.getArguments().putString("query", query);
navigate(experienceSearchFragment, true);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
if (resultCode == RESULT_OK) {
if (data != null) {
if (data.hasExtra(AccountManager.KEY_ACCOUNT_NAME)) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
tryGoogleAccount(accountName, null);
}
}
}
}
} else if (requestCode == REQUEST_CODE_SIGN_IN) {
final GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.getSignInAccount() != null) {
tryGoogleAccount(result.getSignInAccount().getEmail(), result.getSignInAccount().getDisplayName());
}
}
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Features.show_welcome.isEnabled(this)) {
startActivity(new Intent(this, AboutArtcodesActivity.class));
return;
}
binding = DataBindingUtil.setContentView(this, R.layout.navigation);
setSupportActionBar(binding.toolbar);
binding.navigation.setNavigationItemSelectedListener(this);
final View headerView = binding.navigation.inflateHeaderView(R.layout.navigation_header);
final MenuItem featureItem = binding.navigation.getMenu().findItem(R.id.nav_features);
if (Features.edit_features.isEnabled(this)) {
featureItem.setVisible(true);
} else {
headerView.setLongClickable(true);
headerView.setOnLongClickListener(v -> {
featureItem.setVisible(true);
Features.edit_features.setEnabled(this, true);
return false;
});
}
updateAccounts();
drawerToggle = new ActionBarDrawerToggle(this, binding.drawer, binding.toolbar, R.string.open, R.string.close) {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
updateAccounts();
}
};
binding.drawer.addDrawerListener(drawerToggle);
drawerToggle.syncState();
int navigationIndex = R.id.nav_home;
if (savedInstanceState != null) {
navigationIndex = savedInstanceState.getInt(NAV_ITEM_ID, R.id.nav_home);
}
MenuItem item = binding.navigation.getMenu().findItem(navigationIndex);
if (item == null) {
item = binding.navigation.getMenu().findItem(R.id.nav_home);
}
navigate(item, false);
final GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.oauth_client_id))
.requestEmail()
.requestProfile()
.build();
apiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, connectionResult -> Log.i("Signin", "Failed " + connectionResult))
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
apiClient.connect();
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
if (selected != null) {
outState.putInt(NAV_ITEM_ID, selected.getItemId());
}
}
private void tryGoogleAccount(final String name, final String displayName) {
new Thread(() -> {
try {
final Account account = getServer().createAccount("google:" + name);
if (account.validates()) {
account.setDisplayName(displayName);
getServer().add(account);
new Handler(Looper.getMainLooper()).post(() -> {
updateAccounts();
final Bundle bundle = new Bundle();
bundle.putString("account", account.getId());
final Fragment fragment = new ExperienceLibraryFragment();
fragment.setArguments(bundle);
navigate(fragment, true);
});
}
} catch (UserRecoverableAuthException userRecoverableException) {
Log.i("intent", "Intent = " + userRecoverableException.getIntent());
startActivityForResult(userRecoverableException.getIntent(), REQUEST_CODE_PICK_ACCOUNT);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
private void selectAccount() {
apiClient.clearDefaultAccountAndReconnect();
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(apiClient);
startActivityForResult(signInIntent, REQUEST_CODE_SIGN_IN);
}
private void navigate(MenuItem item, boolean addToBackStack) {
switch (item.getItemId()) {
case R.id.nav_home:
navigate(new ExperienceRecommendFragment(), addToBackStack);
break;
case R.id.nav_starred:
navigate(new ExperienceStarFragment(), addToBackStack);
break;
case R.id.nav_features:
navigate(new FeatureListFragment(), addToBackStack);
break;
case R.id.nav_recent:
navigate(new ExperienceRecentFragment(), addToBackStack);
break;
case R.id.nav_about_artcodes:
startActivity(new Intent(this, AboutArtcodesActivity.class));
break;
case R.id.nav_addaccount:
selectAccount();
break;
default:
final List<Account> accounts = getServer().getAccounts();
if (item.getItemId() < accounts.size()) {
final Account account = accounts.get(item.getItemId());
Bundle bundle = new Bundle();
bundle.putString("account", account.getId());
final Fragment fragment = new ExperienceLibraryFragment();
fragment.setArguments(bundle);
navigate(fragment, addToBackStack);
}
break;
}
}
}
| horizon-institute/artcodes-android | app/src/main/java/uk/ac/horizon/artcodes/activity/NavigationActivity.java | Java | agpl-3.0 | 14,391 |
/*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2017 Tanaguru.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.rgaa32017;
import java.util.Iterator;
import java.util.regex.Pattern;
import org.jsoup.nodes.Element;
import org.tanaguru.processor.SSPHandler;
import org.tanaguru.ruleimplementation.AbstractPageRuleWithSelectorAndCheckerImplementation;
import org.tanaguru.rules.elementchecker.headings.HeadingsHierarchyChecker;
import org.tanaguru.rules.elementselector.SimpleElementSelector;
import static org.tanaguru.rules.keystore.CssLikeQueryStore.HEADINGS_CSS_LIKE_QUERY;
import static org.tanaguru.rules.keystore.CssLikeQueryStore.ARIA_HEADINGS_CSS_LIKE_QUERY;
/**
* Implementation of the rule 9.1.2 of the referential Rgaa 3-2017.
* <br>
* For more details about the implementation, refer to <a
* href="http://tanaguru-rules-rgaa3.readthedocs.org/en/latest/Rule-9-1-2">the rule 9.1.2
* design page.</a>
*
* @see <a
* href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-9-1-2">
* 9.1.2 rule specification</a>
*
*/
public class Rgaa32017Rule090102 extends AbstractPageRuleWithSelectorAndCheckerImplementation {
private static final Pattern PATTERN = Pattern.compile("[1-9][0-9]?");
/**
* Default constructor
*/
public Rgaa32017Rule090102() {
super(
new SimpleElementSelector(
HEADINGS_CSS_LIKE_QUERY + ", " + ARIA_HEADINGS_CSS_LIKE_QUERY),
new HeadingsHierarchyChecker());
}
@Override
protected void select(SSPHandler sspHandler) {
super.select(sspHandler);
Iterator<Element> elementsIterator = getElements().get().iterator();
while (elementsIterator.hasNext()) {
Element element = elementsIterator.next();
if (element.hasAttr("aria-level")) {
if (!PATTERN.matcher(element.attr("aria-level")).matches()) {
elementsIterator.remove();
}
}
}
}
}
| Tanaguru/Tanaguru | rules/rgaa3-2017/src/main/java/org/tanaguru/rules/rgaa32017/Rgaa32017Rule090102.java | Java | agpl-3.0 | 2,735 |
/*
* Copyright (C) 2016-2020 the original author or authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package space.npstr.wolfia.game;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import space.npstr.wolfia.game.definitions.Alignments;
import space.npstr.wolfia.game.definitions.Roles;
/**
* A configuration of roles that define a game setup, mainly used by mafia games
*/
public class CharakterSetup {
private final List<Charakter> charakters = new ArrayList<>();
public Collection<Charakter> getRandedCharakters() {
Collections.shuffle(this.charakters);
return Collections.unmodifiableList(this.charakters);
}
public CharakterSetup addRoleAndAlignment(final Alignments alignment, final Roles role, final int... amount) {
if (amount.length > 0) { //add a few times
for (int i = 0; i < amount[0]; i++) {
this.charakters.add(new Charakter(alignment, role));
}
} else { //add just once
this.charakters.add(new Charakter(alignment, role));
}
return this;
}
public int size() {
return this.charakters.size();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
for (final Charakter c : this.charakters) {
sb.append(c.alignment.textRepMaf).append(" ").append(c.role.textRep).append("\n");
}
return sb.toString();
}
}
| napstr/wolfia | src/main/java/space/npstr/wolfia/game/CharakterSetup.java | Java | agpl-3.0 | 2,144 |
/**
* Copyright (C) 2001-2017 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.tools.math;
import com.rapidminer.tools.Tools;
import java.io.Serializable;
/**
* Objects of this class hold all information about a single ROC data point.
*
* @author Ingo Mierswa
*/
public class ROCPoint implements Serializable {
private static final long serialVersionUID = 1L;
private final double falsePositives;
private final double truePositives;
private final double confidence;
public ROCPoint(double falsePositives, double truePositives, double confidence) {
this.falsePositives = falsePositives;
this.truePositives = truePositives;
this.confidence = confidence;
}
/** Returns the number of false positives, not the rate. */
public double getFalsePositives() {
return falsePositives;
}
/** Returns the number of true positives, not the rate. */
public double getTruePositives() {
return truePositives;
}
public double getConfidence() {
return confidence;
}
@Override
public String toString() {
return "fp: " + Tools.formatIntegerIfPossible(falsePositives) + ", tp: "
+ Tools.formatIntegerIfPossible(truePositives) + ", confidence: "
+ Tools.formatIntegerIfPossible(confidence);
}
}
| boob-sbcm/3838438 | src/main/java/com/rapidminer/tools/math/ROCPoint.java | Java | agpl-3.0 | 2,062 |
package org.kramerlab.cfpminer.weka.eval2;
import java.io.Serializable;
import org.apache.commons.lang3.SerializationUtils;
import org.mg.wekalib.eval2.persistance.ResultProvider;
import com.lambdaworks.redis.RedisConnection;
public class RedisResultProvider implements ResultProvider
{
RedisConnection<byte[], byte[]> con;
public RedisResultProvider(RedisConnection<byte[], byte[]> con)
{
this.con = con;
con.select(1);
}
@SuppressWarnings("deprecation")
@Override
public boolean contains(String key)
{
//return con.get(key.getBytes()) != null;
return con.exists(key.toString().getBytes());
}
@Override
public Serializable get(String key)
{
return SerializationUtils.deserialize(con.get(key.toString().getBytes()));
}
@Override
public void set(String key, Serializable value)
{
if (con.get(key.toString().getBytes()) != null)
throw new IllegalStateException("alreay computed!");
con.set(key.toString().getBytes(), SerializationUtils.serialize(value));
}
@Override
public void clear()
{
con.flushdb();
}
}
| mguetlein/cfp-miner | src/main/java/org/kramerlab/cfpminer/weka/eval2/RedisResultProvider.java | Java | agpl-3.0 | 1,056 |
/**
* Axelor Business Solutions
*
* Copyright (C) 2016 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.axelor.apps.crm.service;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.mail.MessagingException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.axelor.apps.base.db.Address;
import com.axelor.apps.base.db.ICalendarUser;
import com.axelor.apps.base.db.Partner;
import com.axelor.apps.base.ical.ICalendarException;
import com.axelor.apps.base.service.PartnerService;
import com.axelor.apps.crm.db.CrmConfig;
import com.axelor.apps.crm.db.Event;
import com.axelor.apps.crm.db.Lead;
import com.axelor.apps.crm.db.RecurrenceConfiguration;
import com.axelor.apps.crm.db.repo.EventRepository;
import com.axelor.apps.crm.db.repo.RecurrenceConfigurationRepository;
import com.axelor.apps.crm.exception.IExceptionMessage;
import com.axelor.apps.crm.service.config.CrmConfigService;
import com.axelor.apps.message.db.EmailAddress;
import com.axelor.apps.message.db.Message;
import com.axelor.apps.message.db.Template;
import com.axelor.apps.message.db.repo.EmailAddressRepository;
import com.axelor.apps.message.db.repo.MessageRepository;
import com.axelor.apps.message.service.MailAccountService;
import com.axelor.apps.message.service.MessageService;
import com.axelor.apps.message.service.TemplateMessageService;
import com.axelor.auth.db.User;
import com.axelor.auth.db.repo.UserRepository;
import com.axelor.exception.AxelorException;
import com.axelor.exception.db.IException;
import com.axelor.i18n.I18n;
import com.axelor.inject.Beans;
import com.axelor.mail.db.MailAddress;
import com.axelor.mail.db.repo.MailAddressRepository;
import com.axelor.mail.db.repo.MailFollowerRepository;
import com.axelor.meta.db.MetaFile;
import com.google.common.base.Strings;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.property.Method;
public class EventService {
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("dd/MM/yyyy");
private static final DateTimeFormatter MONTH_FORMAT = DateTimeFormatter.ofPattern("dd/MM");
@Inject
private EventAttendeeService eventAttendeeService;
@Inject
private PartnerService partnerService;
@Inject
private EventRepository eventRepo;
@Inject
protected MailFollowerRepository mailFollowerRepo;
static final String REQUEST = "REQUEST";
public Duration computeDuration(LocalDateTime startDateTime, LocalDateTime endDateTime) {
return Duration.between(startDateTime, endDateTime);
}
public int getDuration(Duration duration) {
return new Integer(new Long(duration.getSeconds()).toString());
}
public LocalDateTime computeStartDateTime(int duration, LocalDateTime endDateTime) {
return endDateTime.minusSeconds(duration);
}
public LocalDateTime computeEndDateTime(LocalDateTime startDateTime, int duration) {
return startDateTime.plusSeconds(duration);
}
@Transactional
public void saveEvent(Event event){
eventRepo.save(event);
}
@Transactional
public void addLeadAttendee(Event event, Lead lead, Partner contactPartner) {
event.addEventAttendeeListItem(eventAttendeeService.createEventAttendee(event, lead, contactPartner));
eventRepo.save(event);
}
public Event createEvent(LocalDateTime fromDateTime, LocalDateTime toDateTime, User user, String description, int type, String subject){
Event event = new Event();
event.setSubject(subject);
event.setStartDateTime(fromDateTime);
event.setEndDateTime(toDateTime);
event.setUser(user);
event.setTypeSelect(type);
if(!Strings.isNullOrEmpty(description)){
event.setDescription(description);
}
return event;
}
public String getInvoicingAddressFullName(Partner partner) {
Address address = partnerService.getInvoicingAddress(partner);
if(address != null){
return address.getFullName();
}
return null;
}
public void manageFollowers(Event event){
List<ICalendarUser> attendeesSet = event.getAttendees();
if(attendeesSet != null){
for (ICalendarUser user : attendeesSet) {
if(user.getUser() != null){
mailFollowerRepo.follow(event, user.getUser());
}
else{
MailAddress mailAddress = Beans.get(MailAddressRepository.class).findOrCreate(user.getEmail(), user.getName());
mailFollowerRepo.follow(event, mailAddress);
}
}
}
}
public Event checkModifications(Event event, Event previousEvent) throws AxelorException, ClassNotFoundException, InstantiationException, IllegalAccessException, IOException, MessagingException{
Set<User> previousUserSet = previousEvent.getInternalGuestSet();
Set<User> userSet = event.getInternalGuestSet();
Set<Partner> previousContactSet = previousEvent.getExternalGuestSet();
Set<Partner> contactSet = previousEvent.getExternalGuestSet();
List<User> deletedUsers = this.deletedGuests(previousUserSet, userSet);
List<User> addedUsers = this.addedGuests(previousUserSet, userSet);
List<Partner> deletedContacts = this.deletedGuests(previousContactSet, contactSet);
List<Partner> addedContacts = this.addedGuests(previousContactSet, contactSet);
Template deletedGuestsTemplate = Beans.get(CrmConfigService.class).getCrmConfig(event.getUser().getActiveCompany()).getMeetingGuestDeletedTemplate();
Template addedGuestsTemplate = Beans.get(CrmConfigService.class).getCrmConfig(event.getUser().getActiveCompany()).getMeetingGuestAddedTemplate();
Template changedDateTemplate = Beans.get(CrmConfigService.class).getCrmConfig(event.getUser().getActiveCompany()).getMeetingDateChangeTemplate();
if(deletedGuestsTemplate == null || addedGuestsTemplate == null || changedDateTemplate == null){
throw new AxelorException(String.format(I18n.get(IExceptionMessage.CRM_CONFIG_TEMPLATES),event.getUser().getActiveCompany()),
IException.CONFIGURATION_ERROR);
}
if(!event.getEndDateTime().isEqual(previousEvent.getEndDateTime())){
for (Partner partner : contactSet) {
Message message = Beans.get(TemplateMessageService.class).generateMessage(event, changedDateTemplate);
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(event.getUser().getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(partner.getEmailAddress());
message = Beans.get(MessageService.class).sendByEmail(message);
}
for (User user : userSet) {
Message message = Beans.get(TemplateMessageService.class).generateMessage(event, changedDateTemplate);
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(event.getUser().getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(user.getPartner().getEmailAddress());
message = Beans.get(MessageService.class).sendByEmail(message);
}
Message message = Beans.get(TemplateMessageService.class).generateMessage(event, changedDateTemplate);
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(event.getUser().getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(event.getUser().getPartner().getEmailAddress());
message = Beans.get(MessageService.class).sendByEmail(message);
}
for (Partner partner : addedContacts) {
Message message = Beans.get(TemplateMessageService.class).generateMessage(event, addedGuestsTemplate);
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(event.getUser().getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(partner.getEmailAddress());
message = Beans.get(MessageService.class).sendByEmail(message);
}
for (Partner partner : deletedContacts) {
Message message = Beans.get(TemplateMessageService.class).generateMessage(event, deletedGuestsTemplate);
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(event.getUser().getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(partner.getEmailAddress());
message = Beans.get(MessageService.class).sendByEmail(message);
}
for (User user : addedUsers) {
Message message = Beans.get(TemplateMessageService.class).generateMessage(event, addedGuestsTemplate);
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(event.getUser().getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(user.getPartner().getEmailAddress());
message = Beans.get(MessageService.class).sendByEmail(message);
}
for (User user : deletedUsers) {
Message message = Beans.get(TemplateMessageService.class).generateMessage(event, deletedGuestsTemplate);
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(event.getUser().getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(user.getPartner().getEmailAddress());
message = Beans.get(MessageService.class).sendByEmail(message);
}
return event;
}
public <T> List<T> deletedGuests (Set<T> previousSet, Set<T> set){
List<T> deletedList = new ArrayList<T>();
if(previousSet != null){
for (T object : previousSet) {
if(set == null || set.isEmpty() || !set.contains(object)){
deletedList.add(object);
}
}
}
return deletedList;
}
public <T> List<T> addedGuests (Set<T> previousSet, Set<T> set){
List<T> addedList = new ArrayList<T>();
if(set != null){
for (T object : set) {
if(previousSet == null || previousSet.isEmpty() || !previousSet.contains(object)){
addedList.add(object);
}
}
}
return addedList;
}
public void sendMails(Event event) throws AxelorException, ClassNotFoundException, InstantiationException, IllegalAccessException, IOException, MessagingException{
Template guestAddedTemplate = Beans.get(CrmConfigService.class).getCrmConfig(event.getUser().getActiveCompany()).getMeetingGuestAddedTemplate();
if(guestAddedTemplate == null){
throw new AxelorException(String.format(I18n.get(IExceptionMessage.CRM_CONFIG_TEMPLATES),event.getUser().getActiveCompany()),
IException.CONFIGURATION_ERROR);
}
if(event.getExternalGuestSet() != null){
for (Partner partner : event.getExternalGuestSet()) {
Message message = Beans.get(TemplateMessageService.class).generateMessage(event, guestAddedTemplate);
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(event.getUser().getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(partner.getEmailAddress());
message = Beans.get(MessageService.class).sendByEmail(message);
}
}
if(event.getInternalGuestSet() != null){
for (User user : event.getInternalGuestSet()) {
Message message = Beans.get(TemplateMessageService.class).generateMessage(event, guestAddedTemplate);
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(event.getUser().getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(user.getPartner().getEmailAddress());
message = Beans.get(MessageService.class).sendByEmail(message);
}
}
Message message = Beans.get(TemplateMessageService.class).generateMessage(event, guestAddedTemplate);
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(event.getUser().getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(event.getUser().getPartner().getEmailAddress());
message = Beans.get(MessageService.class).sendByEmail(message);
}
@Transactional
public void addUserGuest(User user, Event event) throws ClassNotFoundException, InstantiationException, IllegalAccessException, AxelorException, MessagingException, IOException, ICalendarException, ValidationException, ParseException{
if(user.getPartner() != null && user.getPartner().getEmailAddress() != null){
String email = user.getPartner().getEmailAddress().getAddress();
if(event.getAttendees() != null && !Strings.isNullOrEmpty(email)){
boolean exist = false;
for (ICalendarUser attendee : event.getAttendees()) {
if(email.equals(attendee.getEmail())){
exist = true;
break;
}
}
if(!exist){
ICalendarUser calUser = new ICalendarUser();
calUser.setEmail(email);
calUser.setName(user.getFullName());
calUser.setUser(user);
event.addAttendee(calUser);
eventRepo.save(event);
if(event.getCalendarCrm() != null){
Beans.get(CalendarService.class).sync(event.getCalendarCrm());
}
this.sendMail(event, email);
}
}
}
else{
throw new AxelorException(I18n.get("This user doesn't have any partner or email address"),IException.CONFIGURATION_ERROR);
}
}
@Transactional
public void addPartnerGuest(Partner partner, Event event) throws ClassNotFoundException, InstantiationException, IllegalAccessException, AxelorException, MessagingException, IOException, ICalendarException, ValidationException, ParseException{
if(partner.getEmailAddress() != null){
String email = partner.getEmailAddress().getAddress();
if(event.getAttendees() != null && !Strings.isNullOrEmpty(email)){
boolean exist = false;
for (ICalendarUser attendee : event.getAttendees()) {
if(email.equals(attendee.getEmail())){
exist = true;
break;
}
}
if(!exist){
ICalendarUser calUser = new ICalendarUser();
calUser.setEmail(email);
calUser.setName(partner.getFullName());
if(partner.getUser() != null){
calUser.setUser(partner.getUser());
}
event.addAttendee(calUser);
eventRepo.save(event);
if(event.getCalendarCrm() != null){
Beans.get(CalendarService.class).sync(event.getCalendarCrm());
}
this.sendMail(event, email);
}
}
}
else{
throw new AxelorException(I18n.get("This partner doesn't have any email address"),IException.CONFIGURATION_ERROR);
}
}
@Transactional
public void addEmailGuest(EmailAddress email, Event event) throws ClassNotFoundException, InstantiationException, IllegalAccessException, AxelorException, MessagingException, IOException, ICalendarException, ValidationException, ParseException{
if(event.getAttendees() != null && email != null){
boolean exist = false;
for (ICalendarUser attendee : event.getAttendees()) {
if(email.getAddress().equals(attendee.getEmail())){
exist = true;
break;
}
}
if(!exist){
ICalendarUser calUser = new ICalendarUser();
calUser.setEmail(email.getAddress());
calUser.setName(email.getName());
if(email.getPartner() != null && email.getPartner().getUser() != null){
calUser.setUser(email.getPartner().getUser());
}
event.addAttendee(calUser);
eventRepo.save(event);
}
}
}
@Transactional
public void sendMail(Event event, String email) throws AxelorException, MessagingException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, ValidationException, ParseException, ICalendarException{
EmailAddress emailAddress = Beans.get(EmailAddressRepository.class).all().filter("self.address = ?1", email).fetchOne();
User user = Beans.get(UserRepository.class).all().filter("self.partner.emailAddress.address = ?1", email).fetchOne();
CrmConfig crmConfig = Beans.get(CrmConfigService.class).getCrmConfig(user.getActiveCompany());
if(crmConfig.getSendMail() == true) {
if(emailAddress == null){
emailAddress = new EmailAddress(email);
}
Template guestAddedTemplate = crmConfig.getMeetingGuestAddedTemplate();
Message message = new Message();
if(guestAddedTemplate == null){
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(user.getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(emailAddress);
message.setSubject(event.getSubject());
message.setMailAccount(Beans.get(MailAccountService.class).getDefaultMailAccount());
}
else{
message = Beans.get(TemplateMessageService.class).generateMessage(event, guestAddedTemplate);
if(message.getFromEmailAddress() == null){
message.setFromEmailAddress(user.getPartner().getEmailAddress());
}
message.addToEmailAddressSetItem(emailAddress);
}
if(event.getUid() != null){
CalendarService calendarService = Beans.get(CalendarService.class);
Calendar cal = calendarService.getCalendar(event.getUid(), event.getCalendarCrm());
cal.getProperties().add(Method.REQUEST);
File file = calendarService.export(cal);
Path filePath = file.toPath();
MetaFile metaFile = new MetaFile();
metaFile.setFileName( file.getName() );
metaFile.setFileType( Files.probeContentType( filePath ) );
metaFile.setFileSize( Files.size( filePath ) );
metaFile.setFilePath( file.getName() );
Set<MetaFile> fileSet = new HashSet<MetaFile>();
fileSet.add(metaFile);
Beans.get(MessageRepository.class).save(message);
Beans.get(MessageService.class).attachMetaFiles(message, fileSet);
}
message = Beans.get(MessageService.class).sendByEmail(message);
}
}
@Transactional
public void addRecurrentEventsByDays(Event event, int periodicity, int endType, int repetitionsNumber, LocalDate endDate){
Event lastEvent = event;
if(endType == 1){
int repeated = 0;
while(repeated != repetitionsNumber){
Event copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
copy.setStartDateTime(copy.getStartDateTime().plusDays(periodicity));
copy.setEndDateTime(copy.getEndDateTime().plusDays(periodicity));
eventRepo.save(copy);
repeated++;
lastEvent = copy;
}
}
else{
while(!lastEvent.getStartDateTime().plusDays(periodicity).isAfter(endDate.atStartOfDay())){
Event copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
copy.setStartDateTime(copy.getStartDateTime().plusDays(periodicity));
copy.setEndDateTime(copy.getEndDateTime().plusDays(periodicity));
eventRepo.save(copy);
lastEvent = copy;
}
}
}
@Transactional
public void addRecurrentEventsByWeeks(Event event, int periodicity, int endType, int repetitionsNumber, LocalDate endDate, Map<Integer, Boolean> daysCheckedMap){
Event lastEvent = event;
List<Integer> list = new ArrayList<Integer>();
for (int day : daysCheckedMap.keySet()) {
list.add(day);
}
Collections.sort(list);
if(endType == 1){
int repeated = 0;
Event copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
int dayOfWeek = copy.getStartDateTime().getDayOfWeek().getValue();
LocalDateTime nextDateTime = LocalDateTime.now();
if(dayOfWeek < list.get(0)){
nextDateTime = copy.getStartDateTime().plusDays(list.get(0) - dayOfWeek);
}
else if(dayOfWeek > list.get(0)){
nextDateTime = copy.getStartDateTime().plusDays((7-dayOfWeek)+list.get(0));
}
Duration dur = Duration.between(copy.getStartDateTime(), copy.getEndDateTime());
for (Integer integer : list) {
nextDateTime.plusDays(integer - nextDateTime.getDayOfWeek().getValue());
copy.setStartDateTime(nextDateTime);
copy.setEndDateTime(nextDateTime.plus(dur));
eventRepo.save(copy);
lastEvent = copy;
repeated++;
}
while(repeated < repetitionsNumber){
copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
copy.setStartDateTime(copy.getStartDateTime().plusWeeks(periodicity));
copy.setEndDateTime(copy.getEndDateTime().plusWeeks(periodicity));
dayOfWeek = copy.getStartDateTime().getDayOfWeek().getValue();
nextDateTime = LocalDateTime.now();
if(dayOfWeek < list.get(0)){
nextDateTime = copy.getStartDateTime().plusDays(list.get(0) - dayOfWeek);
}
else if(dayOfWeek > list.get(0)){
nextDateTime = copy.getStartDateTime().plusDays((7-dayOfWeek)+list.get(0));
}
dur = Duration.between(copy.getStartDateTime(), copy.getEndDateTime());
for (Integer integer : list) {
nextDateTime.plusDays(integer - nextDateTime.getDayOfWeek().getValue());
copy.setStartDateTime(nextDateTime);
copy.setEndDateTime(nextDateTime.plus(dur));
eventRepo.save(copy);
lastEvent = copy;
repeated++;
}
}
}
else{
Event copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
int dayOfWeek = copy.getStartDateTime().getDayOfWeek().getValue();
LocalDateTime nextDateTime = LocalDateTime.now();
if(dayOfWeek < list.get(0)){
nextDateTime = copy.getStartDateTime().plusDays(list.get(0) - dayOfWeek);
}
else if(dayOfWeek > list.get(0)){
nextDateTime = copy.getStartDateTime().plusDays((7-dayOfWeek)+list.get(0));
}
Duration dur = Duration.between(copy.getStartDateTime(), copy.getEndDateTime());
for (Integer integer : list) {
nextDateTime.plusDays(integer - nextDateTime.getDayOfWeek().getValue());
copy.setStartDateTime(nextDateTime);
copy.setEndDateTime(nextDateTime.plus(dur));
eventRepo.save(copy);
lastEvent = copy;
}
while(!copy.getStartDateTime().plusWeeks(periodicity).isAfter(endDate.atStartOfDay())){
copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
copy.setStartDateTime(copy.getStartDateTime().plusWeeks(periodicity));
copy.setEndDateTime(copy.getEndDateTime().plusWeeks(periodicity));
dayOfWeek = copy.getStartDateTime().getDayOfWeek().getValue();
nextDateTime = LocalDateTime.now();
if(dayOfWeek < list.get(0)){
nextDateTime = copy.getStartDateTime().plusDays(list.get(0) - dayOfWeek);
}
else if(dayOfWeek > list.get(0)){
nextDateTime = copy.getStartDateTime().plusDays((7-dayOfWeek)+list.get(0));
}
dur = Duration.between(copy.getStartDateTime(), copy.getEndDateTime());
for (Integer integer : list) {
nextDateTime.plusDays(integer - nextDateTime.getDayOfWeek().getValue());
copy.setStartDateTime(nextDateTime);
copy.setEndDateTime(nextDateTime.plus(dur));
eventRepo.save(copy);
lastEvent = copy;
}
}
}
}
@Transactional
public void addRecurrentEventsByMonths(Event event, int periodicity, int endType, int repetitionsNumber, LocalDate endDate, int monthRepeatType){
Event lastEvent = event;
if(monthRepeatType == 1){
int dayOfMonth = event.getStartDateTime().getDayOfMonth();
if(endType == 1){
int repeated = 0;
while(repeated != repetitionsNumber){
Event copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
if(copy.getStartDateTime().plusMonths(periodicity).toLocalDate().lengthOfMonth() >= dayOfMonth){
copy.setStartDateTime(copy.getStartDateTime().plusMonths(periodicity));
copy.setEndDateTime(copy.getEndDateTime().plusMonths(periodicity));
eventRepo.save(copy);
repeated++;
lastEvent = copy;
}
}
}
else{
while(!lastEvent.getStartDateTime().plusMonths(periodicity).isAfter(endDate.atStartOfDay())){
Event copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
if(copy.getStartDateTime().plusMonths(periodicity).toLocalDate().lengthOfMonth() >= dayOfMonth){
copy.setStartDateTime(copy.getStartDateTime().plusMonths(periodicity));
copy.setEndDateTime(copy.getEndDateTime().plusMonths(periodicity));
eventRepo.save(copy);
lastEvent = copy;
}
}
}
}
else{
int dayOfWeek = event.getStartDateTime().getDayOfWeek().getValue();
int positionInMonth = 0;
if(event.getStartDateTime().getDayOfMonth() % 7 == 0){
positionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
}
else{
positionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
}
if(endType == 1){
int repeated = 0;
while(repeated != repetitionsNumber){
Event copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
LocalDateTime nextDateTime = copy.getStartDateTime();
nextDateTime.plusMonths(periodicity);
int nextDayOfWeek = nextDateTime.getDayOfWeek().getValue();
if(nextDayOfWeek > dayOfWeek){
nextDateTime.minusDays(nextDayOfWeek - dayOfWeek);
}
else{
nextDateTime.plusDays(dayOfWeek - nextDayOfWeek);
}
int nextPositionInMonth = 0;
if(event.getStartDateTime().getDayOfMonth() % 7 == 0){
nextPositionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
}
else{
nextPositionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
}
if(nextPositionInMonth > positionInMonth){
nextDateTime.minusWeeks(nextPositionInMonth - positionInMonth);
}
else{
nextDateTime.plusWeeks(positionInMonth - nextPositionInMonth);
}
Duration dur = Duration.between(copy.getStartDateTime(), copy.getEndDateTime());
copy.setStartDateTime(nextDateTime);
copy.setEndDateTime(nextDateTime.plus(dur));
eventRepo.save(copy);
repeated++;
lastEvent = copy;
}
}
else{
LocalDateTime nextDateTime = lastEvent.getStartDateTime();
nextDateTime.plusMonths(periodicity);
int nextDayOfWeek = nextDateTime.getDayOfWeek().getValue();
if(nextDayOfWeek > dayOfWeek){
nextDateTime.minusDays(nextDayOfWeek - dayOfWeek);
}
else{
nextDateTime.plusDays(dayOfWeek - nextDayOfWeek);
}
int nextPositionInMonth = 0;
if(event.getStartDateTime().getDayOfMonth() % 7 == 0){
nextPositionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
}
else{
nextPositionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
}
if(nextPositionInMonth > positionInMonth){
nextDateTime.minusWeeks(nextPositionInMonth - positionInMonth);
}
else{
nextDateTime.plusWeeks(positionInMonth - nextPositionInMonth);
}
while(!nextDateTime.isAfter(endDate.atStartOfDay())){
Event copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
Duration dur = Duration.between(copy.getStartDateTime(), copy.getEndDateTime());
copy.setStartDateTime(nextDateTime);
copy.setEndDateTime(nextDateTime.plus(dur));
eventRepo.save(copy);
lastEvent = copy;
nextDateTime = lastEvent.getStartDateTime();
nextDateTime.plusMonths(periodicity);
nextDayOfWeek = nextDateTime.getDayOfWeek().getValue();
if(nextDayOfWeek > dayOfWeek){
nextDateTime.minusDays(nextDayOfWeek - dayOfWeek);
}
else{
nextDateTime.plusDays(dayOfWeek - nextDayOfWeek);
}
nextPositionInMonth = 0;
if(event.getStartDateTime().getDayOfMonth() % 7 == 0){
nextPositionInMonth = event.getStartDateTime().getDayOfMonth() / 7;
}
else{
nextPositionInMonth = (event.getStartDateTime().getDayOfMonth() / 7) + 1;
}
if(nextPositionInMonth > positionInMonth){
nextDateTime.minusWeeks(nextPositionInMonth - positionInMonth);
}
else{
nextDateTime.plusWeeks(positionInMonth - nextPositionInMonth);
}
}
}
}
}
@Transactional
public void addRecurrentEventsByYears(Event event, int periodicity, int endType, int repetitionsNumber, LocalDate endDate){
Event lastEvent = event;
if(endType == 1){
int repeated = 0;
while(repeated != repetitionsNumber){
Event copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
copy.setStartDateTime(copy.getStartDateTime().plusYears(periodicity));
copy.setEndDateTime(copy.getEndDateTime().plusYears(periodicity));
eventRepo.save(copy);
repeated++;
lastEvent = copy;
}
}
else{
while(!lastEvent.getStartDateTime().plusYears(periodicity).isAfter(endDate.atStartOfDay())){
Event copy = eventRepo.copy(lastEvent, false);
copy.setParentEvent(lastEvent);
copy.setStartDateTime(copy.getStartDateTime().plusYears(periodicity));
copy.setEndDateTime(copy.getEndDateTime().plusYears(periodicity));
eventRepo.save(copy);
lastEvent = copy;
}
}
}
@Transactional
public void applyChangesToAll(Event event){
Event child = eventRepo.all().filter("self.parentEvent.id = ?1", event.getId()).fetchOne();
Event parent = event.getParentEvent();
Event copyEvent = eventRepo.copy(event, false);
while(child != null){
child.setSubject(event.getSubject());
child.setCalendar(event.getCalendar());
child.setStartDateTime(child.getStartDateTime().withHour(event.getStartDateTime().getHour()));
child.setStartDateTime(child.getStartDateTime().withMinute(event.getStartDateTime().getMinute()));
child.setEndDateTime(child.getEndDateTime().withHour(event.getEndDateTime().getHour()));
child.setEndDateTime(child.getEndDateTime().withMinute(event.getEndDateTime().getMinute()));
child.setDuration(event.getDuration());
child.setUser(event.getUser());
child.setTeam(event.getTeam());
child.setDisponibilitySelect(event.getDisponibilitySelect());
child.setVisibilitySelect(event.getVisibilitySelect());
child.setDescription(event.getDescription());
child.setClientPartner(event.getClientPartner());
child.setContactPartner(event.getContactPartner());
child.setLead(event.getLead());
child.setTypeSelect(event.getTypeSelect());
child.setLocation(event.getLocation());
eventRepo.save(child);
copyEvent = child;
child = eventRepo.all().filter("self.parentEvent.id = ?1", copyEvent.getId()).fetchOne();
}
while(parent != null){
Event nextParent = parent.getParentEvent();
parent.setSubject(event.getSubject());
parent.setCalendar(event.getCalendar());
parent.setStartDateTime(parent.getStartDateTime().withHour(event.getStartDateTime().getHour()));
parent.setStartDateTime(parent.getStartDateTime().withMinute(event.getStartDateTime().getMinute()));
parent.setEndDateTime(parent.getEndDateTime().withHour(event.getEndDateTime().getHour()));
parent.setEndDateTime(parent.getEndDateTime().withMinute(event.getEndDateTime().getMinute()));
parent.setDuration(event.getDuration());
parent.setUser(event.getUser());
parent.setTeam(event.getTeam());
parent.setDisponibilitySelect(event.getDisponibilitySelect());
parent.setVisibilitySelect(event.getVisibilitySelect());
parent.setDescription(event.getDescription());
parent.setClientPartner(event.getClientPartner());
parent.setContactPartner(event.getContactPartner());
parent.setLead(event.getLead());
parent.setTypeSelect(event.getTypeSelect());
parent.setLocation(event.getLocation());
eventRepo.save(parent);
parent = nextParent;
}
}
public String computeRecurrenceName(RecurrenceConfiguration recurrConf){
String recurrName = "";
switch (recurrConf.getRecurrenceType()) {
case RecurrenceConfigurationRepository.TYPE_DAY:
if(recurrConf.getPeriodicity() == 1){
recurrName += I18n.get("Every day");
}
else{
recurrName += String.format(I18n.get("Every %d days"), recurrConf.getPeriodicity());
}
if(recurrConf.getEndType() == RecurrenceConfigurationRepository.END_TYPE_REPET){
recurrName += String.format(I18n.get(", %d times"), recurrConf.getRepetitionsNumber());
}
else if(recurrConf.getEndDate() != null){
recurrName += I18n.get(", until the ") + recurrConf.getEndDate().format(DATE_FORMAT);
}
break;
case RecurrenceConfigurationRepository.TYPE_WEEK:
if(recurrConf.getPeriodicity() == 1){
recurrName += I18n.get("Every week ");
}
else{
recurrName += String.format(I18n.get("Every %d weeks "), recurrConf.getPeriodicity());
}
if(recurrConf.getMonday() && recurrConf.getTuesday() && recurrConf.getWednesday() && recurrConf.getThursday() && recurrConf.getFriday()
&& !recurrConf.getSaturday() && !recurrConf.getSunday()){
recurrName += I18n.get("every week's day");
}
else if(recurrConf.getMonday() && recurrConf.getTuesday() && recurrConf.getWednesday() && recurrConf.getThursday() && recurrConf.getFriday()
&& recurrConf.getSaturday() && recurrConf.getSunday()){
recurrName += I18n.get("everyday");
}
else{
recurrName += I18n.get("on ");
if(recurrConf.getMonday()){
recurrName += I18n.get("mon,");
}
if(recurrConf.getTuesday()){
recurrName += I18n.get("tues,");
}
if(recurrConf.getWednesday()){
recurrName += I18n.get("wed,");
}
if(recurrConf.getThursday()){
recurrName += I18n.get("thur,");
}
if(recurrConf.getFriday()){
recurrName += I18n.get("fri,");
}
if(recurrConf.getSaturday()){
recurrName += I18n.get("sat,");
}
if(recurrConf.getSunday()){
recurrName += I18n.get("sun,");
}
}
if(recurrConf.getEndType() == RecurrenceConfigurationRepository.END_TYPE_REPET){
recurrName += String.format(I18n.get(" %d times"), recurrConf.getRepetitionsNumber());
}
else if(recurrConf.getEndDate() != null){
recurrName += I18n.get(" until the ") + recurrConf.getEndDate().format(DATE_FORMAT);
}
break;
case RecurrenceConfigurationRepository.TYPE_MONTH:
if(recurrConf.getPeriodicity() == 1){
recurrName += I18n.get("Every month the ") + recurrConf.getStartDate().getDayOfMonth();
}
else{
recurrName += String.format(I18n.get("Every %d months the %d"), recurrConf.getPeriodicity(), recurrConf.getStartDate().getDayOfMonth());
}
if(recurrConf.getEndType() == RecurrenceConfigurationRepository.END_TYPE_REPET){
recurrName += String.format(I18n.get(", %d times"), recurrConf.getRepetitionsNumber());
}
else if(recurrConf.getEndDate() != null){
recurrName += I18n.get(", until the ") + recurrConf.getEndDate().format(DATE_FORMAT);
}
break;
case RecurrenceConfigurationRepository.TYPE_YEAR:
if(recurrConf.getPeriodicity() == 1){
recurrName += I18n.get("Every year the ") + recurrConf.getStartDate().format(MONTH_FORMAT);
}
else{
recurrName += String.format(I18n.get("Every %d years the %s"), recurrConf.getPeriodicity(), recurrConf.getStartDate().format(MONTH_FORMAT));
}
if(recurrConf.getEndType() == RecurrenceConfigurationRepository.END_TYPE_REPET){
recurrName += String.format(I18n.get(", %d times"), recurrConf.getRepetitionsNumber());
}
else if(recurrConf.getEndDate() != null){
recurrName += I18n.get(", until the ") + recurrConf.getEndDate().format(DATE_FORMAT);
}
break;
default:
break;
}
return recurrName;
}
}
| jph-axelor/axelor-business-suite | axelor-crm/src/main/java/com/axelor/apps/crm/service/EventService.java | Java | agpl-3.0 | 35,175 |
package com.x.processplatform.assemble.designer.element.factory;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.x.processplatform.assemble.designer.AbstractFactory;
import com.x.processplatform.assemble.designer.Business;
import com.x.processplatform.core.entity.element.Embed;
import com.x.processplatform.core.entity.element.Embed_;
import com.x.processplatform.core.entity.element.FormField;
import com.x.processplatform.core.entity.element.FormField_;
public class FormFieldFactory extends AbstractFactory {
public FormFieldFactory(Business business) throws Exception {
super(business);
}
public List<String> listWithApplication(String application) throws Exception {
EntityManager em = this.entityManagerContainer().get(FormField.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<FormField> root = cq.from(FormField.class);
Predicate p = cb.equal(root.get(FormField_.application), application);
cq.select(root.get(FormField_.id)).where(p);
return em.createQuery(cq).getResultList();
}
public List<String> listWithForm(String form) throws Exception {
EntityManager em = this.entityManagerContainer().get(FormField.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<FormField> root = cq.from(FormField.class);
Predicate p = cb.equal(root.get(FormField_.form), form);
cq.select(root.get(FormField_.id)).where(p);
return em.createQuery(cq).getResultList();
}
public List<FormField> listWithFormObject(String formId) throws Exception {
EntityManager em = this.entityManagerContainer().get(FormField.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<FormField> cq = cb.createQuery(FormField.class);
Root<FormField> root = cq.from(FormField.class);
Predicate p = cb.equal(root.get(FormField_.form), formId);
cq.select(root).where(p);
return em.createQuery(cq).getResultList();
}
} | o2oa/o2oa | o2server/x_processplatform_assemble_designer/src/main/java/com/x/processplatform/assemble/designer/element/factory/FormFieldFactory.java | Java | agpl-3.0 | 2,200 |
package models;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import play.db.jpa.Model;
@Entity
@SuppressWarnings("serial")
public class ModuleRating extends Model {
@ManyToOne
public Module module;
@ManyToOne
public User owner;
public int mark;
}
| lucaswerkmeister/ceylon-herd | app/models/ModuleRating.java | Java | agpl-3.0 | 286 |
package dynagent.tools.importers.migration;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.naming.NamingException;
import javax.xml.transform.TransformerConfigurationException;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.IllegalDataException;
import org.jdom.JDOMException;
import dynagent.common.Constants;
import dynagent.common.communication.Changes;
import dynagent.common.communication.ObjectChanged;
import dynagent.common.exceptions.CardinalityExceedException;
import dynagent.common.exceptions.DataErrorException;
import dynagent.common.exceptions.FileException;
import dynagent.common.exceptions.IncoherenceInMotorException;
import dynagent.common.exceptions.IncompatibleValueException;
import dynagent.common.exceptions.NotFoundException;
import dynagent.common.exceptions.OperationNotPermitedException;
import dynagent.common.knowledge.action;
import dynagent.common.utils.QueryConstants;
import dynagent.common.utils.jdomParser;
import dynagent.common.xml.XMLTransformer;
import dynagent.migration.relational.Migrator;
import dynagent.server.dbmap.ClassInfo;
import dynagent.server.dbmap.DBQueries;
import dynagent.server.dbmap.DataBaseMap;
import dynagent.server.dbmap.NoSuchColumnException;
import dynagent.server.dbmap.PropertyInfo;
import dynagent.server.dbmap.Table;
import dynagent.server.ejb.ConnectionDB;
import dynagent.server.ejb.FactoryConnectionDB;
import dynagent.server.gestorsDB.GenerateSQL;
import dynagent.server.gestorsDB.GestorsDBConstants;
import dynagent.server.services.FactsAdapter;
import dynagent.server.services.InstanceService;
import dynagent.server.services.XMLConstants;
import dynagent.tools.importers.configxml.AuxiliarMigrator;
import dynagent.tools.importers.configxml.Menu;
import dynagent.tools.importers.owl.OWLParser;
public class ODatosAtribToXml2 {
private static boolean isAbstract(FactoryConnectionDB fcdbOrigin, int idto, ClassInfo classInfo) throws SQLException, NamingException {
boolean abstracta = false;
// String gestor = fcdbOrigin.getGestorDB();
// if (gestor.equals(GestorsDBConstants.mySQL)) {
// String sql = "select * from access where idto=" + idto + " and accesstype=" + Constants.ACCESS_ABSTRACT;
// List<List<String>> lList = DBQueries.executeQuery(fcdbOrigin, sql);
// abstracta = lList.size()>0;
// } else if (gestor.equals(GestorsDBConstants.postgreSQL)) {
abstracta = classInfo.isAbstractClass();
// }
return abstracta;
}
public static void transform(DataBaseMap dataBaseMapOrigin, DataBaseMap dataBaseMapDestination, FactoryConnectionDB fcdbOrigin, FactoryConnectionDB fcdbDestination,
HashSet<String> setRdnsNewC, HashSet<String> setRdnsDelC, HashSet<String> setRdnsNoAbsToAbs,
HashSet<String> propsStructToNoStruct, File xsltFile, OWLParser owlParserDestination,
boolean importReports, boolean importQuerys, String pathXML, boolean replica,
String nameXmlFile, String pathReport, String pathQuery, String pathImportOtherXml, String pathImportReports,
boolean insertUserAndRoles, boolean insertIndex) throws Exception {
// Modificamos la base de datos para que tenga las tablas con las que trabaja el nuevo modelo.
owlParserDestination.buildDataBase("BusinessFunctions",true,true);
InstanceService instanceServiceOrigin = Menu.setConnection(fcdbOrigin, dataBaseMapOrigin);
Set<ClassInfo> sClassInfo = dataBaseMapOrigin.getAllClasses();
HashSet<String> rdnsCPreProcesados = new HashSet<String>();
HashSet<String> rdnsCProcesados = new HashSet<String>();
//x cada clase
String pathLogFile = "C:\\DYNAGENT\\logODAToRelational.txt";
String pathDeletedLogFile = "C:\\DYNAGENT\\logDeletedODAToRelational.txt";
FileWriter f = null;
FileWriter deletedLogFile=null;
try {
//f = new FileWriter(pathLogFile);
//deletedLogFile = new FileWriter(pathDeletedLogFile);
HashMap<Integer,Integer> idoFicticioReal = new HashMap<Integer,Integer>();
HashSet<Integer> idosProcesadosEnIdtosNoProcesados = new HashSet<Integer>();
HashSet<String> systemTablesNames = Menu.getSystemTablesNames();
for (ClassInfo classInfo : sClassInfo) {
int idto = classInfo.getIdto();
String className = classInfo.getName();
if (!isAbstract(fcdbOrigin, idto, classInfo) && !setRdnsNewC.contains(className)) {
Set<ClassInfo> sClassInfoRef = dataBaseMapOrigin.getClassesReferencingClass(idto);
boolean continuar = false;
if (sClassInfoRef==null) {
continuar = true;
} else {
//solo se apunta por el mismo
boolean someDistinct = false;
for (ClassInfo classInfoRef : sClassInfoRef) {
Integer idtoClassInfoRef = classInfoRef.getIdto();
if (!idtoClassInfoRef.equals(idto)) {
someDistinct = true;
break;
}
}
if (!someDistinct)
continuar = true;
}
if (continuar) {
//obtener clases hijas e iterar x ellas
//llamar a metodo recursivo que se encarga de:
//hacer get de un nivel sobre la otra bd
//llamar a migrator sobre la nueva bd
dataTransform(f, dataBaseMapOrigin, dataBaseMapDestination, fcdbOrigin, fcdbDestination,
classInfo, idoFicticioReal, rdnsCPreProcesados, rdnsCProcesados,
systemTablesNames, setRdnsNewC, setRdnsDelC, setRdnsNoAbsToAbs,
propsStructToNoStruct, xsltFile, true, deletedLogFile);
//AuxiliarMigrator.dataMigration(f, classInfo, rdnsCPreProcesados, rdnsCProcesados, idosProcesadosEnIdtosNoProcesados, xsltFile, dataBaseMapOrigin, dataBaseMapDestination, fcdbOrigin, fcdbDestination, instanceServiceOrigin, systemTablesNames, setRdnsNewC, setRdnsDelC, setRdnsNoAbsToAbs, propsStructToNoStruct, true, deletedLogFile);
}
}
}
//importar con config
owlParserDestination.insertModelIndividuals();
owlParserDestination.insertHelp();
//importo solo configuracion
System.out.println("Antes de importar configuración");
Menu menu = new Menu();
menu.importXML(importReports, importQuerys, pathXML, replica, fcdbDestination,
nameXmlFile, insertUserAndRoles, insertIndex, pathReport, pathQuery,
pathImportOtherXml, pathImportReports);
} finally {
if(f!=null){
f.close();
}
fcdbOrigin.removeConnections();
fcdbDestination.removeConnections();
if(deletedLogFile!=null){
deletedLogFile.close();
}
}
}
private static boolean hasDatasOfIdto(FactoryConnectionDB fcdbOrigin, String tableName, int idto) throws SQLException, NamingException {
String gestor = fcdbOrigin.getGestorDB();
GenerateSQL gSQL = new GenerateSQL(gestor);
String sql = null;
if (gestor.equals(GestorsDBConstants.mySQL)) {
sql = "select * from o_datos_atrib where id_to=" + idto + " limit 1";
} else if (gestor.equals(GestorsDBConstants.postgreSQL)) {
sql = "select * from " + gSQL.getCharacterBegin() + tableName + gSQL.getCharacterEnd() + " limit 1";
}
List<List<String>> lList = DBQueries.executeQuery(fcdbOrigin, sql);
return lList.size()>0;
}
private static void dataTransform(FileWriter f, DataBaseMap dataBaseMapOrigin, DataBaseMap dataBaseMapDestination,
FactoryConnectionDB fcdbOrigin, FactoryConnectionDB fcdbDestination,
ClassInfo classInfo, HashMap<Integer,Integer> idoFicticioIdoReal,
HashSet<String> rdnsCPreProcesados, HashSet<String> rdnsCProcesados,
HashSet<String> systemTablesNames,
HashSet<String> setRdnsNewC, HashSet<String> setRdnsDelC, HashSet<String> setRdnsNoAbsToAbs, HashSet<String> propsStructToNoStruct, File xsltFile,
boolean first,FileWriter deletedLogFile) throws SQLException, NamingException, JDOMException, IOException, NotFoundException, IncoherenceInMotorException, IncompatibleValueException, CardinalityExceedException, OperationNotPermitedException, NoSuchColumnException, TransformerConfigurationException, FileException {
int idto = classInfo.getIdto();
String className = classInfo.getName();
System.out.println("classInfo->idto " + idto + ", name " + className);
String tableName = dataBaseMapOrigin.getTable(idto).getName();
System.out.println("tableName " + tableName);
rdnsCPreProcesados.add(className);
// boolean hasData = true;
// if (first) {
// //comprueba si hay datos
// hasData = hasDatasOfIdto(fcdbOrigin, tableName, idto);
// }
// if (!hasData) {
// System.out.println("No hay datos de " + className);
// } else {
//obtener clases hijas e iterar x ellas
for (Integer idto2 : classInfo.getReferencedClasses()) {
ClassInfo classInfo2 = dataBaseMapOrigin.getClass(idto2);
// boolean iterate = notInverseToIterate(classInfo, idto2, dataBaseMap);
// if (iterate) {
Set<Integer> idtosSpec = classInfo2.getChildClasses();
idtosSpec.add(idto2);
for (Integer idtoSpec : idtosSpec) {
String nameSpec=dataBaseMapOrigin.getClass(idtoSpec).getName();
if (!rdnsCPreProcesados.contains(nameSpec)) {
ClassInfo classInfoSpec = dataBaseMapOrigin.getClass(idtoSpec);
if (!isAbstract(fcdbOrigin, idtoSpec, classInfoSpec) && !setRdnsNewC.contains(classInfoSpec.getName())) {
dataTransform(f, dataBaseMapOrigin, dataBaseMapDestination, fcdbOrigin, fcdbDestination,
classInfoSpec, idoFicticioIdoReal, rdnsCPreProcesados, rdnsCProcesados,
systemTablesNames, setRdnsNewC, setRdnsDelC, setRdnsNoAbsToAbs,
propsStructToNoStruct, xsltFile, false, deletedLogFile);
}
}
}
// }
}
//migrar solo si no es del sistema
if (!systemTablesNames.contains(tableName)) {
boolean dataTransform = xsltFile!=null;
Document factDocument = constructFactsXML(dataBaseMapOrigin, fcdbOrigin, idto);
if (factDocument.getRootElement().getChildren().size()>0) {
Document resultXML = FactsAdapter.factsXMLToDataXML(dataBaseMapOrigin, factDocument);
if (dataTransform) {
System.out.println("Element antes de transformar en tools " + jdomParser.returnXML(resultXML.getRootElement()));
if(f!=null){
f.write("Element antes de transformar en tools " + jdomParser.returnXML(resultXML.getRootElement()) + "\n");
}
resultXML = XMLTransformer.getTransformedDocument(resultXML, xsltFile);
}
Document resultXMLPostProcess = postProcessXML(f, systemTablesNames, dataBaseMapOrigin,
dataBaseMapDestination, rdnsCProcesados, setRdnsDelC, setRdnsNoAbsToAbs,
resultXML.getRootElement(), propsStructToNoStruct, idoFicticioIdoReal, deletedLogFile);
rdnsCProcesados.add(className);
if (resultXMLPostProcess!=null) {
InstanceService instanceService = new InstanceService(fcdbDestination, null, false);
instanceService.setDataBaseMap(dataBaseMapDestination);
// ServerEngine serverEngine = new ServerEngine(fcdbDestination);
// instanceService.setIk(serverEngine);
DBQueries.execute(fcdbDestination, "START TRANSACTION");
Changes changes = instanceService.serverTransitionObject("migration", resultXMLPostProcess, null, null, true, false, null,true);
DBQueries.execute(fcdbDestination, "END");
ArrayList<ObjectChanged> aObjectChanged = changes.getAObjectChanged();
for (ObjectChanged objectChanged : aObjectChanged) {
Integer oldIdo = objectChanged.getOldIdo();
if (oldIdo!=null) {
int newIdo = objectChanged.getNewIdo();
idoFicticioIdoReal.put(oldIdo, QueryConstants.getTableId(newIdo));
}
}
}
} else
System.out.println("No hay datos de " + className);
factDocument = null;
}
// }
}
private static Document postProcessXML(FileWriter f, HashSet<String> systemTablesNames,
DataBaseMap dataBaseMapOrigin, DataBaseMap dataBaseMapDestination, HashSet<String> rdnsCProcesados,
HashSet<String> setRdnsDelC, HashSet<String> setRdnsNoAbsToAbs, Element data,
HashSet<String> propsStructToNoStruct, HashMap<Integer,Integer> idoFicticioIdoReal,
FileWriter deletedLogFile) throws DataErrorException, SQLException, NamingException, JDOMException, IOException {
Document docDataPostProcess = null;
Element dataPostProcess = null;
Element objectsPostProcess = null;
boolean first = true;
int contIdoNeg = -1;
Element objects = data.getChild(XMLConstants.TAG_OBJECTS);
List<Element> children = objects.getChildren();
Iterator it = children.iterator();
while (it.hasNext()) {
Element clase = (Element)it.next();
String className = clase.getName();
ClassInfo classInfo = dataBaseMapDestination.getClass(className);
if (first) {
System.out.println("Element antes de procesar en tools " + jdomParser.returnXML(data));
if(f!=null){
f.write("Element antes de procesar en tools " + jdomParser.returnXML(data) + "\n");
}
// if (setIdsDelC.contains(classInfo.getIdto())) {
if (classInfo==null || setRdnsNoAbsToAbs.contains(classInfo.getName())) {
System.out.println("ELIMINACION -> No existe la clase " + className);
if(f!=null){
f.write("ELIMINACION -> No existe la clase " + className + "\n");
}
break;
} else {
dataPostProcess = jdomParser.cloneNode(data);
objectsPostProcess = jdomParser.cloneNode(objects);
dataPostProcess.addContent(objectsPostProcess);
Set<Integer> deletedIdNodes=AuxiliarMigrator.transformTableIdOfClassAndProperties(objects,dataBaseMapOrigin,dataBaseMapDestination,deletedLogFile,objects);
AuxiliarMigrator.deleteRefNodes(objects,deletedIdNodes,deletedLogFile,dataBaseMapOrigin);
first = false;
}
}
Element clasePostProcess = jdomParser.cloneNode(clase);
//eliminar dataProperties que para esta clase no esten en el nuevo modelo
processDataProperties(f, dataBaseMapOrigin, dataBaseMapDestination, className, clase, clasePostProcess);
objectsPostProcess.addContent(clasePostProcess);
boolean firstNode = true;
postProcessXMLRec(f, systemTablesNames, dataBaseMapOrigin, dataBaseMapDestination, rdnsCProcesados,
objects, objectsPostProcess, clase, clasePostProcess, propsStructToNoStruct, firstNode, idoFicticioIdoReal, setRdnsNoAbsToAbs);
}
if (dataPostProcess!=null) {
docDataPostProcess = new Document(dataPostProcess);
//System.out.println("Element despues de procesar en tools " + jdomParser.returnXML(dataPostProcess) + "\n\n");
if(f!=null){
f.write("Element despues de procesar en tools " + jdomParser.returnXML(dataPostProcess) + "\n\n\n");
}
}
return docDataPostProcess;
}
private static void processDataProperties(FileWriter f, DataBaseMap dataBaseMapOrigin, DataBaseMap dataBaseMapDestination,
String className, Element clase, Element clasePostProcess) throws IOException {
List<Attribute> listAttr = clase.getAttributes();
for (Attribute attribute : listAttr) {
System.out.println("className " + className + ", attribute " + attribute);
String propName = attribute.getName();
boolean remove = processDataProperty(propName, dataBaseMapOrigin, dataBaseMapDestination, className);
if (remove) {
clasePostProcess.removeAttribute(propName);
System.out.println("ELIMINACION -> No existe la DP para clase " + className + ", dp " + propName);
if(f!=null){
f.write("ELIMINACION -> No existe la DP para clase " + className + ", dp " + propName + "\n");
}
}
}
}
private static boolean processDataProperty(String propName, DataBaseMap dataBaseMapOrigin, DataBaseMap dataBaseMapDestination,
String className) {
boolean remove = false;
Integer idPropOrig = dataBaseMapOrigin.getPropertyId(propName);
if (idPropOrig!=null) {
Integer idProp = dataBaseMapDestination.getPropertyId(propName);
if (idProp!=null) {
ClassInfo classInfo = dataBaseMapDestination.getClass(className);
PropertyInfo propInfo = classInfo.getProperty(idProp);
if (propInfo==null)
remove = true;
} else
remove = true;
}
return remove;
}
private static boolean existsObjectProperty(FileWriter f, DataBaseMap dataBaseMapDestination, String classNameParent, String className, String propName)
throws IOException {
boolean exists = true;
ClassInfo classInfoDomain = dataBaseMapDestination.getClass(classNameParent);
Integer idProp = dataBaseMapDestination.getPropertyId(propName);
if (idProp!=null) {
ClassInfo classInfoRange = dataBaseMapDestination.getClass(className);
if (classInfoRange!=null) {
//buscar superiores a classInfoRange
PropertyInfo propInfo = classInfoDomain.getProperty(idProp);
if (propInfo!=null) {
Set<Integer> types = propInfo.getPropertyTypes();
Set<Integer> idtoAndSuperiors = classInfoRange.getParentClasses();
idtoAndSuperiors.addAll(classInfoRange.getChildClasses());
idtoAndSuperiors.add(classInfoRange.getIdto());
boolean contains = false;
Iterator<Integer> it = idtoAndSuperiors.iterator();
while (it.hasNext() && !contains) {
Integer idtoRange = it.next();
if (types.contains(idtoRange))
contains = true;
}
if (!contains)
exists = false;
} else
exists = false;
} else
exists = false;
} else
exists = false;
if (!exists) {
System.out.println("ELIMINACION -> No existe la OP para clasePadre " + classNameParent + ", op " + propName + ", clase " + className);
if(f!=null){
f.write("ELIMINACION -> No existe la OP para clasePadre " + classNameParent + ", op " + propName + ", clase " + className + "\n");
}
}
return exists;
}
private static Integer processTableId(FileWriter f, Element clasePostProcess, int idto, HashMap<Integer,Integer> idoFicticioIdoReal) throws IOException {
Integer tableIdReturn = null;
String action = clasePostProcess.getAttributeValue(XMLConstants.ATTRIBUTE_ACTION);
if (action.equals(XMLConstants.ACTION_SET)) {
Integer tableIdFict = Integer.parseInt(clasePostProcess.getAttributeValue(XMLConstants.ATTRIBUTE_TABLEID));
if (tableIdFict<0) { //es un ido negativo, al ser un set tengo que poner el tableId
tableIdReturn = idoFicticioIdoReal.get(tableIdFict);
System.out.println("DEBUG -> en un set cambia el ido " + tableIdFict + " por " + tableIdReturn);
clasePostProcess.setAttribute(XMLConstants.ATTRIBUTE_TABLEID, String.valueOf(tableIdReturn));
} else {
tableIdReturn = tableIdFict;
}
} else if (action.equals(XMLConstants.ACTION_NEW)) {
String tableIdReturnStr = clasePostProcess.getAttributeValue(XMLConstants.ATTRIBUTE_TABLEID);
if (tableIdReturnStr!=null)
tableIdReturn = Integer.parseInt(tableIdReturnStr);
else
tableIdReturn = null;
}
return tableIdReturn;
}
private static void postProcessXMLRec(FileWriter f, HashSet<String> systemTablesNames,
DataBaseMap dataBaseMapOrigin, DataBaseMap dataBaseMapDestination,
HashSet<String> rdnsCProcesados,
Element objects, Element objectsPostProcess, Element clase, Element clasePostProcess, HashSet<String> propsStructToNoStruct, boolean firstNode,
HashMap<Integer,Integer> idoFicticioIdoReal, HashSet<String> setRdnsNoAbsToAbs)
throws DataErrorException, SQLException, NamingException, JDOMException, IOException {
//añadir action en nodos
String className = clase.getName();
ClassInfo classInfo = dataBaseMapDestination.getClass(className);
int idto = classInfo.getIdto();
if (firstNode) {
clasePostProcess.setAttribute(XMLConstants.ATTRIBUTE_ACTION, XMLConstants.ACTION_NEW);
Integer tableId = processTableId(f, clasePostProcess, idto, idoFicticioIdoReal);
if (tableId!=null) {
if (idoFicticioIdoReal.get(tableId)!=null) {
clasePostProcess.setAttribute(XMLConstants.ATTRIBUTE_ACTION, XMLConstants.ACTION_SET);
processTableId(f, clasePostProcess, idto, idoFicticioIdoReal);
}
}
} else {
ArrayList<String> namesAttr = new ArrayList<String>();
List<Attribute> lAttr = clasePostProcess.getAttributes();
for (Attribute attribute : lAttr) {
String propName = attribute.getName();
if ( !propName.equals(XMLConstants.ATTRIBUTE_ACTION) &&
!propName.equals(XMLConstants.ATTRIBUTE_IDNODE) &&
!propName.equals(XMLConstants.ATTRIBUTE_PROPERTYm) &&
!propName.equals(XMLConstants.ATTRIBUTE_TABLEID) &&
!propName.equals(Constants.PROP_RDN) &&
!propName.equals(XMLConstants.ATTRIBUTE_REFNODE))
namesAttr.add(propName);
}
for (String name : namesAttr) {
clasePostProcess.removeAttribute(name);
}
Attribute actionAttribute = clasePostProcess.getAttribute(XMLConstants.ATTRIBUTE_ACTION);
System.out.println("IDTO "+idto);
Table t=dataBaseMapDestination.getTable(idto);
Integer tableId=null;
String tableName =null;
if(t!=null){
tableName=t.getName();
tableId = processTableId(f, clasePostProcess, idto, idoFicticioIdoReal);
}
if (tableId!=null) {
if (systemTablesNames.contains(tableName) || rdnsCProcesados.contains(className) || idoFicticioIdoReal.get(tableId)!=null) {
if(tableId>0 || idoFicticioIdoReal.get(tableId)!=null){
clasePostProcess.setAttribute(XMLConstants.ATTRIBUTE_ACTION, XMLConstants.ACTION_SET);
}else{
clasePostProcess.setAttribute(XMLConstants.ATTRIBUTE_ACTION, XMLConstants.ACTION_NEW);
}
processTableId(f, clasePostProcess, idto, idoFicticioIdoReal);
} else {
clasePostProcess.setAttribute(XMLConstants.ATTRIBUTE_ACTION, XMLConstants.ACTION_NEW);
String property = clasePostProcess.getAttributeValue(XMLConstants.ATTRIBUTE_PROPERTYm);
if (propsStructToNoStruct.contains(property)) {
clasePostProcess.setAttribute(Constants.PROP_RDN, Constants.DEFAULT_RDN_CHAR + tableId + Constants.DEFAULT_RDN_CHAR);
}
}
}else{
String rdn = clasePostProcess.getAttributeValue(Constants.PROP_RDN);
String action = actionAttribute.getValue();
System.out.println("ACTION "+action);
if (rdn!=null&&!action.equals(XMLConstants.ACTION_NEW)) {
//buscar en bd a que tableId corresponde ese rdn
Integer ido=InstanceService.getIdo(dataBaseMapDestination.getFactoryConnectionDB(), dataBaseMapDestination, idto, rdn, false);
if (ido!=null) {
Integer tableIdDB = QueryConstants.getTableId(ido);
System.out.println("TABLE DE RDN "+tableIdDB);
if(action.equals(XMLConstants.ACTION_CREATE_IF_NOT_EXIST)) actionAttribute.setValue(XMLConstants.ACTION_SET);
clasePostProcess.setAttribute(XMLConstants.ATTRIBUTE_TABLEID, String.valueOf(tableIdDB));
clasePostProcess.removeAttribute(Constants.PROP_RDN);
} else {
/*
if(action.equals(XMLConstants.ACTION_CREATE_IF_NOT_EXIST)) actionAttribute.setValue(XMLConstants.ACTION_NEW);
clasePostProcess.setAttribute(XMLConstants.ATTRIBUTE_TABLEID, String.valueOf(contIdoNeg));
if(rdn.equals("tableId")) clasePostProcess.setAttribute(Constants.PROP_RDN, "&id"+contIdoNeg+"&");
contIdoNeg--;
*/
throw new DataErrorException("Nodo " + className + " con operation "+ action + " y rdn "+rdn+" no existe en base de datos");
}
}
}
}
//if (firstNode) { //solo quiero 1 nivel
//iterar por los hijos
Iterator it = clase.getChildren().iterator();
while (it.hasNext()) {
Element claseChild = (Element)it.next();
String claseChildName = claseChild.getName();
if (claseChildName.equals(XMLConstants.TAG_MEMO) ||
claseChildName.equals(XMLConstants.TAG_DATA_PROPERTY)) {
String propName = claseChild.getAttributeValue(XMLConstants.ATTRIBUTE_PROPERTYm);
boolean remove = processDataProperty(propName, dataBaseMapOrigin, dataBaseMapDestination, className);
if (!remove) {
Element claseChildPostProcess = jdomParser.cloneNode(claseChild);
if (claseChildName.equals(XMLConstants.TAG_DATA_PROPERTY))
claseChildPostProcess.setAttribute(XMLConstants.ATTRIBUTE_ACTION, XMLConstants.ACTION_NEW);
else if (claseChildName.equals(XMLConstants.TAG_MEMO)) {
Iterator it2 = claseChild.getChildren().iterator();
while (it2.hasNext()) {
Element childMemo = (Element)it2.next();
Element childMemoPostProcess = jdomParser.cloneNode(childMemo);
claseChildPostProcess.addContent(childMemoPostProcess);
}
}
clasePostProcess.addContent(claseChildPostProcess);
}
} else {
ClassInfo classInfoChild = dataBaseMapDestination.getClass(claseChildName);
//si es nulo es xq no está en la base de datos con el nuevo modelo, no se ha transformado
boolean eliminacion = true;
if (classInfoChild!=null) {
int idtoChild = classInfoChild.getIdto();
String nameChild = classInfoChild.getName();
if (!setRdnsNoAbsToAbs.contains(nameChild)) {
eliminacion = false;
if (existsObjectProperty(f, dataBaseMapDestination, className, claseChildName, claseChild.getAttributeValue(XMLConstants.ATTRIBUTE_PROPERTYm))) {
Element claseChildPostProcess = jdomParser.cloneNode(claseChild);
//eliminar dataProperties que para esta clase no esten en el nuevo modelo
processDataProperties(f, dataBaseMapOrigin, dataBaseMapDestination, claseChildName, claseChild, claseChildPostProcess);
clasePostProcess.addContent(claseChildPostProcess);
postProcessXMLRec(f, systemTablesNames, dataBaseMapOrigin, dataBaseMapDestination, rdnsCProcesados,
objects, objectsPostProcess, claseChild, claseChildPostProcess, propsStructToNoStruct, false, idoFicticioIdoReal, setRdnsNoAbsToAbs);
}
}
} else
classInfoChild = dataBaseMapOrigin.getClass(claseChildName);
if (eliminacion) {
System.out.println("ELIMINACION -> No existe la clase " + claseChildName);
if(f!=null){
f.write("ELIMINACION -> No existe la clase " + claseChildName + "\n");
}
}
}
}
// }
}
private static void printTimeResults(long beginTime, long mapConstructTime, long beginTimeTransform,
long timeAfterFactConstruct, long timeForTraduction, long endTime) {
float mapTime = (mapConstructTime - beginTime) / 1000.0F;
float factTime = (timeAfterFactConstruct - beginTimeTransform) / 1000.0F;
float traductionTime = (timeForTraduction - timeAfterFactConstruct) / 1000.0F;
float writeFileTime = (endTime - timeForTraduction) / 1000.0F;
float totalTime = (endTime - beginTime) / 1000.0F;
System.out.println("Se ha tardado " + totalTime + " segundos en todo el proceso");
System.out.println("\tSe ha tardado " + mapTime + " segundos en construir el mapeo de la base de datos");
System.out.println("\tSe ha tardado " + factTime + " segundos en traducir o_datos_atrib al XML de Facts");
System.out.println("\tSe ha tardado " + traductionTime + " segundos en traducir el XML de Facts al nuevo modelo de XML");
System.out.println("\tSe ha tardado " + writeFileTime + " en construir el fichero resultante del XML del nuevo modelo");
}
private static Document constructFactsXML(DataBaseMap dataBaseMap, FactoryConnectionDB fcdb, int idto) {
Element factsRootElement = new Element("FACTS");
Document factsDocument = new Document(factsRootElement);
constructFactsODAXML(dataBaseMap, fcdb, idto, factsRootElement);
constructFactsODAMXML(dataBaseMap, fcdb, idto, factsRootElement);
return factsDocument;
}
private static void constructFactsODAXML(DataBaseMap dataBaseMap, FactoryConnectionDB fcdb, int idto, Element factsRootElement) {
String sqlGetODatosAtrib = "SELECT DISTINCT ID_TO, ID_O, PROPERTY, VAL_NUM, VAL_TEXTO, VALUE_CLS, Q_MAX, DESTINATION FROM o_datos_atrib " +
"WHERE id_to =" + idto;
ConnectionDB connectionDB = fcdb.createConnection(true);
Statement statement = null;
ResultSet resultSet = null;
try {
statement = connectionDB.getBusinessConn().createStatement();
statement.setFetchSize(100);
resultSet = statement.executeQuery(sqlGetODatosAtrib);
while (resultSet.next()) {
Integer ido = resultSet.getInt(2);
if (resultSet.wasNull()) {
ido = null;
}
Integer property = resultSet.getInt(3);
if (resultSet.wasNull()) {
property = null;
}
Integer valNum = resultSet.getInt(4);
if (resultSet.wasNull()) {
valNum = null;
}
String valText = resultSet.getString(5);
if (resultSet.wasNull()) {
valText = null;
}
Integer valueCls = resultSet.getInt(6);
if (resultSet.wasNull()) {
valueCls = null;
}
Double qMax = resultSet.getDouble(7);
if (resultSet.wasNull()) {
qMax = null;
}
if (valNum == null && valText == null && qMax == null){
// Entrada que solo tiene system value y que de momento vamos a ignorar.
continue;
}
String destination = resultSet.getString(8);
Element newElement = constructFactElement(ido, idto, property, valNum, valText, valueCls, qMax, destination, dataBaseMap, fcdb);
factsRootElement.addContent(newElement);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private static void constructFactsODAMXML(DataBaseMap dataBaseMap, FactoryConnectionDB fcdb, int idto, Element factsRootElement) {
String sqlGetODatosAtrib = "SELECT DISTINCT ID_TO, ID_O, PROPERTY, MEMO, VALUE_CLS, DESTINATION FROM o_datos_atrib_memo " +
"WHERE id_to =" + idto;
ConnectionDB connectionDB = fcdb.createConnection(true);
Statement statement = null;
ResultSet resultSet = null;
try {
statement = connectionDB.getBusinessConn().createStatement();
statement.setFetchSize(100);
resultSet = statement.executeQuery(sqlGetODatosAtrib);
while (resultSet.next()) {
Integer ido = resultSet.getInt(2);
if (resultSet.wasNull()) {
ido = null;
}
Integer property = resultSet.getInt(3);
if (resultSet.wasNull()) {
property = null;
}
String memo = resultSet.getString(4);
if (resultSet.wasNull()) {
memo = null;
}
Integer valueCls = resultSet.getInt(5);
if (resultSet.wasNull()) {
valueCls = null;
}
if (memo == null){
// Entrada que solo tiene system value y que de momento vamos a ignorar.
continue;
}
String destination = resultSet.getString(6);
Element newElement = constructFactElement(ido, idto, property, null, memo, valueCls, null, destination, dataBaseMap, fcdb);
factsRootElement.addContent(newElement);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private static Element constructFactElement(Integer ido, Integer idto, Integer property, Integer valNum,
String valText, Integer valueCls, Double qMax, String destination, DataBaseMap dataBaseMap, FactoryConnectionDB fcdb) {
Element factElement = new Element("FACT");
Element newFactElement = new Element("NEW_FACT");
factElement.addContent(newFactElement);
newFactElement.setAttribute(new Attribute("IDO", "-" + ido.toString()));
newFactElement.setAttribute(new Attribute("IDTO", idto.toString()));
newFactElement.setAttribute(new Attribute("PROP", property.toString()));
newFactElement.setAttribute(new Attribute("VALUECLS", valueCls.toString()));
newFactElement.setAttribute(new Attribute("ORDER", String.valueOf(action.NEW)));
if (destination != null && ! destination.isEmpty()){
newFactElement.setAttribute(new Attribute("DESTINATION_SYSTEM", destination));
}
if (qMax != null) {
newFactElement.setAttribute(new Attribute("QMAX", qMax.toString()));
} else {
String content;
if (valNum != null) {
content = "-" + valNum.toString();
if (valText!=null)
newFactElement.setAttribute(new Attribute("RDNVALUE", valText));
} else {
content = valText;
}
try {
// Esto se hace porque las contraseñas no se pueden añadir tal y como vienen de base de datos, hay que
// desencriptarlas
newFactElement.addContent(content);
} catch (IllegalDataException e) {
GenerateSQL generateSQL = new GenerateSQL(fcdb.getGestorDB());
String sqlDecrypt = "select " + generateSQL.getDecryptFunction("dynamicIntelligent", "'" + content + "'");
ConnectionDB connectionDB = fcdb.createConnection(true);
Statement statement = null;
ResultSet resultSet = null;
try {
statement = connectionDB.getBusinessConn().createStatement();
resultSet = statement.executeQuery(sqlDecrypt);
while (resultSet.next()) {
content = generateSQL.getDecryptData(resultSet, 1);
}
} catch (SQLException e1) {
e1.printStackTrace();
} catch (NamingException e1) {
e1.printStackTrace();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
newFactElement.addContent(content);
}
}
return factElement;
}
}
| semantic-web-software/dynagent | Tools/src/dynagent/tools/importers/migration/ODatosAtribToXml2.java | Java | agpl-3.0 | 33,673 |
/*
* Copyright (c) 2006-2009 by Dirk Riehle, http://dirkriehle.com
*
* This file is part of the Wahlzeit photo rating application.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.wahlzeit.model;
import com.google.api.client.util.ArrayMap;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.images.Image;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Ignore;
import com.googlecode.objectify.annotation.Parent;
import org.wahlzeit.services.DataObject;
import org.wahlzeit.services.EmailAddress;
import org.wahlzeit.services.Language;
import org.wahlzeit.services.ObjectManager;
import org.wahlzeit.utils.PatternInstance;
import java.util.Map;
/**
* A photo represents a user-provided (uploaded) photo.
*
*/
@Entity
public class Photo extends DataObject {
/**
*
*/
public static final String IMAGE = "image";
public static final String THUMB = "thumb";
public static final String LINK = "link";
public static final String PRAISE = "praise";
public static final String NO_VOTES = "noVotes";
public static final String CAPTION = "caption";
public static final String DESCRIPTION = "description";
public static final String KEYWORDS = "keywords";
public static final String TAGS = "tags";
public static final String OWNER_ID = "ownerId";
public static final String STATUS = "status";
public static final String IS_INVISIBLE = "isInvisible";
public static final String UPLOADED_ON = "uploadedOn";
/**
*
*/
public static final int MAX_PHOTO_WIDTH = 420;
public static final int MAX_PHOTO_HEIGHT = 600;
public static final int MAX_THUMB_PHOTO_WIDTH = 105;
public static final int MAX_THUMB_PHOTO_HEIGHT = 150;
protected PhotoId id = null;
/**
*
*/
protected String ownerId;
/**
* specific location of a Photo
*/
private Location location;
/**
* Each photo can be viewed in different sizes (XS, S, M, L, XL)
* Images are pre-computed in these sizes to optimize bandwidth when requested.
*/
@Ignore
transient protected Map<PhotoSize, Image> images = new ArrayMap<PhotoSize, Image>();
/**
*
*/
protected boolean ownerNotifyAboutPraise = false;
protected EmailAddress ownerEmailAddress = EmailAddress.EMPTY;
protected Language ownerLanguage = Language.ENGLISH;
/**
*
*/
protected int width;
protected int height;
protected PhotoSize maxPhotoSize = PhotoSize.MEDIUM; // derived
/**
*
*/
protected Tags tags = Tags.EMPTY_TAGS;
/**
*
*/
protected PhotoStatus status = PhotoStatus.VISIBLE;
/**
*
*/
protected int praiseSum = 10;
protected int noVotes = 1;
protected int noVotesAtLastNotification = 1;
/**
*
*/
protected long creationTime = System.currentTimeMillis();
/**
* The default type is jpg
*/
protected String ending = "jpg";
/**
*
*/
//TODO: change it to a single long
@Id
Long idLong;
@Parent
Key parent = ObjectManager.applicationRootKey;
/**
*
*/
public Photo() {
id = PhotoId.getNextId();
incWriteCount();
}
/**
* @methodtype constructor
*/
public Photo(PhotoId myId) {
id = myId;
incWriteCount();
}
/**
* @methodtype get
*/
public Location getLocation(){
return this.location;
}
/**
* @methodtype get
*/
public Image getImage(PhotoSize photoSize) {
return images.get(photoSize);
}
/**
* @methodtype set
*/
public void setImage(PhotoSize photoSize, Image image) {
this.images.put(photoSize, image);
}
/**
* @methodtype get
*/
public String getIdAsString() {
return id.asString();
}
/**
* @methodtype get
*/
public PhotoId getId() {
return id;
}
/**
* @methodtype get
*/
public String getOwnerId() {
return ownerId;
}
/**
* @methodtype set
*/
public void setOwnerId(String newName) {
ownerId = newName;
incWriteCount();
}
/**
* @methodtype get
*/
public String getSummary(ModelConfig cfg) {
return cfg.asPhotoSummary(ownerId);
}
/**
* @methodtype get
*/
public String getCaption(ModelConfig cfg) {
String ownerName = UserManager.getInstance().getUserById(ownerId).getNickName();
return cfg.asPhotoCaption(ownerName);
}
/**
* @methodtype get
*/
public boolean getOwnerNotifyAboutPraise() {
return ownerNotifyAboutPraise;
}
/**
* @methodtype set
*/
public void setOwnerNotifyAboutPraise(boolean newNotifyAboutPraise) {
ownerNotifyAboutPraise = newNotifyAboutPraise;
incWriteCount();
}
/**
*
*/
public Language getOwnerLanguage() {
return ownerLanguage;
}
/**
*
*/
public void setOwnerLanguage(Language newLanguage) {
ownerLanguage = newLanguage;
incWriteCount();
}
/**
* @methodtype boolean-query
*/
public boolean hasSameOwner(Photo photo) {
return photo.getOwnerEmailAddress().equals(ownerEmailAddress);
}
/**
* @methodtype get
*/
public EmailAddress getOwnerEmailAddress() {
return ownerEmailAddress;
}
/**
* @methodtype set
*/
public void setOwnerEmailAddress(EmailAddress newEmailAddress) {
ownerEmailAddress = newEmailAddress;
incWriteCount();
}
/**
* @methodtype get
*/
public int getWidth() {
return width;
}
/**
* @methodtype get
*/
public int getHeight() {
return height;
}
/**
* @methodtype get
*/
public int getThumbWidth() {
return isWiderThanHigher() ? MAX_THUMB_PHOTO_WIDTH : (width * MAX_THUMB_PHOTO_HEIGHT / height);
}
/**
* @methodtype boolean-query
*/
public boolean isWiderThanHigher() {
return (height * MAX_PHOTO_WIDTH) < (width * MAX_PHOTO_HEIGHT);
}
/**
* @methodtype get
*/
public int getThumbHeight() {
return isWiderThanHigher() ? (height * MAX_THUMB_PHOTO_WIDTH / width) : MAX_THUMB_PHOTO_HEIGHT;
}
/**
* @methodtype set
*/
public void setWidthAndHeight(int newWidth, int newHeight) {
width = newWidth;
height = newHeight;
maxPhotoSize = PhotoSize.getFromWidthHeight(width, height);
incWriteCount();
}
/**
* Can this photo satisfy provided photo size?
*
* @methodtype boolean-query
*/
public boolean hasPhotoSize(PhotoSize size) {
return maxPhotoSize.asInt() >= size.asInt();
}
/**
* @methodtype get
*/
public PhotoSize getMaxPhotoSize() {
return maxPhotoSize;
}
/**
* @methodtype get
*/
public String getPraiseAsString(ModelConfig cfg) {
return cfg.asPraiseString(getPraise());
}
/**
* @methodtype get
*/
public double getPraise() {
return (double) praiseSum / noVotes;
}
/**
*
*/
public void addToPraise(int value) {
praiseSum += value;
noVotes += 1;
incWriteCount();
}
/**
* @methodtype boolean-query
*/
public boolean isVisible() {
return status.isDisplayable();
}
/**
* @methodtype get
*/
public PhotoStatus getStatus() {
return status;
}
/**
* @methodtype set
*/
public void setStatus(PhotoStatus newStatus) {
status = newStatus;
incWriteCount();
}
/**
* @methodtype boolean-query
*/
public boolean hasTag(String tag) {
return tags.hasTag(tag);
}
/**
* @methodtype get
*/
public Tags getTags() {
return tags;
}
/**
* @methodtype set
*/
public void setTags(Tags newTags) {
tags = newTags;
incWriteCount();
}
/**
* @methodtype get
*/
public long getCreationTime() {
return creationTime;
}
public String getEnding() {
return ending;
}
public void setEnding(String ending) {
this.ending = ending;
}
/**
* @methodtype boolean query
*/
public boolean hasNewPraise() {
return noVotes > noVotesAtLastNotification;
}
/**
* @methodtype set
*/
public void setNoNewPraise() {
noVotesAtLastNotification = noVotes;
incWriteCount();
}
}
| GregorFendt/wahlzeit | src/main/java/org/wahlzeit/model/Photo.java | Java | agpl-3.0 | 8,282 |
/*
* StuReSy - Student Response System
* Copyright (C) 2012-2014 StuReSy-Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sturesy.core.ui.loaddialog;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import sturesy.core.backend.filter.filechooser.XMLFileFilter;
import sturesy.core.ui.loaddialog.ui.LoadDialogUI;
/**
* The load dialog provides handling for file loading. It provides two methods
* for loading. The first method is to load internal files. For this a internal
* directory is needed. The files will be allocated by two lists. The first list
* is the directory and the second list is the filename+type. The second method
* is external file loading. It provides a FileChooser which shown files and
* directories can be subsetted by a FileFilter. If more possibilities for
* loading are needed an external button can be injected, but the client has two
* handle ui interactions for this button The Northpanel is free and there can
* be injected any component
*
* @author jens.dallmann
*
*/
public class LoadDialog extends LoadDialogObservable implements SelectedDirectorySource
{
/**
* The button bar for the load buttons
*/
private LoadButtonBar _loadButtonBar;
/**
* the subsetted j list pair
*/
private final TreeListPair _treeListPair;
/**
* Internal directory path which points to the directories shown in the left
* list
*/
private final String _internalDirectoryPath;
/**
* the ui for the load dialog to layout the elements and provide user
* interaction
*/
private LoadDialogUI _loadDialogUI;
/**
* Initialize the load dialog with an internal directory path and a title.
* The default filefilter is a XMLFileFilter which subsets to .xml files and
* directories in the external filechoser
*
* @param internalDirectoryPath
* @param title
*/
public LoadDialog(String internalDirectoryPath, String title)
{
this(internalDirectoryPath, title, new XMLFileFilter());
}
/**
* Initialize the load dialog with an internal directory path, a title and a
* file filter
*
* @param internalDirectoryPath
* @param title
* @param filter
*/
public LoadDialog(String internalDirectoryPath, String title, FileFilter filter)
{
_internalDirectoryPath = internalDirectoryPath;
_loadButtonBar = new LoadButtonBar(this, filter);
_treeListPair = new TreeListPair();
_loadDialogUI = new LoadDialogUI(title, null, _treeListPair.getPanel(), _loadButtonBar.getButtonBar());
registerLoadListener();
}
/**
* Initialize the load dialog with an internal directory path, a title, a
* file filter, the ui and the two components displayed in the laod dialog
* by default.
*
* @param internalDirectoryPath
* @param ui
* @param loadbuttonbar
* @param listpair
*/
public LoadDialog(String internalDirectoryPath, LoadDialogUI ui, LoadButtonBar loadButtonBar,
TreeListPair treelistPair)
{
_internalDirectoryPath = internalDirectoryPath;
_loadButtonBar = loadButtonBar;
_treeListPair = treelistPair;
_loadDialogUI = ui;
registerLoadListener();
}
/**
* overwrite the old file filter with a new one
*
* @param filter
*/
public void setFileFilter(FileFilter filter)
{
_loadButtonBar.setFileFilter(filter);
}
/**
* replace the northern panel with a passed panel
*
* @param panel
*/
public void replaceNorthernPanel(JPanel panel)
{
_loadDialogUI.replaceNorthPanel(panel);
}
private void registerLoadListener()
{
_treeListPair.registerListener(new SubsettedListPairListener()
{
@Override
public void subsettedListKeyEvent(int keyCode)
{
if (keyCode == KeyEvent.VK_ENTER)
{
loadInternalFile();
}
}
@Override
public void subsetSourceListKeyEvent(int keyCode)
{
if (keyCode == KeyEvent.VK_ENTER)
{
loadInternalFile();
}
}
@Override
public void subsetSourceListChanged(boolean valueIsAdjusting)
{
if (valueIsAdjusting)
{
String newSubsetSourceListValue = getDirectoryAbsolutePath();
if (newSubsetSourceListValue != null && newSubsetSourceListValue.length() > 0)
{
File subsetSourceDirectory = new File(newSubsetSourceListValue);
informSubsetSourceListChanged(subsetSourceDirectory);
}
}
setNewInternalLoadButtonState();
}
});
_loadButtonBar.registerListener(new LoadButtonBarListener()
{
@Override
public void loadedInternalFile(File f)
{
loadInternalFile(f);
}
@Override
public void loadedExternalFile(File file)
{
externalFileLoaded(file);
}
});
}
/**
* sets the internal load button state to enabled or disabled
*/
private void setNewInternalLoadButtonState()
{
_loadButtonBar.setInternalLoadButtonEnabled(isInternalLoadButtonEnabled());
}
/**
* returns if the load button for internal files is enabled. the internal
* load button is enabled if in both list one entry is selected. Else it
* returns false.
*
* @return hasSelectedEntries of subsettedListPair
*/
private boolean isInternalLoadButtonEnabled()
{
return _treeListPair.hasSelectedEntries();
}
/**
* informs that an external file has been loaded and closes the dialog
*
* @param file
*/
private void externalFileLoaded(File file)
{
informExternalFileLoaded(file);
_loadDialogUI.closeDialog();
}
/**
* informs that an internal file has been loaded and closes the dialog
*
* @param file
*/
private void loadInternalFile(File file)
{
informInternalFileLoaded(file);
_loadDialogUI.closeDialog();
}
@Override
public String getFileName()
{
return _treeListPair.getContentListItem();
}
@Override
public String getDirectoryAbsolutePath()
{
return _treeListPair.getSourceListElement();
}
/**
* show the dialog
*/
public void show()
{
_loadDialogUI.showDialog();
}
/**
* sets new content for the subset source list.
*
* @param rootNode
*/
public void setNewSourceListContent(String rootNode)
{
_treeListPair.setNewSourceListContent(rootNode);
setNewInternalLoadButtonState();
}
/**
* sets the new content for the subsetted list.
*
* @param newContent
*/
public void setNewContentListContent(List<String> newContent)
{
_treeListPair.setNewContentListContent(newContent);
setNewInternalLoadButtonState();
}
/**
* shows an error message on the screen
*
* @param resourceKey
*/
public void showErrorMessage(String resourceKey)
{
_loadDialogUI.showErrorMessage(resourceKey);
}
/**
* closes the dialog
*/
public void closeDialog()
{
_loadDialogUI.closeDialog();
}
public void loadInternalFile()
{
if (isInternalLoadButtonEnabled())
{
_loadButtonBar.loadInternalFile();
}
setNewInternalLoadButtonState();
}
/**
* adds an extra button on the first position
*
* @param extraButton
*/
public void addExtraButton(JButton extraButton)
{
_loadButtonBar.addExtraButtonOnFirstPosition(extraButton);
}
/**
* sets if the load dialog should be modal or not
*
* @param isModal
*/
public void setModal(boolean isModal)
{
_loadDialogUI.setModal(isModal);
}
}
| sturesy/client | src/src-main/sturesy/core/ui/loaddialog/LoadDialog.java | Java | agpl-3.0 | 9,396 |
/**
* Copyright (C) 2009-2014 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cn.dlb.bim.models.ifc2x3tc1.impl;
import org.eclipse.emf.ecore.EClass;
import cn.dlb.bim.models.ifc2x3tc1.Ifc2x3tc1Package;
import cn.dlb.bim.models.ifc2x3tc1.IfcFaceOuterBound;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Ifc Face Outer Bound</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class IfcFaceOuterBoundImpl extends IfcFaceBoundImpl implements IfcFaceOuterBound {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IfcFaceOuterBoundImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Ifc2x3tc1Package.Literals.IFC_FACE_OUTER_BOUND;
}
} //IfcFaceOuterBoundImpl
| shenan4321/BIMplatform | generated/cn/dlb/bim/models/ifc2x3tc1/impl/IfcFaceOuterBoundImpl.java | Java | agpl-3.0 | 1,503 |
/**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.management;
public interface Cache
{
final String NAME = "Cache";
String getCacheType();
int getNodeCacheSize();
int getRelationshipCacheSize();
void clear();
}
| dmontag/graphdb-traversal-context | management/src/main/java/org/neo4j/management/Cache.java | Java | agpl-3.0 | 1,021 |
package it.unitn.disi.smatch.matchers.structure.tree.spsm.ted.data.impl;
/**
* Implements a tuple (a pair of objects). One object occurs on
* the left and the other object on the right.
*/
public class GenericTuple<E> {
private E left;
private E right;
/**
* Constructor.
* <p/>
* Takes the left and the right object of this object tuple.
*
* @param left the left object
* @param right the right object
*/
public GenericTuple(E left, E right) {
this.left = left;
this.right = right;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof GenericTuple)) return false;
GenericTuple that = (GenericTuple) o;
if (left != null ? !left.equals(that.left) : that.left != null) return false;
if (right != null ? !right.equals(that.right) : that.right != null) return false;
return true;
}
@Override
public int hashCode() {
int result = left != null ? left.hashCode() : 0;
result = 31 * result + (right != null ? right.hashCode() : 0);
return result;
}
public String toString() {
return getLeft().toString() + ":" + getRight().toString();
}
/**
* Return the left object.
*
* @return left object.
*/
public E getLeft() {
return left;
}
/**
* Return the right object.
*
* @return right object
*/
public E getRight() {
return right;
}
}
| opendatatrentino/s-match | src/main/java/it/unitn/disi/smatch/matchers/structure/tree/spsm/ted/data/impl/GenericTuple.java | Java | lgpl-2.1 | 1,608 |
package net.minecraftforge.gradle.patcher;
import net.minecraftforge.gradle.common.Constants;
final class PatcherConstants
{
// @formatter:off
private PatcherConstants() {}
// @formatter:on
// installer stuff
static final String REPLACE_INSTALLER = "{INSTALLER}";
static final String INSTALLER_URL = "http://files.minecraftforge.net/installer/forge-installer-" + REPLACE_INSTALLER + "-shrunk.jar";
// new project defaults
static final String DEFAULT_PATCHES_DIR = "patches";
static final String DEFAULT_SRC_DIR = "src/main/java";
static final String DEFAULT_RES_DIR = "src/main/resources";
static final String DEFAULT_TEST_SRC_DIR = "src/test/java";
static final String DEFAULT_TEST_RES_DIR = "src/test/resources";
// constants for paths in the workspace dir
static final String DIR_EXTRACTED_SRC = "/src/main/java";
static final String DIR_EXTRACTED_RES = "/src/main/resources";
static final String DIR_EXTRACTED_START = "/src/main/start";
static final String REPLACE_PROJECT_NAME = "{NAME}";
static final String REPLACE_PROJECT_CAP_NAME = "{CAPNAME}";
// the only actually cached thing
static final String DEOBF_DATA = Constants.DIR_MCP_DATA + "/deobfuscation_data-" + Constants.REPLACE_MC_VERSION + ".lzma";
// cached stuff
static final String DIR_LOCAL_CACHE = Constants.REPLACE_BUILD_DIR + "/localCache";
static final String JAR_DEOBF = DIR_LOCAL_CACHE + "/deobfuscated.jar";
static final String JAR_DECOMP = DIR_LOCAL_CACHE + "/decompiled.zip";
static final String JAR_DECOMP_POST = DIR_LOCAL_CACHE + "/decompiled-processed.zip";
static final String JAR_REMAPPED = DIR_LOCAL_CACHE + "/remapped-clean.zip";
// cached project stuff
static final String DIR_PROJECT_CACHE = DIR_LOCAL_CACHE + "/" + REPLACE_PROJECT_CAP_NAME;
static final String JAR_PROJECT_PATCHED = DIR_PROJECT_CACHE + "/patched.zip";
static final String JAR_PROJECT_RECOMPILED = DIR_PROJECT_CACHE + "/recompiled.jar";
static final String JAR_PROJECT_REMAPPED = DIR_PROJECT_CACHE + "/mcp-named.zip";
static final String JAR_PROJECT_RETROMAPPED = DIR_PROJECT_CACHE + "/retromapped-mc.zip";
static final String JAR_PROJECT_RETRO_NONMC = DIR_PROJECT_CACHE + "/retromapped-nonMc.zip";
static final String RANGEMAP_PROJECT = DIR_PROJECT_CACHE + "/rangemap.txt";
static final String EXC_PROJECT = DIR_PROJECT_CACHE + "/extracted.exc";
// stuff for packaging only
static final String DIR_OUTPUT = "build/distributions";
static final String DIR_PACKAGING = DIR_LOCAL_CACHE + "/packaging";
static final String JAR_INSTALLER = DIR_PACKAGING + "/installer-fresh.jar";
static final String JAR_OBFUSCATED = DIR_PACKAGING + "/reobfuscated.jar";
static final String BINPATCH_RUN = DIR_PACKAGING + "/binpatches.pack.lzma";
static final String JSON_INSTALLER = DIR_PACKAGING + "/install_profile.json";
static final String JSON_UNIVERSAL = DIR_PACKAGING + "/version.json";
static final String DIR_USERDEV_PATCHES = DIR_PACKAGING + "/userdevPatches";
static final String DIR_USERDEV = DIR_PACKAGING + "/userdev";
static final String ZIP_USERDEV_PATCHES = DIR_USERDEV + "/patches.zip";
static final String ZIP_USERDEV_SOURCES = DIR_USERDEV + "/sources.zip";
static final String ZIP_USERDEV_RES = DIR_USERDEV + "/resources.zip";
static final String BINPATCH_DEV = DIR_USERDEV + "/devbinpatches.pack.lzma";
static final String JAR_OBF_CLASSES = DIR_USERDEV + "/classes.jar";
static final String SRG_MERGED_USERDEV = DIR_USERDEV + "/merged.srg";
static final String EXC_MERGED_USERDEV = DIR_USERDEV + "/merged.exc";
static final String AT_MERGED_USERDEV = DIR_USERDEV + "/merged_at.cfg";
// top level tasks
static final String TASK_SETUP = "setup";
static final String TASK_CLEAN = "clean";
static final String TASK_GEN_PATCHES = "genPatches";
static final String TASK_BUILD = "build";
// internal tasks
static final String TASK_SETUP_PROJECTS = "setupProjects";
static final String TASK_DEOBF = "deobfuscateJar";
static final String TASK_DECOMP = "decompileJar";
static final String TASK_POST_DECOMP = "sourceProcessJar";
static final String TASK_GEN_PROJECTS = "genGradleProjects";
static final String TASK_GEN_IDES = "genIdeProjects";
// packaging tasks
static final String TASK_REOBFUSCATE = "reobfuscate";
static final String TASK_GEN_BIN_PATCHES = "genBinaryPatches";
static final String TASK_EXTRACT_OBF_CLASSES = "extractNonMcClasses";
static final String TASK_PROCESS_JSON = "processJson";
static final String TASK_OUTPUT_JAR = "outputJar";
static final String TASK_GEN_PATCHES_USERDEV = "genUserdevPatches";
static final String TASK_PATCHES_USERDEV = "packagedUserdevPatches";
static final String TASK_EXTRACT_OBF_SOURCES = "extractNonMcSources";
static final String TASK_COMBINE_RESOURCES = "combineResources";
static final String TASK_MERGE_FILES = "mergeFiles";
static final String TASK_BUILD_USERDEV = "buildUserdev";
static final String TASK_BUILD_INSTALLER = "installer";
// project tasks
static final String TASK_PROJECT_SETUP = "setupProject" + REPLACE_PROJECT_CAP_NAME;
static final String TASK_PROJECT_SETUP_DEV = "setupDevProject" + REPLACE_PROJECT_CAP_NAME;
static final String TASK_PROJECT_PATCH = "patch" + REPLACE_PROJECT_CAP_NAME + "Jar";
static final String TASK_PROJECT_REMAP_JAR = "remap" + REPLACE_PROJECT_CAP_NAME + "Jar";
static final String TASK_PROJECT_EXTRACT_SRC = "extract" + REPLACE_PROJECT_CAP_NAME + "Sources";
static final String TASK_PROJECT_EXTRACT_RES = "extract" + REPLACE_PROJECT_CAP_NAME + "Resources";
static final String TASK_PROJECT_MAKE_START = "make" + REPLACE_PROJECT_CAP_NAME + "Start";
static final String TASK_PROJECT_RUNE_CLIENT = "makeEclipse" + REPLACE_PROJECT_CAP_NAME + "RunClient";
static final String TASK_PROJECT_RUNE_SERVER = "makeEclipse" + REPLACE_PROJECT_CAP_NAME + "RunServer";
static final String TASK_PROJECT_RUNJ_CLIENT = "makeIdea" + REPLACE_PROJECT_CAP_NAME + "RunClient";
static final String TASK_PROJECT_RUNJ_SERVER = "makeIdea" + REPLACE_PROJECT_CAP_NAME + "RunServer";
static final String TASK_PROJECT_COMPILE = "makeJar" + REPLACE_PROJECT_CAP_NAME + "";
static final String TASK_PROJECT_GEN_EXC = "extractExc" + REPLACE_PROJECT_CAP_NAME + "";
static final String TASK_PROJECT_RANGEMAP = "extract" + REPLACE_PROJECT_CAP_NAME + "Rangemap";
static final String TASK_PROJECT_RETROMAP = "retromapMc" + REPLACE_PROJECT_CAP_NAME;
static final String TASK_PROJECT_RETRO_NONMC = "retromapNonMc" + REPLACE_PROJECT_CAP_NAME;
static final String TASK_PROJECT_GEN_PATCHES = "gen" + REPLACE_PROJECT_CAP_NAME + "Patches";
}
| clienthax/ForgeGradle | src/main/java/net/minecraftforge/gradle/patcher/PatcherConstants.java | Java | lgpl-2.1 | 7,365 |
package com.cherokeelessons.cards;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import commons.lang3.StringUtils;
@SuppressWarnings("serial")
public class Card implements Serializable, Comparable<Card> {
private static final boolean debug = false;
public int id;
public List<String> challenge = new ArrayList<>();
public List<String> answer = new ArrayList<>();
public String key;
public String pgroup;
public String vgroup;
public boolean reversed;
public Card() {
}
public Card(Card card) {
answer.addAll(card.answer);
challenge.addAll(card.challenge);
id = card.id;
key = card.key;
pgroup = card.pgroup;
vgroup = card.vgroup;
}
@Override
public int compareTo(Card o) {
return sortKey().compareTo(o.sortKey());
}
private String sortKey() {
StringBuilder key = new StringBuilder();
if (challenge.size() != 0) {
String tmp = challenge.get(0);
tmp = tmp.replaceAll("[¹²³⁴ɂ" + SpecialChars.SPECIALS + "]", "");
tmp = StringUtils.substringBefore(tmp, ",");
if (tmp.matches(".*[Ꭰ-Ᏼ].*")) {
tmp = tmp.replaceAll("[^Ꭰ-Ᏼ]", "");
}
String length = tmp.length() + "";
while (length.length() < 4) {
length = "0" + length;
}
key.append(length);
key.append("+");
key.append(tmp);
key.append("+");
}
for (String s : challenge) {
key.append(s);
key.append("+");
}
for (String s : answer) {
key.append(s);
key.append("+");
}
if (debug) {
this.key = key.toString();
}
return key.toString();
}
/**
* id of card in main deck based on pgroup/vgroup combinations
*/
// public String getId() {
// return (pgroup + "+" + vgroup).intern();
// };
}
| mjoyner-vbservices-net/CherokeeDictionary | src/main/java/com/cherokeelessons/cards/Card.java | Java | lgpl-2.1 | 1,701 |
/**
* Copyright (c) 2015, Lucee Assosication Switzerland. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
package lucee.transformer.util;
import java.util.ArrayList;
import lucee.commons.digest.HashUtil;
import lucee.commons.io.SystemUtil;
import lucee.transformer.Position;
/**
* this class is a Parser String optimized for the transfomer (CFML Parser)
*/
public class SourceCode {
public static final short AT_LEAST_ONE_SPACE = 0;
public static final short ZERO_OR_MORE_SPACE = 1;
protected int pos = 0;
protected final char[] text;
protected final char[] lcText;
protected final Integer[] lines; // TODO to int[]
private final boolean writeLog;
private final int dialect;
private int hash;
/**
* Constructor of the class
*
* @param text
* @param charset
*/
public SourceCode(String strText, boolean writeLog, int dialect) {
this.text = strText.toCharArray();
this.hash = strText.hashCode();
this.dialect = dialect;
lcText = new char[text.length];
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i = 0; i < text.length; i++) {
pos = i;
if (text[i] == '\n') {
arr.add(new Integer(i));
lcText[i] = ' ';
}
else if (text[i] == '\r') {
if (isNextRaw('\n')) {
lcText[i++] = ' ';
}
arr.add(new Integer(i));
lcText[i] = ' ';
}
else if (text[i] == '\t') lcText[i] = ' ';
else lcText[i] = Character.toLowerCase(text[i]);
}
pos = 0;
arr.add(new Integer(text.length));
lines = arr.toArray(new Integer[arr.size()]);
this.writeLog = writeLog;
}
public boolean hasPrevious() {
return pos > 0;
}
/**
* returns if the internal pointer is not on the last positions
*/
public boolean hasNext() {
return pos + 1 < lcText.length;
}
public boolean hasNextNext() {
return pos + 2 < lcText.length;
}
/**
* moves the internal pointer to the next position, no check if the next position is still valid
*/
public void next() {
pos++;
}
/**
* moves the internal pointer to the previous position, no check if the next position is still valid
*/
public void previous() {
pos--;
}
/**
* returns the character of the current position of the internal pointer
*/
public char getCurrent() {
return text[pos];
}
/**
* returns the lower case representation of the character of the current position
*/
public char getCurrentLower() {
return lcText[pos];
}
/**
* returns the character at the given position
*/
public char charAt(int pos) {
return text[pos];
}
/**
* returns the character at the given position as lower case representation
*/
public char charAtLower(int pos) {
return lcText[pos];
}
public boolean isPrevious(char c) {
if (!hasPrevious()) return false;
return lcText[pos - 1] == c;
}
/**
* is the character at the next position the same as the character provided by the input parameter
*/
public boolean isNext(char c) {
if (!hasNext()) return false;
return lcText[pos + 1] == c;
}
public boolean isNext(char a, char b) {
if (!hasNextNext()) return false;
return lcText[pos + 1] == a && lcText[pos + 2] == b;
}
private boolean isNextRaw(char c) {
if (!hasNext()) return false;
return text[pos + 1] == c;
}
/**
* is the character at the current position (internal pointer) in the range of the given input
* characters?
*
* @param left lower value.
* @param right upper value.
*/
public boolean isCurrentBetween(char left, char right) {
if (!isValidIndex()) return false;
return lcText[pos] >= left && lcText[pos] <= right;
}
/**
* returns if the character at the current position (internal pointer) is a valid variable character
*/
public boolean isCurrentVariableCharacter() {
if (!isValidIndex()) return false;
return isCurrentLetter() || isCurrentNumber() || isCurrent('$') || isCurrent('_');
}
/**
* returns if the current character is a letter (a-z,A-Z)
*
* @return is a letter
*/
public boolean isCurrentLetter() {
if (!isValidIndex()) return false;
return lcText[pos] >= 'a' && lcText[pos] <= 'z';
}
/**
* returns if the current character is a number (0-9)
*
* @return is a letter
*/
public boolean isCurrentNumber() {
if (!isValidIndex()) return false;
return lcText[pos] >= '0' && lcText[pos] <= '9';
}
/**
* retuns if the current character (internal pointer) is a valid special sign (_, $, Pound Symbol,
* Euro Symbol)
*/
public boolean isCurrentSpecial() {
if (!isValidIndex()) return false;
return lcText[pos] == '_' || lcText[pos] == '$' || lcText[pos] == SystemUtil.CHAR_EURO || lcText[pos] == SystemUtil.CHAR_POUND;
}
/**
* is the current character (internal pointer) the same as the given
*/
public boolean isCurrent(char c) {
if (!isValidIndex()) return false;
return lcText[pos] == c;
}
/**
* forward the internal pointer plus one if the next character is the same as the given input
*/
public boolean forwardIfCurrent(char c) {
if (isCurrent(c)) {
pos++;
return true;
}
return false;
}
/**
* returns if the current character (internal pointer) and the following are the same as the given
* input
*/
public boolean isCurrent(String str) {
if (pos + str.length() > lcText.length) return false;
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) != lcText[pos + i]) return false;
}
return true;
}
/**
* forwards if the current character (internal pointer) and the following are the same as the given
* input
*/
public boolean forwardIfCurrent(String str) {
boolean is = isCurrent(str);
if (is) pos += str.length();
return is;
}
/**
* @param str string to check against current position
* @param startWithSpace if true there must be whitespace at the current position
* @return does the criteria match?
*/
public boolean forwardIfCurrent(String str, boolean startWithSpace) {
if (!startWithSpace) return forwardIfCurrent(str);
int start = pos;
if (!removeSpace()) return false;
if (!forwardIfCurrent(str)) {
pos = start;
return false;
}
return true;
}
/**
* @param str string to check against current position
* @param startWithSpace if true there must be whitespace at the current position
* @param followedByNoVariableCharacter the character following the string must be a none variable
* character (!a-z,A-Z,0-9,_$) (not eaten)
* @return does the criteria match?
*/
public boolean forwardIfCurrent(String str, boolean startWithSpace, boolean followedByNoVariableCharacter) {
int start = pos;
if (startWithSpace && !removeSpace()) return false;
if (!forwardIfCurrent(str)) {
pos = start;
return false;
}
if (followedByNoVariableCharacter && isCurrentVariableCharacter()) {
pos = start;
return false;
}
return true;
}
/**
* forwards if the current character (internal pointer) and the following are the same as the given
* input, followed by a none word character
*/
public boolean forwardIfCurrentAndNoWordAfter(String str) {
int c = pos;
if (forwardIfCurrent(str)) {
if (!isCurrentBetween('a', 'z') && !isCurrent('_')) return true;
}
pos = c;
return false;
}
/**
* forwards if the current character (internal pointer) and the following are the same as the given
* input, followed by a none word character or a number
*/
public boolean forwardIfCurrentAndNoVarExt(String str) {
int c = pos;
if (forwardIfCurrent(str)) {
if (!isCurrentBetween('a', 'z') && !isCurrentBetween('0', '9') && !isCurrent('_')) return true;
}
pos = c;
return false;
}
/**
* Gibt zurueck ob first den folgenden Zeichen entspricht, gefolgt von Leerzeichen und second.
*
* @param first Erste Zeichen zum Vergleich (Vor den Leerzeichen).
* @param second Zweite Zeichen zum Vergleich (Nach den Leerzeichen).
* @return Gibt zurueck ob die eingegebenen Werte dem Inhalt beim aktuellen Stand des Zeigers
* entsprechen.
*/
public boolean isCurrent(String first, char second) {
int start = pos;
if (!forwardIfCurrent(first)) return false;
removeSpace();
boolean rtn = isCurrent(second);
pos = start;
return rtn;
}
/**
* Gibt zurueck ob first den folgenden Zeichen entspricht, gefolgt von Leerzeichen und second.
*
* @param first Erstes Zeichen zum Vergleich (Vor den Leerzeichen).
* @param second Zweites Zeichen zum Vergleich (Nach den Leerzeichen).
* @return Gibt zurueck ob die eingegebenen Werte dem Inhalt beim aktuellen Stand des Zeigers
* entsprechen.
*/
public boolean isCurrent(char first, char second) {
int start = pos;
if (!forwardIfCurrent(first)) return false;
removeSpace();
boolean rtn = isCurrent(second);
pos = start;
return rtn;
}
/**
* Gibt zurueck ob first den folgenden Zeichen entspricht, gefolgt von Leerzeichen und second, wenn
* ja wird der Zeiger um die Laenge der uebereinstimmung nach vorne gestellt.
*
* @param first Erste Zeichen zum Vergleich (Vor den Leerzeichen).
* @param second Zweite Zeichen zum Vergleich (Nach den Leerzeichen).
* @return Gibt zurueck ob der Zeiger vorwaerts geschoben wurde oder nicht.
*/
public boolean forwardIfCurrent(String first, char second) {
int start = pos;
if (!forwardIfCurrent(first)) return false;
removeSpace();
boolean rtn = forwardIfCurrent(second);
if (!rtn) pos = start;
return rtn;
}
/**
* Gibt zurueck ob ein Wert folgt und vor und hinterher Leerzeichen folgen.
*
* @param before Definition der Leerzeichen vorher.
* @param val Gefolgter Wert der erartet wird.
* @param after Definition der Leerzeichen nach dem Wert.
* @return Gibt zurueck ob der Zeiger vorwaerts geschoben wurde oder nicht.
*/
public boolean forwardIfCurrent(short before, String val, short after) {
int start = pos;
// space before
if (before == AT_LEAST_ONE_SPACE) {
if (!removeSpace()) return false;
}
else removeSpace();
// value
if (!forwardIfCurrent(val)) {
setPos(start);
return false;
}
// space after
if (after == AT_LEAST_ONE_SPACE) {
if (!removeSpace()) {
setPos(start);
return false;
}
}
else removeSpace();
return true;
}
/**
* Gibt zurueck ob first den folgenden Zeichen entspricht, gefolgt von Leerzeichen und second, wenn
* ja wird der Zeiger um die Laenge der uebereinstimmung nach vorne gestellt.
*
* @param first Erste Zeichen zum Vergleich (Vor den Leerzeichen).
* @param second Zweite Zeichen zum Vergleich (Nach den Leerzeichen).
* @return Gibt zurueck ob der Zeiger vorwaerts geschoben wurde oder nicht.
*/
public boolean forwardIfCurrent(char first, char second) {
int start = pos;
if (!forwardIfCurrent(first)) return false;
removeSpace();
boolean rtn = forwardIfCurrent(second);
if (!rtn) pos = start;
return rtn;
}
/**
* Gibt zurueck ob first den folgenden Zeichen entspricht, gefolgt von Leerzeichen und second.
*
* @param first Erste Zeichen zum Vergleich (Vor den Leerzeichen).
* @param second Zweite Zeichen zum Vergleich (Nach den Leerzeichen).
* @return Gibt zurueck ob die eingegebenen Werte dem Inhalt beim aktuellen Stand des Zeigers
* entsprechen.
*/
public boolean isCurrent(String first, String second) {
int start = pos;
if (!forwardIfCurrent(first)) return false;
removeSpace();
boolean rtn = isCurrent(second);
pos = start;
return rtn;
}
/**
* Gibt zurueck ob first den folgenden Zeichen entspricht, gefolgt von Leerzeichen und second, wenn
* ja wird der Zeiger um die Laenge der uebereinstimmung nach vorne gestellt.
*
* @param first Erste Zeichen zum Vergleich (Vor den Leerzeichen).
* @param second Zweite Zeichen zum Vergleich (Nach den Leerzeichen).
* @return Gibt zurueck ob der Zeiger vorwaerts geschoben wurde oder nicht.
*/
public boolean forwardIfCurrent(String first, String second) {
int start = pos;
if (!forwardIfCurrent(first)) return false;
if (!removeSpace()) {
pos = start;
return false;
}
boolean rtn = forwardIfCurrent(second);
if (!rtn) pos = start;
return rtn;
}
public boolean forwardIfCurrent(String first, String second, String third) {
int start = pos;
if (!forwardIfCurrent(first)) return false;
if (!removeSpace()) {
pos = start;
return false;
}
if (!forwardIfCurrent(second)) {
pos = start;
return false;
}
if (!removeSpace()) {
pos = start;
return false;
}
boolean rtn = forwardIfCurrent(third);
if (!rtn) pos = start;
return rtn;
}
public boolean forwardIfCurrent(String first, String second, String third, boolean startWithSpace) {
if (!startWithSpace) return forwardIfCurrent(first, second, third);
int start = pos;
if (!removeSpace()) return false;
if (!forwardIfCurrent(first, second, third)) {
pos = start;
return false;
}
return true;
}
public boolean forwardIfCurrent(String first, String second, String third, boolean startWithSpace, boolean followedByNoVariableCharacter) {
int start = pos;
if (startWithSpace && !removeSpace()) return false;
if (!forwardIfCurrent(first, second, third)) {
pos = start;
return false;
}
if (followedByNoVariableCharacter && isCurrentVariableCharacter()) {
pos = start;
return false;
}
return true;
}
public boolean forwardIfCurrent(String first, String second, boolean startWithSpace, boolean followedByNoVariableCharacter) {
int start = pos;
if (startWithSpace && !removeSpace()) return false;
if (!forwardIfCurrent(first, second)) {
pos = start;
return false;
}
if (followedByNoVariableCharacter && isCurrentVariableCharacter()) {
pos = start;
return false;
}
return true;
}
public boolean forwardIfCurrent(String first, String second, String third, String forth) {
int start = pos;
if (!forwardIfCurrent(first)) return false;
if (!removeSpace()) {
pos = start;
return false;
}
if (!forwardIfCurrent(second)) {
pos = start;
return false;
}
if (!removeSpace()) {
pos = start;
return false;
}
if (!forwardIfCurrent(third)) {
pos = start;
return false;
}
if (!removeSpace()) {
pos = start;
return false;
}
boolean rtn = forwardIfCurrent(forth);
if (!rtn) pos = start;
return rtn;
}
/**
* Gibt zurueck ob sich vor dem aktuellen Zeichen Leerzeichen befinden.
*
* @return Gibt zurueck ob sich vor dem aktuellen Zeichen Leerzeichen befinden.
*/
public boolean hasSpaceBefore() {
return pos > 0 && lcText[pos - 1] == ' ';
}
public boolean hasNLBefore() {
int index = 0;
while (pos - (++index) >= 0) {
if (text[pos - index] == '\n') return true;
if (text[pos - index] == '\r') return true;
if (lcText[pos - index] != ' ') return false;
}
return false;
}
/**
* Stellt den Zeiger nach vorne, wenn er sich innerhalb von Leerzeichen befindet, bis die
* Leerzeichen fertig sind.
*
* @return Gibt zurueck ob der Zeiger innerhalb von Leerzeichen war oder nicht.
*/
public boolean removeSpace() {
int start = pos;
while (pos < lcText.length && lcText[pos] == ' ') {
pos++;
}
return (start < pos);
}
public void revertRemoveSpace() {
while (hasSpaceBefore()) {
previous();
}
}
public String removeAndGetSpace() {
int start = pos;
while (pos < lcText.length && lcText[pos] == ' ') {
pos++;
}
return substring(start, pos - start);
}
/**
* Stellt den internen Zeiger an den Anfang der naechsten Zeile, gibt zurueck ob eine weitere Zeile
* existiert oder ob es bereits die letzte Zeile war.
*
* @return Existiert eine weitere Zeile.
*/
public boolean nextLine() {
while (isValidIndex() && text[pos] != '\n' && text[pos] != '\r') {
next();
}
if (!isValidIndex()) return false;
if (text[pos] == '\n') {
next();
return isValidIndex();
}
if (text[pos] == '\r') {
next();
if (isValidIndex() && text[pos] == '\n') {
next();
}
return isValidIndex();
}
return false;
}
/**
* Gibt eine Untermenge des CFMLString als Zeichenkette zurueck, ausgehend von start bis zum Ende
* des CFMLString.
*
* @param start Von wo aus die Untermege ausgegeben werden soll.
* @return Untermenge als Zeichenkette
*/
public String substring(int start) {
return substring(start, lcText.length - start);
}
/**
* Gibt eine Untermenge des CFMLString als Zeichenkette zurueck, ausgehend von start mit einer
* maximalen Laenge count.
*
* @param start Von wo aus die Untermenge ausgegeben werden soll.
* @param count Wie lange die zurueckgegebene Zeichenkette maximal sein darf.
* @return Untermenge als Zeichenkette.
*/
public String substring(int start, int count) {
return String.valueOf(text, start, count);
}
/**
* Gibt eine Untermenge des CFMLString als Zeichenkette in Kleinbuchstaben zurueck, ausgehend von
* start bis zum Ende des CFMLString.
*
* @param start Von wo aus die Untermenge ausgegeben werden soll.
* @return Untermenge als Zeichenkette in Kleinbuchstaben.
*/
public String substringLower(int start) {
return substringLower(start, lcText.length - start);
}
/**
* Gibt eine Untermenge des CFMLString als Zeichenkette in Kleinbuchstaben zurueck, ausgehend von
* start mit einer maximalen Laenge count.
*
* @param start Von wo aus die Untermenge ausgegeben werden soll.
* @param count Wie lange die zurueckgegebene Zeichenkette maximal sein darf.
* @return Untermenge als Zeichenkette in Kleinbuchstaben.
*/
public String substringLower(int start, int count) {
return String.valueOf(lcText, start, count);
}
/**
* Gibt eine Untermenge des CFMLString als CFMLString zurueck, ausgehend von start bis zum Ende des
* CFMLString.
*
* @param start Von wo aus die Untermenge ausgegeben werden soll.
* @return Untermenge als CFMLString
*/
public SourceCode subCFMLString(int start) {
return subCFMLString(start, text.length - start);
}
/**
* return a subset of the current SourceCode
*
* @param start start position of the new subset.
* @param count length of the new subset.
* @return subset of the SourceCode as new SourcCode
*/
public SourceCode subCFMLString(int start, int count) {
return new SourceCode(String.valueOf(text, start, count), writeLog, dialect);
}
/**
* Gibt den CFMLString als String zurueck.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return new String(this.text);
}
/**
* Gibt die aktuelle Position des Zeigers innerhalb des CFMLString zurueck.
*
* @return Position des Zeigers
*/
public int getPos() {
return pos;
}
/**
* Setzt die Position des Zeigers innerhalb des CFMLString, ein ungueltiger index wird ignoriert.
*
* @param pos Position an die der Zeiger gestellt werde soll.
*/
public void setPos(int pos) {
this.pos = pos;
}
/**
* Gibt die aktuelle Zeile zurueck in der der Zeiger des CFMLString steht.
*
* @return Zeilennummer
*/
public int getLine() {
return getLine(pos);
}
public Position getPosition() {
return getPosition(pos);
}
public Position getPosition(int pos) {
int line = 0;
int posAtStart = 0;
for (int i = 0; i < lines.length; i++) {
if (pos <= lines[i].intValue()) {
line = i + 1;
if (i > 0) posAtStart = lines[i - 1].intValue();
break;
}
}
if (line == 0) throw new RuntimeException("syntax error");
int column = pos - posAtStart;
return new Position(line, column, pos);
}
/**
* Gibt zurueck in welcher Zeile die angegebene Position ist.
*
* @param pos Position von welcher die Zeile erfragt wird
* @return Zeilennummer
*/
public int getLine(int pos) {
for (int i = 0; i < lines.length; i++) {
if (pos <= lines[i].intValue()) return i + 1;
}
return lines.length;
}
/**
* Gibt die Stelle in der aktuelle Zeile zurueck, in welcher der Zeiger steht.
*
* @return Position innerhalb der Zeile.
*/
public int getColumn() {
return getColumn(pos);
}
/**
* Gibt die Stelle in der Zeile auf die pos zeigt zurueck.
*
* @param pos Position von welcher die Zeile erfragt wird
* @return Position innerhalb der Zeile.
*/
public int getColumn(int pos) {
int line = getLine(pos) - 1;
if (line == 0) return pos + 1;
return pos - lines[line - 1].intValue();
}
/**
* Gibt die Zeile auf welcher der Zeiger steht als String zurueck.
*
* @return Zeile als Zeichenkette
*/
public String getLineAsString() {
return getLineAsString(getLine(pos));
}
/**
* Gibt die angegebene Zeile als String zurueck.
*
* @param line Zeile die zurueck gegeben werden soll
* @return Zeile als Zeichenkette
*/
public String getLineAsString(int line) {
int index = line - 1;
if (lines.length <= index) return null;
int max = lines[index].intValue();
int min = 0;
if (index != 0) min = lines[index - 1].intValue() + 1;
if (min < max && max - 1 < lcText.length) return this.substring(min, max - min);
return "";
}
/**
* Gibt zurueck ob der Zeiger auf dem letzten Zeichen steht.
*
* @return Gibt zurueck ob der Zeiger auf dem letzten Zeichen steht.
*/
public boolean isLast() {
return pos == lcText.length - 1;
}
/**
* Gibt zurueck ob der Zeiger nach dem letzten Zeichen steht.
*
* @return Gibt zurueck ob der Zeiger nach dem letzten Zeichen steht.
*/
public boolean isAfterLast() {
return pos >= lcText.length;
}
/**
* Gibt zurueck ob der Zeiger einen korrekten Index hat.
*
* @return Gibt zurueck ob der Zeiger einen korrekten Index hat.
*/
public boolean isValidIndex() {
return pos < lcText.length && pos > -1;
}
/**
* Gibt zurueck, ausgehend von der aktuellen Position, wann das naechste Zeichen folgt das gleich
* ist wie die Eingabe, falls keines folgt wird -1 zurueck gegeben. Gross- und Kleinschreibung der
* Zeichen werden igoriert.
*
* @param c gesuchtes Zeichen
* @return Zeichen das gesucht werden soll.
*/
public int indexOfNext(char c) {
for (int i = pos; i < lcText.length; i++) {
if (lcText[i] == c) return i;
}
return -1;
}
public int indexOfNext(String str) {
char[] carr = str.toCharArray();
outer: for (int i = pos; i < lcText.length; i++) {
if (lcText[i] == carr[0]) {
// print.e("- "+lcText[i]);
for (int y = 1; y < carr.length; y++) {
// print.e("-- "+y);
if (lcText.length <= i + y || lcText[i + y] != carr[y]) {
// print.e("ggg");
continue outer;
}
}
return i;
}
}
return -1;
}
/**
* Gibt das letzte Wort das sich vor dem aktuellen Zeigerstand befindet zurueck, falls keines
* existiert wird null zurueck gegeben.
*
* @return Word vor dem aktuellen Zeigerstand.
*/
public String lastWord() {
int size = 1;
while (pos - size > 0 && lcText[pos - size] == ' ') {
size++;
}
while (pos - size > 0 && lcText[pos - size] != ' ' && lcText[pos - size] != ';') {
size++;
}
return this.substring((pos - size + 1), (pos - 1));
}
/**
* Gibt die Laenge des CFMLString zurueck.
*
* @return Laenge des CFMLString.
*/
public int length() {
return lcText.length;
}
/**
* Prueft ob das uebergebene Objekt diesem Objekt entspricht.
*
* @param o Object zum vergleichen.
* @return Ist das uebergebene Objekt das selbe wie dieses.
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof SourceCode)) return false;
return o.toString().equals(this.toString());
}
public boolean getWriteLog() {
return writeLog;
}
public String getText() {
return new String(text);
}
public String id() {
return HashUtil.create64BitHashAsString(getText());
}
public int getDialect() {
return dialect;
}
@Override
public int hashCode() {
return hash;
}
} | lucee/Lucee | core/src/main/java/lucee/transformer/util/SourceCode.java | Java | lgpl-2.1 | 24,320 |
package de.akquinet.jbosscc.blog;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import de.akquinet.jbosscc.blog.dao.BlogEntryDao;
import de.akquinet.jbosscc.blog.dao.UserDao;
@Stateless
public class BlogEntryTestdata {
private static final String CONTENT = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet";
private static final String TITLE = "Lorem ipsum dolor sit amet";
private static final int QUANTITY = 5;
@EJB
private BlogEntryDao blogEntryDao;
@EJB
private UserDao userDao;
public void insert() {
List<User> users = userDao.findAll();
for (User user : users) {
for (int i = 0; i < QUANTITY; i++) {
BlogEntry blogEntry = new BlogEntry();
blogEntry.setAuthor(user);
blogEntry.setTitle(TITLE);
blogEntry.setContent(CONTENT);
blogEntryDao.persist(blogEntry);
}
}
}
}
| akquinet/needle | src/examples/jbosscc-blog-example/jbosscc-blog-example-bootstrap/src/main/java/de/akquinet/jbosscc/blog/BlogEntryTestdata.java | Java | lgpl-2.1 | 1,394 |
package wtf.worldgen.caves.types.nether;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockHugeMushroom;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import wtf.init.WTFBlocks;
import wtf.worldgen.GeneratorMethods;
import wtf.worldgen.caves.AbstractCaveType;
public class NetherMushroom extends AbstractCaveType{
public NetherMushroom() {
super("NetherMushroom", 0, 1);
// TODO Auto-generated constructor stub
}
@Override
public void generateCeiling(GeneratorMethods gen, Random random, BlockPos pos, float depth) {
// TODO Auto-generated method stub
}
@Override
public void generateFloor(GeneratorMethods gen, Random random, BlockPos pos, float depth) {
gen.replaceBlock(pos, WTFBlocks.mycorrack.getDefaultState());
}
@Override
public void generateCeilingAddons(GeneratorMethods gen, Random random, BlockPos pos, float depth) {
// TODO Auto-generated method stub
}
@Override
public void generateFloorAddons(GeneratorMethods gen, Random random, BlockPos pos, float depth) {
generateMushroom(gen, random, pos);
}
@Override
public void generateWall(GeneratorMethods gen, Random random, BlockPos pos, float depth, int height) {
// TODO Auto-generated method stub
}
public void generateMushroom(GeneratorMethods gen, Random rand, BlockPos position)
{
Block block = rand.nextBoolean() ? Blocks.BROWN_MUSHROOM_BLOCK : Blocks.RED_MUSHROOM_BLOCK;
int i = rand.nextInt(3) + 4;
if (rand.nextInt(12) == 0)
{
i *= 2;
}
boolean flag = true;
if (position.getY() >= 1 && position.getY() + i + 1 < 256)
{
for (int j = position.getY(); j <= position.getY() + 1 + i; ++j)
{
int k = 3;
if (j <= position.getY() + 3)
{
k = 0;
}
BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();
for (int l = position.getX() - k; l <= position.getX() + k && flag; ++l)
{
for (int i1 = position.getZ() - k; i1 <= position.getZ() + k && flag; ++i1)
{
if (j >= 0 && j < 256)
{
IBlockState state = gen.getWorld().getBlockState(blockpos$mutableblockpos.setPos(l, j, i1));
if (state.getBlock().hashCode() != Blocks.AIR.hashCode())
{
flag = false;
}
}
else
{
flag = false;
}
}
}
}
if (!flag)
{
}
else
{
Block block1 = gen.getWorld().getBlockState(position.down()).getBlock();
if (block1.hashCode() != WTFBlocks.mycorrack.hashCode())
{
}
else
{
int k2 = position.getY() + i;
if (block == Blocks.RED_MUSHROOM_BLOCK)
{
k2 = position.getY() + i - 3;
}
for (int l2 = k2; l2 <= position.getY() + i; ++l2)
{
int j3 = 1;
if (l2 < position.getY() + i)
{
++j3;
}
if (block == Blocks.BROWN_MUSHROOM_BLOCK)
{
j3 = 3;
}
int k3 = position.getX() - j3;
int l3 = position.getX() + j3;
int j1 = position.getZ() - j3;
int k1 = position.getZ() + j3;
for (int l1 = k3; l1 <= l3; ++l1)
{
for (int i2 = j1; i2 <= k1; ++i2)
{
int j2 = 5;
if (l1 == k3)
{
--j2;
}
else if (l1 == l3)
{
++j2;
}
if (i2 == j1)
{
j2 -= 3;
}
else if (i2 == k1)
{
j2 += 3;
}
BlockHugeMushroom.EnumType blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.byMetadata(j2);
if (block == Blocks.BROWN_MUSHROOM_BLOCK || l2 < position.getY() + i)
{
if ((l1 == k3 || l1 == l3) && (i2 == j1 || i2 == k1))
{
continue;
}
if (l1 == position.getX() - (j3 - 1) && i2 == j1)
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.NORTH_WEST;
}
if (l1 == k3 && i2 == position.getZ() - (j3 - 1))
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.NORTH_WEST;
}
if (l1 == position.getX() + (j3 - 1) && i2 == j1)
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.NORTH_EAST;
}
if (l1 == l3 && i2 == position.getZ() - (j3 - 1))
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.NORTH_EAST;
}
if (l1 == position.getX() - (j3 - 1) && i2 == k1)
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.SOUTH_WEST;
}
if (l1 == k3 && i2 == position.getZ() + (j3 - 1))
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.SOUTH_WEST;
}
if (l1 == position.getX() + (j3 - 1) && i2 == k1)
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.SOUTH_EAST;
}
if (l1 == l3 && i2 == position.getZ() + (j3 - 1))
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.SOUTH_EAST;
}
}
if (blockhugemushroom$enumtype == BlockHugeMushroom.EnumType.CENTER && l2 < position.getY() + i)
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.ALL_INSIDE;
}
if (position.getY() >= position.getY() + i - 1 || blockhugemushroom$enumtype != BlockHugeMushroom.EnumType.ALL_INSIDE)
{
BlockPos blockpos = new BlockPos(l1, l2, i2);
IBlockState state = gen.getWorld().getBlockState(blockpos);
gen.replaceBlock( blockpos, block.getDefaultState().withProperty(BlockHugeMushroom.VARIANT, blockhugemushroom$enumtype));
}
}
}
}
for (int i3 = 0; i3 < i; ++i3)
{
IBlockState iblockstate = gen.getWorld().getBlockState(position.up(i3));
if (iblockstate.getBlock().canBeReplacedByLeaves(iblockstate, gen.chunk.getWorld(), position.up(i3)))
{
gen.replaceBlock(position.up(i3), block.getDefaultState().withProperty(BlockHugeMushroom.VARIANT, BlockHugeMushroom.EnumType.STEM));
}
}
}
}
}
else
{
}
}
}
| Tencao/Expedition | src/main/java/wtf/worldgen/caves/types/nether/NetherMushroom.java | Java | lgpl-2.1 | 9,182 |
package com.lessoner.treeores.WorldGen;
import com.lessoner.treeores.Blocks.TreeOresBlocks;
import net.minecraft.block.Block;
import net.minecraft.block.BlockSapling;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenAbstractTree;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.Random;
/**
* Created by Anguarmas on 9/23/2015.
*/
public class WorldGenTreeOres2
extends WorldGenAbstractTree {
private final int minTreeHeight;
private final int randomTreeHeight;
private final boolean vinesGrow;
private final Block wood;
private final Block leaves;
private final int metaWood;
private final int metaLeaves;
public WorldGenTreeOres2(Block wood, Block leaves, int metaWood, int metaLeaves) {
this(wood, leaves, metaWood, metaLeaves, false, 4, 3, false);
}
public WorldGenTreeOres2(Block wood, Block leaves, int metaWood, int metaLeaves, boolean doBlockNotify, int minTreeHeight, int randomTreeHeight, boolean vinesGrow) {
super(doBlockNotify);
this.wood = wood;
this.leaves = leaves;
this.randomTreeHeight = randomTreeHeight;
this.minTreeHeight = minTreeHeight;
this.metaWood = metaWood;
this.metaLeaves = metaLeaves;
this.vinesGrow = vinesGrow;
}
public boolean generate(World world, Random random, int x, int y, int z) {
int l = random.nextInt(3) + this.minTreeHeight;
boolean flag = true;
if ((y >= 1) && (y + l + 1 <= 256)) {
for (int i1 = y; i1 <= y + 1 + l; i1++) {
byte b0 = 1;
if (i1 == y) {
b0 = 0;
}
if (i1 >= y + 1 + l - 2) {
b0 = 2;
}
for (int j1 = x - b0; (j1 <= x + b0) && (flag); j1++) {
for (int k1 = z - b0; (k1 <= z + b0) && (flag); k1++) {
if ((i1 >= 0) && (i1 < 256)) {
Block block = world.getBlock(j1, i1, k1);
if (!isReplaceable(world, j1, i1, k1)) {
flag = false;
}
} else {
flag = false;
}
}
}
}
if (!flag) {
return false;
}
Block block2 = world.getBlock(x, y - 1, z);
boolean isSoil = block2.canSustainPlant(world, x, y - 1, z, ForgeDirection.UP, (BlockSapling) TreeOresBlocks.TreeOresSaplings2);
if ((isSoil) && (y < 256 - l - 1)) {
block2.onPlantGrow(world, x, y - 1, z, x, y, z);
byte b0 = 3;
byte b1 = 0;
for (int k1 = y - b0 + l; k1 <= y + l; k1++) {
int i3 = k1 - (y + l);
int l1 = b1 + 1 - i3 / 2;
for (int i2 = x - l1; i2 <= x + l1; i2++) {
int j2 = i2 - x;
for (int k2 = z - l1; k2 <= z + l1; k2++) {
int l2 = k2 - z;
if ((Math.abs(j2) != l1) || (Math.abs(l2) != l1) || ((random.nextInt(2) != 0) && (i3 != 0))) {
Block block1 = world.getBlock(i2, k1, k2);
if ((block1.isAir(world, i2, k1, k2)) || (block1.isLeaves(world, i2, k1, k2))) {
setBlockAndNotifyAdequately(world, i2, k1, k2, TreeOresBlocks.TreeOresLeaves2, this.metaLeaves);
}
}
}
}
}
for (int k1 = 0; k1 < l; k1++) {
Block block = world.getBlock(x, y + k1, z);
if ((block.isAir(world, x, y + k1, z)) || (block.isLeaves(world, x, y + k1, z))) {
setBlockAndNotifyAdequately(world, x, y + k1, z, TreeOresBlocks.TreeOresLogs2, this.metaWood);
if ((this.vinesGrow) && (k1 > 0)) {
if ((random.nextInt(3) > 0) && (world.isAirBlock(x - 1, y + k1, z))) {
setBlockAndNotifyAdequately(world, x - 1, y + k1, z, Blocks.vine, 8);
}
if ((random.nextInt(3) > 0) && (world.isAirBlock(x + 1, y + k1, z))) {
setBlockAndNotifyAdequately(world, x + 1, y + k1, z, Blocks.vine, 2);
}
if ((random.nextInt(3) > 0) && (world.isAirBlock(x, y + k1, z - 1))) {
setBlockAndNotifyAdequately(world, x, y + k1, z - 1, Blocks.vine, 1);
}
if ((random.nextInt(3) > 0) && (world.isAirBlock(x, y + k1, z + 1))) {
setBlockAndNotifyAdequately(world, x, y + k1, z + 1, Blocks.vine, 4);
}
}
}
}
if (this.vinesGrow) {
for (int k1 = y - 3 + l; k1 <= y + l; k1++) {
int i3 = k1 - (y + l);
int l1 = 2 - i3 / 2;
for (int i2 = x - l1; i2 <= x + l1; i2++) {
for (int j2 = z - l1; j2 <= z + l1; j2++) {
if (world.getBlock(i2, k1, j2).isLeaves(world, i2, k1, j2)) {
if ((random.nextInt(4) == 0) && (world.getBlock(i2 - 1, k1, j2).isAir(world, i2 - 1, k1, j2))) {
growVines(world, i2 - 1, k1, j2, 8);
}
if ((random.nextInt(4) == 0) && (world.getBlock(i2 + 1, k1, j2).isAir(world, i2 + 1, k1, j2))) {
growVines(world, i2 + 1, k1, j2, 2);
}
if ((random.nextInt(4) == 0) && (world.getBlock(i2, k1, j2 - 1).isAir(world, i2, k1, j2 - 1))) {
growVines(world, i2, k1, j2 - 1, 1);
}
if ((random.nextInt(4) == 0) && (world.getBlock(i2, k1, j2 + 1).isAir(world, i2, k1, j2 + 1))) {
growVines(world, i2, k1, j2 + 1, 4);
}
}
}
}
}
if ((random.nextInt(5) == 0) && (l > 5)) {
for (int k1 = 0; k1 < 2; k1++) {
for (int i3 = 0; i3 < 4; i3++) {
if (random.nextInt(4 - k1) == 0) {
int l1 = random.nextInt(3);
setBlockAndNotifyAdequately(world, x + net.minecraft.util.Direction.offsetX[net.minecraft.util.Direction.rotateOpposite[i3]], y + l - 5 + k1, z + net.minecraft.util.Direction.offsetZ[net.minecraft.util.Direction.rotateOpposite[i3]], Blocks.cocoa, l1 << 2 | i3);
}
}
}
}
}
return true;
}
return false;
}
return false;
}
private void growVines(World world, int x, int y, int z, int i) {
setBlockAndNotifyAdequately(world, x, y, z, Blocks.vine, i);
int i1 = 4;
for (; ; ) {
y--;
if ((!world.getBlock(x, y, z).isAir(world, x, y, z)) || (i1 <= 0)) {
return;
}
setBlockAndNotifyAdequately(world, x, y, z, Blocks.vine, i);
i1--;
}
}
}
| devkevanishvili/TreeOresMod | src/main/java/com/lessoner/treeores/WorldGen/WorldGenTreeOres2.java | Java | lgpl-2.1 | 7,976 |
/*
* Cacheonix Systems licenses this file to You under the LGPL 2.1
* (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm
*
* 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.cacheonix.impl.net.tcp;
import java.io.IOException;
import org.cacheonix.CacheonixException;
/**
* This exception is thrown when an unrecoverable server socket exception occurs.
*/
public final class UnrecoverableAcceptException extends CacheonixException {
private static final long serialVersionUID = 7908749977067442371L;
/**
* Creates UnrecoverableAcceptException
*
* @param cause cause.
*/
public UnrecoverableAcceptException(final IOException cause) {
super(cause);
}
}
| cacheonix/cacheonix-core | src/org/cacheonix/impl/net/tcp/UnrecoverableAcceptException.java | Java | lgpl-2.1 | 1,133 |
/* This file is part of the Joshua Machine Translation System.
*
* Joshua 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 joshua.decoder.ff.lm.distributed_lm;
import joshua.decoder.BuildinSymbol;
import joshua.decoder.SrilmSymbol;
import joshua.decoder.Support;
import joshua.decoder.Symbol;
import joshua.decoder.ff.lm.LMGrammar;
import joshua.decoder.ff.lm.buildin_lm.LMGrammarJAVA;
import joshua.decoder.ff.lm.srilm.LMGrammarSRILM;
import joshua.util.FileUtility;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
/**
* this class implement
* (1) load lm file
* (2) listen to connection request
* (3) serve request for LM probablity
*
* @author Zhifei Li, <[email protected]>
* @version $LastChangedDate$
*/
public class LMServer {
//common options
public static int port = 9800;
static boolean use_srilm = true;
public static boolean use_left_euqivalent_state = false;
public static boolean use_right_euqivalent_state = false;
static int g_lm_order = 3;
static double lm_ceiling_cost = 100;//TODO: make sure LMGrammar is using this number
static String remote_symbol_tbl = null;
//lm specific
static String lm_file = null;
static Double interpolation_weight = null;//the interpolation weight of this lm
static String g_host_name = null;
//pointer
static LMGrammar p_lm;
static HashMap request_cache = new HashMap();//cmd with result
static int cache_size_limit = 3000000;
// stat
static int g_n_request = 0;
static int g_n_cache_hit = 0;
static Symbol p_symbol;
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("wrong command, correct command should be: java LMServer config_file");
System.out.println("num of args is "+ args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("arg is: " + args[i]);
}
System.exit(1);
}
String config_file = args[0].trim();
read_config_file(config_file);
ServerSocket serverSocket = null;
LMServer server = new LMServer();
//p_lm.write_vocab_map_srilm(remote_symbol_tbl);
//####write host infomation
//String hostname=LMServer.findHostName();//this one is not stable, sometimes throw exception
//String hostname="unknown";
//### begin loop
try {
serverSocket = new ServerSocket(port);
if (null == serverSocket) {
System.out.println("Error: server socket is null");
System.exit(0);
}
init_lm_grammar();
System.out.println("finished lm reading, wait for connection");
// serverSocket = new ServerSocket(0);//0 means any free port
// port = serverSocket.getLocalPort();
while (true) {
Socket socket = serverSocket.accept();
System.out.println("accept a connection from client");
ClientHandler handler = new ClientHandler(socket,server);
handler.start();
}
} catch(IOException ioe) {
System.out.println("cannot create serversocket at port or connection fail");
ioe.printStackTrace();
} finally {
try {
serverSocket.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
public static void init_lm_grammar() {
if (use_srilm) {
if (use_left_euqivalent_state || use_right_euqivalent_state) {
System.out.println("use local srilm, we cannot use suffix stuff");
System.exit(0);
}
p_symbol = new SrilmSymbol(remote_symbol_tbl, g_lm_order);
p_lm = new LMGrammarSRILM((SrilmSymbol)p_symbol, g_lm_order, lm_file);
} else {
//p_lm = new LMGrammar_JAVA(g_lm_order, lm_file, use_left_euqivalent_state);
//big bug: should load the consistent symbol files
p_symbol = new BuildinSymbol(remote_symbol_tbl);
p_lm = new LMGrammarJAVA((BuildinSymbol)p_symbol, g_lm_order, lm_file, use_left_euqivalent_state, use_right_euqivalent_state);
}
}
public static void read_config_file(String config_file) {
BufferedReader t_reader_config = FileUtility.getReadFileStream(config_file);
String line;
while((line = FileUtility.read_line_lzf(t_reader_config)) != null) {
//line = line.trim().toLowerCase();
line = line.trim();
if (line.matches("^\\s*\\#.*$")
|| line.matches("^\\s*$")) {
continue;
}
if (line.indexOf("=") != -1) { //parameters
String[] fds = line.split("\\s*=\\s*");
if (fds.length != 2) {
Support.write_log_line("Wrong config line: " + line, Support.ERROR);
System.exit(0);
}
if (0 == fds[0].compareTo("lm_file")) {
lm_file = fds[1].trim();
System.out.println(String.format("lm file: %s", lm_file));
} else if (0 == fds[0].compareTo("use_srilm")) {
use_srilm = new Boolean(fds[1]);
System.out.println(String.format("use_srilm: %s", use_srilm));
} else if (0 == fds[0].compareTo("lm_ceiling_cost")) {
lm_ceiling_cost = new Double(fds[1]);
System.out.println(String.format("lm_ceiling_cost: %s", lm_ceiling_cost));
} else if (0 == fds[0].compareTo("use_left_euqivalent_state")) {
use_left_euqivalent_state = new Boolean(fds[1]);
System.out.println(String.format("use_left_euqivalent_state: %s", use_left_euqivalent_state));
} else if (0 == fds[0].compareTo("use_right_euqivalent_state")) {
use_right_euqivalent_state = new Boolean(fds[1]);
System.out.println(String.format("use_right_euqivalent_state: %s", use_right_euqivalent_state));
} else if (0 == fds[0].compareTo("order")) {
g_lm_order = new Integer(fds[1]);
System.out.println(String.format("g_lm_order: %s", g_lm_order));
} else if (0 == fds[0].compareTo("remote_lm_server_port")) {
port = new Integer(fds[1]);
System.out.println(String.format("remote_lm_server_port: %s", port));
} else if (0 == fds[0].compareTo("remote_symbol_tbl")) {
remote_symbol_tbl = new String(fds[1]);
System.out.println(String.format("remote_symbol_tbl: %s", remote_symbol_tbl));
} else if (0 == fds[0].compareTo("hostname")) {
g_host_name = fds[1].trim();
System.out.println(String.format("host name is: %s", g_host_name));
} else if (0 == fds[0].compareTo("interpolation_weight")) {
interpolation_weight = new Double(fds[1]);
System.out.println(String.format("interpolation_weightt: %s", interpolation_weight));
} else {
Support.write_log_line("Warning: not used config line: " + line, Support.ERROR);
//System.exit(0);
}
}
}
FileUtility.close_read_file(t_reader_config);
}
private static String read_host_name(String fhostname) {
BufferedReader t_reader_config = FileUtility.getReadFileStream(fhostname);
String res = null;
String line;
while((line = FileUtility.read_line_lzf(t_reader_config)) != null) {
//line = line.trim().toLowerCase();
line = line.trim();
if (line.matches("^\\s*\\#.*$")
|| line.matches("^\\s*$")) {
continue;
}
res = line;
break;
}
FileUtility.close_read_file(t_reader_config);
return res;
}
static private String findHostName() {
try {
//return InetAddress.getLocalHost().getHostName();
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
System.out.println("Unknown host address");
System.exit(1);
return null;
}
}
// used by server to process diffent Client
public static class ClientHandler
extends Thread {
public class DecodedStructure {
String cmd;
int num;
int[] wrds;
}
LMServer parent;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ClientHandler(Socket sock, LMServer pa) throws IOException {
parent = pa;
socket = sock;
in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
out = new PrintWriter( new OutputStreamWriter(socket.getOutputStream()));
}
public void run() {
String line_in;
String line_out;
try {
while((line_in = in.readLine()) != null) {
//TODO block read
//System.out.println("coming in: " + line);
//line_out = process_request(line_in);
line_out = process_request_no_cache(line_in);
out.println(line_out);
out.flush();
}
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
try {
in.close();
out.close();
socket.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
private String process_request_no_cache(String packet) {
//search cache
g_n_request++;
String cmd_res = process_request_helper(packet);
if (g_n_request % 50000 == 0) {
System.out.println("n_requests: " + g_n_request);
}
return cmd_res;
}
private String process_request(String packet) {
//search cache
String cmd_res = (String)request_cache.get(packet);
g_n_request++;
if (null == cmd_res) { //cache fail
cmd_res = process_request_helper(packet);
//update cache
if (request_cache.size() > cache_size_limit) {
request_cache.clear();
}
request_cache.put(packet, cmd_res);
} else {
g_n_cache_hit++;
}
if (g_n_request % 50000 == 0) {
System.out.println(
"n_requests: " + g_n_request
+ "; n_cache_hits: " + g_n_cache_hit
+ "; cache size= " + request_cache.size()
+ "; hit rate= " + g_n_cache_hit * 1.0 / g_n_request);
}
return cmd_res;
}
//This is the funciton that application specific
private String process_request_helper(String line) {
DecodedStructure ds = decode_packet(line);
if (0 == ds.cmd.compareTo("prob")) {
return get_prob(ds);
} else if (0 == ds.cmd.compareTo("prob_bow")) {
return get_prob_backoff_state(ds);
} else if (0 == ds.cmd.compareTo("equiv_left")) {
return get_left_equiv_state(ds);
} else if (0 == ds.cmd.compareTo("equiv_right")) {
return get_right_equiv_state(ds);
} else {
System.out.println("error : Wrong request line: " + line);
//System.exit(1);
return "";
}
}
// format: prob order wrds
private String get_prob(DecodedStructure ds) {
Double res = p_lm.get_prob(ds.wrds, ds.num, false);
return res.toString();
}
// format: prob order wrds
private String get_prob_backoff_state(DecodedStructure ds) {
System.out.println("Error: call get_prob_backoff_state in lmserver, must exit");
System.exit(1);
return null;
/*Double res = p_lm.get_prob_backoff_state(ds.wrds, ds.num, ds.num);
return res.toString();*/
}
// format: prob order wrds
private String get_left_equiv_state(DecodedStructure ds) {
System.out.println("Error: call get_left_equiv_state in lmserver, must exit");
System.exit(1);
return null;
}
// format: prob order wrds
private String get_right_equiv_state(DecodedStructure ds) {
System.out.println("Error: call get_right_equiv_state in lmserver, must exit");
System.exit(1);
return null;
}
private DecodedStructure decode_packet(String packet) {
String[] fds = packet.split("\\s+");
DecodedStructure res = new DecodedStructure();
res.cmd = fds[0].trim();
res.num = new Integer(fds[1]);
int[] wrds = new int[fds.length-2];
for (int i = 2; i < fds.length; i++) {
wrds[i-2] = new Integer(fds[i]);
}
res.wrds = wrds;
return res;
}
}
}
| dowobeha/joshua-multilingual | src/joshua/decoder/ff/lm/distributed_lm/LMServer.java | Java | lgpl-2.1 | 12,246 |
/**
* Helios, OpenSource Monitoring
* Brought to you by the Helios Development Group
*
* Copyright 2007, Helios Development Group 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.helios.rindle.store.redis.netty;
import java.util.Set;
/**
* <p>Title: PatternReply</p>
* <p>Description: </p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>org.helios.rindle.store.redis.netty.PatternReply</code></p>
*/
public class PatternReply extends MessageReply {
/** The pattern of the subscription */
private final String pattern;
/**
* Creates a new PatternReply
* @param message The received message
* @param channel The originating channel
* @param pattern The pattern of the subscription
*/
protected PatternReply(String message, String channel, String pattern) {
super(message, channel);
this.pattern = pattern;
}
/**
* Publishes the message to the passed listeners
* @param listeners The listeners to publish to
*/
@Override
public void publish(Set<SubListener> listeners) {
for(SubListener listener: listeners) {
listener.onPatternMessage(pattern, channel, message);
}
}
/**
* Returns the pattern of the subscription
* @return the pattern of the subscription
*/
public String getPattern() {
return pattern;
}
/**
* Indicates if this reply is a pattern reply
* @return true if this reply is a pattern reply, false if it is a channel reply
*/
@Override
public boolean isPattern() {
return true;
}
/**
* Indicates if this reply is a channel reply
* @return true if this reply is a channel reply, false if it is a pattern reply
*/
@Override
public boolean isChannelMessage() {
return false;
}
/**
* Constructs a <code>String</code> with all attributes in <code>name:value</code> format.
* @return a <code>String</code> representation of this object.
*/
@Override
public String toString() {
final String TAB = "\n\t";
StringBuilder retValue = new StringBuilder();
retValue.append("MessageReply [")
.append(TAB).append("channel:").append(this.channel)
.append(TAB).append("pattern:").append(this.pattern)
.append(TAB).append("message:").append(this.message)
.append("\n]");
return retValue.toString();
}
}
| nickman/Rindle | pag-core/src/main/java/org/helios/rindle/store/redis/netty/PatternReply.java | Java | lgpl-2.1 | 3,226 |
/*
* JCaptcha, the open source java framework for captcha definition and integration
* Copyright (c) 2007 jcaptcha.net. All Rights Reserved.
* See the LICENSE.txt file distributed with this package.
*/
package com.octo.captcha.component.image.textpaster.textdecorator;
import com.octo.captcha.component.image.color.ColorGenerator;
import com.octo.captcha.component.image.color.SingleColorGenerator;
import com.octo.captcha.component.image.textpaster.ChangeableAttributedString;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.security.SecureRandom;
import java.text.AttributedString;
import java.util.Random;
/**
* <p/>
* text decorator that paint holes on the string (erase some parts) </p> You may specify the number of holes per glyph :
* 3 by default. You may specify the color of holes : white by default.
*
* @author <a href="mailto:[email protected]">Marc-Antoine Garrigue </a>
* @version 1.0
* @see {http://www.parc.xerox.com/research/istl/projects/captcha/default.html}
*/
public class BaffleTextDecorator implements TextDecorator {
private Random myRandom = new SecureRandom();
/**
* circleXRatio
*/
private static double circleXRatio = 0.7;
/**
* circleYRatio
*/
private static double circleYRatio = 0.5;
/**
* Number of holes per glyph. Default : 3
*/
private Integer numberOfHolesPerGlyph = new Integer(3);
/**
* ColorGenerator for the holes
*/
private ColorGenerator holesColorGenerator = null;
private int alphaCompositeType = AlphaComposite.SRC_OVER;
/**
* @param holesColor Color of the holes
*/
public BaffleTextDecorator(Integer numberOfHolesPerGlyph, Color holesColor) {
this.numberOfHolesPerGlyph = numberOfHolesPerGlyph != null ? numberOfHolesPerGlyph
: this.numberOfHolesPerGlyph;
this.holesColorGenerator = new SingleColorGenerator(holesColor != null ? holesColor
: Color.white);
}
/**
* @param numberOfHolesPerGlyph Number of holes around glyphes
* @param holesColorGenerator The colors for holes
*/
public BaffleTextDecorator(Integer numberOfHolesPerGlyph, ColorGenerator holesColorGenerator) {
this.numberOfHolesPerGlyph = numberOfHolesPerGlyph != null ? numberOfHolesPerGlyph
: this.numberOfHolesPerGlyph;
this.holesColorGenerator = holesColorGenerator != null ? holesColorGenerator
: new SingleColorGenerator(Color.white);
}
/**
* @param numberOfHolesPerGlyph Number of holes around glyphes
* @param holesColorGenerator The colors for holes
*/
public BaffleTextDecorator(Integer numberOfHolesPerGlyph, ColorGenerator holesColorGenerator, Integer alphaCompositeType) {
this(numberOfHolesPerGlyph, holesColorGenerator);
this.alphaCompositeType = alphaCompositeType != null ? alphaCompositeType.intValue() : this.alphaCompositeType;
}
public void decorateAttributedString(Graphics2D g2, AttributedString attributedWord, ChangeableAttributedString newAttrString) {
Color oldColor = g2.getColor();
Composite oldComp = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(alphaCompositeType));
for (int j = 0; j < attributedWord.getIterator().getEndIndex(); j++) {
g2.setColor(holesColorGenerator.getNextColor());
Rectangle2D bounds = newAttrString.getBounds(j).getFrame();
double circleMaxSize = (double) bounds.getWidth() / 2;
for (int i = 0; i < numberOfHolesPerGlyph.intValue(); i++) {
double circleSize = circleMaxSize * (1 + myRandom.nextDouble()) / 2;
double circlex = bounds.getMinX() + bounds.getWidth() * circleXRatio
* myRandom.nextDouble();
double circley = bounds.getMinY() - bounds.getHeight() * circleYRatio
* myRandom.nextDouble();
Ellipse2D circle = new Ellipse2D.Double(circlex, circley, circleSize, circleSize);
g2.fill(circle);
}
}
g2.setColor(oldColor);
g2.setComposite(oldComp);
}
}
| pengqiuyuan/jcaptcha | src/main/java/com/octo/captcha/component/image/textpaster/textdecorator/BaffleTextDecorator.java | Java | lgpl-2.1 | 4,244 |
package aboullaite;
import javax.swing.*;
//Class to precise who is connected : Client or Server
public class ClientServer {
public ClientServer(){
Object[] selectioValues = { "Server","Client"};
String initialSection = "Server";
Object selection = JOptionPane.showInputDialog(null, "Opciones : ", "Chat Corporativo", JOptionPane.QUESTION_MESSAGE, null, selectioValues, initialSection);
if(selection.equals("Server")){
String[] arguments = new String[] {};
new MultiThreadChatServerSync(arguments);
}else if(selection.equals("Client")){
String IPServer = JOptionPane.showInputDialog("Ingresa El IP Del Servidor");
String[] arguments = new String[] {IPServer};
new ChatClient(arguments);
}
}
}
| jonatan182/JavaSE | Sockets/4.SocketChatMultiSala/src/aboullaite/ClientServer.java | Java | lgpl-2.1 | 801 |
package org.curriki.xwiki.servlet;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.user.api.XWikiUser;
import com.xpn.xwiki.render.XWikiVelocityRenderer;
import com.xpn.xwiki.web.XWikiResponse;
import com.xpn.xwiki.web.XWikiRequest;
import com.xpn.xwiki.web.XWikiEngineContext;
import com.xpn.xwiki.web.XWikiServletRequest;
import com.xpn.xwiki.web.Utils;
import com.xpn.xwiki.web.XWikiURLFactory;
import com.xpn.xwiki.web.XWikiServletContext;
import com.xpn.xwiki.web.XWikiServletResponse;
import com.noelios.restlet.ext.servlet.ServletConverter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.curriki.xwiki.servlet.restlet.router.BaseRouter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.container.servlet.ServletContainerInitializer;
import org.xwiki.container.servlet.ServletContainerException;
import org.xwiki.container.Container;
import org.xwiki.context.Execution;
/**
*/
public class RestletServlet extends BaseServlet {
protected ServletConverter converter;
private static final Logger LOG = LoggerFactory.getLogger(RestletServlet.class);
@Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
converter = new ServletConverter(getServletContext());
XWikiContext context = getXWikiContext(req, res);
converter.getContext().getAttributes().put("XWikiContext", context);
try {
converter.setTarget(new BaseRouter(converter.getContext()));
converter.service(req, res);
} finally {
cleanupComponents();
}
} catch (XWikiException e) {
log("Exception at serving Restlet.",e);
throw new ServletException(e);
}
}
private Object generateDummy(Class someClass) {
ClassLoader loader = someClass.getClassLoader();
InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return null;
}
};
Class[] interfaces = new Class[] {someClass};
return Proxy.newProxyInstance(loader, interfaces, handler);
}
protected XWikiContext getXWikiContext(HttpServletRequest req, HttpServletResponse res) throws XWikiException, ServletException {
XWikiEngineContext engine;
ServletContext sContext = null;
try {
sContext = getServletContext();
} catch (Exception ignore) { }
if (sContext != null) {
engine = new XWikiServletContext(sContext);
} else {
// use fake server context (created as dynamic proxy)
ServletContext contextDummy = (ServletContext)generateDummy(ServletContext.class);
engine = new XWikiServletContext(contextDummy);
}
XWikiRequest request = new XWikiServletRequest(req);
XWikiResponse response = new XWikiServletResponse(res);
XWikiContext context = Utils.prepareContext("", request, response, engine);
context.setMode(XWikiContext.MODE_SERVLET);
context.setDatabase("xwiki");
// We need to initialize the new components for Velocity to work
initializeContainerComponent(context);
XWiki xwiki = XWiki.getXWiki(context);
XWikiURLFactory urlf = xwiki.getURLFactoryService().createURLFactory(context.getMode(), context);
context.setURLFactory(urlf);
// TODO: Fix velocity init in servlet
// XWikiVelocityRenderer.prepareContext(context);
xwiki.prepareResources(context);
String username = "XWiki.XWikiGuest";
XWikiUser user = context.getWiki().checkAuth(context);
if (user != null) {
username = user.getUser();
}
context.setUser(username);
// Give servlet "programming" rights
XWikiDocument rightsDoc = context.getWiki().getDocument("XWiki.XWikiPreferences", context);
context.put("sdoc", rightsDoc);
if (context.getDoc() == null) {
context.setDoc(new XWikiDocument("Fake", "Document"));
}
context.put("ajax", new Boolean(true));
return context;
}
protected void initializeContainerComponent(XWikiContext context)
throws ServletException
{
// Initialize the Container fields (request, response, session).
// Note that this is a bridge between the old core and the component architecture.
// In the new component architecture we use ThreadLocal to transport the request,
// response and session to components which require them.
// In the future this Servlet will be replaced by the XWikiPlexusServlet Servlet.
ServletContainerInitializer containerInitializer =
(ServletContainerInitializer) Utils.getComponent(ServletContainerInitializer.class);
try {
containerInitializer.initializeRequest(context.getRequest().getHttpServletRequest(),
context);
containerInitializer.initializeResponse(context.getResponse().getHttpServletResponse());
containerInitializer.initializeSession(context.getRequest().getHttpServletRequest());
} catch (ServletContainerException e) {
throw new ServletException("Failed to initialize Request/Response or Session", e);
}
}
protected void cleanupComponents()
{
Container container = (Container) Utils.getComponent(Container.class);
Execution execution = (Execution) Utils.getComponent(Execution.class);
// We must ensure we clean the ThreadLocal variables located in the Container and Execution
// components as otherwise we will have a potential memory leak.
container.removeRequest();
container.removeResponse();
container.removeSession();
execution.removeContext();
}
}
| xwiki-contrib/currikiorg | plugins/servlet/src/main/java/org/curriki/xwiki/servlet/RestletServlet.java | Java | lgpl-2.1 | 6,370 |
package jfcraft.block;
/** Block with X pattern w/variables 2 blocks high
*
* @author pquiring
*
* Created : Mar 25, 2014
*/
import jfcraft.data.*;
import jfcraft.opengl.*;
public class BlockXVar2 extends BlockX2 {
public BlockXVar2(String id, String names[], String images[]) {
super(id, names, images);
isOpaque = false;
isAlpha = false;
isVar = true;
isComplex = true;
isSolid = false;
resetBoxes(Type.BOTH);
}
}
| pquiring/jfcraft | src/base/jfcraft/block/BlockXVar2.java | Java | lgpl-2.1 | 456 |
/**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.dump;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import lucee.commons.io.SystemUtil;
import lucee.commons.io.SystemUtil.TemplateLine;
import lucee.commons.lang.StringUtil;
import lucee.runtime.PageContext;
import lucee.runtime.engine.ThreadLocalPageContext;
public class HTMLDumpWriter implements DumpWriter {
private static int count = 0;
@Override
public void writeOut(PageContext pc, DumpData data, Writer writer, boolean expand) throws IOException {
writeOut(pc, data, writer, expand, false);
}
private void writeOut(PageContext pc, DumpData data, Writer writer, boolean expand, boolean inside) throws IOException {
if (data == null) return;
if (!(data instanceof DumpTable)) {
writer.write(StringUtil.escapeHTML(data.toString()));
return;
}
DumpTable table = (DumpTable) data;
String id = "_dump" + (count++);
// prepare data
DumpRow[] rows = table.getRows();
int cols = 0;
for (int i = 0; i < rows.length; i++)
if (rows[i].getItems().length > cols) cols = rows[i].getItems().length;
if (!inside) {
writer.write("<script>");
writer.write("function dumpOC(name){");
writer.write("var tds=document.all?document.getElementsByTagName('tr'):document.getElementsByName('_'+name);");
// writer.write("var button=document.images['__btn'+name];");
writer.write("var s=null;");
// writer.write("if(button.src.indexOf('plus')==-1)
// button.src=button.src.replace('minus','plus');");
// writer.write("else button.src=button.src.replace('plus','minus');");
writer.write("name='_'+name;");
writer.write("for(var i=0;i<tds.length;i++) {");
writer.write("if(document.all && tds[i].name!=name)continue;");
writer.write("s=tds[i].style;");
writer.write("if(s.display=='none') s.display='';");
writer.write("else s.display='none';");
writer.write("}");
writer.write("}");
writer.write("</script>");
}
TemplateLine tl = null;
if (!inside) tl = SystemUtil.getCurrentContext();
String context = tl == null ? "" : tl.toString();
writer.write(
"<table" + (table.getWidth() != null ? " width=\"" + table.getWidth() + "\"" : "") + "" + (table.getHeight() != null ? " height=\"" + table.getHeight() + "\"" : "")
+ " cellpadding=\"3\" cellspacing=\"1\" style=\"font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;font-size : 11px;color :" + table.getFontColor()
+ " ;empty-cells:show;\">");
// header
if (!StringUtil.isEmpty(table.getTitle())) {
writer.write("<tr><td title=\"" + context + "\" onclick=\"dumpOC('" + id + "')\" colspan=\"" + cols + "\" bgcolor=\"" + table.getHighLightColor()
+ "\" style=\"border : 1px solid " + table.getBorderColor() + "; empty-cells:show;\">");
// isSetContext=true;
String contextPath = "";
pc = ThreadLocalPageContext.get(pc);
if (pc != null) {
contextPath = pc.getHttpServletRequest().getContextPath();
if (contextPath == null) contextPath = "";
}
writer.write("<span style=\"font-weight:bold;\">" + (!StringUtil.isEmpty(table.getTitle()) ? table.getTitle() : "") + "</span>"
+ (!StringUtil.isEmpty(table.getComment()) ? "<br>" + table.getComment() : "") + "</td></tr>");
}
else id = null;
// items
DumpData value;
for (int i = 0; i < rows.length; i++) {
if (id != null) writer.write("<tr name=\"_" + id + "\">");
else writer.write("<tr>");
DumpData[] items = rows[i].getItems();
int hType = rows[i].getHighlightType();
int comperator = 1;
for (int y = 0; y < cols; y++) {
if (y <= items.length - 1) value = items[y];
else value = new SimpleDumpData(" ");
boolean highLightIt = hType == -1 || ((hType & (comperator)) > 0);
comperator *= 2;
if (value == null) value = new SimpleDumpData("null");
// else if(value.equals(""))value=" ";
if (!inside) {
writer.write("<td valign=\"top\" title=\"" + context + "\"");
}
else writer.write("<td valign=\"top\"");
writer.write(" bgcolor=\"" + ((highLightIt) ? table.getHighLightColor() : table.getNormalColor()) + "\" style=\"border : 1px solid " + table.getBorderColor()
+ ";empty-cells:show;\">");
writeOut(pc, value, writer, expand, true);
writer.write("</td>");
}
writer.write("</tr>");
}
// footer
writer.write("</table>");
if (!expand) writer.write("<script>dumpOC('" + id + "');</script>");
}
@Override
public String toString(PageContext pc, DumpData data, boolean expand) {
StringWriter sw = new StringWriter();
try {
writeOut(pc, data, sw, expand);
}
catch (IOException e) {
return "";
}
return sw.toString();
}
} | jzuijlek/Lucee | core/src/main/java/lucee/runtime/dump/HTMLDumpWriter.java | Java | lgpl-2.1 | 5,445 |
/**
* RUBBoS: Rice University Bulletin Board System.
* Copyright (C) 2001-2004 Rice University and French National Institute For
* Research In Computer Science And Control (INRIA).
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or 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.
*
* Initial developer(s): Emmanuel Cecchet.
* Contributor(s): Niraj Tolia.
*/
package edu.rice.rubbos.servlets;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.EmptyStackException;
import java.util.Properties;
import java.util.Stack;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Provides the method to initialize connection to the database. All the
* servlets inherit from this class
*/
public abstract class RubbosHttpServlet extends HttpServlet
{
/** Controls connection pooling */
private static final boolean enablePooling = true;
/** Stack of available connections (pool) */
private Stack freeConnections = null;
private int poolSize;
private int currentConn = 0;
private Properties dbProperties = null;
public abstract int getPoolSize(); // Get the pool size for this class
/** Load the driver and get a connection to the database */
public void init() throws ServletException
{
InputStream in = null;
poolSize = getPoolSize();
try
{
// Get the properties for the database connection
dbProperties = new Properties();
in = new FileInputStream(Config.DatabaseProperties);
dbProperties.load(in);
// load the driver
Class.forName(dbProperties.getProperty("datasource.classname"));
freeConnections = new Stack();
initializeConnections();
}
catch (FileNotFoundException f)
{
throw new UnavailableException(
"Couldn't find file mysql.properties: " + f + "<br>");
}
catch (IOException io)
{
throw new UnavailableException(
"Cannot open read mysql.properties: " + io + "<br>");
}
catch (ClassNotFoundException c)
{
throw new UnavailableException(
"Couldn't load database driver: " + c + "<br>");
}
catch (SQLException s)
{
throw new UnavailableException(
"Couldn't get database connection: " + s + "<br>");
}
finally
{
try
{
if (in != null)
in.close();
}
catch (Exception e)
{
}
}
}
/**
* Initialize the pool of connections to the database.
* The caller must ensure that the driver has already been
* loaded else an exception will be thrown.
*
* @exception SQLException if an error occurs
*/
public synchronized void initializeConnections() throws SQLException
{
if (enablePooling)
{
for (int i = 0; i < poolSize; i++)
{
// Get connections to the database
freeConnections.push(
DriverManager.getConnection(
dbProperties.getProperty("datasource.url"),
dbProperties.getProperty("datasource.username"),
dbProperties.getProperty("datasource.password")));
}
}
}
// public Connection getConnection()
// {
// // currentConn = (currentConn + 1) % poolSize;
// // return conn[currentConn];
// try
// {
// return DriverManager.getConnection(
// dbProperties.getProperty("datasource.url"),
// dbProperties.getProperty("datasource.username"),
// dbProperties.getProperty("datasource.password"));
// }
// catch (SQLException e)
// {
// return null;
// }
//
// }
/**
* Closes a <code>Connection</code>.
* @param connection to close
*/
private void closeConnection(Connection connection)
{
try
{
connection.close();
}
catch (Exception e)
{
}
}
/**
* Gets a connection from the pool (round-robin)
*
* @return a <code>Connection</code> or
* null if no connection is available
*/
public synchronized Connection getConnection()
{
if (enablePooling)
{
try
{
// Wait for a connection to be available
while (freeConnections.isEmpty())
{
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println("Connection pool wait interrupted.");
}
}
Connection c = (Connection) freeConnections.pop();
return c;
}
catch (EmptyStackException e)
{
System.out.println("Out of connections.");
return null;
}
}
else
{
try
{
return DriverManager.getConnection(
dbProperties.getProperty("datasource.url"),
dbProperties.getProperty("datasource.username"),
dbProperties.getProperty("datasource.password"));
}
catch (SQLException ex)
{
ex.printStackTrace();
return null;
}
}
}
/**
* Releases a connection to the pool.
*
* @param c the connection to release
*/
public synchronized void releaseConnection(Connection c)
{
if (enablePooling)
{
boolean mustNotify = freeConnections.isEmpty();
freeConnections.push(c);
// Wake up one servlet waiting for a connection (if any)
if (mustNotify)
notifyAll();
}
else
{
closeConnection(c);
}
}
/**
* Release all the connections to the database.
*
* @exception SQLException if an error occurs
*/
public synchronized void finalizeConnections() throws SQLException
{
if (enablePooling)
{
Connection c = null;
while (!freeConnections.isEmpty())
{
c = (Connection) freeConnections.pop();
c.close();
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
}
/**
* Clean up database connections.
*/
public void destroy()
{
try
{
finalizeConnections();
}
catch (SQLException e)
{
}
}
}
| hanjae/RUBBoS | Servlets/edu/rice/rubbos/servlets/RubbosHttpServlet.java | Java | lgpl-2.1 | 7,159 |
/*
* eXist Open Source Native XML Database
* Copyright (C) 2001-2014 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.indexing.lucene;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.queryparser.classic.QueryParserBase;
import org.apache.lucene.queryparser.flexible.standard.CommonQueryParserConfiguration;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.Version;
import org.exist.xquery.XPathException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Wrapper around Lucene parsers which are based on
* {@link QueryParserBase}.
*
* @author Wolfgang
*/
public class ClassicQueryParserWrapper extends QueryParserWrapper {
private final static Logger LOG = Logger.getLogger(ClassicQueryParserWrapper.class);
private QueryParserBase parser = null;
public ClassicQueryParserWrapper(String className, String field, Analyzer analyzer) {
super(field, analyzer);
try {
Class<?> clazz = Class.forName(className);
if (QueryParserBase.class.isAssignableFrom(clazz)) {
final Class<?> cParamClasses[] = new Class<?>[] {
Version.class, String.class, Analyzer.class
};
final Constructor<?> cstr = clazz.getDeclaredConstructor(cParamClasses);
parser = (QueryParserBase) cstr.newInstance(LuceneIndex.LUCENE_VERSION_IN_USE, field, analyzer);
}
} catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException e) {
LOG.warn("Failed to instantiate lucene query parser class: " + className, e);
} catch (NoSuchMethodException | InstantiationException e) {
LOG.warn("Failed to instantiate lucene query parser class: " + className + ": " + e.getMessage(), e);
}
}
public ClassicQueryParserWrapper(String field, Analyzer analyzer) {
super(field, analyzer);
parser = new QueryParser(LuceneIndex.LUCENE_VERSION_IN_USE, field, analyzer);
}
public Query parse(String query) throws XPathException {
try {
return parser.parse(query);
} catch (ParseException e) {
throw new XPathException("Syntax error in Lucene query string: " + e.getMessage());
}
}
@Override
public CommonQueryParserConfiguration getConfiguration() {
return parser;
}
}
| shabanovd/exist | extensions/indexes/lucene/src/org/exist/indexing/lucene/ClassicQueryParserWrapper.java | Java | lgpl-2.1 | 3,355 |
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2011, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.wfs.bindings;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.xml.namespace.QName;
import net.opengis.wfs20.FeatureCollectionType;
import net.opengis.wfs20.Wfs20Factory;
import org.eclipse.emf.ecore.EObject;
import org.geotools.data.DataUtilities;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.FeatureCollection;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.wfs.CompositeFeatureCollection;
import org.geotools.wfs.v2_0.WFS;
import org.geotools.xsd.EMFUtils;
import org.geotools.xsd.ElementInstance;
import org.geotools.xsd.Node;
import org.opengis.feature.simple.SimpleFeature;
public class WFSParsingUtils {
public static EObject FeatureCollectionType_parse(
EObject fct, ElementInstance instance, Node node) {
// gml:featureMembers
SimpleFeatureCollection fc =
(SimpleFeatureCollection) node.getChildValue(FeatureCollection.class);
if (fc == null) {
fc = new DefaultFeatureCollection(null, null);
}
// check for an array
SimpleFeature[] featureMembers = node.getChildValue(SimpleFeature[].class);
if (featureMembers != null) {
Collection<SimpleFeature> collection = DataUtilities.collectionCast(fc);
for (SimpleFeature featureMember : featureMembers) {
collection.add(featureMember);
}
} else {
Collection<SimpleFeature> collection = DataUtilities.collectionCast(fc);
List<SimpleFeature> featureMember = node.getChildValues(SimpleFeature.class);
for (SimpleFeature f : featureMember) {
collection.add(f);
}
}
if (!fc.isEmpty()) {
if (EMFUtils.has(fct, "feature")) {
// wfs 1.0, 1.1
EMFUtils.add(fct, "feature", fc);
} else {
// wfs 2.0
EMFUtils.add(fct, "member", fc);
}
}
return fct;
}
public static Object FeatureCollectionType_getProperty(EObject fc, QName name) {
List<FeatureCollection> features = features(fc);
FeatureCollection first = features.get(0);
if ("boundedBy".equals(name.getLocalPart())) {
ReferencedEnvelope bounds = null;
if (features.size() == 1) {
bounds = first.getBounds();
} else {
// aggregate
bounds = new ReferencedEnvelope(first.getBounds());
for (int i = 1; i < features.size(); i++) {
bounds.expandToInclude(features.get(i).getBounds());
}
}
if (bounds == null || bounds.isNull()) {
// wfs 2.0 does not allow for "gml:Null"
if (WFS.NAMESPACE.equals(name.getNamespaceURI())) {
return null;
}
}
return bounds;
}
if ("featureMember".equals(name.getLocalPart()) || "member".equals(name.getLocalPart())) {
if (features.size() == 1) {
// just return the single
return first;
}
// different behaviour across versions, in wfs < 2.0 we merge all the features into
// a single collection, wfs 2.0+ we create a feature collection that contains multiple
// feature collections
if ("featureMember".equals(name.getLocalPart())) {
// wrap in a single
return new CompositeFeatureCollection(features);
}
// we need to recalculate numberMatched, and numberRetunred
int numberMatched = -1;
if (EMFUtils.has(fc, "numberMatched")) {
Number n = (Number) EMFUtils.get(fc, "numberMatched");
numberMatched = n != null ? n.intValue() : -1;
} else if (EMFUtils.has(fc, "numberOfFeatures")) {
Number n = (Number) EMFUtils.get(fc, "numberOfFeatures");
numberMatched = n != null ? n.intValue() : -1;
}
// create new feature collections
List<FeatureCollectionType> members = new ArrayList<>(features.size());
for (Iterator<FeatureCollection> it = features.iterator(); it.hasNext(); ) {
FeatureCollection featureCollection = it.next();
FeatureCollectionType member = Wfs20Factory.eINSTANCE.createFeatureCollectionType();
member.setTimeStamp((Calendar) EMFUtils.get(fc, "timeStamp"));
member.getMember().add(featureCollection);
members.add(member);
if (numberMatched == -1) {
continue;
}
// TODO: calling size() here is bad because it requires a nother trip to the
// underlying datastore... perhaps try to keep count of the size of each feature
// collection at a higher level
int size = featureCollection.size();
member.setNumberReturned(BigInteger.valueOf(size));
if (it.hasNext()) {
numberMatched -= size;
member.setNumberMatched(BigInteger.valueOf(size));
} else {
member.setNumberMatched(BigInteger.valueOf(numberMatched));
}
}
return members;
}
return null;
}
@SuppressWarnings("unchecked")
public static List<FeatureCollection> features(EObject obj) {
return (List)
(EMFUtils.has(obj, "feature")
? EMFUtils.get(obj, "feature")
: EMFUtils.get(obj, "member"));
}
}
| geotools/geotools | modules/extension/xsd/xsd-wfs/src/main/java/org/geotools/wfs/bindings/WFSParsingUtils.java | Java | lgpl-2.1 | 6,619 |
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2001 - 2013 Object Refinery Ltd, Hitachi Vantara and Contributors.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.core.modules.misc.configstore.base;
import org.pentaho.reporting.libraries.base.boot.AbstractModule;
import org.pentaho.reporting.libraries.base.boot.ModuleInitializeException;
import org.pentaho.reporting.libraries.base.boot.SubSystem;
/**
* The module definition for the config store system.
*
* @author Thomas Morgner
*/
public class ConfigStoreBaseModule extends AbstractModule {
/**
* DefaultConstructor. Loads the module specification.
*
* @throws ModuleInitializeException
* if an error occured.
*/
public ConfigStoreBaseModule() throws ModuleInitializeException {
loadModuleInfo();
}
/**
* Initializes the module. Use this method to perform all initial setup operations. This method is called only once in
* a modules lifetime. If the initializing cannot be completed, throw a ModuleInitializeException to indicate the
* error,. The module will not be available to the system.
*
* @param subSystem
* the subSystem.
* @throws ModuleInitializeException
* if an error ocurred while initializing the module.
*/
public void initialize( final SubSystem subSystem ) throws ModuleInitializeException {
}
}
| mbatchelor/pentaho-reporting | engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/modules/misc/configstore/base/ConfigStoreBaseModule.java | Java | lgpl-2.1 | 2,117 |
package org.exist.xquery.functions.xmldb;
import java.util.List;
import org.apache.log4j.Logger;
import org.exist.dom.QName;
import org.exist.xquery.BasicFunction;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.Type;
import org.exist.xquery.Cardinality;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.FunctionParameterSequenceType;
import org.exist.xquery.value.FunctionReturnSequenceType;
import org.exist.xquery.value.ValueSequence;
import org.exist.xquery.value.StringValue;
/**
*
* @author Adam Retter <[email protected]>
*/
public class XMLDBMatchCollection extends BasicFunction {
protected static final Logger logger = Logger.getLogger(XMLDBMatchCollection.class);
public final static FunctionSignature signature = new FunctionSignature(
new QName("match-collection", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX),
"Looks for collection names in the collection index that match the provided regexp",
new SequenceType[]{
new FunctionParameterSequenceType("regexp", Type.STRING, Cardinality.EXACTLY_ONE, "The expression to use for matching collection names"),
},
new FunctionReturnSequenceType(Type.STRING, Cardinality.ZERO_OR_MORE, "The names of the collections that match the expression"));
public XMLDBMatchCollection(XQueryContext context) {
super(context, signature);
}
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
Sequence result = Sequence.EMPTY_SEQUENCE;
final String regexp = args[0].getStringValue();
final List<String> collectionNames = context.getBroker().findCollectionsMatching(regexp);
if(collectionNames.size() > 0) {
result = copyListToValueSequence(collectionNames);
}
return result;
}
private Sequence copyListToValueSequence(List<String> collectionNames) {
final ValueSequence seq = new ValueSequence(collectionNames.size());
for(final String collectionName : collectionNames) {
seq.add(new StringValue(collectionName));
}
return seq;
}
} | shabanovd/exist | src/org/exist/xquery/functions/xmldb/XMLDBMatchCollection.java | Java | lgpl-2.1 | 2,386 |
/*
* 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.test.immutable.entitywithmutablecollection;
import java.util.Iterator;
import org.junit.Test;
import org.hibernate.MappingException;
import org.hibernate.Session;
import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
import org.hibernate.Transaction;
import org.hibernate.TransactionException;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Gail Badner
*/
public abstract class AbstractEntityWithManyToManyTest extends BaseCoreFunctionalTestCase {
private boolean isPlanContractsInverse;
private boolean isPlanContractsBidirectional;
private boolean isPlanVersioned;
private boolean isContractVersioned;
@Override
public void configure(Configuration cfg) {
cfg.setProperty( Environment.GENERATE_STATISTICS, "true");
}
@Override
protected void prepareTest() throws Exception {
super.prepareTest();
isPlanContractsInverse = sessionFactory().getCollectionPersister( Plan.class.getName() + ".contracts" ).isInverse();
try {
sessionFactory().getCollectionPersister( Contract.class.getName() + ".plans" );
isPlanContractsBidirectional = true;
}
catch ( MappingException ex) {
isPlanContractsBidirectional = false;
}
isPlanVersioned = sessionFactory().getEntityPersister( Plan.class.getName() ).isVersioned();
isContractVersioned = sessionFactory().getEntityPersister( Contract.class.getName() ).isVersioned();
sessionFactory().getStatistics().clear();
}
@Test
public void testUpdateProperty() {
clearCounts();
Plan p = new Plan( "plan" );
p.addContract( new Contract( null, "gail", "phone") );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist(p);
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = (Plan) s.createCriteria( Plan.class ).uniqueResult();
p.setDescription( "new plan" );
assertEquals( 1, p.getContracts().size() );
Contract c = ( Contract ) p.getContracts().iterator().next();
c.setCustomerName( "yogi" );
t.commit();
s.close();
assertUpdateCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = (Plan) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 1, p.getContracts().size() );
c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertEquals( 1, c.getPlans().size() );
assertSame( p, c.getPlans().iterator().next() );
}
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria( Contract.class ).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria( Plan.class ).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 2 );
}
@Test
public void testCreateWithNonEmptyManyToManyCollectionOfNew() {
clearCounts();
Plan p = new Plan( "plan" );
p.addContract( new Contract( null, "gail", "phone") );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist(p);
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 1, p.getContracts().size() );
Contract c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertEquals( 1, c.getPlans().size() );
assertSame( p, c.getPlans().iterator().next() );
}
s.delete(p);
assertEquals( new Long( 0 ), s.createCriteria( Contract.class ).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria( Plan.class ).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 2 );
}
@Test
public void testCreateWithNonEmptyManyToManyCollectionOfExisting() {
clearCounts();
Contract c = new Contract( null, "gail", "phone");
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist(c);
t.commit();
s.close();
assertInsertCount( 1 );
assertUpdateCount( 0 );
clearCounts();
Plan p = new Plan( "plan" );
p.addContract( c );
s = openSession();
t = s.beginTransaction();
s.save(p);
t.commit();
s.close();
assertInsertCount( 1 );
assertUpdateCount( isContractVersioned ? 1 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 1, p.getContracts().size() );
c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertEquals( 1, c.getPlans().size() );
assertSame( p, c.getPlans().iterator().next() );
}
s.delete(p);
assertEquals( new Long( 0 ), s.createCriteria( Contract.class ).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria( Plan.class ).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 2 );
}
@Test
public void testAddNewManyToManyElementToPersistentEntity() {
clearCounts();
Plan p = new Plan( "plan" );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
t.commit();
s.close();
assertInsertCount( 1 );
assertUpdateCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.get( Plan.class, p.getId() );
assertEquals( 0, p.getContracts().size() );
p.addContract( new Contract( null, "gail", "phone") );
t.commit();
s.close();
assertInsertCount( 1 );
assertUpdateCount( isContractVersioned ? 1 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 1, p.getContracts().size() );
Contract c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertEquals( 1, c.getPlans().size() );
assertSame( p, c.getPlans().iterator().next() );
}
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria( Contract.class ).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria( Plan.class ).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 2 );
}
@Test
public void testAddExistingManyToManyElementToPersistentEntity() {
clearCounts();
Plan p = new Plan( "plan" );
Contract c = new Contract( null, "gail", "phone" );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
s.persist( c );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.get( Plan.class, p.getId() );
assertEquals( 0, p.getContracts().size() );
c = ( Contract ) s.get( Contract.class, c.getId() );
if ( isPlanContractsBidirectional ) {
assertEquals( 0, c.getPlans().size() );
}
p.addContract( c );
t.commit();
s.close();
assertInsertCount( 0 );
assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 1, p.getContracts().size() );
c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertSame( p, c.getPlans().iterator().next() );
}
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria( Plan.class ).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria( Contract.class ).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 2 );
}
@Test
public void testCreateWithEmptyManyToManyCollectionUpdateWithExistingElement() {
clearCounts();
Plan p = new Plan( "plan" );
Contract c = new Contract( null, "gail", "phone");
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
s.persist( c );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
p.addContract( c );
s = openSession();
t = s.beginTransaction();
s.update( p );
t.commit();
s.close();
assertInsertCount( 0 );
assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 1, p.getContracts().size() );
c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertSame( p, c.getPlans().iterator().next() );
}
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria( Contract.class ).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria( Plan.class ).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 2 );
}
@Test
public void testCreateWithNonEmptyManyToManyCollectionUpdateWithNewElement() {
clearCounts();
Plan p = new Plan( "plan" );
Contract c = new Contract( null, "gail", "phone");
p.addContract( c );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist(p);
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
Contract newC = new Contract( null, "sherman", "telepathy" );
p.addContract( newC );
s = openSession();
t = s.beginTransaction();
s.update( p );
t.commit();
s.close();
assertInsertCount( 1 );
assertUpdateCount( isContractVersioned ? 1 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 2, p.getContracts().size() );
for ( Iterator it=p.getContracts().iterator(); it.hasNext(); ) {
Contract aContract = ( Contract ) it.next();
if ( aContract.getId() == c.getId() ) {
assertEquals( "gail", aContract.getCustomerName() );
}
else if ( aContract.getId() == newC.getId() ) {
assertEquals( "sherman", aContract.getCustomerName() );
}
else {
fail( "unknown contract" );
}
if ( isPlanContractsBidirectional ) {
assertSame( p, aContract.getPlans().iterator().next() );
}
}
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria(Plan.class).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 3 );
}
@Test
public void testCreateWithEmptyManyToManyCollectionMergeWithExistingElement() {
clearCounts();
Plan p = new Plan( "plan" );
Contract c = new Contract( null, "gail", "phone");
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
s.persist( c );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
p.addContract( c );
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.merge( p );
t.commit();
s.close();
assertInsertCount( 0 );
assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 1, p.getContracts().size() );
c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertSame( p, c.getPlans().iterator().next() );
}
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria(Plan.class).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 2 );
}
@Test
public void testCreateWithNonEmptyManyToManyCollectionMergeWithNewElement() {
clearCounts();
Plan p = new Plan( "plan" );
Contract c = new Contract( null, "gail", "phone");
p.addContract( c );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
Contract newC = new Contract( null, "yogi", "mail" );
p.addContract( newC );
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.merge( p );
t.commit();
s.close();
assertInsertCount( 1 );
assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 2, p.getContracts().size() );
for ( Iterator it=p.getContracts().iterator(); it.hasNext(); ) {
Contract aContract = ( Contract ) it.next();
if ( aContract.getId() == c.getId() ) {
assertEquals( "gail", aContract.getCustomerName() );
}
else if ( ! aContract.getCustomerName().equals( newC.getCustomerName() ) ) {
fail( "unknown contract:" + aContract.getCustomerName() );
}
if ( isPlanContractsBidirectional ) {
assertSame( p, aContract.getPlans().iterator().next() );
}
}
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria( Plan.class ).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria( Contract.class ).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 3 );
}
@Test
public void testRemoveManyToManyElementUsingUpdate() {
clearCounts();
Plan p = new Plan( "plan" );
Contract c = new Contract( null, "gail", "phone");
p.addContract( c );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
p.removeContract( c );
assertEquals( 0, p.getContracts().size() );
if ( isPlanContractsBidirectional ) {
assertEquals( 0, c.getPlans().size() );
}
s = openSession();
t = s.beginTransaction();
s.update( p );
t.commit();
s.close();
assertUpdateCount( isContractVersioned ? 1 : 0 );
assertDeleteCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
if ( isPlanContractsInverse ) {
assertEquals( 1, p.getContracts().size() );
c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
assertSame( p, c.getPlans().iterator().next() );
}
else {
assertEquals( 0, p.getContracts().size() );
c = ( Contract ) s.createCriteria( Contract.class ).uniqueResult();
if ( isPlanContractsBidirectional ) {
assertEquals( 0, c.getPlans().size() );
}
s.delete( c );
}
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria(Plan.class).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 2 );
}
@Test
public void testRemoveManyToManyElementUsingUpdateBothSides() {
clearCounts();
Plan p = new Plan( "plan" );
Contract c = new Contract( null, "gail", "phone");
p.addContract( c );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
p.removeContract( c );
assertEquals( 0, p.getContracts().size() );
if ( isPlanContractsBidirectional ) {
assertEquals( 0, c.getPlans().size() );
}
s = openSession();
t = s.beginTransaction();
s.update( p );
s.update( c );
t.commit();
s.close();
assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0 );
assertDeleteCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 0, p.getContracts().size() );
c = ( Contract ) s.createCriteria( Contract.class ).uniqueResult();
if ( isPlanContractsBidirectional ) {
assertEquals( 0, c.getPlans().size() );
}
s.delete( c );
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria(Plan.class).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 2 );
}
@Test
public void testRemoveManyToManyElementUsingMerge() {
clearCounts();
Plan p = new Plan( "plan" );
Contract c = new Contract( null, "gail", "phone");
p.addContract( c );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
p.removeContract( c );
assertEquals( 0, p.getContracts().size() );
if ( isPlanContractsBidirectional ) {
assertEquals( 0, c.getPlans().size() );
}
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.merge( p );
t.commit();
s.close();
assertUpdateCount( isContractVersioned ? 1 : 0 );
assertDeleteCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
if ( isPlanContractsInverse ) {
assertEquals( 1, p.getContracts().size() );
c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
assertSame( p, c.getPlans().iterator().next() );
}
else {
assertEquals( 0, p.getContracts().size() );
c = ( Contract ) s.createCriteria( Contract.class ).uniqueResult();
if ( isPlanContractsBidirectional ) {
assertEquals( 0, c.getPlans().size() );
}
s.delete( c );
}
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria(Plan.class).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 2 );
}
@Test
public void testRemoveManyToManyElementUsingMergeBothSides() {
clearCounts();
Plan p = new Plan( "plan" );
Contract c = new Contract( null, "gail", "phone");
p.addContract( c );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
p.removeContract( c );
assertEquals( 0, p.getContracts().size() );
if ( isPlanContractsBidirectional ) {
assertEquals( 0, c.getPlans().size() );
}
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.merge( p );
c = ( Contract ) s.merge( c );
t.commit();
s.close();
assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0 );
assertDeleteCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 0, p.getContracts().size() );
c = ( Contract ) s.createCriteria( Contract.class ).uniqueResult();
if ( isPlanContractsBidirectional ) {
assertEquals( 0, c.getPlans().size() );
}
s.delete( c );
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria(Plan.class).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 2 );
}
@Test
public void testDeleteManyToManyElement() {
clearCounts();
Plan p = new Plan( "plan" );
Contract c = new Contract( null, "gail", "phone");
p.addContract( c );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
s.update( p );
p.removeContract( c );
s.delete( c );
t.commit();
s.close();
assertUpdateCount( isContractVersioned ? 1 : 0 );
assertDeleteCount( 1 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 0, p.getContracts().size() );
c = ( Contract ) s.createCriteria( Contract.class ).uniqueResult();
assertNull( c );
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria(Plan.class).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 1 );
}
@Test
public void testRemoveManyToManyElementByDelete() {
clearCounts();
Plan p = new Plan( "plan" );
Contract c = new Contract( null, "gail", "phone");
p.addContract( c );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
p.removeContract( c );
assertEquals( 0, p.getContracts().size() );
if ( isPlanContractsBidirectional ) {
assertEquals( 0, c.getPlans().size() );
}
s = openSession();
t = s.beginTransaction();
s.update( p );
s.delete( c );
t.commit();
s.close();
assertUpdateCount( isPlanVersioned ? 1 : 0 );
assertDeleteCount( 1 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 0, p.getContracts().size() );
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria(Plan.class).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 1 );
}
@Test
public void testManyToManyCollectionOptimisticLockingWithMerge() {
clearCounts();
Plan pOrig = new Plan( "plan" );
Contract cOrig = new Contract( null, "gail", "phone");
pOrig.addContract( cOrig );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( pOrig );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
Plan p = ( Plan ) s.get( Plan.class, pOrig.getId() );
Contract newC = new Contract( null, "sherman", "note" );
p.addContract( newC );
t.commit();
s.close();
assertInsertCount( 1 );
assertUpdateCount( isContractVersioned ? 1 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
pOrig.removeContract( cOrig );
try {
s.merge( pOrig );
assertFalse( isContractVersioned );
}
catch (StaleObjectStateException ex) {
assertTrue( isContractVersioned);
}
finally {
t.rollback();
}
s.close();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
s.delete( p );
assertEquals( new Long( 0 ), s.createCriteria(Plan.class).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 3 );
}
@Test
public void testManyToManyCollectionOptimisticLockingWithUpdate() {
clearCounts();
Plan pOrig = new Plan( "plan" );
Contract cOrig = new Contract( null, "gail", "phone");
pOrig.addContract( cOrig );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist(pOrig);
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
Plan p = ( Plan ) s.get( Plan.class, pOrig.getId() );
Contract newC = new Contract( null, "yogi", "pawprint" );
p.addContract( newC );
t.commit();
s.close();
assertInsertCount( 1 );
assertUpdateCount( isContractVersioned ? 1 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
pOrig.removeContract( cOrig );
s.update( pOrig );
try {
t.commit();
assertFalse( isContractVersioned );
}
catch (StaleStateException ex) {
t.rollback();
assertTrue( isContractVersioned );
if ( ! sessionFactory().getSessionFactoryOptions().isJdbcBatchVersionedData() ) {
assertTrue( StaleObjectStateException.class.isInstance( ex ) );
}
}
s.close();
s = openSession();
t = s.beginTransaction();
p = ( Plan ) s.createCriteria( Plan.class ).uniqueResult();
s.delete( p );
s.createQuery( "delete from Contract" ).executeUpdate();
assertEquals( new Long( 0 ), s.createCriteria(Plan.class).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
}
@Test
public void testMoveManyToManyElementToNewEntityCollection() {
clearCounts();
Plan p = new Plan( "plan" );
p.addContract( new Contract( null, "gail", "phone" ) );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
t.commit();
s.close();
assertInsertCount( 2 );
assertUpdateCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = (Plan) s.createCriteria( Plan.class ).uniqueResult();
assertEquals( 1, p.getContracts().size() );
Contract c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertSame( p, c.getPlans().iterator().next() );
}
p.removeContract( c );
Plan p2 = new Plan( "new plan" );
p2.addContract( c );
s.save( p2 );
t.commit();
s.close();
assertInsertCount( 1 );
assertUpdateCount( isPlanVersioned && isContractVersioned ? 2 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = (Plan) s.createCriteria( Plan.class ).add( Restrictions.idEq( new Long( p.getId() ) )).uniqueResult();
p2 = (Plan) s.createCriteria( Plan.class ).add( Restrictions.idEq( new Long( p2.getId() ) )).uniqueResult();
/*
if ( isPlanContractsInverse ) {
assertEquals( 1, p.getContracts().size() );
c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertSame( p, c.getPlans().iterator().next() );
}
assertEquals( 0, p2.getContracts().size() );
}
else {
*/
assertEquals( 0, p.getContracts().size() );
assertEquals( 1, p2.getContracts().size() );
c = ( Contract ) p2.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertSame( p2, c.getPlans().iterator().next() );
}
//}
s.delete( p );
s.delete( p2 );
assertEquals( new Long( 0 ), s.createCriteria( Plan.class ).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria( Contract.class ).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 3 );
}
@Test
public void testMoveManyToManyElementToExistingEntityCollection() {
clearCounts();
Plan p = new Plan( "plan" );
p.addContract( new Contract( null, "gail", "phone" ) );
Plan p2 = new Plan( "plan2" );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
s.persist( p2 );
t.commit();
s.close();
assertInsertCount( 3 );
assertUpdateCount( 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = (Plan) s.createCriteria( Plan.class ).add( Restrictions.idEq( new Long( p.getId() ) )).uniqueResult();
assertEquals( 1, p.getContracts().size() );
Contract c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertSame( p, c.getPlans().iterator().next() );
}
p.removeContract( c );
t.commit();
s.close();
assertInsertCount( 0 );
assertUpdateCount( isPlanVersioned && isContractVersioned ? 2 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p2 = (Plan) s.createCriteria( Plan.class ).add( Restrictions.idEq( new Long( p2.getId() ) )).uniqueResult();
c = (Contract) s.createCriteria( Contract.class ).add( Restrictions.idEq( new Long( c.getId() ) )).uniqueResult();
p2.addContract( c );
t.commit();
s.close();
assertInsertCount( 0 );
assertUpdateCount( isPlanVersioned && isContractVersioned ? 2 : 0 );
clearCounts();
s = openSession();
t = s.beginTransaction();
p = (Plan) s.createCriteria( Plan.class ).add( Restrictions.idEq( new Long( p.getId() ) )).uniqueResult();
p2 = (Plan) s.createCriteria( Plan.class ).add( Restrictions.idEq( new Long( p2.getId() ) )).uniqueResult();
/*
if ( isPlanContractsInverse ) {
assertEquals( 1, p.getContracts().size() );
c = ( Contract ) p.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertSame( p, c.getPlans().iterator().next() );
}
assertEquals( 0, p2.getContracts().size() );
}
else {
*/
assertEquals( 0, p.getContracts().size() );
assertEquals( 1, p2.getContracts().size() );
c = ( Contract ) p2.getContracts().iterator().next();
assertEquals( "gail", c.getCustomerName() );
if ( isPlanContractsBidirectional ) {
assertSame( p2, c.getPlans().iterator().next() );
}
//}
s.delete( p );
s.delete( p2 );
assertEquals( new Long( 0 ), s.createCriteria( Plan.class ).setProjection( Projections.rowCount() ).uniqueResult() );
assertEquals( new Long( 0 ), s.createCriteria( Contract.class ).setProjection( Projections.rowCount() ).uniqueResult() );
t.commit();
s.close();
assertUpdateCount( 0 );
assertDeleteCount( 3 );
}
protected void clearCounts() {
sessionFactory().getStatistics().clear();
}
protected void assertInsertCount(int expected) {
int inserts = ( int ) sessionFactory().getStatistics().getEntityInsertCount();
assertEquals( "unexpected insert count", expected, inserts );
}
protected void assertUpdateCount(int expected) {
int updates = ( int ) sessionFactory().getStatistics().getEntityUpdateCount();
assertEquals( "unexpected update counts", expected, updates );
}
protected void assertDeleteCount(int expected) {
int deletes = ( int ) sessionFactory().getStatistics().getEntityDeleteCount();
assertEquals( "unexpected delete counts", expected, deletes );
}
}
| 1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/immutable/entitywithmutablecollection/AbstractEntityWithManyToManyTest.java | Java | lgpl-2.1 | 32,283 |
package fr.toss.FF7itemsf;
public class itemf101 extends FF7itemsfbase {
public itemf101(int id) {
super(id);
setUnlocalizedName("itemf101");
}
}
| GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7itemsf/itemf101.java | Java | lgpl-2.1 | 159 |
//$HeadURL$
/*----------------------------------------------------------------------------
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: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.model.coverage.grid;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.renderable.ParameterBlock;
import java.awt.image.renderable.RenderableImage;
import javax.media.jai.Interpolation;
import javax.media.jai.InterpolationNearest;
import javax.media.jai.JAI;
import javax.media.jai.RenderableGraphics;
import javax.media.jai.RenderedOp;
import org.deegree.model.crs.CoordinateSystem;
import org.deegree.model.spatialschema.Envelope;
import org.deegree.ogcwebservices.wcs.describecoverage.CoverageOffering;
/**
* GridCoverage implementation for holding grids stored in an <tt>BufferedImage</tt> or in a set of
* <tt>ImageGridCoverage</tt>s
*
* @author <a href="mailto:[email protected]">Andreas Poth</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class ImageGridCoverage extends AbstractGridCoverage {
private static final long serialVersionUID = -531939507044569726L;
private transient BufferedImage image = null;
/**
*
* @param coverageOffering
* @param envelope
* @param image
*/
public ImageGridCoverage( CoverageOffering coverageOffering, Envelope envelope, BufferedImage image ) {
this( coverageOffering, envelope, false, image );
}
/**
*
* @param coverageOffering
* @param envelope
* @param isEditable
* @param image
*/
public ImageGridCoverage( CoverageOffering coverageOffering, Envelope envelope, boolean isEditable,
BufferedImage image ) {
super( coverageOffering, envelope, isEditable );
this.image = image;
}
/**
*
* @param coverageOffering
* @param envelope
* @param crs
* @param isEditable
* @param image
*/
public ImageGridCoverage( CoverageOffering coverageOffering, Envelope envelope, CoordinateSystem crs,
boolean isEditable, BufferedImage image ) {
super( coverageOffering, envelope, crs, isEditable );
this.image = image;
}
/**
*
* @param coverageOffering
* @param envelope
* @param sources
*/
public ImageGridCoverage( CoverageOffering coverageOffering, Envelope envelope, ImageGridCoverage[] sources ) {
super( coverageOffering, envelope, sources );
}
/**
* The number of sample dimensions in the coverage. For grid coverages, a sample dimension is a band.
*
* @return The number of sample dimensions in the coverage.
*/
public int getNumSampleDimensions() {
if ( image != null ) {
return image.getData().getNumBands();
}
return sources[0].getNumSampleDimensions();
}
/**
* Returns 2D view of this coverage as a renderable image. This optional operation allows interoperability with <A
* HREF="http://java.sun.com/products/java-media/2D/">Java2D</A>. If this coverage is a
* {@link "org.opengis.coverage.grid.GridCoverage"} backed by a {@link java.awt.image.RenderedImage}, the underlying
* image can be obtained with:
*
* <code>getRenderableImage(0,1).{@linkplain RenderableImage#createDefaultRendering()
* createDefaultRendering()}</code>
*
* @param xAxis
* Dimension to use for the <var>x</var> axis.
* @param yAxis
* Dimension to use for the <var>y</var> axis.
* @return A 2D view of this coverage as a renderable image.
* @throws UnsupportedOperationException
* if this optional operation is not supported.
* @throws IndexOutOfBoundsException
* if <code>xAxis</code> or <code>yAxis</code> is out of bounds.
*/
@Override
public RenderableImage getRenderableImage( int xAxis, int yAxis )
throws UnsupportedOperationException, IndexOutOfBoundsException {
if ( image != null ) {
if ( xAxis > 0 && yAxis > 0 ) {
Rectangle rect = new Rectangle( xAxis, yAxis );
RenderableGraphics rg = new RenderableGraphics( rect );
rg.drawImage( image, 0, 0, xAxis, yAxis, null );
return rg;
}
Rectangle rect = new Rectangle( image.getWidth(), image.getHeight() );
RenderableGraphics rg = new RenderableGraphics( rect );
rg.drawImage( image, 0, 0, null );
return rg;
}
// TODO if multi images -> sources.length > 0
return null;
}
/**
* this is a deegree convenience method which returns the source image of an <tt>ImageGridCoverage</tt>. In procipal
* the same can be done with the getRenderableImage(int xAxis, int yAxis) method. but creating a
* <tt>RenderableImage</tt> image is very slow. I xAxis or yAxis <= 0 then the size of the returned image will be
* calculated from the source images of the coverage.
*
* @param xAxis
* Dimension to use for the <var>x</var> axis.
* @param yAxis
* Dimension to use for the <var>y</var> axis.
* @return the source image of an <tt>ImageGridCoverage</tt>.
*/
@Override
public BufferedImage getAsImage( int xAxis, int yAxis ) {
if ( xAxis <= 0 || yAxis <= 0 ) {
// get default size if passed target size is <= 0
Rectangle rect = calculateOriginalSize();
xAxis = rect.width;
yAxis = rect.height;
}
BufferedImage bi = null;
if ( image != null ) {
if ( xAxis == image.getWidth() && yAxis == image.getHeight() ) {
bi = image;
} else {
// it's a simple ImageGridCoverage just made up of one image
ParameterBlock pb = new ParameterBlock();
pb.addSource( image );
pb.add( xAxis / (float) image.getWidth() ); // The xScale
pb.add( yAxis / (float) image.getHeight() ); // The yScale
pb.add( 0.0F ); // The x translation
pb.add( 0.0F ); // The y translation
Interpolation interpolation = new InterpolationNearest();
pb.add( interpolation ); // The interpolation
// Create the scale operation
RenderedOp ro = JAI.create( "scale", pb, null );
bi = ro.getAsBufferedImage();
}
} else {
String natFrm = coverageOffering.getSupportedFormats().getNativeFormat().getCode();
if ( "jpg".equalsIgnoreCase( natFrm ) || "jpeg".equalsIgnoreCase( natFrm )
|| "bmp".equalsIgnoreCase( natFrm ) ) {
bi = new BufferedImage( xAxis, yAxis, BufferedImage.TYPE_INT_RGB );
} else {
bi = new BufferedImage( xAxis, yAxis, BufferedImage.TYPE_INT_ARGB );
}
// it's a complex ImageGridCoverage made up of different
// source coverages
if ( sources == null || sources.length == 0 ) {
return bi;
}
for ( int i = 0; i < sources.length; i++ ) {
BufferedImage sourceImg = ( (ImageGridCoverage) sources[i] ).getAsImage( -1, -1 );
bi = paintImage( bi, getEnvelope(), sourceImg, sources[i].getEnvelope() );
}
}
return bi;
}
/**
* calculates the original size of a gridcoverage based on its resolution and the envelope(s) of its source(s).
*
*/
private Rectangle calculateOriginalSize() {
if ( image != null ) {
return new Rectangle( image.getWidth(), image.getHeight() );
}
BufferedImage bi = ( (ImageGridCoverage) sources[0] ).getAsImage( -1, -1 );
Envelope env = sources[0].getEnvelope();
double dx = env.getWidth() / bi.getWidth();
double dy = env.getHeight() / bi.getHeight();
env = this.getEnvelope();
int w = (int) Math.round( env.getWidth() / dx );
int h = (int) Math.round( env.getHeight() / dy );
return new Rectangle( w, h );
}
}
| lat-lon/deegree2-base | deegree2-core/src/main/java/org/deegree/model/coverage/grid/ImageGridCoverage.java | Java | lgpl-2.1 | 9,668 |
package nl.idgis.publisher.domain.service;
import java.io.Serializable;
public final class ColumnDiff implements Serializable {
private static final long serialVersionUID = -8575827236061364000L;
private final Column column;
private final ColumnDiffOperation operation;
public ColumnDiff (final Column column, final ColumnDiffOperation operation) {
if (column == null) {
throw new NullPointerException ("column cannot be null");
}
if (operation == null) {
throw new NullPointerException ("operation cannot be null");
}
this.column = column;
this.operation = operation;
}
public Column getColumn () {
return column;
}
public ColumnDiffOperation getOperation () {
return operation;
}
}
| IDgis/geo-publisher | publisher-domain/src/main/java/nl/idgis/publisher/domain/service/ColumnDiff.java | Java | lgpl-2.1 | 756 |
package m.c.m.proxyma;
/**
* <p>
* This class is only a constants aggregator
* </p><p>
* NOTE: this software is released under GPL License.
* See the LICENSE of this distribution for more informations.
* </p>
*
* @author Marco Casavecchia Morganti (marcolinuz) [marcolinuz-at-gmail.com]
* @version $Id: ProxymaTags.java 157 2010-06-27 19:24:02Z marcolinuz $
*/
public class ProxymaTags {
//Resource Handler available Types
public static enum HandlerType { PREPROCESSOR, RETRIVER, TRANSFORMER, SERIALIZER };
public static enum LogLevels {SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST, ALL };
// Global Configuration Parameter names
public static final String DEFAULT_LOGGER_PREFIX = "m.c.m.proxyma";
public static final String GLOBAL_DEFAULT_ENCODING = "global/defaultEncoding";
public static final String CONFIG_FILE_VERSION = "global/version";
public static final String GLOBAL_BUFFERS_IMPLEMENTATION = "global/byteBufferImplementation";
public static final String GLOBAL_SHOW_FOLDERS_LIST = "global/showProxyFoldersOnRootPath";
public static final String GLOBAL_LOGLEVEL = "global/logging/@level";
public static final String GLOBAL_LOGFILE_MAXSIZE = "global/logging/@maxLinesPerFile";
public static final String GLOBAL_LOGFILES_RETENTION = "global/logging/@retentionPolicy";
//Plugins Parameter configuration names
public static final String AVAILABLE_CACHE_PROVIDERS = "plugins/avaliableCacheProviders/cacheProvider";
public static final String AVAILABLE_PREPROCESSORS = "plugins/avaliablePreprocessors/resourceHandler";
public static final String AVAILABLE_TRANSFORMERS = "plugins/avaliableTransformers/resourceHandler";
public static final String AVAILABLE_SERIALIZERS = "plugins/availableSerializers/resourceHandler";
public static final String AVAILABLE_RETRIVERS = "plugins/availableRetrivers/resourceHandler";
//Context configuration parameter names
public static final String FOLDER_MAX_POST_SIZE = "defaultContext/folderSettings/@maxPostSize";
public static final String FOLDER_ENABLED = "defaultContext/folderSettings/@enabled";
public static final String FOLDER_PREPROCESSORS = "defaultContext/folderSettings/preprocessors/resourceHandler/@class";
public static final String FOLDER_CACHEPROVIDER = "defaultContext/folderSettings/cacheProvider/@class";
public static final String FOLDER_RETRIVER = "defaultContext/folderSettings/retriver/@class";
public static final String FOLDER_TRANSFORMERS = "defaultContext/folderSettings/transformers/resourceHandler/@class";
public static final String FOLDER_SERIALIZER = "defaultContext/folderSettings/serializer/@class";
//Misc constants
public static final int UNSPECIFIED_POST_SIZE = 5000;
public static final String UNSPECIFIED_CACHEPROVIDER = "m.c.m.proxyma.plugins.caches.NullCacheProvider";
public static final String UNSPECIFIED_RETRIVER = "m.c.m.proxyma.plugins.retrivers.TestPageRetriver";
public static final String UNSPECIFIED_SERIALIZER = "m.c.m.proxyma.plugins.serializers.SimpleSerializer";
public static final String UNSPECIFIED_LOGLEVEL = "INFO";
}
| dpoldrugo/proxyma | proxyma-core/src/main/java/m/c/m/proxyma/ProxymaTags.java | Java | lgpl-2.1 | 3,173 |
package dr.app.bss;
import java.io.File;
import dr.app.beagle.evomodel.branchmodel.BranchModel;
import dr.app.beagle.evomodel.branchmodel.HomogeneousBranchModel;
import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel;
import dr.app.beagle.evomodel.substmodel.FrequencyModel;
import dr.app.beagle.evomodel.substmodel.GTR;
import dr.app.beagle.evomodel.substmodel.GY94CodonModel;
import dr.app.beagle.evomodel.substmodel.HKY;
import dr.app.beagle.evomodel.substmodel.TN93;
import dr.evolution.datatype.Codons;
import dr.evolution.datatype.Nucleotides;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.StrictClockBranchRates;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.Parameter;
//TODO: serialize
public class PartitionData {
public int from = 1;
public int to = 1000;
public int every = 1;
// //////////////////
// ---TREE MODEL---//
// //////////////////
public File treeFile = null;
public TreeModel treeModel = null;
// ///////////////////////////
// ---SUBSTITUTION MODELS---//
// ///////////////////////////
public int substitutionModel = 0;
public static String[] substitutionModels = { "HKY", //
"GTR", //
"TN93", //
"Yang Codon Model" //
};
public static String[] substitutionParameterNames = new String[] {
"Kappa value", // HKY
"AC", // GTR
"AG", // GTR
"AT", // GTR
"CG", // GTR
"CT", // GTR
"GT", // GTR
"Kappa 1", // TN93
"Kappa 2", // TN93
"Omega value", // Yang Codon Model
"Kappa value" // Yang Codon Model
};
public int[][] substitutionParameterIndices = { { 0 }, // HKY
{ 1, 2, 3, 4, 5, 6 }, // GTR
{ 7, 8 }, // TN93
{ 9, 10 }, // Yang Codon Model
};
public double[] substitutionParameterValues = new double[] { 1.0, // Kappa-value
1.0, // AC
1.0, // AG
1.0, // AT
1.0, // CG
1.0, // CT
1.0, // GT
1.0, // Kappa 1
1.0, // Kappa 2
0.1, // Omega value
1.0 // Kappa value
};
public BranchModel createBranchModel() {
BranchModel branchModel = null;
if (this.substitutionModel == 0) { // HKY
Parameter kappa = new Parameter.Default(1, substitutionParameterValues[0]);
FrequencyModel frequencyModel = this.createFrequencyModel();
HKY hky = new HKY(kappa, frequencyModel);
branchModel = new HomogeneousBranchModel(hky);
} else if (this.substitutionModel == 1) { // GTR
Parameter ac = new Parameter.Default(1, substitutionParameterValues[1]);
Parameter ag = new Parameter.Default(1, substitutionParameterValues[2]);
Parameter at = new Parameter.Default(1, substitutionParameterValues[3]);
Parameter cg = new Parameter.Default(1, substitutionParameterValues[4]);
Parameter ct = new Parameter.Default(1, substitutionParameterValues[5]);
Parameter gt = new Parameter.Default(1, substitutionParameterValues[6]);
FrequencyModel frequencyModel = this.createFrequencyModel();
GTR gtr = new GTR(ac, ag, at, cg, ct, gt, frequencyModel);
branchModel = new HomogeneousBranchModel(gtr);
} else if (this.substitutionModel == 2) { // TN93
Parameter kappa1 = new Parameter.Default(1, substitutionParameterValues[7]);
Parameter kappa2 = new Parameter.Default(1, substitutionParameterValues[8]);
FrequencyModel frequencyModel = this.createFrequencyModel();
TN93 tn93 = new TN93(kappa1, kappa2, frequencyModel);
branchModel = new HomogeneousBranchModel(tn93);
} else if (this.substitutionModel == 3) { // Yang Codon Model
FrequencyModel frequencyModel = this.createFrequencyModel();
Parameter kappa = new Parameter.Default(1, substitutionParameterValues[9]);
Parameter omega = new Parameter.Default(1, substitutionParameterValues[10]);
GY94CodonModel yangCodonModel = new GY94CodonModel(Codons.UNIVERSAL, omega, kappa, frequencyModel);
branchModel = new HomogeneousBranchModel(yangCodonModel);
} else if (this.substitutionModel == 4) {
System.out.println("Not yet implemented");
}
return branchModel;
}// END: createBranchSubstitutionModel
// ////////////////////
// ---CLOCK MODELS---//
// ////////////////////
public int clockModel = 0;
public static String[] clockModels = { "Strict Clock", //
};
public static String[] clockParameterNames = new String[] { "Clock rate", //
};
public int[][] clockParameterIndices = { { 0 }, // StrictClock
};
public double[] clockParameterValues = new double[] { 1.2E-2, // clockrate
};
public BranchRateModel createBranchRateModel() {
BranchRateModel branchRateModel = null;
if (this.clockModel == 0) { // Strict Clock
Parameter rateParameter = new Parameter.Default(1, clockParameterValues[0]);
branchRateModel = new StrictClockBranchRates(rateParameter);
} else if (this.clockModel == 1) {
System.out.println("Not yet implemented");
}
return branchRateModel;
}// END: createBranchRateModel
// ////////////////////////
// ---FREQUENCY MODELS---//
// ////////////////////////
public int frequencyModel = 0;
public static String[] frequencyModels = { "Nucleotide frequencies", //
"Codon frequencies"
};
public static String[] frequencyParameterNames = new String[] {
"Nucleotide frequencies 1", //
"Nucleotide frequencies 2", //
"Nucleotide frequencies 3", //
"Nucleotide frequencies 4", //
"Codon frequencies 1", //
"Codon frequencies 2", //
"Codon frequencies 3", //
"Codon frequencies 4", //
"Codon frequencies 5", //
"Codon frequencies 6", //
"Codon frequencies 7", //
"Codon frequencies 8", //
"Codon frequencies 9", //
"Codon frequencies 10", //
"Codon frequencies 11", //
"Codon frequencies 12", //
"Codon frequencies 13", //
"Codon frequencies 14", //
"Codon frequencies 15", //
"Codon frequencies 16", //
"Codon frequencies 17", //
"Codon frequencies 18", //
"Codon frequencies 19", //
"Codon frequencies 20", //
"Codon frequencies 21", //
"Codon frequencies 22", //
"Codon frequencies 23", //
"Codon frequencies 24", //
"Codon frequencies 25", //
"Codon frequencies 26", //
"Codon frequencies 27", //
"Codon frequencies 28", //
"Codon frequencies 29", //
"Codon frequencies 30", //
"Codon frequencies 31", //
"Codon frequencies 32", //
"Codon frequencies 33", //
"Codon frequencies 34", //
"Codon frequencies 35", //
"Codon frequencies 36", //
"Codon frequencies 37", //
"Codon frequencies 38", //
"Codon frequencies 39", //
"Codon frequencies 40", //
"Codon frequencies 41", //
"Codon frequencies 42", //
"Codon frequencies 43", //
"Codon frequencies 44", //
"Codon frequencies 45", //
"Codon frequencies 46", //
"Codon frequencies 47", //
"Codon frequencies 48", //
"Codon frequencies 49", //
"Codon frequencies 50", //
"Codon frequencies 51", //
"Codon frequencies 52", //
"Codon frequencies 53", //
"Codon frequencies 54", //
"Codon frequencies 55", //
"Codon frequencies 56", //
"Codon frequencies 57", //
"Codon frequencies 58", //
"Codon frequencies 59", //
"Codon frequencies 60", //
"Codon frequencies 61", //
};
public int[][] frequencyParameterIndices = { { 0, 1, 2, 3 }, // Nucleotidefrequencies
{ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, //
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, //
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, //
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, //
44, 45, 46, 47, 48, 49, 50, 51, 52, 53, //
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, //
64 } // Codonfrequencies
};
public double[] frequencyParameterValues = new double[] { 0.25, // nucleotidefrequencies1
0.25, // nucleotidefrequencies2
0.25, // nucleotidefrequencies3
0.25, // nucleotidefrequencies4
0.0163936, // codonfrequencies1
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344 // codonfrequencies61
};
public FrequencyModel createFrequencyModel() {
FrequencyModel frequencyModel = null;
if (this.frequencyModel == 0) { // Nucleotidefrequencies
Parameter freqs = new Parameter.Default(new double[] {
frequencyParameterValues[0], frequencyParameterValues[1],
frequencyParameterValues[2], frequencyParameterValues[3] });
frequencyModel = new FrequencyModel(Nucleotides.INSTANCE, freqs);
} else if (this.frequencyModel == 1) {
Parameter freqs = new Parameter.Default(new double[] {
frequencyParameterValues[4], frequencyParameterValues[5],
frequencyParameterValues[6], frequencyParameterValues[7],
frequencyParameterValues[8], frequencyParameterValues[9],
frequencyParameterValues[10], frequencyParameterValues[11],
frequencyParameterValues[12], frequencyParameterValues[13],
frequencyParameterValues[14], frequencyParameterValues[15],
frequencyParameterValues[16], frequencyParameterValues[17],
frequencyParameterValues[18], frequencyParameterValues[19],
frequencyParameterValues[20], frequencyParameterValues[21],
frequencyParameterValues[22], frequencyParameterValues[23],
frequencyParameterValues[24], frequencyParameterValues[25],
frequencyParameterValues[26], frequencyParameterValues[27],
frequencyParameterValues[28], frequencyParameterValues[29],
frequencyParameterValues[30], frequencyParameterValues[31],
frequencyParameterValues[32], frequencyParameterValues[33],
frequencyParameterValues[34], frequencyParameterValues[35],
frequencyParameterValues[36], frequencyParameterValues[37],
frequencyParameterValues[38], frequencyParameterValues[39],
frequencyParameterValues[40], frequencyParameterValues[41],
frequencyParameterValues[42], frequencyParameterValues[43],
frequencyParameterValues[44], frequencyParameterValues[45],
frequencyParameterValues[46], frequencyParameterValues[47],
frequencyParameterValues[48], frequencyParameterValues[49],
frequencyParameterValues[50], frequencyParameterValues[51],
frequencyParameterValues[52], frequencyParameterValues[53],
frequencyParameterValues[54], frequencyParameterValues[55],
frequencyParameterValues[56], frequencyParameterValues[57],
frequencyParameterValues[58], frequencyParameterValues[59],
frequencyParameterValues[60], frequencyParameterValues[61],
frequencyParameterValues[62], frequencyParameterValues[63],
frequencyParameterValues[64] });
frequencyModel = new FrequencyModel(Codons.UNIVERSAL, freqs);
} else if (this.frequencyModel == 2) {
System.out.println("Not yet implemented");
}
return frequencyModel;
}// END: createFrequencyModel
// ////////////////////////
// ---SITE RATE MODELS---//
// ////////////////////////
public int siteModel = 0;
public static String[] siteModels = { "No model", //
"Gamma Site Rate Model", //
};
public static String[] siteParameterNames = new String[] {
"Gamma categories", //
"alpha", //
};
public int[][] siteParameterIndices = { {}, // nomodel
{ 0, 1 }, // GammaSiteRateModel
};
public double[] siteParameterValues = new double[] { 4.0, // GammaCategories
0.5, // alpha
};
public GammaSiteRateModel createSiteRateModel() {
GammaSiteRateModel siteModel = null;
String name = "siteModel";
if (this.siteModel == 0) { // no model
siteModel = new GammaSiteRateModel("siteModel");
} else if (this.siteModel == 1) { // GammaSiteRateModel
siteModel = new GammaSiteRateModel(name, siteParameterValues[1],
(int) siteParameterValues[0]);
} else if (this.siteModel == 2) {
System.out.println("Not yet implemented");
}
return siteModel;
}// END: createGammaSiteRateModel
public PartitionData() {
}// END: Constructor
// ///////////////////
// ---EPOCH MODEL---//
// ///////////////////
// public int epochCount = 3;
//
// public int[] transitionTimes = new int[] { 10, 20 };
//
// public double[] parameterValues = new double[] { 1.0, 10.0, 1.0 };
//
// public EpochBranchModel createEpochBranchModel() {
//
// // create Frequency Model
// FrequencyModel frequencyModel = this.createFrequencyModel();
// List<FrequencyModel> frequencyModelList = new ArrayList<FrequencyModel>();
// frequencyModelList.add(frequencyModel);
//
// // create branch rate model
//// BranchRateModel branchRateModel = this.createBranchRateModel();
//
// // 1st epoch
// Parameter epochTimes = null;
// List<SubstitutionModel> substModelList = new ArrayList<SubstitutionModel>();
// Parameter kappa = new Parameter.Default(1, parameterValues[0]);
// HKY hky = new HKY(kappa, frequencyModel);
// substModelList.add(hky);
//
// // epochs 2, 3, ...
// for (int i = 1; i < epochCount; i++) {
//
// if (i == 1) {
// epochTimes = new Parameter.Default(1, transitionTimes[0]);
// } else {
// epochTimes.addDimension(1, transitionTimes[i - 1]);
// }
//
// kappa = new Parameter.Default(1, parameterValues[i]);
// hky = new HKY(kappa, frequencyModel);
// substModelList.add(hky);
//
// }//END: i loop
//
// EpochBranchModel epochModel = new EpochBranchModel(
// treeModel,
// substModelList, //
// epochTimes //
// );
//
// return (epochModel);
// }// END: createBranchRateModel
}// END: class
| whdc/ieo-beast | src/dr/app/bss/PartitionData.java | Java | lgpl-2.1 | 14,210 |
//$HeadURL$
/*----------------------------------------------------------------------------
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: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.protocol.wps.client.process;
import org.deegree.commons.tom.ows.CodeType;
import org.deegree.commons.tom.ows.LanguageString;
/**
* Encapsulates all information on a WPS process that's available from the capabilities document.
*
* @author <a href="mailto:[email protected]">Markus Schneider</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class ProcessInfo {
private String version;
private CodeType id;
private LanguageString title;
private LanguageString processAbstract;
/**
* Creates a new {@link ProcessInfo} instance.
*
* @param id
* the identifier of the process, must not be <code>null</code>
* @param title
* the title of the process, must not be <code>null</code>
* @param processAbstract
* the abstract of the process, can be <code>null</code>
* @param version
* the version of the process, must not be <code>null</code>
*/
public ProcessInfo( CodeType id, LanguageString title, LanguageString processAbstract, String version ) {
this.version = version;
this.id = id;
this.title = title;
this.processAbstract = processAbstract;
}
/**
* Returns the identifier of the process.
*
* @return the identifier, never <code>null</code>
*/
public CodeType getId() {
return id;
}
/**
* Returns the version of the process.
*
* @return the version, never <code>null</code>
*/
public String getVersion() {
return version;
}
/**
* Returns the title of the process.
*
* @return the title, never <code>null</code>
*/
public LanguageString getTitle() {
return title;
}
/**
* Returns the abstract of the process.
*
* @return the abstract, can be <code>null</code> (if the process description does not define an abstract)
*/
public LanguageString getAbstract() {
return processAbstract;
}
}
| deegree/deegree3 | deegree-core/deegree-core-protocol/deegree-protocol-commons/src/main/java/org/deegree/protocol/wps/client/process/ProcessInfo.java | Java | lgpl-2.1 | 3,382 |
package jade.wrapper.gateway;
//#J2ME_EXCLUDE_FILE
import jade.core.Agent;
import jade.core.behaviours.*;
import jade.util.Logger;
/**
* This agent is the gateway able to execute all commands requests received via JadeGateway.
* <p>
* <code>JadeGateway</code> enables two alternative ways to implement a gateway
* that allows non-JADE code to communicate with JADE agents.
* <br> The first one is to extend the <code>GatewayAgent</code>
* <br> The second one is to extend this <code>GatewayBehaviour</code> and add an instance
* of this Behaviour to your own agent that will have to function as a gateway (see its javadoc for reference).
* @see JadeGateway
* @see GatewayBehaviour
* @author Fabio Bellifemine, Telecom Italia LAB
* @version $Date: 2010-01-26 17:27:22 +0100 (mar, 26 gen 2010) $ $Revision: 6253 $
**/
public class GatewayAgent extends Agent {
private GatewayBehaviour myB = null;
private GatewayListener listener;
private final Logger myLogger = Logger.getMyLogger(this.getClass().getName());
/** subclasses may implement this method.
* The method is called each time a request to process a command
* is received from the JSP Gateway.
* <p> The recommended pattern is the following implementation:
<code>
if (c instanceof Command1)
exexCommand1(c);
else if (c instanceof Command2)
exexCommand2(c);
</code>
* </p>
* <b> REMIND THAT WHEN THE COMMAND HAS BEEN PROCESSED,
* YOU MUST CALL THE METHOD <code>releaseCommand</code>.
* <br>Sometimes, you might prefer launching a new Behaviour that processes
* this command and release the command just when the Behaviour terminates,
* i.e. in its <code>onEnd()</code> method.
**/
protected void processCommand(final Object command) {
if (command instanceof Behaviour) {
SequentialBehaviour sb = new SequentialBehaviour(this);
sb.addSubBehaviour((Behaviour) command);
sb.addSubBehaviour(new OneShotBehaviour(this) {
public void run() {
GatewayAgent.this.releaseCommand(command);
}
});
addBehaviour(sb);
}
else {
myLogger.log(Logger.WARNING, "Unknown command "+command);
}
}
/**
* notify that the command has been processed and remove the command from the queue
* @param command is the same object that was passed in the processCommand method
**/
final public void releaseCommand(Object command) {
myB.releaseCommand(command);
}
public GatewayAgent() {
// enable object2agent communication with queue of infinite length
setEnabledO2ACommunication(true, 0);
}
/*
* Those classes that extends this setup method of the GatewayAgent
* MUST absolutely call <code>super.setup()</code> otherwise this
* method is not executed and the system would not work.
* @see jade.core.Agent#setup()
*/
protected void setup() {
myLogger.log(Logger.INFO, "Started GatewayAgent "+getLocalName());
myB = new GatewayBehaviour() {
protected void processCommand(Object command){
((GatewayAgent)myAgent).processCommand(command);
}
};
addBehaviour(myB);
setO2AManager(myB);
if (listener != null) {
listener.handleGatewayConnected();
}
}
protected void takeDown() {
if (listener != null) {
listener.handleGatewayDisconnected();
}
}
// No need for synchronizations since this is only called when the Agent Thread has not started yet
void setListener(GatewayListener listener) {
this.listener = listener;
}
}
| automenta/jadehell | src/main/java/jade/wrapper/gateway/GatewayAgent.java | Java | lgpl-2.1 | 3,417 |
package de.fiduciagad.anflibrary.anFReceiver.anFContextDetection.deviceCheck;
import android.content.Context;
import android.media.AudioManager;
import android.provider.Settings;
/**
* Created by Felix Schiefer on 16.01.2016.
*/
public class DeviceSignals {
private Context context;
public DeviceSignals(Context context) {
this.context = context;
}
public boolean checkVibrationIsOn() {
boolean status = false;
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
status = true;
} else if (1 == Settings.System.getInt(context.getContentResolver(), "vibrate_when_ringing", 0)) //vibrate on
status = true;
return status;
}
}
| fiduciagad/active-notification-framework | src/main/java/de/fiduciagad/anflibrary/anFReceiver/anFContextDetection/deviceCheck/DeviceSignals.java | Java | lgpl-2.1 | 812 |
/* LanguageTool, a natural language style checker
* Copyright (C) 2011 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.tagging.krj;
import java.util.Locale;
import de.danielnaber.languagetool.JLanguageTool;
import de.danielnaber.languagetool.tagging.BaseTagger;
/**
* Filipino Part-of-speech tagger.
*
* @author Nathaniel Oco
*/
public class Kinaray_aTagger extends BaseTagger {
@Override
public final String getFileName() {
return JLanguageTool.getDataBroker().getResourceDir() + "/krj/kinaray_a.dict";
}
public Kinaray_aTagger() {
super();
setLocale(Locale.ENGLISH);
}
}
| ManolitoOctaviano/Language-Identification | src/java/de/danielnaber/languagetool/tagging/krj/Kinaray_aTagger.java | Java | lgpl-2.1 | 1,386 |
/**
* ***************************************************************
* Agent.GUI is a framework to develop Multi-agent based simulation
* applications based on the JADE - Framework in compliance with the
* FIPA specifications.
* Copyright (C) 2010 Christian Derksen and DAWIS
* http://www.dawis.wiwi.uni-due.de
* http://sourceforge.net/projects/agentgui/
* http://www.agentgui.org
*
* GNU Lesser General Public License
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation,
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
* **************************************************************
*/
package agentgui.core.charts.timeseriesChart.gui;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import javax.swing.JToolBar;
import agentgui.core.charts.gui.ChartEditorJPanel;
import agentgui.core.charts.timeseriesChart.TimeSeriesDataModel;
import agentgui.core.charts.timeseriesChart.TimeSeriesOntologyModel;
import agentgui.core.config.GlobalInfo;
import agentgui.ontology.Chart;
import de.enflexit.common.ontology.gui.DynForm;
/**
* Implementation of OntologyClassEditorJPanel for TimeSeriesChart
*
* @author Nils Loose - DAWIS - ICB University of Duisburg - Essen
*/
public class TimeSeriesChartEditorJPanel extends ChartEditorJPanel {
private static final long serialVersionUID = 6342520178418229017L;
/** The data model. */
protected TimeSeriesDataModel dataModel;
/**
* Instantiates a new TimeSeriesChartEditorJPanel.
*
* @param dynForm the current DynForm
* @param startArgIndex the current start argument index
*/
public TimeSeriesChartEditorJPanel(DynForm dynForm, int startArgIndex) {
super(dynForm, startArgIndex);
}
/* (non-Javadoc)
* @see agentgui.core.charts.gui.ChartEditorJPanel#getDataModel()
*/
@Override
public TimeSeriesDataModel getDataModel() {
if (this.dataModel==null) {
this.dataModel = new TimeSeriesDataModel();
}
return this.dataModel;
}
/* (non-Javadoc)
* @see de.enflexit.common.ontology.gui.OntologyClassEditorJPanel#setOntologyClassInstance(java.lang.Object)
*/
@Override
public void setOntologyClassInstance(Object objectInstance) {
this.getDataModel().setDefaultTimeFormat(this.getDefaultTimeFormat());
this.getDataModel().setOntologyInstanceChart((Chart) objectInstance);
this.getChartTab().replaceModel(this.getDataModel());
this.getChartSettingsTab().replaceModel(this.getDataModel().getChartSettingModel());
}
/* (non-Javadoc)
* @see de.enflexit.common.ontology.gui.OntologyClassEditorJPanel#getOntologyClassInstance()
*/
@Override
public Object getOntologyClassInstance() {
return ((TimeSeriesOntologyModel)this.getDataModel().getOntologyModel()).getTimeSeriesChart();
}
/* (non-Javadoc)
* @see agentgui.core.charts.gui.ChartEditorJPanel#getChartTab()
*/
@Override
protected TimeSeriesChartTab getChartTab(){
if(chartTab == null){
chartTab = new TimeSeriesChartTab((TimeSeriesDataModel) this.dataModel, this);
}
return (TimeSeriesChartTab) chartTab;
}
/* (non-Javadoc)
* @see agentgui.core.charts.gui.ChartEditorJPanel#getTableTab()
*/
@Override
protected TimeSeriesTableTab getTableTab(){
if(tableTab == null){
tableTab = new TimeSeriesTableTab((TimeSeriesDataModel) this.dataModel, this);
}
return (TimeSeriesTableTab) tableTab;
}
/* (non-Javadoc)
* @see agentgui.core.charts.gui.ChartEditorJPanel#getSettingsTab()
*/
@Override
protected TimeSeriesChartSettingsTab getChartSettingsTab(){
if(this.settingsTab == null){
this.settingsTab = new TimeSeriesChartSettingsTab(this.dataModel.getChartSettingModel(), this);
}
return (TimeSeriesChartSettingsTab) settingsTab;
}
/* (non-Javadoc)
* @see agentgui.core.charts.gui.ChartEditorJPanel#parseKey(java.lang.String, java.lang.String, java.lang.Number)
*/
@Override
protected Number parseKey(String key, String keyFormat, Number keyOffset) {
long timestamp = 0;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(keyFormat).withZone(GlobalInfo.getCurrentZoneId());
ZonedDateTime zdt = ZonedDateTime.parse(key, formatter);
timestamp = zdt.toInstant().toEpochMilli();
if (keyOffset!=null) {
timestamp = timestamp + (Long) keyOffset;
}
return timestamp;
}
/* (non-Javadoc)
* @see agentgui.core.charts.gui.ChartEditorJPanel#parseValue(java.lang.String)
*/
@Override
protected Number parseValue(String value) {
return Float.parseFloat(value);
}
/* (non-Javadoc)
* @see de.enflexit.common.ontology.gui.OntologyClassEditorJPanel#getJToolBarUserFunctions()
*/
@Override
public JToolBar getJToolBarUserFunctions() {
return this.getToolBar();
}
}
| EnFlexIT/AgentWorkbench | eclipseProjects/org.agentgui/bundles/org.agentgui.core/src/agentgui/core/charts/timeseriesChart/gui/TimeSeriesChartEditorJPanel.java | Java | lgpl-2.1 | 5,254 |
package me.lake.librestreaming.client;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import java.io.IOException;
import java.util.List;
import me.lake.librestreaming.core.CameraHelper;
import me.lake.librestreaming.core.RESHardVideoCore;
import me.lake.librestreaming.core.RESSoftVideoCore;
import me.lake.librestreaming.core.RESVideoCore;
import me.lake.librestreaming.core.listener.RESScreenShotListener;
import me.lake.librestreaming.core.listener.RESVideoChangeListener;
import me.lake.librestreaming.filter.hardvideofilter.BaseHardVideoFilter;
import me.lake.librestreaming.filter.softvideofilter.BaseSoftVideoFilter;
import me.lake.librestreaming.model.RESConfig;
import me.lake.librestreaming.model.RESCoreParameters;
import me.lake.librestreaming.model.Size;
import me.lake.librestreaming.rtmp.RESFlvDataCollecter;
import me.lake.librestreaming.tools.BuffSizeCalculator;
import me.lake.librestreaming.tools.LogTools;
/**
* Created by lake on 16-5-24.
*/
public class RESVideoClient {
RESCoreParameters resCoreParameters;
private final Object syncOp = new Object();
private Camera camera;
private SurfaceTexture camTexture;
private int cameraNum;
private int currentCameraIndex;
private RESVideoCore videoCore;
private boolean isStreaming;
private boolean isPreviewing;
public RESVideoClient(RESCoreParameters parameters) {
resCoreParameters = parameters;
cameraNum = Camera.getNumberOfCameras();
currentCameraIndex = Camera.CameraInfo.CAMERA_FACING_BACK;
isStreaming = false;
isPreviewing = false;
}
public boolean prepare(RESConfig resConfig) {
synchronized (syncOp) {
if ((cameraNum - 1) >= resConfig.getDefaultCamera()) {
currentCameraIndex = resConfig.getDefaultCamera();
}
if (null == (camera = createCamera(currentCameraIndex))) {
LogTools.e("can not open camera");
return false;
}
Camera.Parameters parameters = camera.getParameters();
CameraHelper.selectCameraPreviewWH(parameters, resCoreParameters, resConfig.getTargetVideoSize());
CameraHelper.selectCameraFpsRange(parameters, resCoreParameters);
if (resConfig.getVideoFPS() > resCoreParameters.previewMaxFps / 1000) {
resCoreParameters.videoFPS = resCoreParameters.previewMaxFps / 1000;
} else {
resCoreParameters.videoFPS = resConfig.getVideoFPS();
}
resoveResolution(resCoreParameters, resConfig.getTargetVideoSize());
if (!CameraHelper.selectCameraColorFormat(parameters, resCoreParameters)) {
LogTools.e("CameraHelper.selectCameraColorFormat,Failed");
resCoreParameters.dump();
return false;
}
if (!CameraHelper.configCamera(camera, resCoreParameters)) {
LogTools.e("CameraHelper.configCamera,Failed");
resCoreParameters.dump();
return false;
}
switch (resCoreParameters.filterMode) {
case RESCoreParameters.FILTER_MODE_SOFT:
videoCore = new RESSoftVideoCore(resCoreParameters);
break;
case RESCoreParameters.FILTER_MODE_HARD:
videoCore = new RESHardVideoCore(resCoreParameters);
break;
}
if (!videoCore.prepare(resConfig)) {
return false;
}
videoCore.setCurrentCamera(currentCameraIndex);
prepareVideo();
return true;
}
}
private Camera createCamera(int cameraId) {
try {
camera = Camera.open(cameraId);
camera.setDisplayOrientation(0);
} catch (SecurityException e) {
LogTools.trace("no permission", e);
return null;
} catch (Exception e) {
LogTools.trace("camera.open()failed", e);
return null;
}
return camera;
}
private boolean prepareVideo() {
if (resCoreParameters.filterMode == RESCoreParameters.FILTER_MODE_SOFT) {
camera.addCallbackBuffer(new byte[resCoreParameters.previewBufferSize]);
camera.addCallbackBuffer(new byte[resCoreParameters.previewBufferSize]);
}
return true;
}
private boolean startVideo() {
camTexture = new SurfaceTexture(RESVideoCore.OVERWATCH_TEXTURE_ID);
if (resCoreParameters.filterMode == RESCoreParameters.FILTER_MODE_SOFT) {
camera.setPreviewCallbackWithBuffer(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
synchronized (syncOp) {
if (videoCore != null && data != null) {
((RESSoftVideoCore) videoCore).queueVideo(data);
}
camera.addCallbackBuffer(data);
}
}
});
} else {
camTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {
@Override
public void onFrameAvailable(SurfaceTexture surfaceTexture) {
synchronized (syncOp) {
if (videoCore != null) {
((RESHardVideoCore) videoCore).onFrameAvailable();
}
}
}
});
}
try {
camera.setPreviewTexture(camTexture);
} catch (IOException e) {
LogTools.trace(e);
camera.release();
return false;
}
camera.startPreview();
return true;
}
public boolean startPreview(SurfaceTexture surfaceTexture, int visualWidth, int visualHeight) {
synchronized (syncOp) {
if (!isStreaming && !isPreviewing) {
if (!startVideo()) {
resCoreParameters.dump();
LogTools.e("RESVideoClient,start(),failed");
return false;
}
videoCore.updateCamTexture(camTexture);
}
videoCore.startPreview(surfaceTexture, visualWidth, visualHeight);
isPreviewing = true;
return true;
}
}
public void updatePreview(int visualWidth, int visualHeight) {
videoCore.updatePreview(visualWidth, visualHeight);
}
public boolean stopPreview(boolean releaseTexture) {
synchronized (syncOp) {
if (isPreviewing) {
videoCore.stopPreview(releaseTexture);
if (!isStreaming) {
camera.stopPreview();
videoCore.updateCamTexture(null);
camTexture.release();
}
}
isPreviewing = false;
return true;
}
}
public boolean startStreaming(RESFlvDataCollecter flvDataCollecter) {
synchronized (syncOp) {
if (!isStreaming && !isPreviewing) {
if (!startVideo()) {
resCoreParameters.dump();
LogTools.e("RESVideoClient,start(),failed");
return false;
}
videoCore.updateCamTexture(camTexture);
}
videoCore.startStreaming(flvDataCollecter);
isStreaming = true;
return true;
}
}
public boolean stopStreaming() {
synchronized (syncOp) {
if (isStreaming) {
videoCore.stopStreaming();
if (!isPreviewing) {
camera.stopPreview();
videoCore.updateCamTexture(null);
camTexture.release();
}
}
isStreaming = false;
return true;
}
}
public boolean destroy() {
synchronized (syncOp) {
camera.release();
videoCore.destroy();
videoCore = null;
camera = null;
return true;
}
}
public boolean swapCamera() {
synchronized (syncOp) {
LogTools.d("RESClient,swapCamera()");
camera.stopPreview();
camera.release();
camera = null;
if (null == (camera = createCamera(currentCameraIndex = (++currentCameraIndex) % cameraNum))) {
LogTools.e("can not swap camera");
return false;
}
videoCore.setCurrentCamera(currentCameraIndex);
CameraHelper.selectCameraFpsRange(camera.getParameters(), resCoreParameters);
if (!CameraHelper.configCamera(camera, resCoreParameters)) {
camera.release();
return false;
}
prepareVideo();
camTexture.release();
videoCore.updateCamTexture(null);
startVideo();
videoCore.updateCamTexture(camTexture);
return true;
}
}
public boolean toggleFlashLight() {
synchronized (syncOp) {
try {
Camera.Parameters parameters = camera.getParameters();
List<String> flashModes = parameters.getSupportedFlashModes();
String flashMode = parameters.getFlashMode();
if (!Camera.Parameters.FLASH_MODE_TORCH.equals(flashMode)) {
if (flashModes.contains(Camera.Parameters.FLASH_MODE_TORCH)) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
return true;
}
} else if (!Camera.Parameters.FLASH_MODE_OFF.equals(flashMode)) {
if (flashModes.contains(Camera.Parameters.FLASH_MODE_OFF)) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
return true;
}
}
} catch (Exception e) {
LogTools.d("toggleFlashLight,failed" + e.getMessage());
return false;
}
return false;
}
}
public boolean setZoomByPercent(float targetPercent) {
synchronized (syncOp) {
targetPercent = Math.min(Math.max(0f, targetPercent), 1f);
Camera.Parameters p = camera.getParameters();
p.setZoom((int) (p.getMaxZoom() * targetPercent));
camera.setParameters(p);
return true;
}
}
public void reSetVideoBitrate(int bitrate) {
synchronized (syncOp) {
if (videoCore != null) {
videoCore.reSetVideoBitrate(bitrate);
}
}
}
public int getVideoBitrate() {
synchronized (syncOp) {
if (videoCore != null) {
return videoCore.getVideoBitrate();
} else {
return 0;
}
}
}
public void reSetVideoFPS(int fps) {
synchronized (syncOp) {
int targetFps;
if (fps > resCoreParameters.previewMaxFps / 1000) {
targetFps = resCoreParameters.previewMaxFps / 1000;
} else {
targetFps = fps;
}
if (videoCore != null) {
videoCore.reSetVideoFPS(targetFps);
}
}
}
public boolean reSetVideoSize(Size targetVideoSize) {
synchronized (syncOp) {
RESCoreParameters newParameters = new RESCoreParameters();
newParameters.isPortrait = resCoreParameters.isPortrait;
newParameters.filterMode = resCoreParameters.filterMode;
Camera.Parameters parameters = camera.getParameters();
CameraHelper.selectCameraPreviewWH(parameters, newParameters, targetVideoSize);
resoveResolution(newParameters, targetVideoSize);
boolean needRestartCamera = (newParameters.previewVideoHeight != resCoreParameters.previewVideoHeight
|| newParameters.previewVideoWidth != resCoreParameters.previewVideoWidth);
if (needRestartCamera) {
newParameters.previewBufferSize = BuffSizeCalculator.calculator(resCoreParameters.previewVideoWidth,
resCoreParameters.previewVideoHeight, resCoreParameters.previewColorFormat);
resCoreParameters.previewVideoWidth = newParameters.previewVideoWidth;
resCoreParameters.previewVideoHeight = newParameters.previewVideoHeight;
resCoreParameters.previewBufferSize = newParameters.previewBufferSize;
if ((isPreviewing || isStreaming)) {
LogTools.d("RESClient,reSetVideoSize.restartCamera");
camera.stopPreview();
camera.release();
camera = null;
if (null == (camera = createCamera(currentCameraIndex))) {
LogTools.e("can not createCamera camera");
return false;
}
if (!CameraHelper.configCamera(camera, resCoreParameters)) {
camera.release();
return false;
}
prepareVideo();
videoCore.updateCamTexture(null);
camTexture.release();
startVideo();
videoCore.updateCamTexture(camTexture);
}
}
videoCore.reSetVideoSize(newParameters);
return true;
}
}
public BaseSoftVideoFilter acquireSoftVideoFilter() {
if (resCoreParameters.filterMode == RESCoreParameters.FILTER_MODE_SOFT) {
return ((RESSoftVideoCore) videoCore).acquireVideoFilter();
}
return null;
}
public void releaseSoftVideoFilter() {
if (resCoreParameters.filterMode == RESCoreParameters.FILTER_MODE_SOFT) {
((RESSoftVideoCore) videoCore).releaseVideoFilter();
}
}
public void setSoftVideoFilter(BaseSoftVideoFilter baseSoftVideoFilter) {
if (resCoreParameters.filterMode == RESCoreParameters.FILTER_MODE_SOFT) {
((RESSoftVideoCore) videoCore).setVideoFilter(baseSoftVideoFilter);
}
}
public BaseHardVideoFilter acquireHardVideoFilter() {
if (resCoreParameters.filterMode == RESCoreParameters.FILTER_MODE_HARD) {
return ((RESHardVideoCore) videoCore).acquireVideoFilter();
}
return null;
}
public void releaseHardVideoFilter() {
if (resCoreParameters.filterMode == RESCoreParameters.FILTER_MODE_HARD) {
((RESHardVideoCore) videoCore).releaseVideoFilter();
}
}
public void setHardVideoFilter(BaseHardVideoFilter baseHardVideoFilter) {
if (resCoreParameters.filterMode == RESCoreParameters.FILTER_MODE_HARD) {
((RESHardVideoCore) videoCore).setVideoFilter(baseHardVideoFilter);
}
}
public void takeScreenShot(RESScreenShotListener listener) {
synchronized (syncOp) {
if (videoCore != null) {
videoCore.takeScreenShot(listener);
}
}
}
public void setVideoChangeListener(RESVideoChangeListener listener) {
synchronized (syncOp) {
if (videoCore != null) {
videoCore.setVideoChangeListener(listener);
}
}
}
public float getDrawFrameRate() {
synchronized (syncOp) {
return videoCore == null ? 0 : videoCore.getDrawFrameRate();
}
}
private void resoveResolution(RESCoreParameters resCoreParameters, Size targetVideoSize) {
if (resCoreParameters.filterMode == RESCoreParameters.FILTER_MODE_SOFT) {
if (resCoreParameters.isPortrait) {
resCoreParameters.videoHeight = resCoreParameters.previewVideoWidth;
resCoreParameters.videoWidth = resCoreParameters.previewVideoHeight;
} else {
resCoreParameters.videoWidth = resCoreParameters.previewVideoWidth;
resCoreParameters.videoHeight = resCoreParameters.previewVideoHeight;
}
} else {
float pw, ph, vw, vh;
if (resCoreParameters.isPortrait) {
resCoreParameters.videoHeight = targetVideoSize.getWidth();
resCoreParameters.videoWidth = targetVideoSize.getHeight();
pw = resCoreParameters.previewVideoHeight;
ph = resCoreParameters.previewVideoWidth;
} else {
resCoreParameters.videoWidth = targetVideoSize.getWidth();
resCoreParameters.videoHeight = targetVideoSize.getHeight();
pw = resCoreParameters.previewVideoWidth;
ph = resCoreParameters.previewVideoHeight;
}
vw = resCoreParameters.videoWidth;
vh = resCoreParameters.videoHeight;
float pr = ph / pw, vr = vh / vw;
if (pr == vr) {
resCoreParameters.cropRatio = 0.0f;
} else if (pr > vr) {
resCoreParameters.cropRatio = (1.0f - vr / pr) / 2.0f;
} else {
resCoreParameters.cropRatio = -(1.0f - pr / vr) / 2.0f;
}
}
}
}
| lakeinchina/librestreaming | librestreaming/src/main/java/me/lake/librestreaming/client/RESVideoClient.java | Java | lgpl-2.1 | 17,680 |
package com.boutique.view;
import java.awt.*;
import javax.swing.*;
/**
* <p>Title: boutique management</p>
* <p>Description: Sistema de administracion de boitiques</p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: SESTO</p>
* @author Aldo Antonio Cuevas Alvarez
* @version 1.0
*/
public class PnlVentas extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
BorderLayout borderLayout1 = new BorderLayout();
JTabbedPane jTabbedPane1 = new JTabbedPane();
PnlVentaCredito pnlPuntoVentaCredito1 = new PnlVentaCredito();
//PnlPuntoVentaContado pnlPuntoVentaContado1 = new PnlPuntoVentaContado();
// PnlDevolucionesEvento pnlDevoluciones1 = new PnlDevolucionesEvento();
//PnlPuntoVentaApartado pnlPuntoVentaApartado1 = new PnlPuntoVentaApartado();
PnlVentaContado pnlVentaContadoEvento1 = new PnlVentaContado();
public PnlVentas() {
try {
jbInit();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
void jbInit() throws Exception {
this.setLayout(borderLayout1);
this.add(jTabbedPane1, BorderLayout.CENTER);
jTabbedPane1.add(pnlPuntoVentaCredito1, "pnlPuntoVentaCredito1");
// jTabbedPane1.add(pnlPuntoVentaContado1, "pnlPuntoVentaContado1");
// jTabbedPane1.add(pnlDevoluciones1, "pnlDevoluciones1");
//jTabbedPane1.add(pnlPuntoVentaApartado1, "Apartados");
jTabbedPane1.add(pnlVentaContadoEvento1, "pnlVentaContadoEvento1");
}
}
| aldocuevas/test | pos/source_code/src/com/boutique/view/PnlVentas.java | Java | lgpl-2.1 | 1,506 |
package com.galvarez.ttw.rendering.components;
import com.artemis.PooledComponent;
public final class MutableMapPosition extends PooledComponent {
public float x, y = 0.f;
public MutableMapPosition() {
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
@Override
protected void reset() {
x = y = 0f;
}
}
| guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/rendering/components/MutableMapPosition.java | Java | lgpl-2.1 | 379 |
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jitsi.service.neomedia;
import java.beans.*;
import java.net.*;
import java.util.*;
import org.jitsi.service.neomedia.device.*;
import org.jitsi.service.neomedia.format.*;
/**
* The <tt>MediaStream</tt> class represents a (generally) bidirectional RTP
* stream between exactly two parties. The class reflects one media stream, in
* the SDP sense of the word. <tt>MediaStream</tt> instances are created through
* the <tt>openMediaStream()</tt> method of the <tt>MediaService</tt>.
*
* @author Emil Ivov
* @author Lyubomir Marinov
*/
public interface MediaStream
{
/**
* The name of the property which indicates whether the local SSRC is
* currently available.
*/
public static final String PNAME_LOCAL_SSRC = "localSSRCAvailable";
/**
* The name of the property which indicates whether the remote SSRC is
* currently available.
*/
public static final String PNAME_REMOTE_SSRC = "remoteSSRCAvailable";
/**
* Adds a new association in this <tt>MediaStream</tt> of the specified RTP
* payload type with the specified <tt>MediaFormat</tt> in order to allow it
* to report <tt>rtpPayloadType</tt> in RTP flows sending and receiving
* media in <tt>format</tt>. Usually, <tt>rtpPayloadType</tt> will be in the
* range of dynamic RTP payload types.
*
* @param rtpPayloadType the RTP payload type to be associated in this
* <tt>MediaStream</tt> with the specified <tt>MediaFormat</tt>
* @param format the <tt>MediaFormat</tt> to be associated in this
* <tt>MediaStream</tt> with <tt>rtpPayloadType</tt>
*/
public void addDynamicRTPPayloadType(
byte rtpPayloadType,
MediaFormat format);
/**
* Adds an additional RTP payload mapping that will overriding one that
* we've set with {@link #addDynamicRTPPayloadType(byte, MediaFormat)}.
* This is necessary so that we can support the RFC3264 case where the
* answerer has the right to declare what payload type mappings it wants to
* receive RTP packets with even if they are different from those in the
* offer. RFC3264 claims this is for support of legacy protocols such as
* H.323 but we've been bumping with a number of cases where multi-component
* pure SIP systems also need to behave this way.
* <p>
*
* @param originalPt the payload type that we are overriding
* @param overloadPt the payload type that we are overriging it with
*/
public void addDynamicRTPPayloadTypeOverride(byte originalPt,
byte overloadPt);
/**
* Adds a property change listener to this stream so that it would be
* notified upon property change events like for example an SSRC ID which
* becomes known.
*
* @param listener the listener that we'd like to register for
* <tt>PropertyChangeEvent</tt>s
*/
public void addPropertyChangeListener(PropertyChangeListener listener);
/**
* Adds or updates an association in this <tt>MediaStream</tt> mapping the
* specified <tt>extensionID</tt> to <tt>rtpExtension</tt> and enabling or
* disabling its use according to the direction attribute of
* <tt>rtpExtension</tt>.
*
* @param extensionID the ID that is mapped to <tt>rtpExtension</tt> for
* the lifetime of this <tt>MediaStream</tt>.
* @param rtpExtension the <tt>RTPExtension</tt> that we are mapping to
* <tt>extensionID</tt>.
*/
public void addRTPExtension(byte extensionID, RTPExtension rtpExtension);
/**
* Releases the resources allocated by this instance in the course of its
* execution and prepares it to be garbage collected.
*/
public void close();
/**
* Returns a map containing all currently active <tt>RTPExtension</tt>s in
* use by this stream.
*
* @return a map containing all currently active <tt>RTPExtension</tt>s in
* use by this stream.
*/
public Map<Byte, RTPExtension> getActiveRTPExtensions();
/**
* Gets the device that this stream uses to play back and capture media.
*
* @return the <tt>MediaDevice</tt> that this stream uses to play back and
* capture media.
*/
public MediaDevice getDevice();
/**
* Gets the direction in which this <tt>MediaStream</tt> is allowed to
* stream media.
*
* @return the <tt>MediaDirection</tt> in which this <tt>MediaStream</tt> is
* allowed to stream media
*/
public MediaDirection getDirection();
/**
* Gets the existing associations in this <tt>MediaStream</tt> of RTP
* payload types to <tt>MediaFormat</tt>s. The returned <tt>Map</tt>
* only contains associations previously added in this instance with
* {@link #addDynamicRTPPayloadType(byte, MediaFormat)} and not globally or
* well-known associations reported by
* {@link MediaFormat#getRTPPayloadType()}.
*
* @return a <tt>Map</tt> of RTP payload type expressed as <tt>Byte</tt> to
* <tt>MediaFormat</tt> describing the existing (dynamic) associations in
* this instance of RTP payload types to <tt>MediaFormat</tt>s. The
* <tt>Map</tt> represents a snapshot of the existing associations at the
* time of the <tt>getDynamicRTPPayloadTypes()</tt> method call and
* modifications to it are not reflected on the internal storage
*/
public Map<Byte, MediaFormat> getDynamicRTPPayloadTypes();
/**
* Returns the <tt>MediaFormat</tt> that this stream is currently
* transmitting in.
*
* @return the <tt>MediaFormat</tt> that this stream is currently
* transmitting in.
*/
public MediaFormat getFormat();
/**
* Returns the synchronization source (SSRC) identifier of the local
* participant or <tt>-1</tt> if that identifier is not yet known at this
* point.
*
* @return the synchronization source (SSRC) identifier of the local
* participant or <tt>-1</tt> if that identifier is not yet known at this
* point.
*/
public long getLocalSourceID();
/**
* Returns a <tt>MediaStreamStats</tt> object used to get statistics about
* this <tt>MediaStream</tt>.
*
* @return the <tt>MediaStreamStats</tt> object used to get statistics about
* this <tt>MediaStream</tt>.
*/
public MediaStreamStats getMediaStreamStats();
/**
* Returns the name of this stream or <tt>null</tt> if no name has been
* set. A stream name is used by some protocols, for diagnostic purposes
* mostly. In XMPP for example this is the name of the content element that
* describes a stream.
*
* @return the name of this stream or <tt>null</tt> if no name has been
* set.
*/
public String getName();
/**
* Gets the value of a specific opaque property of this
* <tt>MediaStream</tt>.
*
* @param propertyName the name of the opaque property of this
* <tt>MediaStream</tt> the value of which is to be returned
* @return the value of the opaque property of this <tt>MediaStrea</tt>
* specified by <tt>propertyName</tt>
*/
public Object getProperty(String propertyName);
/**
* Returns the address that this stream is sending RTCP traffic to.
*
* @return an <tt>InetSocketAddress</tt> instance indicating the address
* that we are sending RTCP packets to.
*/
public InetSocketAddress getRemoteControlAddress();
/**
* Returns the address that this stream is sending RTP traffic to.
*
* @return an <tt>InetSocketAddress</tt> instance indicating the address
* that we are sending RTP packets to.
*/
public InetSocketAddress getRemoteDataAddress();
/**
* Gets the synchronization source (SSRC) identifier of the remote peer or
* <tt>-1</tt> if that identifier is not yet known at this point in the
* execution.
* <p>
* <b>Warning</b>: A <tt>MediaStream</tt> may receive multiple RTP streams
* and may thus have multiple remote SSRCs. Since it is not clear how this
* <tt>MediaStream</tt> instance chooses which of the multiple remote SSRCs
* to be returned by the method, it is advisable to always consider
* {@link #getRemoteSourceIDs()} first.
* </p>
*
* @return the synchronization source (SSRC) identifier of the remote peer
* or <tt>-1</tt> if that identifier is not yet known at this point in the
* execution
*/
public long getRemoteSourceID();
/**
* Gets the synchronization source (SSRC) identifiers of the remote peer.
*
* @return the synchronization source (SSRC) identifiers of the remote peer
*/
public List<Long> getRemoteSourceIDs();
/**
* Gets the <tt>RTPTranslator</tt> which is to forward RTP and RTCP traffic
* between this and other <tt>MediaStream</tt>s.
*/
public RTPTranslator getRTPTranslator();
/**
* The <tt>ZrtpControl</tt> which controls the ZRTP for this stream.
*
* @return the <tt>ZrtpControl</tt> which controls the ZRTP for this stream
*/
public SrtpControl getSrtpControl();
/**
* Returns the target of this <tt>MediaStream</tt> to which it is to send
* and from which it is to receive data (e.g. RTP) and control data (e.g.
* RTCP).
*
* @return the <tt>MediaStreamTarget</tt> describing the data
* (e.g. RTP) and the control data (e.g. RTCP) locations to which this
* <tt>MediaStream</tt> is to send and from which it is to receive
* @see MediaStream#setTarget(MediaStreamTarget)
*/
public MediaStreamTarget getTarget();
/**
* Returns the transport protocol used by the streams.
*
* @return the transport protocol (UDP or TCP) used by the streams. null if
* the stream connector is not instanciated.
*/
public StreamConnector.Protocol getTransportProtocol();
/**
* Determines whether this <tt>MediaStream</tt> is set to transmit "silence"
* instead of the media being fed from its <tt>MediaDevice</tt>. "Silence"
* for video is understood as video data which is not the captured video
* data and may represent, for example, a black image.
*
* @return <tt>true</tt> if this <tt>MediaStream</tt> is set to transmit
* "silence" instead of the media fed from its <tt>MediaDevice</tt>;
* <tt>false</tt>, otherwise
*/
public boolean isMute();
/**
* Determines whether {@link #start()} has been called on this
* <tt>MediaStream</tt> without {@link #stop()} or {@link #close()}
* afterwards.
*
* @return <tt>true</tt> if {@link #start()} has been called on this
* <tt>MediaStream</tt> without {@link #stop()} or {@link #close()}
* afterwards
*/
public boolean isStarted();
/**
* Removes the specified property change <tt>listener</tt> from this stream
* so that it won't receive further property change events.
*
* @param listener the listener that we'd like to remove.
*/
public void removePropertyChangeListener(PropertyChangeListener listener);
/**
* Removes the <tt>ReceiveStream</tt> with SSRC <tt>ssrc</tt>, if there is
* such a <tt>ReceiveStream</tt>, from the receive streams of this
* <tt>MediaStream</tt>
* @param ssrc the SSRC for which to remove a <tt>ReceiveStream</tt>
*/
public void removeReceiveStreamForSsrc(long ssrc);
/**
* Sets the <tt>StreamConnector</tt> to be used by this <tt>MediaStream</tt>
* for sending and receiving media.
*
* @param connector the <tt>StreamConnector</tt> to be used by this
* <tt>MediaStream</tt> for sending and receiving media
*/
public void setConnector(StreamConnector connector);
/**
* Sets the device that this stream should use to play back and capture
* media.
*
* @param device the <tt>MediaDevice</tt> that this stream should use to
* play back and capture media.
*/
public void setDevice(MediaDevice device);
/**
* Sets the direction in which media in this <tt>MediaStream</tt> is to be
* streamed. If this <tt>MediaStream</tt> is not currently started, calls to
* {@link #start()} later on will start it only in the specified
* <tt>direction</tt>. If it is currently started in a direction different
* than the specified, directions other than the specified will be stopped.
*
* @param direction the <tt>MediaDirection</tt> in which this
* <tt>MediaStream</tt> is to stream media when it is started
*/
public void setDirection(MediaDirection direction);
/**
* Sets the <tt>MediaFormat</tt> that this <tt>MediaStream</tt> should
* transmit in.
*
* @param format the <tt>MediaFormat</tt> that this <tt>MediaStream</tt>
* should transmit in.
*/
public void setFormat(MediaFormat format);
/**
* Causes this <tt>MediaStream</tt> to stop transmitting the media being fed
* from this stream's <tt>MediaDevice</tt> and transmit "silence" instead.
* "Silence" for video is understood as video data which is not the captured
* video data and may represent, for example, a black image.
*
* @param mute <tt>true</tt> if we are to start transmitting "silence" and
* <tt>false</tt> if we are to use media from this stream's
* <tt>MediaDevice</tt> again.
*/
public void setMute(boolean mute);
/**
* Sets the name of this stream. Stream names are used by some protocols,
* for diagnostic purposes mostly. In XMPP for example this is the name of
* the content element that describes a stream.
*
* @param name the name of this stream or <tt>null</tt> if no name has been
* set.
*/
public void setName(String name);
/**
* Sets the value of a specific opaque property of this
* <tt>MediaStream</tt>.
*
* @param propertyName the name of the opaque property of this
* <tt>MediaStream</tt> the value of which is to be set to the specified
* <tt>value</tt>
* @param value the value of the opaque property of this <tt>MediaStrea</tt>
* specified by <tt>propertyName</tt> to be set
*/
public void setProperty(String propertyName, Object value);
/**
* Sets the <tt>RTPTranslator</tt> which is to forward RTP and RTCP traffic
* between this and other <tt>MediaStream</tt>s.
*
* @param rtpTranslator the <tt>RTPTranslator</tt> which is to forward RTP
* and RTCP traffic between this and other <tt>MediaStream</tt>s
*/
public void setRTPTranslator(RTPTranslator rtpTranslator);
/**
* Sets the <tt>SSRCFactory</tt> which is to generate new synchronization
* source (SSRC) identifiers.
*
* @param ssrcFactory the <tt>SSRCFactory</tt> which is to generate new
* synchronization source (SSRC) identifiers or <tt>null</tt> if this
* <tt>MediaStream</tt> is to employ internal logic to generate new
* synchronization source (SSRC) identifiers
*/
public void setSSRCFactory(SSRCFactory ssrcFactory);
/**
* Sets the target of this <tt>MediaStream</tt> to which it is to send and
* from which it is to receive data (e.g. RTP) and control data (e.g. RTCP).
*
* @param target the <tt>MediaStreamTarget</tt> describing the data
* (e.g. RTP) and the control data (e.g. RTCP) locations to which this
* <tt>MediaStream</tt> is to send and from which it is to receive
*/
public void setTarget(MediaStreamTarget target);
/**
* Starts capturing media from this stream's <tt>MediaDevice</tt> and then
* streaming it through the local <tt>StreamConnector</tt> toward the
* stream's target address and port. The method also puts the
* <tt>MediaStream</tt> in a listening state that would make it play all
* media received from the <tt>StreamConnector</tt> on the stream's
* <tt>MediaDevice</tt>.
*/
public void start();
/**
* Stops all streaming and capturing in this <tt>MediaStream</tt> and closes
* and releases all open/allocated devices/resources. This method has no
* effect on an already closed stream and is simply ignored.
*/
public void stop();
}
| agh1467/libjitsi | src/org/jitsi/service/neomedia/MediaStream.java | Java | lgpl-2.1 | 16,557 |
/*!
* 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.ui.xul.swing.tags;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulDomException;
import org.pentaho.ui.xul.containers.XulHbox;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.swing.AbstractSwingContainer;
import org.pentaho.ui.xul.swing.ScrollablePanel;
import org.pentaho.ui.xul.util.Orient;
/**
* @author OEM
*
*/
public class SwingHbox extends AbstractSwingContainer implements XulHbox {
private static final Log logger = LogFactory.getLog( SwingHbox.class );
private String background;
private XulDomContainer domContainer;
public SwingHbox( Element self, XulComponent parent, XulDomContainer domContainer, String tagName ) {
super( "Hbox" );
this.domContainer = domContainer;
container = new ScrollablePanel( new GridBagLayout() );
container.setOpaque( false );
setManagedObject( container );
setPadding( 2 );
resetContainer();
}
@Override
public void removeChild( Element ele ) {
super.removeChild( ele );
if ( initialized ) {
resetContainer();
layout();
}
}
public void resetContainer() {
container.removeAll();
gc = new GridBagConstraints();
gc.gridx = GridBagConstraints.RELATIVE;
gc.gridy = 0;
gc.gridheight = GridBagConstraints.REMAINDER;
gc.gridwidth = 1;
int pad = getPadding();
gc.insets = new Insets( pad, pad, pad, pad );
gc.fill = GridBagConstraints.HORIZONTAL;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.weighty = 1;
}
public Orient getOrientation() {
return Orient.HORIZONTAL;
}
@Override
public void replaceChild( XulComponent oldElement, XulComponent newElement ) throws XulDomException {
this.resetContainer();
super.replaceChild( oldElement, newElement );
}
@Override
public void layout() {
resetContainer();
if ( getBgcolor() != null ) {
container.setOpaque( true );
container.setBackground( Color.decode( getBgcolor() ) );
}
super.layout();
}
public String getBackground() {
return background;
}
public void setBackground( String src ) {
this.background = src;
URL url = SwingImage.class.getClassLoader().getResource( this.domContainer.getXulLoader().getRootDir() + src );
// Then try to see if we can get the fully qualified file
if ( url == null ) {
try {
url = new File( src ).toURL();
} catch ( MalformedURLException e ) {
// do nothing and let the null url get caught below.
}
}
if ( url == null ) {
logger.error( "Could not find resource: " + src );
return;
}
final ImageIcon ico = new ImageIcon( url );
container.addComponentListener( new ComponentListener() {
public void componentHidden( ComponentEvent arg0 ) {
}
public void componentMoved( ComponentEvent arg0 ) {
}
public void componentResized( ComponentEvent arg0 ) {
container.getGraphics().drawImage( ico.getImage(), 0, 0, container );
}
public void componentShown( ComponentEvent arg0 ) {
}
} );
}
}
| pentaho/pentaho-commons-xul | swing/src/main/java/org/pentaho/ui/xul/swing/tags/SwingHbox.java | Java | lgpl-2.1 | 4,386 |
package org.geotools.data.geojson.store;
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2015, 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.
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.net.URL;
import org.geotools.data.FeatureReader;
import org.geotools.data.Query;
import org.geotools.data.geojson.GeoJSONReader;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.test.TestData;
import org.junit.Before;
import org.junit.Test;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
public class GeoJSONDataStoreTest {
GeoJSONDataStore ds;
@Before
public void setup() throws IOException {
URL url = TestData.url(GeoJSONDataStore.class, "ne_110m_admin_1_states_provinces.geojson");
ds = new GeoJSONDataStore(url);
}
@Test
public void testSource() throws IOException {
String type = ds.getNames().get(0).getLocalPart();
Query query = new Query(type);
SimpleFeatureSource source = ds.getFeatureSource(ds.getNames().get(0));
assertEquals(51, source.getCount(query)); // includes DC
ReferencedEnvelope expected =
new ReferencedEnvelope(
-171.79111060289117,
-66.96466,
18.916190000000142,
71.35776357694175,
DefaultGeographicCRS.WGS84);
ReferencedEnvelope obs = source.getBounds();
assertNotNull(obs);
assertEquals(expected.getMinX(), obs.getMinX(), 0.00001);
assertEquals(expected.getMinY(), obs.getMinY(), 0.00001);
assertEquals(expected.getMaxX(), obs.getMaxX(), 0.00001);
assertEquals(expected.getMaxY(), obs.getMaxY(), 0.00001);
assertEquals(expected.getCoordinateReferenceSystem(), obs.getCoordinateReferenceSystem());
}
@Test
public void testReader() throws IOException {
String type = ds.getNames().get(0).getLocalPart();
Query query = new Query(type);
try (FeatureReader<SimpleFeatureType, SimpleFeature> reader =
ds.getFeatureReader(query, null)) {
SimpleFeatureType schema = reader.getFeatureType();
assertNotNull(schema);
}
}
@Test
public void testFeatures() throws IOException {
URL url = TestData.url(GeoJSONDataStore.class, "featureCollection.json");
GeoJSONDataStore fds = new GeoJSONDataStore(url);
String type = fds.getNames().get(0).getLocalPart();
Query query = new Query(type);
Class<?> lastGeometryBinding = null;
try (FeatureReader<SimpleFeatureType, SimpleFeature> reader =
fds.getFeatureReader(query, null)) {
SimpleFeatureType schema = reader.getFeatureType();
assertNotNull(schema);
int count = 0;
while (reader.hasNext()) {
SimpleFeature sf = reader.next();
lastGeometryBinding =
sf.getFeatureType().getGeometryDescriptor().getType().getBinding();
count++;
}
assertEquals(7, count);
}
assertEquals(Geometry.class, lastGeometryBinding);
}
// An ogr written file
@Test
public void testLocations() throws IOException {
URL url = TestData.url(GeoJSONDataStore.class, "locations.json");
GeoJSONDataStore fds = new GeoJSONDataStore(url);
String type = fds.getNames().get(0).getLocalPart();
Query query = new Query(type);
try (FeatureReader<SimpleFeatureType, SimpleFeature> reader =
fds.getFeatureReader(query, null)) {
SimpleFeatureType schema = reader.getFeatureType();
// System.out.println(schema);
assertEquals(Point.class, schema.getGeometryDescriptor().getType().getBinding());
assertNotNull(schema);
int count = 0;
while (reader.hasNext()) {
reader.next();
count++;
}
assertEquals(9, count);
}
}
@Test
public void testVeryChangeableSchema() throws IOException {
URL url = TestData.url(GeoJSONDataStore.class, "jagged.json");
GeoJSONDataStore fds = new GeoJSONDataStore(url);
fds.setQuickSchema(false);
assertNotNull(fds);
String name = fds.getTypeNames()[0];
assertNotNull(name);
SimpleFeatureType schema = fds.getSchema();
assertNotNull(schema);
assertEquals(4, schema.getAttributeCount());
int cnt = 0;
for (int i = 0; i < schema.getAttributeCount(); i++) {
if (schema.getDescriptor(i).getLocalName().equals(GeoJSONReader.GEOMETRY_NAME)) {
cnt++;
}
}
assertEquals(1, cnt);
}
}
| geotools/geotools | modules/unsupported/geojson-store/src/test/java/org/geotools/data/geojson/store/GeoJSONDataStoreTest.java | Java | lgpl-2.1 | 5,673 |
/*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2003-2007 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.classfile;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ObjectType;
import edu.umd.cs.findbugs.FieldAnnotation;
import edu.umd.cs.findbugs.MethodAnnotation;
import edu.umd.cs.findbugs.classfile.analysis.MethodInfo;
import edu.umd.cs.findbugs.internalAnnotations.DottedClassName;
import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName;
import edu.umd.cs.findbugs.util.ClassName;
/**
* Factory for creating ClassDescriptors, MethodDescriptors, and
* FieldDescriptors.
*
* @author David Hovemeyer
*/
public class DescriptorFactory {
private static ThreadLocal<DescriptorFactory> instanceThreadLocal = new ThreadLocal<DescriptorFactory>() {
@Override
protected DescriptorFactory initialValue() {
return new DescriptorFactory();
}
};
private final Map<String, ClassDescriptor> classDescriptorMap;
private final Map<String, ClassDescriptor> dottedClassDescriptorMap;
private final Map<MethodDescriptor, MethodDescriptor> methodDescriptorMap;
private final Map<FieldDescriptor, FieldDescriptor> fieldDescriptorMap;
private DescriptorFactory() {
this.classDescriptorMap = new HashMap<String, ClassDescriptor>();
this.dottedClassDescriptorMap = new HashMap<String, ClassDescriptor>();
this.methodDescriptorMap = new HashMap<MethodDescriptor, MethodDescriptor>();
this.fieldDescriptorMap = new HashMap<FieldDescriptor, FieldDescriptor>();
}
/**
* This method was designed to canonicalize String to improve performance,
* but now GC cost is cheaper than calculation cost in application thread
* so removing this old optimization makes SpotBugs 16% faster.
* @return given string instance
* @deprecated this hack is needless for modern JVM, at least Java8
*/
@Deprecated
public static String canonicalizeString(@CheckForNull String s) {
return s;
}
/**
* Get the singleton instance of the DescriptorFactory.
*
* @return the singleton instance of the DescriptorFactory
*/
public static DescriptorFactory instance() {
return instanceThreadLocal.get();
}
public static void clearInstance() {
instanceThreadLocal.remove();
}
public Collection<ClassDescriptor> getAllClassDescriptors() {
return classDescriptorMap.values();
}
public void purge(Collection<ClassDescriptor> unusable) {
for (ClassDescriptor c : unusable) {
classDescriptorMap.remove(c.getClassName());
dottedClassDescriptorMap.remove(c.getClassName().replace('/', '.'));
}
}
public @Nonnull
ClassDescriptor getClassDescriptor(Class<?> actualClass) {
return getClassDescriptorForDottedClassName(actualClass.getName());
}
/**
* Get a ClassDescriptor for a class name in VM (slashed) format.
*
* @param className
* a class name in VM (slashed) format
* @return ClassDescriptor for that class
*/
public @Nonnull
ClassDescriptor getClassDescriptor(@SlashedClassName String className) {
assert className.indexOf('.') == -1;
className = className;
ClassDescriptor classDescriptor = classDescriptorMap.get(className);
if (classDescriptor == null) {
classDescriptor = new ClassDescriptor(className);
classDescriptorMap.put(className, classDescriptor);
}
return classDescriptor;
}
/**
* Get a ClassDescriptor for a class name in dotted format.
*
* @param dottedClassName
* a class name in dotted format
* @return ClassDescriptor for that class
*/
public ClassDescriptor getClassDescriptorForDottedClassName(@DottedClassName String dottedClassName) {
assert dottedClassName != null;
ClassDescriptor classDescriptor = dottedClassDescriptorMap.get(dottedClassName);
if (classDescriptor == null) {
classDescriptor = getClassDescriptor(dottedClassName.replace('.', '/'));
dottedClassDescriptorMap.put(dottedClassName, classDescriptor);
}
return classDescriptor;
}
public MethodDescriptor getMethodDescriptor(JavaClass jClass, Method method) {
return getMethodDescriptor(ClassName.toSlashedClassName(jClass.getClassName()), method.getName(), method.getSignature(),
method.isStatic());
}
/**
* Get a MethodDescriptor.
*
* @param className
* name of the class containing the method, in VM format (e.g.,
* "java/lang/String")
* @param name
* name of the method
* @param signature
* signature of the method
* @param isStatic
* true if method is static, false otherwise
* @return MethodDescriptor
*/
public MethodDescriptor getMethodDescriptor(@SlashedClassName String className, String name, String signature,
boolean isStatic) {
if (className == null) {
throw new NullPointerException("className must be nonnull");
}
MethodDescriptor methodDescriptor = new MethodDescriptor(className, name, signature, isStatic);
MethodDescriptor existing = methodDescriptorMap.get(methodDescriptor);
if (existing == null) {
methodDescriptorMap.put(methodDescriptor, methodDescriptor);
existing = methodDescriptor;
}
return existing;
}
public void profile() {
int total = 0;
int keys = 0;
int values = 0;
int bad = 0;
for (Map.Entry<MethodDescriptor, MethodDescriptor> e : methodDescriptorMap.entrySet()) {
total++;
if (e.getKey() instanceof MethodInfo) {
keys++;
}
if (e.getValue() instanceof MethodInfo) {
values++;
}
}
System.out.printf("Descriptor factory: %d/%d/%d%n", keys, values, total);
}
public void canonicalize(MethodDescriptor m) {
MethodDescriptor existing = methodDescriptorMap.get(m);
if (m != existing) {
methodDescriptorMap.put(m, m);
}
}
public void canonicalize(FieldDescriptor m) {
FieldDescriptor existing = fieldDescriptorMap.get(m);
if (m != existing) {
fieldDescriptorMap.put(m, m);
}
}
public MethodDescriptor getMethodDescriptor(MethodAnnotation ma) {
return getMethodDescriptor(ClassName.toSlashedClassName(ma.getClassName()), ma.getMethodName(), ma.getMethodSignature(),
ma.isStatic());
}
/**
* Get a FieldDescriptor.
*
* @param className
* the name of the class the field belongs to, in VM format
* (e.g., "java/lang/String")
* @param name
* the name of the field
* @param signature
* the field signature (type)
* @param isStatic
* true if field is static, false if not
* @return FieldDescriptor
*/
public FieldDescriptor getFieldDescriptor(@SlashedClassName String className, String name, String signature, boolean isStatic) {
FieldDescriptor fieldDescriptor = new FieldDescriptor(className, name, signature, isStatic);
FieldDescriptor existing = fieldDescriptorMap.get(fieldDescriptor);
if (existing == null) {
fieldDescriptorMap.put(fieldDescriptor, fieldDescriptor);
existing = fieldDescriptor;
}
return existing;
}
public FieldDescriptor getFieldDescriptor(@SlashedClassName String className, Field ma) {
return getFieldDescriptor(className, ma.getName(), ma.getSignature(), ma.isStatic());
}
public FieldDescriptor getFieldDescriptor(FieldAnnotation ma) {
return getFieldDescriptor(ClassName.toSlashedClassName(ma.getClassName()), ma.getFieldName(), ma.getFieldSignature(),
ma.isStatic());
}
/**
* Get a ClassDescriptor for the class described by given ObjectType object.
*
* @param type
* an ObjectType
* @return a ClassDescriptor for the class described by the ObjectType
*/
public static ClassDescriptor getClassDescriptor(ObjectType type) {
return instance().getClassDescriptorForDottedClassName(type.getClassName());
}
public static ClassDescriptor createClassDescriptor(JavaClass c) {
return DescriptorFactory.createClassDescriptorFromDottedClassName(c.getClassName());
}
/**
* Create a class descriptor from a resource name.
*
* @param resourceName
* the resource name
* @return the class descriptor
*/
public static ClassDescriptor createClassDescriptorFromResourceName(String resourceName) {
if (!isClassResource(resourceName)) {
throw new IllegalArgumentException("Resource " + resourceName + " is not a class");
}
return createClassDescriptor(resourceName.substring(0, resourceName.length() - 6));
}
/**
* Create a class descriptor from a field signature
*
*/
public static @CheckForNull
ClassDescriptor createClassDescriptorFromFieldSignature(String signature) {
int start = signature.indexOf('L');
if (start < 0) {
return null;
}
int end = signature.indexOf(';', start);
if (end < 0) {
return null;
}
return createClassDescriptor(signature.substring(start + 1, end));
}
/**
* Determine whether or not the given resource name refers to a class.
*
* @param resourceName
* the resource name
* @return true if the resource is a class, false otherwise
*/
public static boolean isClassResource(String resourceName) {
// This could be more sophisticated.
return resourceName.endsWith(".class");
}
public static ClassDescriptor createClassDescriptorFromSignature(String signature) {
int length = signature.length();
if (length == 0) {
throw new IllegalArgumentException("Empty signature");
}
if (signature.charAt(0) == 'L' && signature.endsWith(";")) {
signature = signature.substring(1, signature.length() - 1);
}
return createClassDescriptor(signature);
}
public static ClassDescriptor createClassOrObjectDescriptorFromSignature(String signature) {
if (signature.charAt(0) == '[') {
return createClassDescriptor("java/lang/Object");
}
return createClassDescriptorFromSignature(signature);
}
public static ClassDescriptor createClassDescriptor(Class<?> aClass) {
return instance().getClassDescriptor(ClassName.toSlashedClassName(aClass.getName()));
}
public static @Nonnull ClassDescriptor createClassDescriptor(@SlashedClassName String className) {
return instance().getClassDescriptor(className);
}
public static ClassDescriptor[] createClassDescriptor(String[] classNames) {
if (classNames.length == 0) {
return ClassDescriptor.EMPTY_ARRAY;
}
ClassDescriptor[] result = new ClassDescriptor[classNames.length];
for (int i = 0; i < classNames.length; i++) {
result[i] = createClassDescriptor(classNames[i]);
}
return result;
}
public static ClassDescriptor createClassDescriptorFromDottedClassName(String dottedClassName) {
return createClassDescriptor(dottedClassName.replace('.', '/'));
}
}
| johnscancella/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/DescriptorFactory.java | Java | lgpl-2.1 | 12,754 |
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.utils;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.commons.beanutils.ConversionException;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
/**
* Contains utility methods.
*
* @author <a href="mailto:[email protected]">Aleksey Nesterenko</a>
*/
public final class CommonUtils {
/** Prefix for the exception when unable to find resource. */
private static final String UNABLE_TO_FIND_EXCEPTION_PREFIX = "Unable to find: ";
/** Stop instances being created. **/
private CommonUtils() {
}
/**
* Returns whether the file extension matches what we are meant to process.
*
* @param file
* the file to be checked.
* @param fileExtensions
* files extensions, empty property in config makes it matches to all.
* @return whether there is a match.
*/
public static boolean matchesFileExtension(File file, String... fileExtensions) {
boolean result = false;
if (fileExtensions == null || fileExtensions.length == 0) {
result = true;
}
else {
// normalize extensions so all of them have a leading dot
final String[] withDotExtensions = new String[fileExtensions.length];
for (int i = 0; i < fileExtensions.length; i++) {
final String extension = fileExtensions[i];
if (startsWithChar(extension, '.')) {
withDotExtensions[i] = extension;
}
else {
withDotExtensions[i] = "." + extension;
}
}
final String fileName = file.getName();
for (final String fileExtension : withDotExtensions) {
if (fileName.endsWith(fileExtension)) {
result = true;
}
}
}
return result;
}
/**
* Returns whether the specified string contains only whitespace up to the specified index.
*
* @param index
* index to check up to
* @param line
* the line to check
* @return whether there is only whitespace
*/
public static boolean hasWhitespaceBefore(int index, String line) {
for (int i = 0; i < index; i++) {
if (!Character.isWhitespace(line.charAt(i))) {
return false;
}
}
return true;
}
/**
* Returns the length of a string ignoring all trailing whitespace.
* It is a pity that there is not a trim() like
* method that only removed the trailing whitespace.
*
* @param line
* the string to process
* @return the length of the string ignoring all trailing whitespace
**/
public static int lengthMinusTrailingWhitespace(String line) {
int len = line.length();
for (int i = len - 1; i >= 0; i--) {
if (!Character.isWhitespace(line.charAt(i))) {
break;
}
len--;
}
return len;
}
/**
* Returns the length of a String prefix with tabs expanded.
* Each tab is counted as the number of characters is
* takes to jump to the next tab stop.
*
* @param inputString
* the input String
* @param toIdx
* index in string (exclusive) where the calculation stops
* @param tabWidth
* the distance between tab stop position.
* @return the length of string.substring(0, toIdx) with tabs expanded.
*/
public static int lengthExpandedTabs(String inputString,
int toIdx,
int tabWidth) {
int len = 0;
for (int idx = 0; idx < toIdx; idx++) {
if (inputString.charAt(idx) == '\t') {
len = (len / tabWidth + 1) * tabWidth;
}
else {
len++;
}
}
return len;
}
/**
* Validates whether passed string is a valid pattern or not.
*
* @param pattern
* string to validate
* @return true if the pattern is valid false otherwise
*/
public static boolean isPatternValid(String pattern) {
try {
Pattern.compile(pattern);
}
catch (final PatternSyntaxException ignored) {
return false;
}
return true;
}
/**
* Helper method to create a regular expression.
*
* @param pattern
* the pattern to match
* @return a created regexp object
* @throws ConversionException
* if unable to create Pattern object.
**/
public static Pattern createPattern(String pattern) {
try {
return Pattern.compile(pattern);
}
catch (final PatternSyntaxException e) {
throw new ConversionException(
"Failed to initialise regular expression " + pattern, e);
}
}
/**
* @param type
* the fully qualified name. Cannot be null
* @return the base class name from a fully qualified name
*/
public static String baseClassName(String type) {
final int index = type.lastIndexOf('.');
if (index == -1) {
return type;
}
else {
return type.substring(index + 1);
}
}
/**
* Constructs a normalized relative path between base directory and a given path.
*
* @param baseDirectory
* the base path to which given path is relativized
* @param path
* the path to relativize against base directory
* @return the relative normalized path between base directory and
* path or path if base directory is null.
*/
public static String relativizeAndNormalizePath(final String baseDirectory, final String path) {
if (baseDirectory == null) {
return path;
}
final Path pathAbsolute = Paths.get(path).normalize();
final Path pathBase = Paths.get(baseDirectory).normalize();
return pathBase.relativize(pathAbsolute).toString();
}
/**
* Tests if this string starts with the specified prefix.
* <p>
* It is faster version of {@link String#startsWith(String)} optimized for
* one-character prefixes at the expense of
* some readability. Suggested by SimplifyStartsWith PMD rule:
* http://pmd.sourceforge.net/pmd-5.3.1/pmd-java/rules/java/optimizations.html#SimplifyStartsWith
* </p>
*
* @param value
* the {@code String} to check
* @param prefix
* the prefix to find
* @return {@code true} if the {@code char} is a prefix of the given {@code String};
* {@code false} otherwise.
*/
public static boolean startsWithChar(String value, char prefix) {
return !value.isEmpty() && value.charAt(0) == prefix;
}
/**
* Tests if this string ends with the specified suffix.
* <p>
* It is faster version of {@link String#endsWith(String)} optimized for
* one-character suffixes at the expense of
* some readability. Suggested by SimplifyStartsWith PMD rule:
* http://pmd.sourceforge.net/pmd-5.3.1/pmd-java/rules/java/optimizations.html#SimplifyStartsWith
* </p>
*
* @param value
* the {@code String} to check
* @param suffix
* the suffix to find
* @return {@code true} if the {@code char} is a suffix of the given {@code String};
* {@code false} otherwise.
*/
public static boolean endsWithChar(String value, char suffix) {
return !value.isEmpty() && value.charAt(value.length() - 1) == suffix;
}
/**
* Gets constructor of targetClass.
* @param targetClass
* from which constructor is returned
* @param parameterTypes
* of constructor
* @return constructor of targetClass or {@link IllegalStateException} if any exception occurs
* @see Class#getConstructor(Class[])
*/
public static Constructor<?> getConstructor(Class<?> targetClass, Class<?>... parameterTypes) {
try {
return targetClass.getConstructor(parameterTypes);
}
catch (NoSuchMethodException ex) {
throw new IllegalStateException(ex);
}
}
/**
* @param constructor
* to invoke
* @param parameters
* to pass to constructor
* @param <T>
* type of constructor
* @return new instance of class or {@link IllegalStateException} if any exception occurs
* @see Constructor#newInstance(Object...)
*/
public static <T> T invokeConstructor(Constructor<T> constructor, Object... parameters) {
try {
return constructor.newInstance(parameters);
}
catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
throw new IllegalStateException(ex);
}
}
/**
* Closes a stream re-throwing IOException as IllegalStateException.
*
* @param closeable
* Closeable object
*/
public static void close(Closeable closeable) {
if (closeable == null) {
return;
}
try {
closeable.close();
}
catch (IOException e) {
throw new IllegalStateException("Cannot close the stream", e);
}
}
/**
* Resolve the specified filename to a URI.
* @param filename name os the file
* @return resolved header file URI
* @throws CheckstyleException on failure
*/
public static URI getUriByFilename(String filename) throws CheckstyleException {
// figure out if this is a File or a URL
URI uri;
try {
final URL url = new URL(filename);
uri = url.toURI();
}
catch (final URISyntaxException | MalformedURLException ignored) {
uri = null;
}
if (uri == null) {
final File file = new File(filename);
if (file.exists()) {
uri = file.toURI();
}
else {
// check to see if the file is in the classpath
try {
final URL configUrl = CommonUtils.class
.getResource(filename);
if (configUrl == null) {
throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename);
}
uri = configUrl.toURI();
}
catch (final URISyntaxException e) {
throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename, e);
}
}
}
return uri;
}
}
| gallandarakhneorg/checkstyle | src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtils.java | Java | lgpl-2.1 | 12,362 |
package org.jboss.test.osgi.msc;
/*
* #%L
* JBossOSGi Framework
* %%
* Copyright (C) 2010 - 2012 JBoss by Red Hat
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import org.jboss.logging.Logger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.junit.After;
import org.junit.Before;
/**
*
* @author [email protected]
* @since 19-Apr-2012
*/
public abstract class AbstractServiceTestCase {
Logger log = Logger.getLogger(AbstractServiceTestCase.class);
ServiceContainer serviceContainer;
ServiceTarget serviceTarget;
@Before
public void setUp() {
serviceContainer = ServiceContainer.Factory.create();
serviceTarget = serviceContainer.subTarget();
}
@After
public void setTearDown() {
serviceContainer.shutdown();
serviceTarget = null;
}
protected ServiceContainer getServiceContainer() {
return serviceContainer;
}
protected ServiceController<?> getService(ServiceName name) {
return serviceContainer.getService(name);
}
protected ServiceController<?> getRequiredService(ServiceName name) {
return serviceContainer.getRequiredService(name);
}
class ServiceA extends TestService {
}
class ServiceB extends TestService {
}
class TestService implements Service<String> {
private String value;
@Override
public void start(StartContext context) throws StartException {
ServiceName sname = context.getController().getName();
log.infof("start: %s", sname);
value = sname.getSimpleName();
}
@Override
public void stop(StopContext context) {
ServiceName sname = context.getController().getName();
log.infof("stop: %s", sname);
value = null;
}
@Override
public String getValue() {
return value;
}
}
}
| jbosgi/jbosgi-framework | core/src/test/java/org/jboss/test/osgi/msc/AbstractServiceTestCase.java | Java | lgpl-2.1 | 2,887 |
package it.unitn.disi.smatch.web.shared.model.exceptions;
/**
* @author <a rel="author" href="http://autayeu.com/">Aliaksandr Autayeu</a>
*/
@HTTPResponseStatus(value = 400)
public class SMatchWebTaskLimitException extends SMatchWebException {
public SMatchWebTaskLimitException() {
}
public SMatchWebTaskLimitException(String errorDescription) {
super(errorDescription);
}
} | s-match/s-match-web | src/main/java/it/unitn/disi/smatch/web/shared/model/exceptions/SMatchWebTaskLimitException.java | Java | lgpl-2.1 | 418 |
/*
* 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.test.annotations.referencedcolumnname;
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
/**
* @author Janario Oliveira
*/
@Entity
public class HousePlaces {
@Id
@GeneratedValue
int id;
@Embedded
Places places;
@Embedded
@AssociationOverrides({
@AssociationOverride(name = "livingRoom", joinColumns = {
@JoinColumn(name = "NEIGHBOUR_LIVINGROOM", referencedColumnName = "NAME"),
@JoinColumn(name = "NEIGHBOUR_LIVINGROOM_OWNER", referencedColumnName = "OWNER") }),
@AssociationOverride(name = "kitchen", joinColumns = @JoinColumn(name = "NEIGHBOUR_KITCHEN", referencedColumnName = "NAME")) })
Places neighbourPlaces;
}
| 1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/referencedcolumnname/HousePlaces.java | Java | lgpl-2.1 | 1,123 |
/*
* jETeL/CloverETL - Java based ETL application framework.
* Copyright (c) Javlin, a.s. ([email protected])
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.graph.runtime;
/**
* This abstract class represents common tracking information on a port.
*
* State of an instance is supposed to be changed over time
* (it is used by WatchDog to gather information during an execution of graph).
*
*
* @author Filip Reichman
* (c) Javlin Consulting (www.javlinconsulting.cz)
*
* @created Jan 2, 2019
*/
public abstract class AbstractPortTrackingProvider {
private static final int MIN_TIMESLICE = 1000;
protected final NodeTrackingProvider parentNodeTracking;
protected final int index;
protected long totalRecords;
protected long totalBytes;
protected int recordFlow;
protected int recordPeak;
protected int byteFlow;
protected int bytePeak;
protected int waitingRecords;
protected int averageWaitingRecords;
protected int usedMemory;
protected long remoteRunId;
private long lastGatherTime;
protected AbstractPortTrackingProvider(NodeTrackingProvider parentNodeTracking, int index) {
this.parentNodeTracking = parentNodeTracking;
this.index = index;
}
abstract void gatherTrackingDetails();
public int getIndex() {
return index;
}
public long getTotalRecords() {
return totalRecords;
}
public long getTotalBytes() {
return totalBytes;
}
public int getRecordFlow() {
return recordFlow;
}
public int getRecordPeak() {
return recordPeak;
}
public int getByteFlow() {
return byteFlow;
}
public int getBytePeak() {
return bytePeak;
}
public int getWaitingRecords() {
return waitingRecords;
}
public int getAverageWaitingRecords() {
return averageWaitingRecords;
}
public int getUsedMemory() {
return usedMemory;
}
public long getRemoteRunId() {
return remoteRunId;
}
protected void gatherTrackingDetails0(long newTotalRecords, long newTotalBytes, int waitingRecords) {
long currentTime = System.currentTimeMillis();
long timespan = lastGatherTime != 0 ? currentTime - lastGatherTime : 0;
if(timespan > MIN_TIMESLICE) { // for too small time slice are statistic values too distorted
//recordFlow
recordFlow = (int) (((long) (newTotalRecords - totalRecords)) * 1000 / timespan);
//recordPeak
recordPeak = Math.max(recordPeak, recordFlow);
//byteFlow
byteFlow = (int) (((long) (newTotalBytes - totalBytes)) * 1000 / timespan);
//bytePeak
bytePeak = Math.max(bytePeak, byteFlow);
lastGatherTime = currentTime;
} else {
if(lastGatherTime == 0) {
lastGatherTime = currentTime;
}
}
//totalRows
totalRecords = newTotalRecords;
//totalBytes
totalBytes = newTotalBytes;
//waitingRecords
this.waitingRecords = waitingRecords;
//averageWaitingRecords
averageWaitingRecords = Math.abs(waitingRecords - averageWaitingRecords) / 2;
}
void phaseFinished() {
long executionTime = getParentNodeTracking().getParentPhaseTracking().getExecutionTime();
if (executionTime > 0) {
//recordFlow - average flow is calculated
recordFlow = (int) ((totalRecords * 1000) / executionTime);
//byteFlow - average flow is calculated
byteFlow = (int) ((totalBytes * 1000) / executionTime);
} else {
recordFlow = 0;
byteFlow = 0;
}
}
private NodeTrackingProvider getParentNodeTracking() {
return parentNodeTracking;
}
}
| CloverETL/CloverETL-Engine | cloveretl.engine/src/org/jetel/graph/runtime/AbstractPortTrackingProvider.java | Java | lgpl-2.1 | 4,295 |
package net.sf.fmj.utility;
import java.awt.*;
import java.text.*;
import java.util.*;
import java.util.List;
import javax.media.Format;
import javax.media.format.*;
import net.sf.fmj.media.*;
import net.sf.fmj.media.format.*;
/**
* A class for converting Format objects to and from strings that can be used as
* arguments in command-line programs, or as parameters in URLs.
*
* The syntax is this: all elements are separated by a colon. Everything is
* uppercase by default, but case is ignored. Only thing that is lowercase is x
* in dimension. Generally, each item corresponds to a constructor argument. The
* Format subclass is inferred from the encoding. ? is used to indicate
* Format.NOT_SPECIFIED (-1). floating point values in audio formats are done as
* integers. In audio formats, Big endian is B, little endian is L, signed is S,
* unsigned is U Data types: B is byte[], S is short[], I is int[] Dimension:
* [width]x[height], like "640x480" Trailing not specified values may be
* omitted.
*
* new AudioFormat(AudioFormat.LINEAR, 44100.0, 16, 2) would be
* LINEAR:44100:16:2
*
*
*
* TODO: support WavAudioFormat, video formats, and other missing audio formats.
*
* @author Ken Larson
*
*/
public class FormatArgUtils
{
private static class Tokens
{
private final String[] items;
private int ix;
public Tokens(String[] items)
{
super();
this.items = items;
ix = 0;
}
public Class<?> nextDataType() throws ParseException
{
String s = nextString();
if (s == null)
return null;
if (s.equals(NOT_SPECIFIED))
return null;
s = s.toUpperCase();
if (s.equals(BYTE_ARRAY))
return Format.byteArray;
else if (s.equals(SHORT_ARRAY))
return Format.shortArray;
else if (s.equals(INT_ARRAY))
return Format.intArray;
else
throw new ParseException("Expected one of [" + BYTE_ARRAY + ","
+ SHORT_ARRAY + "," + INT_ARRAY + "]: " + s, -1);
}
public Dimension nextDimension() throws ParseException
{
String s = nextString();
if (s == null)
return null;
if (s.equals(NOT_SPECIFIED))
return null;
s = s.toUpperCase();
String[] strings = s.split("X");
if (strings.length != 2)
throw new ParseException("Expected WIDTHxHEIGHT: " + s, -1);
int width;
int height;
try
{
width = Integer.parseInt(strings[0]);
} catch (NumberFormatException e)
{
throw new ParseException("Expected integer: " + strings[0], -1);
}
try
{
height = Integer.parseInt(strings[1]);
} catch (NumberFormatException e)
{
throw new ParseException("Expected integer: " + strings[1], -1);
}
return new Dimension(width, height);
}
public double nextDouble() throws ParseException
{
final String s = nextString();
if (s == null)
return Format.NOT_SPECIFIED;
if (s.equals(NOT_SPECIFIED))
return Format.NOT_SPECIFIED;
try
{
return Double.parseDouble(s);
} catch (NumberFormatException e)
{
throw new ParseException("Expected double: " + s, -1);
}
}
public int nextEndian() throws ParseException
{
String s = nextString();
if (s == null)
return Format.NOT_SPECIFIED;
if (s.equals(NOT_SPECIFIED))
return Format.NOT_SPECIFIED;
s = s.toUpperCase();
if (s.equals(BIG_ENDIAN))
return AudioFormat.BIG_ENDIAN;
else if (s.equals(LITTLE_ENDIAN))
return AudioFormat.LITTLE_ENDIAN;
else
throw new ParseException("Expected one of [" + BIG_ENDIAN + ","
+ LITTLE_ENDIAN + "]: " + s, -1);
}
public float nextFloat() throws ParseException
{
final String s = nextString();
if (s == null)
return Format.NOT_SPECIFIED;
if (s.equals(NOT_SPECIFIED))
return Format.NOT_SPECIFIED;
try
{
return Float.parseFloat(s);
} catch (NumberFormatException e)
{
throw new ParseException("Expected float: " + s, -1);
}
}
public int nextInt() throws ParseException
{
final String s = nextString();
if (s == null)
return Format.NOT_SPECIFIED;
if (s.equals(NOT_SPECIFIED))
return Format.NOT_SPECIFIED;
try
{
return Integer.parseInt(s);
} catch (NumberFormatException e)
{
throw new ParseException("Expected integer: " + s, -1);
}
}
public int nextRGBFormatEndian() throws ParseException
{
String s = nextString();
if (s == null)
return Format.NOT_SPECIFIED;
if (s.equals(NOT_SPECIFIED))
return Format.NOT_SPECIFIED;
s = s.toUpperCase();
if (s.equals(BIG_ENDIAN))
return RGBFormat.BIG_ENDIAN;
else if (s.equals(LITTLE_ENDIAN))
return RGBFormat.LITTLE_ENDIAN;
else
throw new ParseException("Expected one of [" + BIG_ENDIAN + ","
+ LITTLE_ENDIAN + "]: " + s, -1);
}
public int nextSigned() throws ParseException
{
String s = nextString();
if (s == null)
return Format.NOT_SPECIFIED;
if (s.equals(NOT_SPECIFIED))
return Format.NOT_SPECIFIED;
s = s.toUpperCase();
if (s.equals(UNSIGNED))
return AudioFormat.UNSIGNED;
else if (s.equals(SIGNED))
return AudioFormat.SIGNED;
else
throw new ParseException("Expected one of [" + UNSIGNED + ","
+ UNSIGNED + "]: " + s, -1);
}
public String nextString()
{
return nextString(null);
}
public String nextString(String defaultResult)
{
if (ix >= items.length)
return defaultResult;
final String result = items[ix];
++ix;
return result;
}
}
private static final char SEP = ':';
public static final String BYTE_ARRAY = "B";
public static final String SHORT_ARRAY = "S";
public static final String INT_ARRAY = "I";
public static final String NOT_SPECIFIED = "?";
// audio format constants:
public static final String BIG_ENDIAN = "B";
public static final String LITTLE_ENDIAN = "L";
public static final String SIGNED = "S";
public static final String UNSIGNED = "U";
private static final Map<String, String> formatEncodings = new HashMap<String, String>(); // corect
// case
private static final Map<String, Class<?>> formatClasses = new HashMap<String, Class<?>>();
static
{
buildFormatMap();
}
private static final void addAudioFormat(String s)
{
addFormat(s, AudioFormat.class);
}
private static final void addFormat(String s, Class<?> clazz)
{
formatClasses.put(s.toLowerCase(), clazz);
formatEncodings.put(s.toLowerCase(), s);
}
private static final void addVideoFormat(String s)
{
addFormat(s, VideoFormat.class);
}
private static final void buildFormatMap()
{
addAudioFormat(AudioFormat.LINEAR);
addAudioFormat(AudioFormat.ULAW); // = "ULAW";
addAudioFormat(AudioFormat.ULAW_RTP); // = "ULAW/rtp";
addAudioFormat(AudioFormat.ALAW); // = "alaw"; // strange that this is
// lower case and ULAW is not...
addAudioFormat(AudioFormat.IMA4); // = "ima4";
addAudioFormat(AudioFormat.IMA4_MS); // = "ima4/ms";
addAudioFormat(AudioFormat.MSADPCM); // = "msadpcm";
addAudioFormat(AudioFormat.DVI); // = "dvi";
addAudioFormat(AudioFormat.DVI_RTP); // = "dvi/rtp";
addAudioFormat(AudioFormat.G723); // = "g723";
addAudioFormat(AudioFormat.G723_RTP); // = "g723/rtp";
addAudioFormat(AudioFormat.G728); // = "g728";
addAudioFormat(AudioFormat.G728_RTP); // = "g728/rtp";
addAudioFormat(AudioFormat.G729); // = "g729";
addAudioFormat(AudioFormat.G729_RTP); // = "g729/rtp";
addAudioFormat(AudioFormat.G729A); // = "g729a";
addAudioFormat(AudioFormat.G729A_RTP); // = "g729a/rtp";
addAudioFormat(AudioFormat.GSM); // = "gsm";
addAudioFormat(AudioFormat.GSM_MS); // = "gsm/ms";
addAudioFormat(AudioFormat.GSM_RTP); // = "gsm/rtp";
addAudioFormat(AudioFormat.MAC3); // = "MAC3";
addAudioFormat(AudioFormat.MAC6); // = "MAC6";
addAudioFormat(AudioFormat.TRUESPEECH); // = "truespeech";
addAudioFormat(AudioFormat.MSNAUDIO); // = "msnaudio";
addAudioFormat(AudioFormat.MPEGLAYER3); // = "mpeglayer3";
addAudioFormat(AudioFormat.VOXWAREAC8); // = "voxwareac8";
addAudioFormat(AudioFormat.VOXWAREAC10); // = "voxwareac10";
addAudioFormat(AudioFormat.VOXWAREAC16); // = "voxwareac16";
addAudioFormat(AudioFormat.VOXWAREAC20); // = "voxwareac20";
addAudioFormat(AudioFormat.VOXWAREMETAVOICE); // = "voxwaremetavoice";
addAudioFormat(AudioFormat.VOXWAREMETASOUND); // = "voxwaremetasound";
addAudioFormat(AudioFormat.VOXWARERT29H); // = "voxwarert29h";
addAudioFormat(AudioFormat.VOXWAREVR12); // = "voxwarevr12";
addAudioFormat(AudioFormat.VOXWAREVR18); // = "voxwarevr18";
addAudioFormat(AudioFormat.VOXWARETQ40); // = "voxwaretq40";
addAudioFormat(AudioFormat.VOXWARETQ60); // = "voxwaretq60";
addAudioFormat(AudioFormat.MSRT24); // = "msrt24";
addAudioFormat(AudioFormat.MPEG); // = "mpegaudio";
addAudioFormat(AudioFormat.MPEG_RTP); // = "mpegaudio/rtp";
addAudioFormat(AudioFormat.DOLBYAC3); // = "dolbyac3";
for (String e : BonusAudioFormatEncodings.ALL)
addAudioFormat(e);
// TODO: MpegEncoding using
// MpegEncoding.MPEG1L1,
// MpegEncoding.MPEG1L2,
// MpegEncoding.MPEG1L3,
// MpegEncoding.MPEG2DOT5L1,
// MpegEncoding.MPEG2DOT5L2,
// MpegEncoding.MPEG2DOT5L3,
// MpegEncoding.MPEG2L1,
// MpegEncoding.MPEG2L2,
// MpegEncoding.MPEG2L3,
// TODO: VorbisEncoding using VorbisEncoding.VORBISENC
// Video formats:
addVideoFormat(VideoFormat.CINEPAK); // ="cvid";
addFormat(VideoFormat.JPEG, JPEGFormat.class);
addVideoFormat(VideoFormat.JPEG_RTP); // ="jpeg/rtp";
addVideoFormat(VideoFormat.MPEG); // ="mpeg";
addVideoFormat(VideoFormat.MPEG_RTP); // ="mpeg/rtp";
addFormat(VideoFormat.H261, H261Format.class);
addVideoFormat(VideoFormat.H261_RTP); // ="h261/rtp";
addFormat(VideoFormat.H263, H263Format.class);
addVideoFormat(VideoFormat.H263_RTP); // ="h263/rtp";
addVideoFormat(VideoFormat.H263_1998_RTP); // ="h263-1998/rtp";
addFormat(VideoFormat.RGB, RGBFormat.class);
addFormat(VideoFormat.YUV, YUVFormat.class);
addFormat(VideoFormat.IRGB, IndexedColorFormat.class);
addVideoFormat(VideoFormat.SMC); // ="smc";
addVideoFormat(VideoFormat.RLE); // ="rle";
addVideoFormat(VideoFormat.RPZA); // ="rpza";
addVideoFormat(VideoFormat.MJPG); // ="mjpg";
addVideoFormat(VideoFormat.MJPEGA); // ="mjpa";
addVideoFormat(VideoFormat.MJPEGB); // ="mjpb";
addVideoFormat(VideoFormat.INDEO32); // ="iv32";
addVideoFormat(VideoFormat.INDEO41); // ="iv41";
addVideoFormat(VideoFormat.INDEO50); // ="iv50";
// TODO: AviVideoFormat
addFormat(BonusVideoFormatEncodings.GIF, GIFFormat.class);
addFormat(BonusVideoFormatEncodings.PNG, PNGFormat.class);
}
private static final String dataTypeToStr(Class<?> clazz)
{
if (clazz == null)
{
return NOT_SPECIFIED;
}
if (clazz == Format.byteArray)
{
return BYTE_ARRAY;
}
if (clazz == Format.shortArray)
{
return SHORT_ARRAY;
}
if (clazz == Format.intArray)
{
return INT_ARRAY;
}
throw new IllegalArgumentException("" + clazz);
}
private static final String dimensionToStr(Dimension d)
{
if (d == null)
return NOT_SPECIFIED;
return ((int) d.getWidth()) + "x" + ((int) d.getHeight());
}
private static final String endianToStr(int endian)
{
if (endian == Format.NOT_SPECIFIED)
return NOT_SPECIFIED;
else if (endian == AudioFormat.BIG_ENDIAN)
return BIG_ENDIAN;
else if (endian == AudioFormat.LITTLE_ENDIAN)
return LITTLE_ENDIAN;
else
throw new IllegalArgumentException("Unknown endianness: " + endian);
}
private static final String floatToStr(float v)
{
if (v == Format.NOT_SPECIFIED)
return NOT_SPECIFIED;
else
return "" + v;
}
private static final String intToStr(int i)
{
if (i == Format.NOT_SPECIFIED)
return NOT_SPECIFIED;
else
return "" + i;
}
public static Format parse(String s) throws ParseException
{
final String[] strings = s.split("" + SEP);
final Tokens t = new Tokens(strings);
int ix = 0;
final String encodingIgnoreCase = t.nextString(null);
if (encodingIgnoreCase == null)
throw new ParseException("No encoding specified", 0);
final Class<?> formatClass = formatClasses.get(encodingIgnoreCase
.toLowerCase());
if (formatClass == null)
throw new ParseException("Unknown encoding: " + encodingIgnoreCase,
-1);
final String encoding = formatEncodings.get(encodingIgnoreCase
.toLowerCase());
if (encoding == null)
throw new ParseException("Unknown encoding: " + encodingIgnoreCase,
-1);
if (AudioFormat.class.isAssignableFrom(formatClass))
{
final double sampleRate = t.nextDouble();
final int sampleSizeInBits = t.nextInt();
final int channels = t.nextInt();
final int endian = t.nextEndian();
final int signed = t.nextSigned();
final int frameSizeInBits = t.nextInt();
final double frameRate = t.nextDouble();
Class<?> dataType = t.nextDataType();
if (dataType == null)
dataType = Format.byteArray; // default
return new AudioFormat(encoding, sampleRate, sampleSizeInBits,
channels, endian, signed, frameSizeInBits, frameRate,
dataType);
} else if (VideoFormat.class.isAssignableFrom(formatClass))
{
if (formatClass == JPEGFormat.class)
{
final java.awt.Dimension size = t.nextDimension();
final int maxDataLength = t.nextInt();
Class<?> dataType = t.nextDataType();
if (dataType == null)
dataType = Format.byteArray; // default
final float frameRate = t.nextFloat();
final int q = Format.NOT_SPECIFIED; // TODO
final int dec = Format.NOT_SPECIFIED; // TODO
return new JPEGFormat(size, maxDataLength, dataType, frameRate,
q, dec);
} else if (formatClass == GIFFormat.class)
{
final java.awt.Dimension size = t.nextDimension();
final int maxDataLength = t.nextInt();
Class<?> dataType = t.nextDataType();
if (dataType == null)
dataType = Format.byteArray; // default
final float frameRate = t.nextFloat();
return new GIFFormat(size, maxDataLength, dataType, frameRate);
} else if (formatClass == PNGFormat.class)
{
final java.awt.Dimension size = t.nextDimension();
final int maxDataLength = t.nextInt();
Class<?> dataType = t.nextDataType();
if (dataType == null)
dataType = Format.byteArray; // default
final float frameRate = t.nextFloat();
return new PNGFormat(size, maxDataLength, dataType, frameRate);
} else if (formatClass == VideoFormat.class)
{
final java.awt.Dimension size = t.nextDimension();
final int maxDataLength = t.nextInt();
Class<?> dataType = t.nextDataType();
if (dataType == null)
dataType = Format.byteArray; // default
final float frameRate = t.nextFloat();
return new VideoFormat(encoding, size, maxDataLength, dataType,
frameRate);
} else if (formatClass == RGBFormat.class)
{
final java.awt.Dimension size = t.nextDimension();
final int maxDataLength = t.nextInt();
Class<?> dataType = t.nextDataType();
if (dataType == null)
dataType = Format.byteArray; // default
final float frameRate = t.nextFloat();
final int bitsPerPixel = t.nextInt();
final int red = t.nextInt();
final int green = t.nextInt();
final int blue = t.nextInt();
final int pixelStride = t.nextInt();
final int lineStride = t.nextInt();
final int flipped = t.nextInt();
final int endian = t.nextRGBFormatEndian();
if (pixelStride == -1 && lineStride == -1 && flipped == -1
&& endian == -1)
return new RGBFormat(size, maxDataLength, dataType,
frameRate, bitsPerPixel, red, green, blue);
return new RGBFormat(size, maxDataLength, dataType, frameRate,
bitsPerPixel, red, green, blue, pixelStride,
lineStride, flipped, endian);
}
// public RGBFormat(java.awt.Dimension size, int maxDataLength,
// Class dataType, float frameRate, int bitsPerPixel,
// int red, int green, int blue, int pixelStride, int lineStride,
// int flipped, int endian)
// TODO: others
throw new RuntimeException("TODO: Unknown class: " + formatClass);
} else
{
throw new RuntimeException("Unknown class: " + formatClass);
}
}
private static final String rgbFormatEndianToStr(int endian)
{
if (endian == Format.NOT_SPECIFIED)
return NOT_SPECIFIED;
else if (endian == RGBFormat.BIG_ENDIAN)
return BIG_ENDIAN;
else if (endian == RGBFormat.LITTLE_ENDIAN)
return LITTLE_ENDIAN;
else
throw new IllegalArgumentException("Unknown endianness: " + endian);
}
private static final String signedToStr(int signed)
{
if (signed == Format.NOT_SPECIFIED)
return NOT_SPECIFIED;
else if (signed == AudioFormat.SIGNED)
return SIGNED;
else if (signed == AudioFormat.UNSIGNED)
return UNSIGNED;
else
throw new IllegalArgumentException("Unknown signedness: " + signed);
}
public static String toString(Format f)
{
final List<String> list = new ArrayList<String>();
list.add(f.getEncoding().toUpperCase());
if (f instanceof AudioFormat)
{
final AudioFormat af = (AudioFormat) f;
list.add(intToStr((int) af.getSampleRate()));
list.add(intToStr(af.getSampleSizeInBits()));
list.add(intToStr(af.getChannels()));
list.add(endianToStr(af.getEndian()));
list.add(signedToStr(af.getSigned()));
list.add(intToStr(af.getFrameSizeInBits()));
list.add(intToStr((int) af.getFrameRate()));
if (af.getDataType() != null
&& af.getDataType() != Format.byteArray)
list.add(dataTypeToStr(af.getDataType()));
} else if (f instanceof VideoFormat)
{
final VideoFormat vf = (VideoFormat) f;
if (f.getClass() == JPEGFormat.class)
{
final JPEGFormat jf = (JPEGFormat) vf;
list.add(dimensionToStr(jf.getSize()));
list.add(intToStr(jf.getMaxDataLength()));
if (jf.getDataType() != null
&& jf.getDataType() != Format.byteArray)
list.add(dataTypeToStr(jf.getDataType()));
list.add(floatToStr(jf.getFrameRate()));
// TODO: Q, decimation
} else if (f.getClass() == GIFFormat.class)
{
final GIFFormat gf = (GIFFormat) vf;
list.add(dimensionToStr(gf.getSize()));
list.add(intToStr(gf.getMaxDataLength()));
if (gf.getDataType() != null
&& gf.getDataType() != Format.byteArray)
list.add(dataTypeToStr(gf.getDataType()));
list.add(floatToStr(gf.getFrameRate()));
} else if (f.getClass() == PNGFormat.class)
{
final PNGFormat pf = (PNGFormat) vf;
list.add(dimensionToStr(pf.getSize()));
list.add(intToStr(pf.getMaxDataLength()));
if (pf.getDataType() != null
&& pf.getDataType() != Format.byteArray)
list.add(dataTypeToStr(pf.getDataType()));
list.add(floatToStr(pf.getFrameRate()));
} else if (f.getClass() == VideoFormat.class)
{
list.add(dimensionToStr(vf.getSize()));
list.add(intToStr(vf.getMaxDataLength()));
if (vf.getDataType() != null
&& vf.getDataType() != Format.byteArray)
list.add(dataTypeToStr(vf.getDataType()));
list.add(floatToStr(vf.getFrameRate()));
} else if (f.getClass() == RGBFormat.class)
{
final RGBFormat rf = (RGBFormat) vf;
list.add(dimensionToStr(vf.getSize()));
list.add(intToStr(vf.getMaxDataLength()));
if (vf.getDataType() != null
&& vf.getDataType() != Format.byteArray)
list.add(dataTypeToStr(vf.getDataType()));
list.add(floatToStr(vf.getFrameRate()));
list.add(intToStr(rf.getBitsPerPixel()));
list.add(intToStr(rf.getRedMask())); // TODO: hex?
list.add(intToStr(rf.getGreenMask()));
list.add(intToStr(rf.getBlueMask()));
list.add(intToStr(rf.getPixelStride()));
list.add(intToStr(rf.getLineStride()));
list.add(intToStr(rf.getFlipped())); // TODO: use a string code
// for this?
list.add(rgbFormatEndianToStr(rf.getEndian()));
} else
throw new IllegalArgumentException(
"Unknown or unsupported format: " + f);
} else
{
throw new IllegalArgumentException("" + f);
}
// remove any default values from the end.
while (list.get(list.size() - 1) == null
|| list.get(list.size() - 1).equals(NOT_SPECIFIED))
list.remove(list.size() - 1);
final StringBuilder b = new StringBuilder();
for (int i = 0; i < list.size(); ++i)
{
if (i > 0)
b.append(SEP);
b.append(list.get(i));
}
return b.toString();
}
}
| champtar/fmj-sourceforge-mirror | src/net/sf/fmj/utility/FormatArgUtils.java | Java | lgpl-2.1 | 25,050 |
package org.uengine.essencia.modeling.editor;
public class EmptyEditor extends Editor {
@Override
public void load() throws Exception {
}
@Override
public void save() throws Exception {
}
@Override
public boolean validate() throws Exception {
return false;
}
}
| iklim/essencia | src/main/java/org/uengine/essencia/modeling/editor/EmptyEditor.java | Java | lgpl-2.1 | 277 |
/*
* 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.notifications.notifiers.internal;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.notifications.NotificationException;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseObjectReference;
/**
* This is the default implementation of {@link ModelBridge}.
*
* @version $Id$
* @since 9.7RC1
*/
@Component
@Singleton
public class DefaultModelBridge implements ModelBridge
{
@Inject
private Provider<XWikiContext> contextProvider;
@Inject
private EntityReferenceSerializer<String> entityReferenceSerializer;
@Override
public void savePropertyInHiddenDocument(BaseObjectReference objectReference, String property, Object value)
throws NotificationException
{
try {
XWikiContext xcontext = contextProvider.get();
DocumentReference documentReference = (DocumentReference) objectReference.getParent();
XWikiDocument doc = xcontext.getWiki().getDocument(documentReference, xcontext);
doc.setHidden(true);
BaseObject obj = doc.getObject(entityReferenceSerializer.serialize(objectReference.getXClassReference()),
true, xcontext);
if (obj != null) {
// Set the value
obj.set(property, value, xcontext);
// Prevent version changes
doc.setMetaDataDirty(false);
doc.setContentDirty(false);
// Save
xcontext.getWiki().saveDocument(doc, String.format("Property [%s] set.", property), xcontext);
}
} catch (XWikiException e) {
throw new NotificationException(String.format("Failed to update the object [%s].", objectReference), e);
}
}
@Override
public String getDocumentURL(DocumentReference documentReference, String action, String parameters)
{
XWikiContext context = contextProvider.get();
return context.getWiki().getExternalURL(documentReference, action, parameters, null, context);
}
}
| xwiki/xwiki-platform | xwiki-platform-core/xwiki-platform-notifications/xwiki-platform-notifications-notifiers/xwiki-platform-notifications-notifiers-default/src/main/java/org/xwiki/notifications/notifiers/internal/DefaultModelBridge.java | Java | lgpl-2.1 | 3,276 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.