repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
schiermike/syncarus | src/net/syncarus/gui/DirSelectComposite.java | 6577 | package net.syncarus.gui;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.filechooser.FileSystemView;
import net.syncarus.core.FileOperation;
import net.syncarus.rcp.ResourceRegistry;
import net.syncarus.rcp.SyncarusPlugin;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TypedListener;
/**
* Useful component allowing the user to choose a directory form a treeViewer.
*/
public class DirSelectComposite extends Composite {
private TableViewer viewer;
public DirSelectComposite(Composite parent, int style) {
super(parent, style);
setBackground(new Color(this.getDisplay(), 255, 0, 0));
setLayout(new FillLayout());
buildListViewer();
}
/**
* build a new listViewer where the initial root is the second element of
* java.io.File.listRoots() if there is only one root, use this one.
*/
private void buildListViewer() {
viewer = new TableViewer(this);
viewer.setLabelProvider(new FileLabelProvider());
viewer.setContentProvider(new FileContentProvider());
viewer.setSorter(new ViewerSorter() {
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
EncapsulatedFile ef1 = (EncapsulatedFile) e1;
EncapsulatedFile ef2 = (EncapsulatedFile) e2;
return ef1.compareTo(ef2);
}
});
viewer.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
setCurrentDirectory(((EncapsulatedFile) selection.getFirstElement()).getFile());
}
});
setCurrentDirectory(FileOperation.getDefaultDirectory());
}
/**
* @param directory
* set this directory as new root of the treeViewer
*/
public void setCurrentDirectory(File directory) {
viewer.setInput(directory);
viewer.getTable().setSelection(viewer.getTable().getItem(0));
notifyListeners(SWT.Selection, null);
}
public void addSelectionListener(SelectionListener listener) {
checkWidget();
if (listener == null)
return;
TypedListener typedListener = new TypedListener(listener);
addListener(SWT.Selection, typedListener);
addListener(SWT.DefaultSelection, typedListener);
}
/**
* @return the currently selected directory
*/
public File getCurrentDirectory() {
return (File) viewer.getInput();
}
}
/**
* Helper class which encapsulates a file and the information whether this file
* is a root (example: C:\, A:\, ..) or if it's a parent (first element in
* treeViewer - UPDIR)
*/
class EncapsulatedFile implements Comparable<EncapsulatedFile> {
private File file = null;
private boolean isParent = false;
private boolean isRoot;
/**
* Constructor for the root of root Files (parent of '/', 'C:\', ...)
*/
public EncapsulatedFile() {
this.file = new File("");
this.isParent = true;
this.isRoot = false;
}
/**
* Constructor for root Files ('/', 'C:\', ...)
*
* @param file
*/
public EncapsulatedFile(File file) {
this.file = file;
this.isParent = false;
this.isRoot = true;
}
/**
* Constructor for regular, existing files and directories
*
* @param file
* @param isParent
*/
public EncapsulatedFile(File file, boolean isParent) {
this.file = file;
this.isParent = isParent;
this.isRoot = false;
}
public File getFile() {
return file;
}
/**
* compares two encapsulated files where the order is as follows:
* <ul>
* <li>isParent()</li>
* <li>compare case-insensitive directory names</li>
* </ul>
*
* @param other
* @return result of comparison
*/
@Override
public int compareTo(EncapsulatedFile other) {
if (isParent())
return -1;
if (other.isParent())
return 1;
return file.getName().compareToIgnoreCase(other.getFile().getName());
}
public boolean isParent() {
return isParent;
}
public boolean isRoot() {
return isRoot;
}
}
class FileContentProvider extends ArrayContentProvider implements IStructuredContentProvider {
@Override
public Object[] getElements(Object inputElement) {
File file = (File) inputElement;
List<EncapsulatedFile> fileList = new ArrayList<EncapsulatedFile>();
if (!file.exists()) // top - level, list drives
{
for (File rootFile : File.listRoots())
fileList.add(new EncapsulatedFile(rootFile));
} else {
if (file.getParentFile() == null) // go to drive selection
fileList.add(new EncapsulatedFile());
else
// go one dir up
fileList.add(new EncapsulatedFile(file.getParentFile(), true));
if (file.listFiles() != null)
for (File subFile : file.listFiles())
if (subFile.isDirectory())
fileList.add(new EncapsulatedFile(subFile, false));
}
return fileList.toArray();
}
}
class FileLabelProvider extends LabelProvider {
@Override
public String getText(Object element) {
EncapsulatedFile encapsFile = (EncapsulatedFile) element;
if (encapsFile.isParent())
return "";
if (encapsFile.isRoot()) {
String rootName = FileSystemView.getFileSystemView().getSystemDisplayName(encapsFile.getFile());
if (rootName == null || rootName.equals(""))
rootName = encapsFile.getFile().getAbsolutePath();
return rootName;
}
String name = encapsFile.getFile().getName();
if (name == null || name.equals(""))
name = encapsFile.getFile().getAbsolutePath();
return name;
}
@Override
public Image getImage(Object element) {
EncapsulatedFile file = (EncapsulatedFile) element;
String imageKey = null;
if (file.isParent())
imageKey = ResourceRegistry.IMAGE_DIR_UP;
else if (file.isRoot()) {
if (FileSystemView.getFileSystemView().isFloppyDrive(file.getFile()))
imageKey = ResourceRegistry.IMAGE_DIR_FLOPPY;
else
imageKey = ResourceRegistry.IMAGE_DIR_HDD;
} else
imageKey = ResourceRegistry.IMAGE_DIR_NORMAL;
return SyncarusPlugin.getInstance().getResourceRegistry().getImage(imageKey);
}
} | gpl-3.0 |
AftonTroll/Avoidance | test/se/chalmers/avoidance/core/components/ScoreTest.java | 1421 | /*
* Copyright (c) 2012 Jakob Svensson
*
* This file is part of Avoidance.
*
* Avoidance is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Avoidance 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 Avoidance. If not, see <http://www.gnu.org/licenses/>.
*
*/
package se.chalmers.avoidance.core.components;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class ScoreTest {
private Score score;
@Before
public void setUp() {
score = new Score();
}
@Test
public void testGetScore() {
assertTrue(score.getScore() == 0);
}
@Test
public void testAddKillScore() {
score.addKillScore(100);
assertTrue(score.getScore() == 100);
}
@Test
public void testAddPowerupScore() {
score.addPowerupScore(200);
assertTrue(score.getScore() == 200);
}
@Test
public void testAddBothScore() {
score.addKillScore(100);
score.addPowerupScore(200);
assertTrue(score.getScore() == 300);
}
}
| gpl-3.0 |
pexcn/BandwagonHost | app/src/main/java/me/pexcn/bandwagonhost/manager/arch/ManagerActivity.java | 1805 | package me.pexcn.bandwagonhost.manager.arch;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import me.pexcn.android.base.arch.mvp.BaseActivity;
import me.pexcn.bandwagonhost.R;
import me.pexcn.bandwagonhost.app.Constants;
import me.pexcn.bandwagonhost.data.local.bean.Host;
import me.pexcn.bandwagonhost.info.arch.InfoFragment;
import me.pexcn.bandwagonhost.manager.adapter.ManagerPagerAdapter;
/**
* Created by pexcn on 2017-03-24.
*/
public class ManagerActivity extends BaseActivity<ManagerContract.Presenter>
implements ManagerContract.View {
private TabLayout mTabLayout;
private ViewPager mViewPager;
private ManagerPagerAdapter mAdapter;
private Host mHost;
@Override
protected ManagerContract.Presenter createPresenter() {
return new ManagerPresenter(this);
}
@Override
protected int getLayoutId() {
return R.layout.activity_manager;
}
@Override
protected void init() {
super.init();
mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mAdapter = new ManagerPagerAdapter(getSupportFragmentManager());
mHost = getIntent().getParcelableExtra(Constants.EXTRA_KEY_HOST);
mAdapter.addPage("Test", InfoFragment.newInstance());
mAdapter.addPage("Test2", InfoFragment.newInstance());
mAdapter.addPage("Test3", InfoFragment.newInstance());
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(mAdapter);
mTabLayout.setupWithViewPager(mViewPager);
setTitle(mHost.title);
}
@Override
protected boolean isSubActivity() {
return true;
}
}
| gpl-3.0 |
openflexo-team/openflexo-technology-adapters | xmlconnector/src/main/java/org/openflexo/technologyadapter/xml/model/XMLModel.java | 4930 | /**
*
* Copyright (c) 2014, Openflexo
*
* This file is part of Xmlconnector, a component of the software infrastructure
* developed at Openflexo.
*
*
* Openflexo is dual-licensed under the European Union Public License (EUPL, either
* version 1.1 of the License, or any later version ), which is available at
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
* and the GNU General Public License (GPL, either version 3 of the License, or any
* later version), which is available at http://www.gnu.org/licenses/gpl.html .
*
* You can redistribute it and/or modify under the terms of either of these licenses
*
* If you choose to redistribute it and/or modify under the terms of the GNU GPL, you
* must include the following additional permission.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with software containing parts covered by the terms
* of EPL 1.0, the licensors of this Program grant you additional permission
* to convey the resulting work. *
*
* 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 http://www.openflexo.org/license.html for details.
*
*
* Please contact Openflexo (openflexo-contacts@openflexo.org)
* or visit www.openflexo.org if you need additional information.
*
*/
package org.openflexo.technologyadapter.xml.model;
import java.lang.reflect.Type;
import java.util.List;
import org.openflexo.foundation.resource.FlexoResource;
import org.openflexo.foundation.technologyadapter.FlexoModel;
import org.openflexo.pamela.annotations.Adder;
import org.openflexo.pamela.annotations.CloningStrategy;
import org.openflexo.pamela.annotations.Embedded;
import org.openflexo.pamela.annotations.Finder;
import org.openflexo.pamela.annotations.Getter;
import org.openflexo.pamela.annotations.ImplementationClass;
import org.openflexo.pamela.annotations.Initializer;
import org.openflexo.pamela.annotations.ModelEntity;
import org.openflexo.pamela.annotations.Parameter;
import org.openflexo.pamela.annotations.PastingPoint;
import org.openflexo.pamela.annotations.Remover;
import org.openflexo.pamela.annotations.Setter;
import org.openflexo.pamela.annotations.CloningStrategy.StrategyType;
import org.openflexo.pamela.annotations.Getter.Cardinality;
import org.openflexo.technologyadapter.xml.metamodel.XMLMetaModel;
import org.openflexo.technologyadapter.xml.metamodel.XMLObject;
import org.openflexo.technologyadapter.xml.metamodel.XMLType;
/**
* @author xtof
*
* This interface defines a PAMELA model to represent an XML Document that is conformant to an {@link XMLMetaModel} that might be: -
* given by an XSD - dynamically built (on purpose)
*
*/
@ModelEntity
@ImplementationClass(XMLModelImpl.class)
public interface XMLModel extends XMLObject, FlexoModel<XMLModel, XMLMetaModel> {
/**
* Reference to the {@link XMLMetaModel} that this document is conformant to
*/
public static final String MM = "metaModel";
/**
* Link to the {@XMLResource} that manages the concrete serialization of this model
*
*/
public static final String RSC = "resource";
/**
* Collection of {@link XMLIndividuals}
*/
public static final String IND = "individuals";
/**
* Root individual of the XML Objects graph
*/
public static final String ROOT = "root";
/**
* Properties that host uri and Namespace prefix for this Model
*/
public static final int NSPREFIX_INDEX = 0;
public static final int NSURI_INDEX = 1;
@Initializer
public XMLModel init();
@Initializer
public XMLModel init(@Parameter(MM) XMLMetaModel mm);
@Override
@Getter(MM)
XMLMetaModel getMetaModel();
@Setter(MM)
void setMetaModel(XMLMetaModel mm);
@Override
@Getter(RSC)
public FlexoResource<XMLModel> getResource();
@Override
@Setter(RSC)
public void setResource(FlexoResource<XMLModel> resource);
@Getter(ROOT)
public XMLIndividual getRoot();
@Setter(ROOT)
public void setRoot(XMLIndividual indiv);
@Getter(value = IND, cardinality = Cardinality.LIST)
@CloningStrategy(StrategyType.CLONE)
@Embedded
public List<? extends XMLIndividual> getIndividuals();
// TODO ask Syl pourkoi on ne peut pas avoir +eurs adders...
public XMLIndividual addNewIndividual(Type aType);
@Adder(IND)
@PastingPoint
public void addIndividual(XMLIndividual ind);
@Remover(IND)
public void removeFromIndividuals(XMLIndividual ind);
@Finder(attribute = XMLIndividual.TYPE, collection = IND, isMultiValued = true)
public List<? extends XMLIndividual> getIndividualsOfType(XMLType aType);
/*
* Non-PAMELA-managed properties
*/
public List<String> getNamespace();
public void setNamespace(String ns, String prefix);
}
| gpl-3.0 |
oghalawinji/InteractiveArabicDictionary | IAD/src/java/sarfDic/Midleware/Noun/trilateral/TimeAndPlaceConjugator.java | 3831 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sarfDic.Midleware.Noun.trilateral;
/**
*
* @author Gowzancha
*/
import sarf.noun.*;
import sarf.verb.trilateral.unaugmented.*;
import java.util.*;
import sarf.*;
import sarf.noun.trilateral.unaugmented.timeandplace.*;
/**
* <p>Title: Sarf Program</p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: ALEXO</p>
*
* @author Haytham Mohtasseb Billah
* @version 1.0
*/
public class TimeAndPlaceConjugator implements IUnaugmentedTrilateralNounConjugator{
private Map formulaClassNamesMap = new HashMap();
//map <symbol,formulaName>
private Map formulaSymbolsNamesMap = new HashMap();
private TimeAndPlaceConjugator() {
for (int i=1; i<=3;i++) {
String formulaClassName = /*getClass().getPackage().getName()*/"sarf.noun.trilateral.unaugmented.timeandplace"+".nonstandard.NounFormula"+i;
try {
Class formulaClass = Class.forName(formulaClassName);
NonStandardTimeAndPlaceNounFormula nounFormula = (NonStandardTimeAndPlaceNounFormula) formulaClass.newInstance();
formulaClassNamesMap.put(nounFormula.getFormulaName(), formulaClass);
formulaSymbolsNamesMap.put(nounFormula.getSymbol(), nounFormula.getFormulaName());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
private static TimeAndPlaceConjugator instance = new TimeAndPlaceConjugator();
public static TimeAndPlaceConjugator getInstance() {
return instance;
}
public NounFormula createNoun(UnaugmentedTrilateralRoot root, int suffixNo, String formulaName) {
Object [] parameters = {root, suffixNo+""};
try {
Class formulaClass = (Class) formulaClassNamesMap.get(formulaName);
NounFormula noun = (NounFormula) formulaClass.getConstructors()[0].newInstance(parameters);
return noun;
}
catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public List createNounList(UnaugmentedTrilateralRoot root, String formulaName) {
List result = new LinkedList();
for (int i = 0; i < 18; i++) {
NounFormula noun = createNoun(root, i, formulaName);
result.add(noun);
}
return result;
}
/**
* إعادة الصيغ الممكنة للجذر
* @param root UnaugmentedTrilateralRoot
* @return List
*/
public List getAppliedFormulaList(UnaugmentedTrilateralRoot root) {
XmlTimeAndPlaceNounFormulaTree formulaTree = sarfDic.Midleware.DatabaseManager.getInstance().getTimeAndPlaceNounFormulaTree(root.getC1());
if (formulaTree == null)
return null;
List result = new LinkedList();
Iterator iter = formulaTree.getFormulaList().iterator();
while (iter.hasNext()) {
XmlTimeAndPlaceNounFormula formula = (XmlTimeAndPlaceNounFormula) iter.next();
if (formula.getNoc().equals(root.getConjugation()) && formula.getC2() == root.getC2() && formula.getC3() == root.getC3()) {
if (formula.getForm1() != null && formula.getForm1() != "")
//add the formula pattern insteaed of the symbol (form1)
result.add(formulaSymbolsNamesMap.get(formula.getForm1()));
//may the verb has two forms of instumentals
if (formula.getForm2() != null && formula.getForm2() != "")
//add the formula pattern insteaed of the symbol (form2)
result.add(formulaSymbolsNamesMap.get(formula.getForm2()));
}
}
return result;
}
}
| gpl-3.0 |
jLisp/jlisp | src/bar/f0o/jlisp/lib/ControlPlane/MapRegister.java | 10354 | /******************************************************************************
* Copyright (c) 2015 by *
* Andreas Stockmayer <stockmay@f0o.bar> and *
* Mark Schmidt <schmidtm@f0o.bar> *
* *
* This file (MapRegister.java) is part of jlisp. *
* *
* jlisp is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* jlisp 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 $project.name.If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
package bar.f0o.jlisp.lib.ControlPlane;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* Map Register
* 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |Type=3 |P| Reserved |M| Record Count |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Nonce . . . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . . . Nonce |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Key ID | Authentication Data Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* ~ Authentication Data ~
* +-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | | Record TTL |
* | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* R | Loc Count | EID mask-len | ACT |A| Reserved |
* e +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* c | Rsvd | Map-Version Number | EID-Prefix-AFI |
* o +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* r | EID-Prefix |
* d +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | /| Priority | Weight | M Priority | M Weight |
* | L +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | o | Unused Flags |L|p|R| Loc-AFI |
* | c +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | \| Loc |
* +-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
/**
* Map Register as defined in RFC6830
*
*/
public class MapRegister extends ControlMessage {
/**
* HMAC for the key used in the Map Register message
*
*/
public enum HmacType {
NONE(0), HMAC_SHA_1_96(1), HMAC_SHA_256_128(2);
private final int val;
private HmacType(int x) {
this.val = x;
}
public int getVal() {
return val;
}
/**
* Hmac create from int
* @param x type of HMAC, 0 = NONE, 1 = SHA1_96, 2 = SHA_256_128
* @return
*/
public static HmacType fromInt(int x) {
switch (x) {
case 0:
return NONE;
case 1:
return HMAC_SHA_1_96;
case 2:
return HMAC_SHA_256_128;
}
return null;
}
/**
*
* @return length of the HMAC
*/
public short getLength() {
switch(val){
case 1:
return (short)20;
case 2:
return (short)24;//???
}
return 0;
}
}
/**
* P: Proxy Map Reply bit: if 1 etr sends map register requesting the map server to proxy a map reply.
* M: Want map notify bit: if 1 ETR wants a map notify as response to this
* Record Count: Number of records in this message
* Nonce 64 bit (not currently used)
* Key ID: Type of key (0 none, 1 HMAC-SHA-1-96, 2 HMAC-SHA-256-128)
* AuthenticationDataLength length in octets of the Authentication Data
* AuthenticationData: the key
*/
private boolean pFlag, mFlag;
private byte recordCount;
private long nonce;
private HmacType keyId;
private short authenticationDataLength;
private byte[] authenticationData;
private ArrayList<Record> records = new ArrayList<>();
/**
*
* @param stream Byte stream containing the Map Register message
* @throws IOException
*/
public MapRegister(DataInputStream stream) throws IOException {
this(stream,stream.readByte());
}
/**
*
* @param stream Byte Stream to create the Map Register Message, missing the first byte
* @param version the missing first byte
* @throws IOException
*/
public MapRegister(DataInputStream stream, byte version) throws IOException {
this.type = 3;
byte flag = version;
this.pFlag = (flag & 8) != 0;
short reserved = stream.readShort();
this.mFlag = (reserved & 1) != 0;
this.recordCount = stream.readByte();
this.nonce = stream.readLong();
short key = stream.readShort();
this.keyId = HmacType.fromInt(key);
this.authenticationDataLength = stream.readShort();
this.authenticationData = new byte[authenticationDataLength];
stream.read(authenticationData);
for (int i = 0; i < recordCount; i++)
this.records.add(new Record(stream));
}
/**
*
* @param pFlag Proxy Map Reply flag
* @param mFlag Map Notify Bit
* @param nonce 64bit Nonce
* @param keyId Type of Hmac as defined in MapRegister.HMAC
* @param authenticationData Key encoded with corresponding HMAC
* @param records Records to register
*/
public MapRegister(boolean pFlag, boolean mFlag, long nonce, HmacType keyId,
byte[] authenticationData, ArrayList<Record> records) {
this.pFlag = pFlag;
this.mFlag = mFlag;
this.recordCount = (byte) records.size();
this.nonce = nonce;
this.keyId = keyId;
this.records = records;
if(keyId != HmacType.NONE){
this.authenticationDataLength = keyId.getLength();
this.authenticationData = new byte[authenticationDataLength];
byte[] toAuthenticate = toByteArray();
String hmac;
if(keyId == HmacType.HMAC_SHA_1_96)
hmac="HmacSha1";
else
hmac="HmacSha256";
SecretKeySpec key = new SecretKeySpec(authenticationData, hmac);
try {
Mac mac = Mac.getInstance(hmac);
mac.init(key);
this.authenticationData = mac.doFinal(toAuthenticate);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
}
}
else{
this.authenticationData = authenticationData;
this.authenticationDataLength = (short) authenticationData.length;
}
}
public byte[] toByteArray() {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
DataOutputStream stream = new DataOutputStream(byteStream);
try {
byte typeFlagTmp = 48;
if (this.pFlag)
typeFlagTmp |= 8;
stream.writeByte(typeFlagTmp);
short reserved = (short) (this.mFlag ? 1 : 0);
stream.writeShort(reserved);
stream.writeByte(this.recordCount);
stream.writeLong(this.nonce);
stream.writeShort(this.keyId.getVal());
stream.writeShort(this.authenticationDataLength);
stream.write(this.authenticationData);
for (Record r : this.records)
stream.write(r.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return byteStream.toByteArray();
}
/**
*
* @return Proxy Map Reply bit
*/
public boolean ispFlag() {
return pFlag;
}
/**
*
* @return Wants Map notify flag
*/
public boolean ismFlag() {
return mFlag;
}
/**
*
* @return Number of records in the Map register
*/
public byte getRecordCount() {
return recordCount;
}
/**
*
* @return 64bit Nonce
*/
public long getNonce() {
return nonce;
}
/**
*
* @return Type of the HMAC as defined in MapRegister.HMAC
*/
public HmacType getKeyId() {
return keyId;
}
/**
*
* @return Length of the authenticationData in octets
*/
public short getAuthenticationDataLength() {
return authenticationDataLength;
}
/**
*
* @return Raw authentification data
*/
public byte[] getAuthenticationData() {
return authenticationData;
}
/**
*
* @return Records included in the Map Register
*/
public ArrayList<Record> getRecords() {
return records;
}
}
| gpl-3.0 |
testing-av/testing-video | generators/src/main/java/band/full/test/video/encoder/EncoderParameters.java | 3811 | package band.full.test.video.encoder;
import static band.full.core.Resolution.STD_1080p;
import static band.full.core.Resolution.STD_2160p;
import static band.full.core.Resolution.STD_720p;
import static band.full.video.buffer.Framerate.FPS_23_976;
import static band.full.video.itu.BT2020.BT2020_10bit;
import static band.full.video.itu.BT709.BT709_8bit;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Optional.empty;
import static java.util.Optional.ofNullable;
import band.full.core.Resolution;
import band.full.video.buffer.Framerate;
import band.full.video.itu.BT2100;
import band.full.video.itu.ColorMatrix;
import java.util.List;
import java.util.Optional;
public class EncoderParameters {
public static final String MASTER_DISPLAY_PRIMARIES =
"G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)";
public static final String MASTER_DISPLAY =
MASTER_DISPLAY_PRIMARIES + "L(10000000,5)";
public static final EncoderParameters HD_MAIN = new EncoderParameters(
STD_720p, BT709_8bit, FPS_23_976);
public static final EncoderParameters FULLHD_MAIN8 = new EncoderParameters(
STD_1080p, BT709_8bit, FPS_23_976);
public static final EncoderParameters UHD4K_MAIN8 = new EncoderParameters(
STD_2160p, BT709_8bit, FPS_23_976);
public static final EncoderParameters UHD4K_MAIN10 = new EncoderParameters(
STD_2160p, BT2020_10bit, FPS_23_976);
public static final EncoderParameters HLG10 = new EncoderParameters(
STD_2160p, BT2100.HLG10, FPS_23_976);
public static final EncoderParameters HLG10ITP = new EncoderParameters(
STD_2160p, BT2100.HLG10ITP, FPS_23_976);
public static final EncoderParameters HDR10 = new EncoderParameters(
STD_2160p, BT2100.PQ10, FPS_23_976)
.withMasterDisplay(MASTER_DISPLAY);
public static final EncoderParameters HDR10FR = new EncoderParameters(
STD_2160p, BT2100.PQ10FR, FPS_23_976)
.withMasterDisplay(MASTER_DISPLAY);
public static final EncoderParameters HDR10ITP = new EncoderParameters(
STD_2160p, BT2100.PQ10ITP, FPS_23_976)
.withMasterDisplay(MASTER_DISPLAY);
public final Resolution resolution;
public final ColorMatrix matrix;
public final Framerate framerate;
public final Optional<String> masterDisplay; // HEVC HDR only
public final List<String> encoderOptions;
public EncoderParameters(Resolution resolution, ColorMatrix matrix,
Framerate framerate) {
this(resolution, matrix, framerate, empty(), emptyList());
}
private EncoderParameters(Resolution resolution, ColorMatrix matrix,
Framerate framerate, Optional<String> masterDisplay,
List<String> encoderOptions) {
this.resolution = resolution;
this.matrix = matrix;
this.framerate = framerate;
this.masterDisplay = masterDisplay;
this.encoderOptions = encoderOptions;
}
public EncoderParameters withFramerate(Framerate framerate) {
return new EncoderParameters(resolution, matrix,
framerate, masterDisplay, encoderOptions);
}
public EncoderParameters withMasterDisplay(String masterDisplay) {
return new EncoderParameters(resolution, matrix,
framerate, ofNullable(masterDisplay), encoderOptions);
}
public EncoderParameters withEncoderOptions(String... options) {
return withEncoderOptions(asList(options));
}
public EncoderParameters withEncoderOptions(List<String> options) {
return new EncoderParameters(resolution, matrix,
framerate, masterDisplay, options);
}
}
| gpl-3.0 |
magarena/magarena | src/magic/ui/widget/ActionButtonTitleBar.java | 919 | package magic.ui.widget;
import java.awt.Dimension;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
@SuppressWarnings("serial")
public class ActionButtonTitleBar extends TitleBar {
private final JPanel actionsPanel = new JPanel();
public ActionButtonTitleBar(String caption, List<JButton> actionButtons) {
super(caption);
setPreferredSize(new Dimension(getPreferredSize().width, 26));
setPreferredSize(getPreferredSize());
actionsPanel.setOpaque(false);
actionsPanel.setLayout(new MigLayout("insets 0, gap 12", "", "grow, fill"));
for (JButton btn : actionButtons) {
actionsPanel.add(btn, "w 16!, h 16!");
}
add(actionsPanel, "alignx right, hidemode 3");
}
public void setActionsVisible(boolean b) {
actionsPanel.setVisible(b);
}
}
| gpl-3.0 |
itszootime/ps-framework | src/main/java/org/uncertweb/ps/data/DataReference.java | 701 | package org.uncertweb.ps.data;
import java.net.URL;
public class DataReference {
private URL url;
private String mimeType;
private boolean compressed;
public DataReference(URL url, String mimeType, boolean compressed) {
this.url = url;
this.mimeType = mimeType;
this.compressed = compressed;
}
public DataReference(URL url, boolean compressed) {
this(url, null, compressed);
}
public DataReference(URL url, String mimeType) {
this(url, mimeType, false);
}
public DataReference(URL url) {
this(url, null, false);
}
public URL getURL() {
return url;
}
public String getMimeType() {
return mimeType;
}
public boolean isCompressed() {
return compressed;
}
}
| gpl-3.0 |
LemoProject/Lemo-Data-Management-Server | src/main/java/de/lemo/dms/connectors/lemo_0_8/mapping/LevelCourseLMS.java | 2522 | /**
* File ./src/main/java/de/lemo/dms/connectors/lemo_0_8/mapping/LevelCourseLMS.java
* Lemo-Data-Management-Server for learning analytics.
* Copyright (C) 2015
* Leonard Kappe, Andreas Pursian, Sebastian Schwarzrock, Boris Wenzlaff
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
/**
* File ./src/main/java/de/lemo/dms/connectors/lemo_0_8/mapping/LevelCourseLMS.java
* Date 2015-01-05
* Project Lemo Learning Analytics
*/
package de.lemo.dms.connectors.lemo_0_8.mapping;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Represanting an object of the level of an hierarchy
* @author Sebastian Schwarzrock
*
*/
@Entity
@Table(name = "level_course")
public class LevelCourseLMS{
private long id;
private long course;
private long level;
private Long platform;
/**
* standard getter for the attribute id
*
* @return the identifier for the association between department and resource
*/
@Id
public long getId() {
return this.id;
}
/**
* standard setter for the attribute id
*
* @param id
* the identifier for the association between department and resource
*/
public void setId(final long id) {
this.id = id;
}
/**
* standard getter for the attribute
*
* @return a department in which the resource is used
*/
@Column(name="course_id")
public long getCourse() {
return this.course;
}
public void setCourse(final long course) {
this.course = course;
}
@Column(name="level_id")
public long getLevel() {
return this.level;
}
public void setLevel(final long degree) {
this.level = degree;
}
@Column(name="platform")
public Long getPlatform() {
return this.platform;
}
public void setPlatform(final Long platform) {
this.platform = platform;
}
}
| gpl-3.0 |
melato/next-bus | src/org/melato/geometry/util/Sequencer.java | 5006 | /*-------------------------------------------------------------------------
* Copyright (c) 2012,2013, Alex Athanasopoulos. All Rights Reserved.
* alex@melato.org
*-------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General 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 org.melato.geometry.util;
public class Sequencer {
private int[] array;
private boolean[] visited;
public Sequencer(int[] array) {
super();
this.array = array;
visited = new boolean[array.length];
}
public void findSequence(int start, int end, Sequence sequence) {
int a = array[start];
sequence.start = start;
sequence.last = start;
sequence.length = 1;
int j = start + 1;
for( ; j < end ;j++ ) {
int b = array[j];
if ( b != -1 && ! visited[j]) {
if ( b == a + 1 ) {
a = b;
sequence.length++;
} else if ( b != a ) {
continue;
}
sequence.last = j;
visited[j] = true;
}
}
System.out.println( "findSequence start=" + start + " end=" + end + " sequence=" + sequence);
}
private void filter() {
System.out.println( "approaches sorted: " + toString(array, 0, array.length));
removeOutOfOrder(0, array.length );
//System.out.println( "approaches in-order: " + toString(approaches, 0, approaches.length));
removeDuplicates();
System.out.println( "approaches unique: " + toString(array, 0, array.length));
}
/** remove array so that the remaining array are in non-decreasing order.
* array are removed by setting them to -1.
* */
private void removeOutOfOrder(int start, int end) {
if ( end <= start )
return;
for( int i = start; i < end; i++ ) {
visited[i] = false;
}
Sequence bestSequence = null;
Sequence sequence = new Sequence();
// find the longest sub-sequence of sequential or equal array
for( int i = start; i < end; i++ ) {
int a = array[i];
if ( a != -1 ) {
//System.out.println( "i=" + i + " visited=" + a.visited);
if ( visited[i] )
continue;
findSequence(i, end, sequence);
if ( bestSequence == null || sequence.length > bestSequence.length ) {
bestSequence = sequence;
sequence = new Sequence();
}
}
}
if ( bestSequence == null ) {
// there is nothing
return;
}
System.out.println( "best sequence: " + bestSequence);
bestSequence.clearInside(array);
bestSequence.clearLeft(array, start);
bestSequence.clearRight(array, end);
//System.out.println( "a: " + toString( approaches, 0, approaches.length ));
// do the same on each side
removeOutOfOrder( start, bestSequence.start);
removeOutOfOrder( bestSequence.last + 1, end );
//System.out.println( "b: " + toString( approaches, 0, approaches.length ));
}
private void removeDuplicates() {
// keep the last position that has the lowest element
int item = -1;
int lastIndex = -1;
int i = 0;
for( ; i < array.length; i++ ) {
int a = array[i];
if ( a != -1 ) {
if ( item == -1 ) {
item = a;
lastIndex = i;
} else if ( item == a ) {
array[lastIndex] = -1;
lastIndex = i;
} else {
item = a;
i++;
break;
}
}
}
// for subsequent array, keep the first one among equal elements
for( ; i < array.length; i++ ) {
int a = array[i];
if ( a != -1 ) {
if ( item == a ) {
array[i] = -1;
} else {
item = a;
}
}
}
}
public static String toString( int[] array, int start, int end ) {
StringBuilder buf = new StringBuilder();
buf.append( "[");
int count = 0;
for( int i = start; i < end; i++ ) {
int a = array[i];
if ( a != -1 ) {
if ( count > 0 ) {
buf.append( " " );
}
count++;
buf.append( String.valueOf(a) );
}
}
buf.append("]");
return buf.toString();
}
/** Find a subsequence of increasing items by setting the remaining items to -1. */
public static void filter(int[] items) {
Sequencer sequencer = new Sequencer(items);
sequencer.filter();
}
}
| gpl-3.0 |
Numerios/ComplexWiring | common/num/complexwiring/world/decor/EnumDecor.java | 2725 | package num.complexwiring.world.decor;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraftforge.oredict.OreDictionary;
import num.complexwiring.lib.Reference;
import num.complexwiring.lib.Strings;
import num.complexwiring.world.ModuleWorld;
public enum EnumDecor {
LIMESTONE_ROUGH(Strings.DECOR_LIMESTONE_ROUGH_NAME, Type.ROUGH),
DOLOMITE_ROUGH(Strings.DECOR_DOLOMITE_ROUGH_NAME, Type.ROUGH),
ARENITE_ROUGH(Strings.DECOR_ARENITE_ROUGH_NAME, Type.ROUGH),
LIMESTONE(Strings.DECOR_LIMESTONE_SMOOTH_NAME, Type.SMOOTH),
DOLOMITE(Strings.DECOR_DOLOMITE_SMOOTH_NAME, Type.SMOOTH),
ARENITE(Strings.DECOR_ARENITE_SMOOTH_NAME, Type.SMOOTH),
DARKDOLOMITE(Strings.DECOR_DARKDOLOMITE_NAME, Type.SMOOTH),
LIMESTONE_BRICK(Strings.DECOR_LIMESTONE_BRICK_NAME, Type.BRICK),
DOLOMITE_BRICK(Strings.DECOR_DOLOMITE_BRICK_NAME, Type.BRICK),
ARENITE_BRICK(Strings.DECOR_ARENITE_BRICK_NAME, Type.BRICK),
DARKDOLOMITE_BRICK(Strings.DECOR_DARKDOLOMITE_BRICK_NAME, Type.BRICK),
LIMESTONE_SMALLBRICK(Strings.DECOR_LIMESTONE_SMALLBRICK_NAME, Type.SMALLBRICK),
DOLOMITE_SMALLBRICK(Strings.DECOR_DOLOMITE_SMALLBRICK_NAME, Type.SMALLBRICK),
ARENITE_SMALLBRICK(Strings.DECOR_ARENITE_SMALLBRICK_NAME, Type.SMALLBRICK),
DARKDOLOMITE_SMALLBRICK(Strings.DECOR_DARKDOLOMITE_SMALLBRICK_NAME, Type.SMALLBRICK),
DOLOMITE_DARKDOLOMITE_MIX(Strings.DECOR_DOLOMITE_DARKDOLOMITE_MIX_NAME, Type.MIX);
public static final EnumDecor[] VALID = values();
public final String name;
public final Type type;
public final int meta = this.ordinal();
public IIcon icon;
private EnumDecor(String name, Type type) {
this.name = name;
this.type = type;
}
public String getUnlocalizedName() {
// removes the "decor" from the name and makes it lowercase (ex. decorLimestone -> limestone)
return name.substring(5, 6).toLowerCase() + name.substring(5 + 1);
}
public void registerIcon(IIconRegister ir) {
icon = ir.registerIcon(Reference.TEXTURE_PATH + "world/ore/decor/" + name);
}
public ItemStack getIS(int amount) {
return new ItemStack(ModuleWorld.decor, amount, meta);
}
public void registerOre() {
if (this.type.equals(Type.SMOOTH)) {
OreDictionary.registerOre(getUnlocalizedName(), this.getIS(1)); // limestone
OreDictionary.registerOre("block" + getUnlocalizedName().substring(0, 1).toUpperCase() + getUnlocalizedName().substring(1), this.getIS(1)); // blockLimestone
}
}
public enum Type {
ROUGH, SMOOTH, BRICK, SMALLBRICK, MIX
}
}
| gpl-3.0 |
Java2Us/jpa2us | src/com/java2us/jpa2us/jpa/JPAFactory.java | 2196 | package com.java2us.jpa2us.jpa;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
* This class is responsible for providing the entire infrastructure for
* connecting to the database. The system needs a {@link JPASessionManager} to
* get the EntityManager to connect to the database. This instance is provided
* by this class.
*
* @author Otavio Ferreira
*
* @version 1.0.0
* @since 1.0.0
*/
public class JPAFactory {
private final EntityManagerFactory factory;
private JPASessionManager sessionManager;
/**
* Constructor of class {@link JPAFactory}. In the call of this builder, the
* factory is also built.
*
* @param persistenceUnitName
* PersistenceUnit name that contains the access settings to the
* bank within persistence.xml.
*
* @author Otavio Ferreira
*
* @version 1.0.0
* @since 1.0.0
*/
public JPAFactory(String persistenceUnitName) {
this.factory = createEntityFactory(persistenceUnitName);
}
/**
* It effectively creates the EntityManagers factory.
*
* @param persistenceUnitName
* PersistenceUnit name that contains the access settings to the
* bank within persistence.xml.
* @return The EntityManagerFactory built.
*
* @author Otavio Ferreira
*
* @version 1.0.0
* @since 1.0.0
*/
private EntityManagerFactory createEntityFactory(String persistenceUnitName) {
try {
return Persistence.createEntityManagerFactory(persistenceUnitName);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return null;
}
/**
* Creates the {@link JPASessionManager}, which is responsible for managing
* and requesting the creation of sessions with the Database.
*
* @return A new {@link JPASessionManager}.
*
* @author Otavio Ferreira
*
* @version 1.0.0
* @since 1.0.0
*/
public JPASessionManager getSessionManager() {
this.sessionManager = new JPASessionManager(factory);
return sessionManager;
}
/**
* Close the EntityManagerFactory.
*
* @author Otavio Ferreira
*
* @version 1.0.0
* @since 1.0.0
*/
public void closeEntityFactory() {
factory.close();
}
}
| gpl-3.0 |
srnsw/xena | plugins/pdf/src/au/gov/naa/digipres/xena/plugin/pdf/PdfView.java | 2869 | /**
* This file is part of Xena.
*
* Xena is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
*
* Xena 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 Xena; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* @author Andrew Keeling
* @author Chris Bitmead
* @author Justin Waddell
*/
package au.gov.naa.digipres.xena.plugin.pdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import org.jpedal.examples.simpleviewer.SimpleViewer;
import org.xml.sax.ContentHandler;
import au.gov.naa.digipres.xena.kernel.XenaException;
import au.gov.naa.digipres.xena.kernel.view.XenaView;
import au.gov.naa.digipres.xena.util.BinaryDeNormaliser;
/**
* View for PDF files.
*
*/
public class PdfView extends XenaView {
public static final String PDFVIEW_VIEW_NAME = "PDF Viewer";
private static final long serialVersionUID = 1L;
private SimpleViewer simpleViewer;
private File pdfFile;
public PdfView() {
}
@Override
public boolean canShowTag(String tag) throws XenaException {
return tag.equals(viewManager.getPluginManager().getTypeManager().lookupXenaFileType(XenaPdfFileType.class).getTag());
}
@Override
public String getViewName() {
return PDFVIEW_VIEW_NAME;
}
@Override
public ContentHandler getContentHandler() throws XenaException {
FileOutputStream xenaTempOS = null;
try {
pdfFile = File.createTempFile("pdffile", ".pdf");
pdfFile.deleteOnExit();
xenaTempOS = new FileOutputStream(pdfFile);
} catch (IOException e) {
throw new XenaException("Problem creating temporary xena output file", e);
}
BinaryDeNormaliser base64Handler = new BinaryDeNormaliser() {
/*
* (non-Javadoc)
* @see au.gov.naa.digipres.xena.kernel.normalise.AbstractDeNormaliser#endDocument()
*/
@Override
public void endDocument() {
if (pdfFile.exists()) {
simpleViewer = new SimpleViewer();
simpleViewer.setRootContainer(PdfView.this);
simpleViewer.setupViewer();
simpleViewer.openDefaultFile(pdfFile.getAbsolutePath());
}
}
};
StreamResult result = new StreamResult(xenaTempOS);
base64Handler.setResult(result);
return base64Handler;
}
/*
* (non-Javadoc)
* @see au.gov.naa.digipres.xena.kernel.view.XenaView#doClose()
*/
@Override
public void doClose() {
super.doClose();
}
}
| gpl-3.0 |
Moergil/ArtificialWars | src/sk/hackcraft/artificialwars/computersim/toolchain/AssemblerEPH32.java | 2925 | package sk.hackcraft.artificialwars.computersim.toolchain;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import sk.epholl.artificialwars.entities.instructionsets.EPH32InstructionSet;
import sk.epholl.artificialwars.entities.instructionsets.EPH32InstructionSet.EPH32MemoryAddressing;
import sk.hackcraft.artificialwars.computersim.Endianness;
public class AssemblerEPH32 extends AbstractAssembler
{
private final int programSegmentStart, dataSegmentStart;
private final int programMemorySize, dataMemorySize;
public AssemblerEPH32(int programSegmentStart, int dataSegmentStart, int programMemorySize, int dataMemorySize)
{
super(EPH32InstructionSet.getInstance(), Endianness.BIG, ".segment", "(.+):");
this.programSegmentStart = programSegmentStart;
this.dataSegmentStart = dataSegmentStart;
this.programMemorySize = programMemorySize;
this.dataMemorySize = dataMemorySize;
// TODO vyhodit ak to nebude potrebne
addSegmentIdentifier(Segment.PROGRAM, "program");
addSegmentIdentifier(Segment.DATA, "data");
addMemoryAddressingFormat(EPH32MemoryAddressing.IMPLIED, "");
addMemoryAddressingFormat(EPH32MemoryAddressing.IMMEDIATE, "%");
LabelType labelType = new LabelType()
{
@Override
public int getOperandsBitsSize()
{
return EPH32InstructionSet.WORD_BYTES_SIZE;
}
@Override
public int getOperandValue(int labelAddress, int programCounterAddress)
{
return labelAddress;
}
};
enableLabels("jmp", labelType);
enableLabels("jmpz", labelType);
enableLabels("jmpc", labelType);
enableLabels("jmpm", labelType);
enableLabels("jmpl", labelType);
addValueParser((value) -> {
return Integer.decode(value);
});
addVariableType("int", Integer.BYTES);
}
@Override
protected AssemblerState started()
{
AssemblerState state = super.started();
state.setSegmentStartAddress(Segment.PROGRAM, programSegmentStart);
state.setSegmentStartAddress(Segment.DATA, dataSegmentStart);
return state;
}
@Override
protected void linkTogether(AssemblerState state, OutputStream output) throws CodeProcessor.CodeProcessException, IOException
{
byte program[] = state.getSegmentBytes(Segment.PROGRAM);
byte data[] = state.getSegmentBytes(Segment.DATA);
// TODO
int programWordLength = program.length / EPH32InstructionSet.WORD_BYTES_SIZE;
if (program.length / Integer.BYTES / 2 > programMemorySize)
{
throw new CodeProcessException(-1, "Program size is bigger than available program memory.");
}
if (data.length / Integer.BYTES > programMemorySize)
{
throw new CodeProcessException(-1, "Data size is bigger than available data memory.");
}
DataOutputStream dataOutput = new DataOutputStream(output);
dataOutput.writeInt(program.length);
dataOutput.writeInt(data.length);
dataOutput.write(program);
dataOutput.write(data);
}
}
| gpl-3.0 |
cbrouillard/epsilon-mobile | epsilon/src/main/java/com/headbangers/epsilon/v3/model/Wish.java | 2798 | package com.headbangers.epsilon.v3.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.util.Date;
@JsonIgnoreProperties({"class"})
public class Wish implements Serializable {
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
@JsonProperty("description")
private String description;
@JsonProperty("price")
private Double price;
@JsonProperty("webShopUrl")
private String webShopUrl;
@JsonProperty("thumbnailUrl")
private String thumbnailUrl;
@JsonProperty("bought")
private Boolean bought;
@JsonProperty("boughtDate")
private Date boughtDate;
@JsonProperty("previsionBuy")
private Date previsionBuy;
@JsonProperty("account")
private String account;
@JsonProperty("category")
private String category;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getWebShopUrl() {
return webShopUrl;
}
public void setWebShopUrl(String webShopUrl) {
this.webShopUrl = webShopUrl;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public Boolean getBought() {
return bought;
}
public void setBought(Boolean bought) {
this.bought = bought;
}
public Date getBoughtDate() {
return boughtDate;
}
public void setBoughtDate(Date boughtDate) {
this.boughtDate = boughtDate;
}
public Date getPrevisionBuy() {
return previsionBuy;
}
public void setPrevisionBuy(Date previsionBuy) {
this.previsionBuy = previsionBuy;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPrevisionBuyFormated() {
if (previsionBuy != null) {
return Account.sdf.format(this.previsionBuy);
}
return "n/a";
}
}
| gpl-3.0 |
miku-nyan/Overchan-Android | src/nya/miku/wishmaster/chans/dvach/DvachSearchReader.java | 4523 | /*
* Overchan Android (Meta Imageboard Client)
* Copyright (C) 2014-2016 miku-nyan <https://github.com/miku-nyan>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General 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 nya.miku.wishmaster.chans.dvach;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nya.miku.wishmaster.api.ChanModule;
import nya.miku.wishmaster.api.models.PostModel;
import nya.miku.wishmaster.api.models.UrlPageModel;
import nya.miku.wishmaster.api.util.RegexUtils;
public class DvachSearchReader implements Closeable {
private final ChanModule _chan;
private final Reader _in;
private StringBuilder readBuffer = new StringBuilder();
private List<PostModel> result;
private static final char[] FILTER_OPEN = "<li class=\"found\">".toCharArray();
private static final char[] FILTER_CLOSE = "</li>".toCharArray();
private static final Pattern HREF_PATTERN = Pattern.compile("<a href=\"(.*?)\"", Pattern.DOTALL);
private static final Pattern SUBJ_PATTERN = Pattern.compile("<a(?:[^>]*)>(.*?)</a>", Pattern.DOTALL);
public DvachSearchReader(Reader reader, ChanModule chan) {
_in = reader;
_chan = chan;
}
public DvachSearchReader(InputStream in, ChanModule chan) {
this(new BufferedReader(new InputStreamReader(in)), chan);
}
public PostModel[] readSerachPage() throws IOException {
result = new ArrayList<>();
int pos = 0;
int len = FILTER_OPEN.length;
int curChar;
while ((curChar = _in.read()) != -1) {
if (curChar == FILTER_OPEN[pos]) {
++pos;
if (pos == len) {
handlePost(readUntilSequence(FILTER_CLOSE));
pos = 0;
}
} else {
if (pos != 0) pos = curChar == FILTER_OPEN[0] ? 1 : 0;
}
}
return result.toArray(new PostModel[result.size()]);
}
private void handlePost(String post) {
Matcher mHref = HREF_PATTERN.matcher(post);
if (mHref.find()) {
try {
PostModel postModel = new PostModel();
UrlPageModel url = _chan.parseUrl(_chan.fixRelativeUrl(mHref.group(1)));
postModel.number = url.postNumber == null ? url.threadNumber : url.postNumber;
postModel.parentThread = url.threadNumber;
postModel.name = "";
Matcher mSubj = SUBJ_PATTERN.matcher(post);
if (mSubj.find()) postModel.subject = RegexUtils.trimToSpace(mSubj.group(1)); else postModel.subject = "";
if (post.contains("<p>")) postModel.comment = post.substring(post.indexOf("<p>")); else postModel.comment = "";
result.add(postModel);
} catch (Exception e) {}
}
}
private String readUntilSequence(char[] sequence) throws IOException {
int len = sequence.length;
if (len == 0) return "";
readBuffer.setLength(0);
int pos = 0;
int curChar;
while ((curChar = _in.read()) != -1) {
readBuffer.append((char) curChar);
if (curChar == sequence[pos]) {
++pos;
if (pos == len) break;
} else {
if (pos != 0) pos = curChar == sequence[0] ? 1 : 0;
}
}
int buflen = readBuffer.length();
if (buflen >= len) {
readBuffer.setLength(buflen - len);
return readBuffer.toString();
} else {
return "";
}
}
@Override
public void close() throws IOException {
_in.close();
}
}
| gpl-3.0 |
postalservice14/Airports | src/main/java/com/nadmm/airports/wx/WxMapFragmentBase.java | 8030 | /*
* FlightIntel for Pilots
*
* Copyright 2012 Nadeem Hasan <nhasan@nadmm.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General 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.nadmm.airports.wx;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.nadmm.airports.FragmentBase;
import com.nadmm.airports.ImageViewActivity;
import com.nadmm.airports.R;
public abstract class WxMapFragmentBase extends FragmentBase {
private String mAction;
private BroadcastReceiver mReceiver;
private IntentFilter mFilter;
private String[] mWxTypeCodes;
private String[] mWxTypeNames;
private String[] mWxMapCodes;
private String[] mWxMapNames;
private String mLabel;
private String mTitle;
private String mHelpText;
private View mPendingRow;
private Spinner mSpinner;
public WxMapFragmentBase( String action, String[] mapCodes, String[] mapNames ) {
mAction = action;
mWxMapCodes = mapCodes;
mWxMapNames = mapNames;
mWxTypeCodes = null;
mWxTypeNames = null;
}
public WxMapFragmentBase( String action, String[] mapCodes, String[] mapNames,
String[] typeCodes, String[] typeNames ) {
mAction = action;
mWxMapCodes = mapCodes;
mWxMapNames = mapNames;
mWxTypeCodes = typeCodes;
mWxTypeNames = typeNames;
}
@Override
public void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setHasOptionsMenu( false );
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive( Context context, Intent intent ) {
String action = intent.getAction();
if ( action.equals( mAction ) ) {
String type = intent.getStringExtra( NoaaService.TYPE );
if ( type.equals( NoaaService.TYPE_IMAGE ) ) {
showWxMap( intent );
}
}
}
};
mFilter = new IntentFilter();
mFilter.addAction( mAction );
}
@Override
public void onResume() {
mPendingRow = null;
LocalBroadcastManager bm = LocalBroadcastManager.getInstance( getActivity() );
bm.registerReceiver( mReceiver, mFilter );
super.onResume();
}
@Override
public void onPause() {
LocalBroadcastManager bm = LocalBroadcastManager.getInstance( getActivity() );
bm.unregisterReceiver( mReceiver );
super.onPause();
}
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState ) {
View v = inflate( R.layout.wx_map_detail_view );
if ( mLabel != null && mLabel.length() > 0 ) {
TextView tv = (TextView) v.findViewById( R.id.wx_map_label );
tv.setText( mLabel );
tv.setVisibility( View.VISIBLE );
}
if ( mHelpText != null && mHelpText.length() > 0 ) {
TextView tv = (TextView) v.findViewById( R.id.help_text );
tv.setText( mHelpText );
tv.setVisibility( View.VISIBLE );
}
OnClickListener listener = new OnClickListener() {
@Override
public void onClick( View v ) {
if ( mPendingRow == null ) {
mPendingRow = v;
String code = getMapCode( v );
requestWxMap( code );
}
}
};
LinearLayout layout = (LinearLayout) v.findViewById( R.id.wx_map_layout );
for ( int i = 0; i < mWxMapCodes.length; ++i ) {
View row = addProgressRow( layout, mWxMapNames[ i ] );
row.setTag( mWxMapCodes[ i ] );
row.setOnClickListener( listener );
row.setBackgroundResource( R.drawable.row_selector_middle );
}
if ( mWxTypeCodes != null ) {
TextView tv = (TextView) v.findViewById( R.id.wx_map_type_label );
tv.setVisibility( View.VISIBLE );
layout = (LinearLayout) v.findViewById( R.id.wx_map_type_layout );
layout.setVisibility( View.VISIBLE );
mSpinner = (Spinner) v.findViewById( R.id.map_type );
ArrayAdapter<String> adapter = new ArrayAdapter<String>( getActivity(),
android.R.layout.simple_spinner_item, mWxTypeNames );
adapter.setDropDownViewResource( R.layout.support_simple_spinner_dropdown_item );
mSpinner.setAdapter( adapter );
}
return v;
}
private void requestWxMap( String code ) {
setProgressBarVisible( true );
Intent service = getServiceIntent();
service.setAction( mAction );
service.putExtra( NoaaService.TYPE, NoaaService.TYPE_IMAGE );
service.putExtra( NoaaService.IMAGE_CODE, code );
if ( mSpinner != null ) {
int pos = mSpinner.getSelectedItemPosition();
service.putExtra( NoaaService.IMAGE_TYPE, mWxTypeCodes[ pos ] );
}
setServiceParams( service );
getActivity().startService( service );
}
protected void setServiceParams( Intent intent ) {
}
private void showWxMap( Intent intent ) {
String path = intent.getStringExtra( NoaaService.RESULT );
if ( path != null ) {
Intent view = new Intent( getActivity(), WxImageViewActivity.class );
view.putExtra( ImageViewActivity.IMAGE_PATH, path );
if ( mTitle != null ) {
view.putExtra( ImageViewActivity.IMAGE_TITLE, mTitle );
} else {
view.putExtra( ImageViewActivity.IMAGE_TITLE, getActivity().getTitle() );
}
String code = intent.getStringExtra( NoaaService.IMAGE_CODE );
String name = getDisplayText( code );
if ( name != null ) {
view.putExtra( ImageViewActivity.IMAGE_SUBTITLE, name );
}
startActivity( view );
} else {
mPendingRow = null;
}
setProgressBarVisible( false );
}
protected String getMapCode( View v ) {
return (String) v.getTag();
}
protected String getDisplayText( String code ) {
for ( int i = 0; i < mWxMapCodes.length; ++i ) {
if ( code.equals( mWxMapCodes[ i ] ) ) {
return mWxMapNames[ i ];
}
}
return "";
}
protected void setLabel( String label ) {
mLabel = label;
}
protected void setTitle( String title ) {
mTitle = title;
}
protected void setHelpText( String text ) {
mHelpText = text;
}
private void setProgressBarVisible( boolean visible ) {
if ( mPendingRow != null ) {
View view = mPendingRow.findViewById( R.id.progress );
view.setVisibility( visible? View.VISIBLE : View.INVISIBLE );
}
}
protected abstract Intent getServiceIntent();
}
| gpl-3.0 |
htwg/UCE_deprecated | icermi/src/de/htwg_konstanz/rmi/registry/RemoteRegistry_Stub.java | 6645 | /**
* Copyright (C) 2012 HTWG Konstanz, Oliver Haase
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Stub class generated by rmic, do not edit.
// Contents subject to change without notice.
package de.htwg_konstanz.rmi.registry;
public final class RemoteRegistry_Stub
extends java.rmi.server.RemoteStub
implements java.rmi.registry.Registry, java.rmi.Remote
{
private static final java.rmi.server.Operation[] operations = {
new java.rmi.server.Operation("void bind(java.lang.String, java.rmi.Remote)"),
new java.rmi.server.Operation("java.lang.String list()[]"),
new java.rmi.server.Operation("java.rmi.Remote lookup(java.lang.String)"),
new java.rmi.server.Operation("void rebind(java.lang.String, java.rmi.Remote)"),
new java.rmi.server.Operation("void unbind(java.lang.String)")
};
private static final long interfaceHash = 4905912898345647071L;
// constructors
public RemoteRegistry_Stub() {
super();
}
public RemoteRegistry_Stub(java.rmi.server.RemoteRef ref) {
super(ref);
}
// methods from remote interfaces
// implementation of bind(String, Remote)
public void bind(java.lang.String $param_String_1, java.rmi.Remote $param_Remote_2)
throws java.rmi.AccessException, java.rmi.AlreadyBoundException, java.rmi.RemoteException
{
try {
java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash);
try {
java.io.ObjectOutput out = call.getOutputStream();
out.writeObject($param_String_1);
out.writeObject($param_Remote_2);
} catch (java.io.IOException e) {
throw new java.rmi.MarshalException("error marshalling arguments", e);
}
ref.invoke(call);
ref.done(call);
} catch (java.lang.RuntimeException e) {
throw e;
} catch (java.rmi.RemoteException e) {
throw e;
} catch (java.rmi.AlreadyBoundException e) {
throw e;
} catch (java.lang.Exception e) {
throw new java.rmi.UnexpectedException("undeclared checked exception", e);
}
}
// implementation of list()
public java.lang.String[] list()
throws java.rmi.AccessException, java.rmi.RemoteException
{
try {
java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash);
ref.invoke(call);
java.lang.String[] $result;
try {
java.io.ObjectInput in = call.getInputStream();
$result = (java.lang.String[]) in.readObject();
} catch (java.io.IOException e) {
throw new java.rmi.UnmarshalException("error unmarshalling return", e);
} catch (java.lang.ClassNotFoundException e) {
throw new java.rmi.UnmarshalException("error unmarshalling return", e);
} finally {
ref.done(call);
}
return $result;
} catch (java.lang.RuntimeException e) {
throw e;
} catch (java.rmi.RemoteException e) {
throw e;
} catch (java.lang.Exception e) {
throw new java.rmi.UnexpectedException("undeclared checked exception", e);
}
}
// implementation of lookup(String)
public java.rmi.Remote lookup(java.lang.String $param_String_1)
throws java.rmi.AccessException, java.rmi.NotBoundException, java.rmi.RemoteException
{
try {
java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash);
try {
java.io.ObjectOutput out = call.getOutputStream();
out.writeObject($param_String_1);
} catch (java.io.IOException e) {
throw new java.rmi.MarshalException("error marshalling arguments", e);
}
ref.invoke(call);
java.rmi.Remote $result;
try {
java.io.ObjectInput in = call.getInputStream();
$result = (java.rmi.Remote) in.readObject();
} catch (java.io.IOException e) {
throw new java.rmi.UnmarshalException("error unmarshalling return", e);
} catch (java.lang.ClassNotFoundException e) {
throw new java.rmi.UnmarshalException("error unmarshalling return", e);
} finally {
ref.done(call);
}
return $result;
} catch (java.lang.RuntimeException e) {
throw e;
} catch (java.rmi.RemoteException e) {
throw e;
} catch (java.rmi.NotBoundException e) {
throw e;
} catch (java.lang.Exception e) {
throw new java.rmi.UnexpectedException("undeclared checked exception", e);
}
}
// implementation of rebind(String, Remote)
public void rebind(java.lang.String $param_String_1, java.rmi.Remote $param_Remote_2)
throws java.rmi.AccessException, java.rmi.RemoteException
{
try {
java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 3, interfaceHash);
try {
java.io.ObjectOutput out = call.getOutputStream();
out.writeObject($param_String_1);
out.writeObject($param_Remote_2);
} catch (java.io.IOException e) {
throw new java.rmi.MarshalException("error marshalling arguments", e);
}
ref.invoke(call);
ref.done(call);
} catch (java.lang.RuntimeException e) {
throw e;
} catch (java.rmi.RemoteException e) {
throw e;
} catch (java.lang.Exception e) {
throw new java.rmi.UnexpectedException("undeclared checked exception", e);
}
}
// implementation of unbind(String)
public void unbind(java.lang.String $param_String_1)
throws java.rmi.AccessException, java.rmi.NotBoundException, java.rmi.RemoteException
{
try {
java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 4, interfaceHash);
try {
java.io.ObjectOutput out = call.getOutputStream();
out.writeObject($param_String_1);
} catch (java.io.IOException e) {
throw new java.rmi.MarshalException("error marshalling arguments", e);
}
ref.invoke(call);
ref.done(call);
} catch (java.lang.RuntimeException e) {
throw e;
} catch (java.rmi.RemoteException e) {
throw e;
} catch (java.rmi.NotBoundException e) {
throw e;
} catch (java.lang.Exception e) {
throw new java.rmi.UnexpectedException("undeclared checked exception", e);
}
}
}
| gpl-3.0 |
xuyazhou18/siciyuan | src/org/qii/weiciyuan/bean/android/TimeLinePosition.java | 645 | package org.qii.weiciyuan.bean.android;
import java.io.Serializable;
import java.util.TreeSet;
/**
* User: qii
* Date: 13-3-23
*/
public class TimeLinePosition implements Serializable {
public TimeLinePosition(int position, int top) {
this.position = position;
this.top = top;
}
public int position = 0;
public int top = 0;
public TreeSet<Long> newMsgIds = null;
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder().append("position:").append(position)
.append("; top=").append(top);
return stringBuilder.toString();
}
}
| gpl-3.0 |
trickyBytes/com.akoolla.financebeta | finance-beta-api/src/main/java/com/akoolla/financebeta/reporting/ITransactionQuery.java | 398 | package com.akoolla.financebeta.reporting;
import java.util.Set;
import org.joda.time.DateTime;
public interface ITransactionQuery {
DateTime getFromDate();
DateTime getToDate();
Set<String> getTransactionTags();
double transactionAmount();
//Range of transactionAmmounts();
double minimumTransactionAmount();
double maximumTransactionAmount();
boolean showSceduledTransactionsOnly();
}
| gpl-3.0 |
docteurdux/code | dux/src/test/java/dux/org/springframework/web/servlet/config/TilesConfigurerBeanDefinitionParserTest.java | 116 | package dux.org.springframework.web.servlet.config;
public class TilesConfigurerBeanDefinitionParserTest {
}
| gpl-3.0 |
idega/platform2 | src/com/idega/util/logging/LoggingHelper.java | 4070 | /*
* Created on Nov 22, 2003
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package com.idega.util.logging;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
/**
* A class which has helper methods for the standard Java 1.4 logging API
* Copyright (c) 2003 idega software
* @author <a href="tryggvi@idega.is">Tryggvi Larusson</a>
*/
public class LoggingHelper {
private static String NEWLINE="\n";
private static String TAB="\t";
private static String COLON = ":";
private static String COLON_WITH_SPACE = " : ";
private static String DOT = ".";
/**
* Logs the exception to the anonymous logger with loglevel Warning:
* @param e the Exception to log
*/
public static void logException(Exception e){
Logger logger = Logger.getAnonymousLogger();
logException(e,null,logger,Level.WARNING);
}
/**
* Logs the exception to the default logger of Object catcher with loglevel Warning:
* @param e the Exception to log
*/
public static void logException(Exception e,Object catcher){
Logger logger = Logger.getLogger(catcher.getClass().getName());
logException(e,catcher,logger,Level.WARNING);
}
/**
* Logs the exception to the specified logger with loglevel Warning:
* @param e the Exception to log
*/
public static void logException(Exception e,Object catcher,Logger logger){
logException(e,catcher,logger,Level.WARNING);
}
public static void logException(Exception e,Object catcher,Logger logger,Level level){
//e.printStackTrace();
StackTraceElement[] ste = e.getStackTrace();
StringBuffer buf = new StringBuffer(e.getClass().getName());
buf.append(COLON_WITH_SPACE);
buf.append(e.getMessage());
buf.append(NEWLINE);
if(ste.length>0){
buf.append(TAB);
buf.append(ste[0].getClassName());
buf.append(DOT);
buf.append(ste[0].getMethodName());
buf.append(COLON);
buf.append(ste[0].getLineNumber());
buf.append(NEWLINE);
}
String str = buf.toString();
logger.log(level,str);
}
public static void getLoggerInfo() {
// Get the Log Manager
LogManager manager = LogManager.getLogManager();
// Get all defined loggers
java.util.Enumeration names = manager.getLoggerNames();
System.out.println("***Begin Logger Information");
// For each logger: show name, level, handlers etc.
while (names.hasMoreElements()) {
String loggername = (String)names.nextElement();
java.util.logging.Logger logger = manager.getLogger(loggername);
System.out.println("-----------------------");
System.out.println("Logger name: >" + logger.getName() + "<");
System.out.println("Logger level: " + logger.getLevel());
// See if a filter is defined
if (logger.getFilter() != null) {
System.out.println("Using a filter");
}
else {
System.out.println("No filter used");
}
// For each handler: show formatter, level, etc.
java.util.logging.Handler[] h = logger.getHandlers();
if (h.length == 0) {
System.out.println("No handlers defined");
}
for (int i = 0; i < h.length; i++) {
if (i == 0) {
System.out.println("Handlers:");
}
java.util.logging.Formatter f = h[i].getFormatter();
System.out.println(h[i].getClass().getName());
System.out.println(" using formatter: " + f.getClass().getName());
System.out.println(" using level: " + h[i].getLevel());
if (h[i].getFilter() != null) {
System.out.println(" using a filter");
}
else {
System.out.println(" no filter");
}
}
// See if a parent exists
java.util.logging.Logger parent = logger.getParent();
if (parent != null) {
System.out.println("Parent: >" + parent.getName() + "<");
}
else {
System.out.println("No parent");
}
}
System.out.println("*** End Logger Information");
}
}
| gpl-3.0 |
da-nrw/DNSCore | ContentBroker/src/test/java/de/uzk/hki/da/cb/ArchiveReplicationActionTests.java | 3550 | /*
DA-NRW Software Suite | ContentBroker
Copyright (C) 2013 Historisch-Kulturwissenschaftliche Informationsverarbeitung
Universität zu Köln
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.uzk.hki.da.cb;
import static org.mockito.Mockito.mock;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import de.uzk.hki.da.grid.GridFacade;
import de.uzk.hki.da.model.Node;
import de.uzk.hki.da.model.Object;
import de.uzk.hki.da.model.Package;
import de.uzk.hki.da.model.PreservationSystem;
import de.uzk.hki.da.model.User;
import de.uzk.hki.da.utils.Path;
/**
* @author Daniel M. de Oliveira
*/
public class ArchiveReplicationActionTests {
private static String workAreaRootPath;
private static Node node = new Node();
private static PreservationSystem ps = new PreservationSystem();
Object object = new Object();
@BeforeClass
public static void prepareNode() {
workAreaRootPath = "src/test/resources/cb/ArchiveReplicationTests/fork/";
node.setWorkAreaRootPath(Path.make(workAreaRootPath));
node.setName("ci");
node.setIdentifier("LN");
}
@Before
public void setUp(){
setUpObject();
}
@Test
public void testHappyPath() throws FileNotFoundException, IOException{
node.setReplDestinations("a");
node.setGridCacheAreaRootPath(Path.make(workAreaRootPath));
User c = new User();
c.setShort_name("TEST");
c.setEmailAddress("noreply");
object.setContractor(c);
node.setAdmin(c);
node.setIdentifier("ci");
ArchiveReplicationAction action = setUpAction(node);
action.implementation();
}
@Test
public void testReplDestsNotSet() throws FileNotFoundException, IOException{
node.setReplDestinations(null);
node.setGridCacheAreaRootPath(Path.make(workAreaRootPath));
User c = new User();
c.setShort_name("TEST");
c.setForbidden_nodes("b");
c.setEmailAddress("noreply");
node.setAdmin(c);
object.setContractor(c);
ArchiveReplicationAction action = setUpAction(node);
action.implementation();
}
@Test
public void testForbiddenNodesNotSet() throws FileNotFoundException, IOException{
node.setReplDestinations("a");
node.setGridCacheAreaRootPath(Path.make(workAreaRootPath));
User c = new User();
c.setEmailAddress("noreply");
c.setShort_name("TEST");
c.setForbidden_nodes(null);
object.setContractor(c);
ArchiveReplicationAction action = setUpAction(node);
action.implementation();
}
private void setUpObject(){
object.setIdentifier("identifier");
Package pkg = new Package();
pkg.setDelta(1);
object.getPackages().add(pkg);
}
private ArchiveReplicationAction setUpAction(Node node){
ArchiveReplicationAction action = new ArchiveReplicationAction();
ps.setMinRepls(0);
action.setPSystem(ps);
GridFacade grid = mock (GridFacade.class);
action.setGridRoot(grid);
action.setObject(object);
action.setLocalNode(node);
return action;
}
}
| gpl-3.0 |
pantelis60/L2Scripts_Underground | gameserver/src/main/java/l2s/gameserver/skills/skillclasses/ClanGate.java | 1353 | package l2s.gameserver.skills.skillclasses;
import java.util.List;
import l2s.gameserver.model.Creature;
import l2s.gameserver.model.Player;
import l2s.gameserver.model.Skill;
import l2s.gameserver.model.pledge.Clan;
import l2s.gameserver.network.l2.components.IStaticPacket;
import l2s.gameserver.network.l2.components.SystemMsg;
import l2s.gameserver.templates.StatsSet;
public class ClanGate extends Skill
{
public ClanGate(StatsSet set)
{
super(set);
}
@Override
public boolean checkCondition(Creature activeChar, Creature target, boolean forceUse, boolean dontMove, boolean first)
{
if(!activeChar.isPlayer())
return false;
Player player = (Player) activeChar;
if(!player.isClanLeader())
{
player.sendPacket(SystemMsg.ONLY_THE_CLAN_LEADER_IS_ENABLED);
return false;
}
IStaticPacket msg = Call.canSummonHere(player);
if(msg != null)
{
activeChar.sendPacket(msg);
return false;
}
return super.checkCondition(activeChar, target, forceUse, dontMove, first);
}
@Override
public void onEndCast(Creature activeChar, List<Creature> targets)
{
super.onEndCast(activeChar, targets);
if(!activeChar.isPlayer())
return;
Player player = (Player) activeChar;
Clan clan = player.getClan();
clan.broadcastToOtherOnlineMembers(SystemMsg.COURT_MAGICIAN_THE_PORTAL_HAS_BEEN_CREATED, player);
}
}
| gpl-3.0 |
LeshiyGS/shikimori | app/src/main/java/org/shikimori/client/gsm/MyGcmListenerService.java | 4246 | /**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.shikimori.client.gsm;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.gms.gcm.GcmListenerService;
import org.json.JSONException;
import org.json.JSONObject;
import org.shikimori.library.tool.push.PushHelperReceiver;
import java.util.Iterator;
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
/**
* Called when message is received.
*
* @param from SenderID of the sender.
* @param data Data bundle containing message data as key/value pairs.
* For Set of keys use data.keySet().
*/
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from + " / " + data.toString());
if (!TextUtils.isEmpty(message)) {
if(message.startsWith("{")){
try {
JSONObject json = new JSONObject(message);
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
String value = json.optString(key);
data.putString(key, value);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
String action = data.getString("action");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
Log.d(TAG, "action: " + action);
PushHelperReceiver.onReceive(this, from, data);
}
//{"action":}
// if (from.startsWith("/topics/")) {
// // message received from some topic.
// } else {
// // normal downstream message.
// }
// [START_EXCLUDE]
/**
* Production applications would usually process the message here.
* Eg: - Syncing with server.
* - Store message in local database.
* - Update UI.
*/
/**
* In some cases it may be useful to show a notification indicating to the user
* that a message was received.
*/
//sendNotification(message);
// [END_EXCLUDE]
}
// [END receive_message]
/**
* Create and show a simple notification containing the received GCM message.
*
* @param message GCM message received.
*/
// private void sendNotification(String message) {
// Intent intent = new Intent(this, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
// PendingIntent.FLAG_ONE_SHOT);
//
// Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
// .setSmallIcon(R.mipmap.ic_launcher)
// .setContentTitle("GCM Message")
// .setContentText(message)
// .setAutoCancel(true)
// .setSound(defaultSoundUri)
// .setContentIntent(pendingIntent);
//
// NotificationManager notificationManager =
// (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//
// notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
// }
}
| gpl-3.0 |
guhb/core | src/com/dotmarketing/business/PermissionedWebAssetUtil.java | 23096 | /**
*
*/
package com.dotmarketing.business;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.dotmarketing.common.db.DotConnect;
import com.dotmarketing.db.DbConnectionFactory;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.exception.DotRuntimeException;
import com.dotmarketing.exception.DotSecurityException;
import com.dotmarketing.factories.InodeFactory;
import com.dotmarketing.portlets.containers.model.Container;
import com.dotmarketing.portlets.contentlet.model.Contentlet;
import com.dotmarketing.portlets.structure.model.Field;
import com.dotmarketing.portlets.structure.model.Structure;
import com.dotmarketing.portlets.templates.model.Template;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.UtilMethods;
import com.liferay.portal.model.User;
/**
* @author Jason Tesser
* The purpose of this class is to pull things like Templates, Pages, and Files with their respecting permissions
* This is needed because if you have a limited user in a system with many object and permissions it can be slow to pull all
* WebAssets and then loop over each one filtering out based on permissions. This class provides methods which get what is needed
* in 1-2 DB pulls per call. This can be faster in the large systems.
*/
public class PermissionedWebAssetUtil {
/**
* THIS METHOD WILL HIT DB AT LEAST ONCE. It loads the templatesIds to load then trys to load from Cache or go back
* to DB using Hibernate to load the ones not in cache with a single Hibernate query (if there are more then 500 it will actually go back to
* db for each 500 as it does an IN (..)).
* NOTE: Returns working templates
* @param searchString - Can be null or empty. Can be used as a filter. Will Search Template TITLE and Host (if searchHost is True)
* @param dbColSort - Name of the DB Column to sort by. If left null or empty will sort by template name by default
* @param offset
* @param limit
* @param permission - The required Permission needed to pull template
* @param user
* @param respectFrontEndPermissions
* @return
* @throws DotSecurityException
* @throws DotDataException
*/
public static List<Template> findTemplatesForLimitedUser(String searchString, String hostName, boolean searchHost,String dbColSort ,int offset, int limit,int permission, User user, boolean respectFrontEndPermissions) throws DotDataException, DotSecurityException{
// PermissionAPI perAPI = APILocator.getPermissionAPI();
// UserAPI uAPI = APILocator.getUserAPI();
// if(uAPI.isCMSAdmin(user)){
// if(UtilMethods.isSet(searchString)){
// return InodeFactory.getInodesOfClassByConditionAndOrderBy(Template.class, "lower(title) LIKE '%" + templateName.toLowerCase() + "%'", dbColSort,limit, offset);
// }else{
// return InodeFactory.getInodesOfClass(Template.class, dbColSort,limit, offset);
// }
// }else{
offset = offset<0?0:offset;
String hostQuery = null;
if(searchHost){
Structure st = CacheLocator.getContentTypeCache().getStructureByVelocityVarName("Host");
Field hostNameField = st.getFieldVar("hostName");
List<Contentlet> list = null;
try {
String query = "+structureInode:" + st.getInode() + " +working:true";
if(UtilMethods.isSet(hostName)){
query += " +" + hostNameField.getFieldContentlet() + ":" + hostName;
}
list = APILocator.getContentletAPI().search(query, 0, 0, null, user, respectFrontEndPermissions);
} catch (Exception e) {
Logger.error(PermissionedWebAssetUtil.class,e.getMessage(),e);
}
if(list!=null){
if(list.size()>0){
hostQuery = "identifier.host_inode IN (";
}
boolean first = true;
for (Contentlet contentlet : list) {
if(!first){
hostQuery+=",";
}
hostQuery+="'" + contentlet.getIdentifier() + "'";
first = false;
}
if(hostQuery != null){
hostQuery+=")";
}
}
}
ArrayList<ColumnItem> columnsToOrderBy = new ArrayList<ColumnItem>();
ColumnItem templateTitle = new ColumnItem("title", "template", null, true, OrderDir.ASC);
//ColumnItem hostName = new ColumnItem("title", "contentlet", "host_name", true, OrderDir.ASC);
//columnsToOrderBy.add(hostName);
columnsToOrderBy.add(templateTitle);
List<String> tIds = queryForAssetIds("template, identifier, inode, template_version_info ",
new String[] {Template.class.getCanonicalName(), Template.TEMPLATE_LAYOUTS_CANONICAL_NAME},
"template.inode",
"identifier.id",
"template.identifier = identifier.id and inode.inode = template.inode and " +
"identifier.id=template_version_info.identifier and template_version_info.working_inode=template.inode and " +
"template_version_info.deleted="+DbConnectionFactory.getDBFalse()
+ (
UtilMethods.isSet(searchString) ?
" and (lower(template.title) LIKE '%" + searchString.toLowerCase() + "%'"
+(UtilMethods.isSet(hostQuery)? " AND (" + hostQuery + ")":"") + ")":
(UtilMethods.isSet(hostQuery)? " AND (" + hostQuery + ")":"")
) , columnsToOrderBy, offset, limit, permission, respectFrontEndPermissions, user);
// CacheLocator.getTemplateCache().
if(tIds != null && tIds.size()>0){
StringBuilder bob = new StringBuilder();
for (String s : tIds) {
bob.append("'").append(s).append("',");
}
return InodeFactory.getInodesOfClassByConditionAndOrderBy(Template.class, "inode in (" + bob.toString().subSequence(0, bob.toString().length()-1) + ")", dbColSort);
}else{
return new ArrayList<Template>();
}
// }
}
/**
* THIS METHOD WILL HIT DB AT LEAST ONCE. It loads the templatesIds to load then trys to load from Cache or go back
* to DB using Hibernate to load the ones not in cache with a single Hibernate query (if there are more then 500 it will actually go back to
* db for each 500 as it does an IN (..)).
* NOTE: Returns working templates
* @param searchString - Can be null or empty. Can be used as a filter. Will Search Template TITLE and Host (if searchHost is True)
* @param dbColSort - Name of the DB Column to sort by. If left null or empty will sort by template name by default
* @param offset
* @param limit
* @param permission - The required Permission needed to pull template
* @param user
* @param respectFrontEndPermissions
* @return
* @throws DotSecurityException
* @throws DotDataException
*/
public static List<Structure> findStructuresForLimitedUser(String searchString, Integer structureType ,String dbColSort ,int offset, int limit,int permission, User user, boolean respectFrontEndPermissions) throws DotDataException, DotSecurityException{
offset = offset<0?0:offset;
ArrayList<ColumnItem> columnsToOrderBy = new ArrayList<ColumnItem>();
ColumnItem structureTitle = new ColumnItem(dbColSort, "structure", null, true, OrderDir.ASC);
columnsToOrderBy.add(structureTitle);
List<String> tIds = queryForAssetIds("structure, inode",
new String[] {Structure.class.getCanonicalName()},
"structure.inode",
"inode.inode",
"inode.inode = structure.inode "
+ (
UtilMethods.isSet(searchString) ?
" and (lower(structure.name) LIKE '%" + searchString.toLowerCase() + "%'"
+(structureType!=null? " AND structuretype = "+ structureType.intValue():"") + ")":
(structureType!=null? " AND structuretype = "+ structureType.intValue():"")
) , columnsToOrderBy, offset, limit, permission, respectFrontEndPermissions, user);
if(tIds != null && tIds.size()>0){
StringBuilder bob = new StringBuilder();
for (String s : tIds) {
bob.append("'").append(s).append("',");
}
return InodeFactory.getInodesOfClassByConditionAndOrderBy(Structure.class, "inode in (" + bob.toString().subSequence(0, bob.toString().length()-1) + ")", dbColSort);
}else{
return new ArrayList<Structure>();
}
// }
}
/**
* Returns the list of {@link Container} objects that the current user has
* access to. This will retrieve a final list of results with a single
* query, instead of programmatically traversing the total list of
* containers and then filtering it to get the permissioned objects from it.
*
* @param searchString
* - Can be null or empty. It is used as a filter to search for
* container's "title".
* @param hostName
* - Can be null or empty. It is used as a filter to search for
* containers in a specific site. The "searchHost" must be set to
* {@code true}.
* @param searchHost
* - If {@code true}, and if "hostName" is not empty, the method
* will only get the containers from the specified site.
* @param dbColSort
* - The column name of the DB table used to order the results.
* @param offset
* - The offset of records to include in the result (used for
* pagination purposes).
* @param limit
* - The limit of records to retrieve (used for pagination
* purposes).
* @param permission
* - The required Permission needed to pull the containers
* information.
* @param user
* - The {@link User} that performs the operation.
* @param respectFrontEndPermissions
* @return The {@code List} of {@link Container} objects that the specified
* user has access to.
* @throws DotDataException
* - If an error occurred when retrieving information from the
* database.
* @throws DotSecurityException
* - If the current user does not have permission to perform the
* required operation.
*/
public static List<Container> findContainersForLimitedUser(
String searchString, String hostName, boolean searchHost,
String dbColSort, int offset, int limit, int permission, User user,
boolean respectFrontEndPermissions) throws DotDataException,
DotSecurityException {
offset = offset < 0 ? 0 : offset;
String hostQuery = null;
if (searchHost) {
Structure st = CacheLocator.getContentTypeCache().getStructureByVelocityVarName("Host");
Field hostNameField = st.getFieldVar("hostName");
List<Contentlet> hostList = null;
try {
String query = "+structureInode:" + st.getInode()
+ " +working:true";
if (UtilMethods.isSet(hostName)) {
query += " +" + hostNameField.getFieldContentlet() + ":"
+ hostName;
}
hostList = APILocator.getContentletAPI().search(query, 0, 0,
null, user, respectFrontEndPermissions);
} catch (Exception e) {
Logger.error(PermissionedWebAssetUtil.class, e.getMessage(), e);
}
if (hostList != null) {
if (hostList.size() > 0) {
hostQuery = "identifier.host_inode IN (";
}
boolean first = true;
for (Contentlet contentlet : hostList) {
if (!first) {
hostQuery += ",";
}
hostQuery += "'" + contentlet.getIdentifier() + "'";
first = false;
}
if (hostQuery != null) {
hostQuery += ")";
}
}
}
ArrayList<ColumnItem> columnsToOrderBy = new ArrayList<ColumnItem>();
ColumnItem templateTitle = new ColumnItem("title", "containers", null,
true, OrderDir.ASC);
columnsToOrderBy.add(templateTitle);
List<String> containerIds = queryForAssetIds(
"containers, identifier, inode, container_version_info ",
new String[] { Container.class.getCanonicalName() },
"containers.inode",
"identifier.id",
"containers.identifier = identifier.id and inode.inode = containers.inode and "
+ "identifier.id=container_version_info.identifier and container_version_info.working_inode=containers.inode and "
+ "container_version_info.deleted="
+ DbConnectionFactory.getDBFalse()
+ (UtilMethods.isSet(searchString) ? " and (lower(containers.title) LIKE '%"
+ searchString.toLowerCase()
+ "%'"
+ (UtilMethods.isSet(hostQuery) ? " AND ("
+ hostQuery + ")" : "") + ")"
: (UtilMethods.isSet(hostQuery) ? " AND ("
+ hostQuery + ")" : "")),
columnsToOrderBy, offset, limit, permission,
respectFrontEndPermissions, user);
if (containerIds != null && containerIds.size() > 0) {
StringBuilder identifiers = new StringBuilder();
for (String id : containerIds) {
identifiers.append("'").append(id).append("',");
}
return InodeFactory.getInodesOfClassByConditionAndOrderBy(
Container.class,
"inode in ("
+ identifiers.toString().subSequence(0,
identifiers.toString().length() - 1) + ")",
dbColSort);
} else {
return new ArrayList<Container>();
}
}
/**
* Will execute the query to get assetIds with required permission
* @param tablesToJoin - This would be the tables to include in where ie... "template,inode,indentifier"
* @param assetWhereClause - ie... "inode.identifier = identifier.inode and inode.inode = template.inode and template.title LIKE '%mytitle%'"
* @param colToSelect ie.. template.inode
* @param colToJoinAssetIdTo The column and table to joing the asset_id or inode_id from permission tables to ie.. identifier.inode
* @param orderByClause - ie... template.name ASC make sure to capitalize the ASC or DESC
* @param offset
* @param limit
* @param requiredTypePermission
* @param respectFrontendRoles
* @param user
* @return
* @throws DotDataException
* @throws DotSecurityException
*/
private static List<String> queryForAssetIds(String tablesToJoin,String[] permissionType ,String colToSelect, String colToJoinAssetIdTo, String assetWhereClause, List<ColumnItem> columnsToOrderBy, int offset, int limit, int requiredTypePermission, boolean respectFrontendRoles, User user) throws DotDataException,DotSecurityException {
Role anonRole;
Role frontEndUserRole;
Role adminRole;
boolean userIsAdmin = false;
try {
adminRole = APILocator.getRoleAPI().loadCMSAdminRole();
anonRole = APILocator.getRoleAPI().loadCMSAnonymousRole();
frontEndUserRole = APILocator.getRoleAPI().loadLoggedinSiteRole();
} catch (DotDataException e1) {
Logger.error(PermissionedWebAssetUtil.class, e1.getMessage(), e1);
throw new DotRuntimeException(e1.getMessage(), e1);
}
List<String> roleIds = new ArrayList<String>();
if(respectFrontendRoles){
// add anonRole and frontEndUser roles
roleIds.add(anonRole.getId());
if(user != null ){
roleIds.add("'"+frontEndUserRole.getId()+"'");
}
}
//If user is null and roleIds are empty return empty list
if(roleIds.isEmpty() && user==null){
return new ArrayList<String>();
}
List<Role> roles;
try {
roles = APILocator.getRoleAPI().loadRolesForUser(user.getUserId());
} catch (DotDataException e1) {
Logger.error(PermissionedWebAssetUtil.class, e1.getMessage(), e1);
throw new DotRuntimeException(e1.getMessage(), e1);
}
for (Role role : roles) {
try{
String roleId = role.getId();
roleIds.add("'"+roleId+"'");
if(roleId.equals(adminRole.getId())){
userIsAdmin = true;
}
}catch (Exception e) {
Logger.error(PermissionedWebAssetUtil.class, "Roleid should be a long : ",e);
}
}
StringBuilder permissionRefSQL = new StringBuilder();
String extraSQLForOffset = "";
String orderByClause = "";
String orderByClauseWithAlias = "";
String orderBySelect = "";
int count = 0;
for(ColumnItem item : columnsToOrderBy){
if(DbConnectionFactory.isPostgres()
|| DbConnectionFactory.isMySql()){
item.setIsString(false);
}
orderByClause += item.getOrderClause(true) + (count<columnsToOrderBy.size()-1?", ":"");
orderByClauseWithAlias += item.getAliasOrderClause() + (count<columnsToOrderBy.size()-1?", ":"");
orderBySelect += item.getSelectClause(true) + (count<columnsToOrderBy.size()-1?", ":"");
count++;
}
if(DbConnectionFactory.isOracle()){
extraSQLForOffset = "ROW_NUMBER() OVER(ORDER BY "+orderByClause+") LINENUM, ";
}else if(DbConnectionFactory.isMsSql()){
extraSQLForOffset = "ROW_NUMBER() OVER (ORDER BY "+orderByClause+") AS LINENUM, ";
}
permissionRefSQL.append("SELECT * FROM (");
permissionRefSQL.append("SELECT ").append(extraSQLForOffset).append(colToSelect).append(" as asset_id,").append(orderBySelect).append(" ");
permissionRefSQL.append("FROM ");
if(!userIsAdmin){
permissionRefSQL.append("permission_reference, permission, ");
}
permissionRefSQL.append(tablesToJoin).append(" ");
permissionRefSQL.append("WHERE ");
if(!userIsAdmin){
permissionRefSQL.append("permission_reference.reference_id = permission.inode_id ");
permissionRefSQL.append("AND permission.permission_type = permission_reference.permission_type ");
permissionRefSQL.append("AND permission_reference.asset_id = ").append(colToJoinAssetIdTo).append(" AND ");
}
permissionRefSQL.append(assetWhereClause).append(" ");
if(!userIsAdmin){
if(permissionType.length==1) {
permissionRefSQL.append("AND permission.permission_type = '").append(permissionType[0]).append("' ");
}
else {
permissionRefSQL.append(" AND (");
boolean first=true;
for(String type : permissionType) {
if(first) {
first=false;
}
else {
permissionRefSQL.append(" OR ");
}
permissionRefSQL.append(" permission.permission_type = '").append(type).append("' ");
}
permissionRefSQL.append(") ");
}
permissionRefSQL.append("AND permission.roleid in( ");
}
StringBuilder individualPermissionSQL = new StringBuilder();
if(!userIsAdmin){
individualPermissionSQL.append("select ").append(extraSQLForOffset).append(colToSelect).append(" as asset_id, ").append(orderBySelect).append(" ");
individualPermissionSQL.append("FROM ");
individualPermissionSQL.append("permission,");
individualPermissionSQL.append(tablesToJoin).append(" WHERE ");
individualPermissionSQL.append("permission_type = 'individual' ");
individualPermissionSQL.append(" and permission.inode_id=").append(colToJoinAssetIdTo).append(" AND ");
individualPermissionSQL.append(assetWhereClause).append(" ");
individualPermissionSQL.append(" and roleid in( ");
int roleIdCount = 0;
for(String roleId : roleIds){
permissionRefSQL.append(roleId);
individualPermissionSQL.append(roleId);
if(roleIdCount<roleIds.size()-1){
permissionRefSQL.append(", ");
individualPermissionSQL.append(", ");
}
roleIdCount++;
}
if(DbConnectionFactory.isOracle()){
permissionRefSQL.append(") and bitand(permission.permission, ").append(requiredTypePermission).append(") > 0 ");
individualPermissionSQL.append(") and bitand(permission, ").append(requiredTypePermission).append(") > 0 ");
}else{
permissionRefSQL.append(") and (permission.permission & ").append(requiredTypePermission).append(") > 0 ");
individualPermissionSQL.append(") and (permission & ").append(requiredTypePermission).append(") > 0 ");
}
}
permissionRefSQL.append(" group by ").append(colToSelect).append(" ");
if(UtilMethods.isSet(individualPermissionSQL.toString())){
individualPermissionSQL.append(" group by ").append(colToSelect).append(" ");
}
for(ColumnItem item : columnsToOrderBy){
if(DbConnectionFactory.isPostgres()
|| DbConnectionFactory.isMySql()){
item.setIsString(false);
}
orderBySelect = item.getSelectClause(true);
permissionRefSQL.append(", ").append(orderBySelect).append(" ");
if(UtilMethods.isSet(individualPermissionSQL.toString())){
individualPermissionSQL.append(", ").append(orderBySelect).append(" ");
}
}
List<String> idsToReturn = new ArrayList<String>();
String sql = "";
DotConnect dc = new DotConnect();
String limitOffsetSQL = null;
boolean limitResults = limit > 0;
if(DbConnectionFactory.isOracle()){
limitOffsetSQL = limitResults ? "WHERE LINENUM BETWEEN " + (offset<=0?offset:offset+1) + " AND " + (offset + limit) : "";
sql = permissionRefSQL.toString() + (UtilMethods.isSet(individualPermissionSQL.toString())?" UNION " +individualPermissionSQL.toString():"") +" ) " + limitOffsetSQL + " ORDER BY " + orderByClauseWithAlias ;
}else if(DbConnectionFactory.isMsSql()){
limitOffsetSQL = limitResults ? "AS MyDerivedTable WHERE MyDerivedTable.LINENUM BETWEEN " + (offset<=0?offset:offset+1) + " AND " + (offset + limit) : "";
sql = permissionRefSQL.toString() + (UtilMethods.isSet(individualPermissionSQL.toString())?" UNION " +individualPermissionSQL.toString():"") +" ) " + limitOffsetSQL + " ORDER BY " + orderByClauseWithAlias;
}else{
limitOffsetSQL = limitResults ? " LIMIT " + limit + " OFFSET " + offset : "";
sql = permissionRefSQL.toString() + (UtilMethods.isSet(individualPermissionSQL.toString())?" UNION " +individualPermissionSQL.toString():"") +" ) " + " as t1 ORDER BY "+ orderByClauseWithAlias + " " + limitOffsetSQL;
}
dc.setSQL(sql);
List<Map<String, Object>> results = (ArrayList<Map<String, Object>>)dc.loadResults();
for (int i = 0; i < results.size(); i++) {
Map<String, Object> hash = (Map<String, Object>) results.get(i);
if(!hash.isEmpty()){
idsToReturn.add((String) hash.get("asset_id"));
}
}
return idsToReturn;
}
private enum OrderDir{
ASC("ASC"),
DESC("DESC");
private String value;
OrderDir (String value) {
this.value = value;
}
public String toString () {
return value;
}
};
private static class ColumnItem{
private String columnName;
private String tableName;
private String alias;
private OrderDir orderDir;
private boolean isStringColumn;
public void setIsString(boolean isStringColumn){
this.isStringColumn = isStringColumn;
}
public ColumnItem(String columnName, String tableName, String alias, boolean isStringColumn, OrderDir orderDir){
this.columnName = columnName;
this.tableName = tableName;
this.alias = alias;
this.isStringColumn=isStringColumn;
this.orderDir = orderDir!=null?orderDir:OrderDir.ASC;
}
public String getOrderClause(boolean includeTableName){
String ret = "";
if(this.isStringColumn){
ret = "lower("+ (includeTableName?this.tableName+".":"") + this.columnName +") " + orderDir.toString();
}else{
ret = (includeTableName?this.tableName+".":"") + this.columnName +" " + orderDir.toString();
}
return ret;
}
public String getAliasOrderClause(){
String ret = "";
if(this.isStringColumn){
ret = "lower("+ (UtilMethods.isSet(this.alias)?this.alias:this.columnName) +") " + orderDir.toString();
}else{
ret = (UtilMethods.isSet(this.alias)?this.alias:this.columnName) +" " + orderDir.toString();
}
return ret;
}
public String getSelectClause(boolean includeTableName){
String ret = (includeTableName?this.tableName+".":"")+this.columnName + (UtilMethods.isSet(this.alias)?" as " + this.alias:"");
return ret;
}
}
}
| gpl-3.0 |
BetaCONCEPT/astroboa | astroboa-engine/src/main/java/org/betaconceptframework/astroboa/engine/jcr/dao/SerializationDao.java | 7722 | /*
* Copyright (C) 2005-2012 BetaCONCEPT Limited
*
* This file is part of Astroboa.
*
* Astroboa is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Astroboa 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 Astroboa. If not, see <http://www.gnu.org/licenses/>.
*/
package org.betaconceptframework.astroboa.engine.jcr.dao;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Session;
import org.betaconceptframework.astroboa.api.model.exception.CmsException;
import org.betaconceptframework.astroboa.api.model.io.FetchLevel;
import org.betaconceptframework.astroboa.api.model.io.SerializationConfiguration;
import org.betaconceptframework.astroboa.api.model.io.SerializationReport;
import org.betaconceptframework.astroboa.api.model.query.criteria.CmsCriteria;
import org.betaconceptframework.astroboa.api.model.query.criteria.ContentObjectCriteria;
import org.betaconceptframework.astroboa.context.AstroboaClientContext;
import org.betaconceptframework.astroboa.context.AstroboaClientContextHolder;
import org.betaconceptframework.astroboa.engine.jcr.PrototypeFactory;
import org.betaconceptframework.astroboa.engine.jcr.io.SerializationBean;
import org.betaconceptframework.astroboa.engine.jcr.io.SerializationBean.CmsEntityType;
import org.betaconceptframework.astroboa.engine.jcr.query.CmsQueryHandler;
import org.betaconceptframework.astroboa.engine.jcr.query.CmsQueryResult;
import org.betaconceptframework.astroboa.engine.jcr.query.CmsScoreNodeIteratorUsingJcrRangeIterator;
import org.betaconceptframework.astroboa.model.impl.io.SerializationReportImpl;
import org.betaconceptframework.astroboa.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
*
* @author Gregory Chomatas (gchomatas@betaconcept.com)
* @author Savvas Triantafyllou (striantafyllou@betaconcept.com)
*
*/
public class SerializationDao {
@Autowired
private CmsQueryHandler cmsQueryHandler;
@Autowired
private SerializationBean serializationBean;
//Use this method only if you want to use SerializationBean in a newly
//created Thread
@Autowired
public PrototypeFactory prototypeFactory;
//TODO : The use of the ExecutorService must be reviewed.
private ExecutorService executorService = Executors.newCachedThreadPool();
public long serializeSearchResults(Session session, CmsCriteria cmsCriteria, OutputStream os, FetchLevel fetchLevel,
SerializationConfiguration serializationConfiguration) throws Exception{
CmsQueryResult cmsQueryResult = null;
NodeIterator nodeIterator = null;
if (cmsCriteria instanceof ContentObjectCriteria){
cmsQueryResult = cmsQueryHandler.getNodesFromXPathQuery(session, cmsCriteria, false);
nodeIterator =
new CmsScoreNodeIteratorUsingJcrRangeIterator(cmsQueryResult.getRowIterator());
}
else{
cmsQueryResult = cmsQueryHandler.getNodesFromXPathQuery(session, cmsCriteria, true);
nodeIterator = cmsQueryResult.getNodeIterator();
}
serializationBean.serializeNodesAsResourceCollection(nodeIterator, os, cmsCriteria, fetchLevel, serializationConfiguration, cmsQueryResult.getTotalRowCount());
return nodeIterator.getSize();
}
public void serializeCmsRepositoryEntity(Node nodeRepresentingEntity, OutputStream os, CmsEntityType entityTypeToSerialize,
List<String> propertyPathsWhoseValuesAreIncludedInTheSerialization, FetchLevel fetchLevel, boolean nodeRepresentsRootElement,
SerializationConfiguration serializationConfiguration) throws Exception{
serializationBean.serializeNode(nodeRepresentingEntity, os, entityTypeToSerialize, serializationConfiguration, propertyPathsWhoseValuesAreIncludedInTheSerialization, fetchLevel, nodeRepresentsRootElement);
}
public Future<SerializationReport> serializeAllInstancesOfEntity(final CmsEntityType entityTypeToSerialize, final SerializationConfiguration serializationConfiguration) {
Calendar now = Calendar.getInstance();
final String serializationPath = DateUtils.format(now, "yyyy/MM/dd");
final AstroboaClientContext clientContext = AstroboaClientContextHolder.getActiveClientContext();
final String filename = createFilename(now, entityTypeToSerialize, clientContext);
final SerializationBean serializationBean = prototypeFactory.newSerializationBean();
final SerializationReport serializationReport = new SerializationReportImpl(filename+".zip", serializationPath);
Future<SerializationReport> future = executorService.submit(new Callable<SerializationReport>() {
@Override
public SerializationReport call() throws Exception {
serializationBean.serialize(entityTypeToSerialize, serializationPath, filename, clientContext, serializationReport, serializationConfiguration);
return serializationReport;
}
});
return future;
}
public Future<SerializationReport> serializeObjectsUsingCriteria(final ContentObjectCriteria contentObjectCriteria, final SerializationConfiguration serializationConfiguration) {
Calendar now = Calendar.getInstance();
final String serializationPath = DateUtils.format(now, "yyyy/MM/dd");
final AstroboaClientContext clientContext = AstroboaClientContextHolder.getActiveClientContext();
final String filename = createFilename(now, CmsEntityType.OBJECT, clientContext);
final SerializationBean serializationBean = prototypeFactory.newSerializationBean();
final SerializationReport serializationReport = new SerializationReportImpl(filename+".zip", serializationPath);
Future<SerializationReport> future = executorService.submit(new Callable<SerializationReport>() {
@Override
public SerializationReport call() throws Exception {
serializationBean.serializeObjectsUsingCriteria(contentObjectCriteria, serializationPath, filename, clientContext, serializationReport, serializationConfiguration);
return serializationReport;
}
});
return future;
}
public String createFilename(Calendar date, CmsEntityType entityTypeToSerialize, AstroboaClientContext clientContext){
if (clientContext == null)
{
throw new CmsException("Astroboa client context is not provided. Serialization failed");
}
/* Build serialization file path
*
* yyyy/MM/dd/<repositoryId>-{repositoryUsers|taxonomies|objects|organizationSpace-}yyyyMMddHHmmssSSS
*
*/
String repositoryId = clientContext.getRepositoryContext().getCmsRepository().getId();
StringBuilder sb = new StringBuilder();
sb.append(repositoryId);
if (entityTypeToSerialize != null)
{
switch (entityTypeToSerialize) {
case OBJECT:
sb.append("-objects");
break;
case ORGANIZATION_SPACE:
sb.append("-organizationSpace");
break;
case REPOSITORY_USER:
sb.append("-repositoryUsers");
break;
case TAXONOMY:
sb.append("-taxonomies");
break;
default:
break;
}
}
sb.append("-");
sb.append(DateUtils.format(date, "yyyyMMddHHmmssSSS"));
return sb.toString();
}
}
| gpl-3.0 |
ferrerverck/englishwords | src/com/words/model/mysqlmodel/MysqlModel.java | 32111 | package com.words.model.mysqlmodel;
import com.words.controller.futurewords.FutureWord;
import com.words.controller.utils.DateTimeUtils;
import com.words.controller.words.Word;
import com.words.controller.words.WordFactory;
import com.words.controller.words.wordkinds.WordComplexity;
import com.words.controller.words.wordkinds.WordType;
import com.words.main.EnglishWords;
import com.words.model.Model;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Objects;
import java.util.Properties;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class MysqlModel implements Model {
private static final int REPEAT_DAYS_TO_EXPIRE = 5;
private static final String GET_WORD_QUERY_WITHOUT_CONDITION =
"SELECT word, translation, synonyms, bundle_date, " +
"complexity_id, times_picked, last_picked_timestamp " +
"FROM words " +
"JOIN bundles ON words.bundle_id = bundles.bundle_id";
private static String getWordQuery(String condition) {
return GET_WORD_QUERY_WITHOUT_CONDITION + " " + condition;
}
private final LocalDate today;
private final Map<WordComplexity, Integer> complexityMap =
new EnumMap<>(WordComplexity.class);
private final String dbName;
private final Connection con;
private final Map<String, Word> wordMap = new TreeMap<>((s1, s2) ->
s1.replaceAll("^to ", "").compareTo(s2.replaceAll("^to ", "")));
public static void main(String[] args) throws Exception {
MysqlModel model = new MysqlModel("EnglishWordsTestDb");
System.out.println(model.getLastBundleName());
System.out.println(model.getPenultimateBundleName());
System.out.println(model.getRepeatWords());
System.out.println(model.getExpiredRepeatWords());
model.addRepeatWord("to abolish");
model.deleteRepeatWord("to abolish");
System.out.println("1 day iters = " + model.getIterationsForDays(1));
System.out.println("2 day iters = " + model.getIterationsForDays(2));
System.out.println("7 day iters = " + model.getIterationsForDays(7));
System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 1)));
System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 2)));
System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 3)));
System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 4)));
System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 5)));
System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 6)));
System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 7)));
System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 8)));
}
public Connection getConnection() { return con; }
private Word getWordFromResultSet(ResultSet rs) throws SQLException {
String englishWord = rs.getString("word");
if (wordMap.containsKey(englishWord)) return wordMap.get(englishWord);
Word word = WordFactory.newWord();
word.setWord(englishWord);
word.setTranslation(rs.getString("translation"));
word.setSynonyms(rs.getString("synonyms"));
word.setBundle(rs.getDate("bundle_date").toLocalDate());
word.setComplexity(getComplexityFromId(rs.getInt("complexity_id")));
word.setTimesPicked(rs.getInt("times_picked"));
word.setLastPickedTimestamp(rs.getLong("last_picked_timestamp"));
wordMap.put(englishWord, word);
return word;
}
private void defaultExceptionHandler(Exception ex) {
ex.printStackTrace();
}
private void rollback() {
try {
con.rollback();
} catch (SQLException ignore) { }
}
private int getIdFromComplexity(WordComplexity complexity) {
return complexityMap.getOrDefault(complexity, 1);
}
private WordComplexity getComplexityFromId(Integer id) {
for (Map.Entry<WordComplexity, Integer> entry : complexityMap.entrySet()) {
if (entry.getValue().equals(id)) return entry.getKey();
}
return WordComplexity.NORMAL;
}
/**
* Gets bundle id. Returns -1 if bundles doesn't exist.
* @param bundle bundle to search
* @return bundle id or -1
* @throws SQLExceptin if something happens with database
*/
private int getBundleId(LocalDate bundle) throws SQLException {
String searchQuery =
"SELECT bundle_id FROM bundles WHERE bundle_date = ?";
try (PreparedStatement ps = con.prepareCall(searchQuery)) {
ps.setString(1, bundle.toString());
ResultSet rs = ps.executeQuery();
if (rs.next()) return rs.getInt("bundle_id");
return -1;
}
}
/**
* Registers new bundle and return generated id.
* @param bundle bundle to insert
* @return newly generated bundle id
* @throws SQLException if something wrong with database or bundle exists
*/
private int registerNewBundle(LocalDate bundle) throws SQLException {
String insertQuery = "INSERT INTO bundles (bundle_date) VALUES (?)";
try (PreparedStatement ps = con.prepareStatement(
insertQuery, Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, bundle.toString());
ps.executeUpdate();
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
if (generatedKeys.next()) return generatedKeys.getInt(1);
else throw new SQLException("Failed to add new bundle");
}
}
}
public MysqlModel(String dbName) throws Exception {
this.dbName = dbName;
Properties props = new Properties();
props.load(getClass().getResource("/resources/mysql/db.properties").openStream());
// Files.newBufferedReader(PROJECT_DIRECTORY.resolve("db.properties"),
// Charset.defaultCharset()));
String user = props.getProperty("db.user");
String password = props.getProperty("db.password");
boolean recreate =
Boolean.parseBoolean(props.getProperty("db.recreate"));
boolean importDb =
Boolean.parseBoolean(props.getProperty("db.import"));
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost/?allowMultiQueries=true&useUnicode=true",
user, password);
con.setAutoCommit(false);
// find if database already exists
boolean dbExists = false;
try (ResultSet resultSet = con.getMetaData().getCatalogs()) {
while (resultSet.next()) {
if (resultSet.getString(1).equals(dbName)) {
dbExists = true;
break;
}
}
}
if (!dbExists || recreate) createDatabase(dbName, importDb);
useDatabase(dbName);
// hash complexity ids
try (Statement statement = con.createStatement()) {
ResultSet rs = statement.executeQuery(
"SELECT complexity_id, complexity_name FROM complexities");
while (rs.next()) {
complexityMap.put(WordComplexity.valueOf(
rs.getString("complexity_name")),
rs.getInt("complexity_id"));
}
}
getAllWords();
today = DateTimeUtils.getCurrentLocalDate();
getRepeatWords();
}
// creates database from scratch using predefined script
// deletes all table and data if exists
// throws Exception if something goes wrong
private void createDatabase(String dbName, boolean importDb)
throws Exception {
// drop database if exists
try (Statement statement = con.createStatement()) {
statement.executeUpdate("DROP DATABASE IF EXISTS " + dbName);
int result = statement.executeUpdate("CREATE DATABASE " + dbName);
if (result != 1) throw new SQLException("Error creating database");
useDatabase(dbName);
Path sqlScriptPath = Paths.get(getClass()
.getResource("/resources/mysql/create_tables.sql").toURI());
String sqlScript = new String(Files.readAllBytes(sqlScriptPath),
StandardCharsets.UTF_8);
statement.executeUpdate(sqlScript);
}
// init complexity table
try (PreparedStatement insertComplexities = con.prepareStatement(
"INSERT INTO complexities (complexity_name, weight, privileged) " +
"VALUES (?, ?, ?)")) {
for (WordComplexity wc : WordComplexity.sortedValues()) {
insertComplexities.setString(1, wc.name());
insertComplexities.setInt(2, wc.getWeight());
insertComplexities.setBoolean(3, wc.isPrivileged());
insertComplexities.executeUpdate();
}
}
con.commit();
if (importDb) importFileModel();
System.out.println("Created db");
}
@Override
public void backup() {
try {
new MysqlModelToFileModel(EnglishWords.PROJECT_DIRECTORY, con)
.backup();
} catch (Exception ex) {
System.err.println("Error while buckuping file model");
}
}
private void importFileModel() throws IOException, SQLException {
FileModelToMysqlModel importer = new FileModelToMysqlModel(con);
importer.insert();
}
private void fillDatabaseWithDefaults() throws Exception {
LocalDate firstBundle = DateTimeUtils.getCurrentLocalDate();
int normalComplexityId;
int firstBundleId;
try (Statement statement = con.createStatement()) {
ResultSet rs = statement.executeQuery(
"SELECT complexity_id FROM complexities WHERE complexity_name='" +
WordComplexity.NORMAL.name() + "'");
rs.next();
normalComplexityId = rs.getInt("complexity_id");
firstBundleId = statement.executeUpdate(
"INSERT INTO bundles (bundle_name) VALUES ('" + firstBundle + "')",
Statement.RETURN_GENERATED_KEYS);
}
try (PreparedStatement insertWords = con.prepareStatement(
"INSERT INTO words (word, translation, synonyms, bundle_id, complexity_id) " +
"VALUES (?, ?, ?, ?, ?)")) {
for (String line : Files.readAllLines(Paths.get(getClass()
.getResource("/resources/irregular_verbs").toURI()),
StandardCharsets.UTF_8)) {
String[] tokens = line.split("\\t+");
insertWords.setString(1, tokens[0]);
insertWords.setString(2, tokens[1]);
insertWords.setString(3, tokens[2]);
insertWords.setInt(4, firstBundleId);
insertWords.setInt(5, normalComplexityId);
insertWords.executeUpdate();
}
}
con.commit();
}
private void useDatabase(String dbName) throws SQLException {
try (Statement useStatement = con.createStatement()) {
useStatement.executeUpdate("USE " + dbName);
}
}
@Override
public Word getWordInstance(String wordToSearch) {
Objects.requireNonNull(wordToSearch);
Word word = wordMap.get(wordToSearch);
if (word != null) return word;
String query = getWordQuery("WHERE word = ?");
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, wordToSearch);
ResultSet rs = ps.executeQuery();
if (rs.next()) return getWordFromResultSet(rs);
else return null;
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return null;
}
}
@Override
public boolean wordExists(String word) {
Objects.requireNonNull(word);
String query = "SELECT 1 FROM words WHERE word IN (?, ?)";
word = word.replaceAll("^to ", "");
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, word);
ps.setString(2, "to " + word);
ResultSet rs = ps.executeQuery();
return rs.next();
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return false;
}
}
@Override
public final Map<String, Word> getAllWords() {
if (!wordMap.isEmpty()) return wordMap;
String query = GET_WORD_QUERY_WITHOUT_CONDITION;
try (PreparedStatement ps = con.prepareStatement(query)) {
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Word word = getWordFromResultSet(rs);
wordMap.put(word.getWord(), word);
}
return Collections.unmodifiableMap(wordMap);
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return Collections.emptyMap();
}
}
@Override
public int getTodayIterations() {
String query =
"SELECT iterations FROM daily_iterations WHERE local_date = ?";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setDate(1, Date.valueOf(today));
ResultSet rs = ps.executeQuery();
if (rs.next()) return rs.getInt("iterations");
else return 0;
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return 0;
}
}
@Override
public long getTotalIterations() {
String query = "SELECT SUM(times_picked) AS sum FROM words";
try (Statement statement = con.createStatement()) {
ResultSet rs = statement.executeQuery(query);
rs.next();
return rs.getLong("sum");
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return 0;
}
}
@Override
public int getThisWeekIterations() {
return getIterationsForDays(today.getDayOfWeek().getValue());
}
@Override
public int getIterationsForDays(int n) {
if (n <= 1) return 0;
LocalDate startDate = today.minusDays(n - 1);
LocalDate endDate = today.minusDays(1);
String query = "SELECT SUM(iterations) FROM daily_iterations " +
"WHERE local_date BETWEEN ? AND ?";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setDate(1, Date.valueOf(startDate));
ps.setDate(2, Date.valueOf(endDate));
ResultSet rs = ps.executeQuery();
if (rs.next()) return rs.getInt(1);
else return 0;
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return 0;
}
}
@Override
public void setTodayIterations(int iter) {
String query = "INSERT INTO daily_iterations (local_date, iterations) " +
"VALUES (?, ?) ON DUPLICATE KEY UPDATE iterations = VALUES(iterations)";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setDate(1, Date.valueOf(today));
ps.setInt(2, iter);
ps.executeUpdate();
con.commit();
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
}
}
@Override
public Collection<Word> getBundle(LocalDate bundle) {
if (bundle == null) return Collections.emptyList();
String query = getWordQuery("WHERE bundle_date = ?");
Collection<Word> words = new ArrayList<>(40);
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setDate(1, Date.valueOf(bundle));
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Word word = getWordFromResultSet(rs);
words.add(word);
}
return words;
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return Collections.emptyList();
}
}
@Override
public boolean deleteWord(String wordToDelete) {
String query = "DELETE FROM words WHERE word = ?";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, wordToDelete);
int result = ps.executeUpdate();
if (result != 0) {
con.commit();
wordMap.remove(wordToDelete);
return true;
}
return false;
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
return false;
}
}
@Override
public Map<String, FutureWord> getFutureWords() {
Map<String, FutureWord> map = new TreeMap<>();
String query = "SELECT future_word, priority, " +
"DATE_FORMAT(date_added, '%d.%m.%Y') AS 'date_added', " +
"DATE_FORMAT(date_changed, '%d.%m.%Y') AS 'date_created' " +
"FROM future_words";
try (Statement statement = con.createStatement()) {
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
FutureWord fw = new FutureWord(rs.getString("future_word"));
fw.setPriority(rs.getInt("priority"));
fw.setDateAdded(rs.getString("date_added"));
fw.setDateChanged(rs.getString("date_created"));
map.put(fw.getWord(), fw);
}
return map;
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return Collections.emptyMap();
}
}
@Override
public void updateFutureWord(String word) {
String query = "INSERT INTO future_words " +
"(future_word, priority, date_added, date_changed) " +
"VALUES(?, 0, CURDATE(), CURDATE()) " +
"ON DUPLICATE KEY UPDATE " +
"priority = priority + 1, date_changed = CURDATE()";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, word);
ps.executeUpdate();
con.commit();
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
}
}
@Override
public void deleteFutureWords(Collection<String> words) {
String query = "DELETE FROM future_words WHERE future_word = ?";
try (PreparedStatement ps = con.prepareStatement(query)) {
words.forEach(word -> {
try {
ps.setString(1, word);
ps.executeUpdate();
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
}
});
con.commit();
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
}
}
private Collection<Word> getRepeatWordsWithCondition(String condition) {
String query = getWordQuery("JOIN repeat_words ON " +
"words.word_id = repeat_words.word_id " + condition);
Collection<Word> words = new ArrayList<>();
try (Statement statement = con.createStatement()) {
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
Word w = getWordFromResultSet(rs);
words.add(w);
}
return words;
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return Collections.emptyList();
}
}
@Override
public Collection<Word> getRepeatWords() {
String query = "WHERE date_added >= DATE(DATE_SUB('" + today +
"', INTERVAL " + REPEAT_DAYS_TO_EXPIRE + " DAY))";
Collection<Word> repeatWords = getRepeatWordsWithCondition(query);
repeatWords.forEach(w -> w.setWordType(WordType.REPEAT));
return repeatWords;
}
@Override
public Collection<Word> getExpiredRepeatWords() {
String query = "WHERE date_added = DATE(DATE_SUB('" + today +
"', INTERVAL " + (REPEAT_DAYS_TO_EXPIRE + 1) + " DAY))";
return getRepeatWordsWithCondition(query);
}
@Override
public void addRepeatWord(String word) {
LocalDate insertDate = today.plusDays(1);
String query = "INSERT IGNORE INTO repeat_words (word_id, date_added) " +
"SELECT word_id, ? FROM words WHERE word = ?";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setDate(1, Date.valueOf(insertDate));
ps.setString(2, word);
ps.executeUpdate();
con.commit();
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
}
}
@Override
public void deleteRepeatWord(String word) {
String query = "DELETE FROM repeat_words WHERE word_id IN " +
"(SELECT word_id FROM words WHERE word = ?) " +
"ORDER BY date_added DESC LIMIT 1";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, word);
ps.executeUpdate();
con.commit();
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
}
}
@Override
public boolean addNewWord(Word word) {
String query = "INSERT INTO words (word, translation, synonyms, " +
"bundle_id, times_picked, last_picked_timestamp, complexity_id) " +
"VALUES (?, ?, ?, ?, ?, ?, ?)";
int complexityId = getIdFromComplexity(word.getComplexity());
try (PreparedStatement ps = con.prepareStatement(query)) {
LocalDate bundle = word.getBundle();
int bundleId = getBundleId(bundle);
if (bundleId == -1) bundleId = registerNewBundle(bundle);
ps.setString(1, word.getWord());
ps.setString(2, word.getTranslation());
ps.setString(3, word.getSynonyms());
ps.setInt(4, bundleId);
ps.setInt(5, word.getTimesPicked());
ps.setLong(6, System.currentTimeMillis());
ps.setInt(7, complexityId);
int result = ps.executeUpdate();
if (result != 0) {
con.commit();
wordMap.put(word.getWord(), word);
return true;
}
return false;
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
return false;
}
}
@Override
public boolean isExistingBundle(LocalDate bundle) {
Objects.requireNonNull(bundle);
String query = "SELECT 1 FROM words JOIN bundles ON " +
"words.bundle_id = bundles.bundle_id WHERE bundle_date = ?";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setDate(1, Date.valueOf(bundle));
return ps.executeQuery().next();
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return false;
}
}
@Override
public LocalDate getLastBundleName() {
String query = "SELECT DISTINCT bundle_date FROM bundles " +
"JOIN words ON bundles.bundle_id = words.bundle_id " +
"ORDER BY bundle_date DESC LIMIT 1";
try (Statement statement = con.createStatement()) {
ResultSet rs = statement.executeQuery(query);
if (rs.next()) return rs.getDate("bundle_date").toLocalDate();
else return null;
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return null;
}
}
@Override
public LocalDate getPenultimateBundleName() {
String query = "SELECT DISTINCT bundle_date FROM bundles " +
"JOIN words ON bundles.bundle_id = words.bundle_id " +
"ORDER BY bundle_date DESC LIMIT 1, 1";
try (Statement statement = con.createStatement()) {
ResultSet rs = statement.executeQuery(query);
if (rs.next()) return rs.getDate("bundle_date").toLocalDate();
else return null;
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return null;
}
}
@Override
public NavigableSet<LocalDate> allBundlesSorted() {
TreeSet<LocalDate> bundles = new TreeSet<>();
String query = "SELECT DISTINCT bundle_date FROM bundles " +
"JOIN words ON bundles.bundle_id = words.bundle_id";
try (Statement statement = con.createStatement()) {
ResultSet rs = statement.executeQuery(query);
while (rs.next())
bundles.add(rs.getDate("bundle_date").toLocalDate());
return bundles;
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return Collections.emptyNavigableSet();
}
}
@Override
public String getDefinition(String word) {
String query = "SELECT definition FROM words WHERE word = ?";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, word);
ResultSet rs = ps.executeQuery();
if (rs.next()) return rs.getString("definition");
else return null;
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return null;
}
}
@Override
public void setDefinition(String word, String definition) {
String query = "UPDATE words SET definition = ? WHERE word = ?";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, definition);
ps.setString(2, word);
ps.executeUpdate();
con.commit();
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
}
}
@Override
public void setComplexity(String word, WordComplexity complexity) {
String query = "UPDATE words SET complexity_id = ? WHERE word = ?";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setInt(1, getIdFromComplexity(complexity));
ps.setString(2, word);
ps.executeUpdate();
con.commit();
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
}
}
@Override
public void setLastPickedTimestamp(String word, long timestamp) {
String query = "UPDATE words SET last_picked_timestamp = ?, "
+ "times_picked = times_picked + 1 WHERE word = ?";
try (PreparedStatement ps = con.prepareStatement(query)) {
ps.setLong(1, timestamp);
ps.setString(2, word);
ps.executeUpdate();
con.commit();
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
}
}
@Override
public void editWords(Map<Word, Word> map) {
for (Map.Entry<Word, Word> entry : map.entrySet()) {
try {
Word originalWord = entry.getValue();
Word editedWord = entry.getKey();
if (!originalWord.getWord().equals(editedWord.getWord())) {
String wordToDelete = originalWord.getWord();
deleteWord(wordToDelete);
wordMap.remove(wordToDelete);
addNewWord(editedWord); // commits changes
continue; // move to the next word
}
String query = "UPDATE words SET translation = ? , synonyms = ?, " +
"bundle_id = ?, times_picked = ?, last_picked_timestamp = ?, " +
"complexity_id = ?, definition = ? WHERE word = ?";
try (PreparedStatement ps = con.prepareStatement(query)) {
int complexityId = getIdFromComplexity(editedWord.getComplexity());
LocalDate bundle = editedWord.getBundle();
int bundleId = getBundleId(bundle);
if (bundleId == -1) bundleId = registerNewBundle(bundle);
ps.setString(1, editedWord.getTranslation());
ps.setString(2, editedWord.getSynonyms());
ps.setInt(3, bundleId);
ps.setInt(4, editedWord.getTimesPicked());
ps.setLong(5, editedWord.getLastPickedTimestamp());
ps.setInt(6, complexityId);
ps.setString(7, getDefinition(editedWord.getWord()));
ps.setString(8, editedWord.getWord());
ps.executeUpdate();
con.commit();
wordMap.put(editedWord.getWord(), editedWord);
}
} catch (SQLException sqle) {
rollback();
defaultExceptionHandler(sqle);
}
}
}
@Override
public boolean addNewBundle(LocalDate bundle, Collection<Word> words) {
if (isExistingBundle(bundle)) return false;
words.forEach(word -> {
word.setBundle(bundle);
addNewWord(word);
});
return true;
}
@Override
public boolean isEmpty() {
String query = "SELECT COUNT(word) FROM words";
try (Statement statement = con.createStatement()) {
ResultSet rs = statement.executeQuery(query);
rs.next();
return rs.getInt(1) == 0;
} catch (SQLException sqle) {
defaultExceptionHandler(sqle);
return true;
}
}
@Override
public void destroy() {
try (PreparedStatement ps = con.prepareStatement(
"DROP DATABASE IF EXISTS ?")) {
ps.setString(1, dbName);
ps.executeUpdate();
} catch (SQLException ex) { }
System.err.println("Model has been completely destroyed");
}
}
| gpl-3.0 |
vjuranek/scias-server | water/water-server/src/main/java/eu/imagecode/scias/model/jpa/StationGroupEntity.java | 2861 | package eu.imagecode.scias.model.jpa;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the station_group database table.
*
*/
@Entity
@Table(name = "station_group")
@NamedQuery(name = "StationGroupEntity.findAll", query = "SELECT s FROM StationGroupEntity s")
public class StationGroupEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "STATION_GROUP_ID_GENERATOR", sequenceName = "STATION_GROUP_ID_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "STATION_GROUP_ID_GENERATOR")
private Integer id;
private String name;
// bi-directional many-to-one association to StationEntity
@OneToMany(mappedBy = "stationGroup")
private List<StationEntity> stations;
// bi-directional many-to-one association to StationGroupEntity
@ManyToOne
@JoinColumn(name = "parent_group_id")
private StationGroupEntity stationGroup;
// bi-directional many-to-one association to StationGroupEntity
@OneToMany(mappedBy = "stationGroup")
private List<StationGroupEntity> stationGroups;
public StationGroupEntity() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public List<StationEntity> getStations() {
return this.stations;
}
public void setStations(List<StationEntity> stations) {
this.stations = stations;
}
public StationEntity addStation(StationEntity station) {
getStations().add(station);
station.setStationGroup(this);
return station;
}
public StationEntity removeStation(StationEntity station) {
getStations().remove(station);
station.setStationGroup(null);
return station;
}
public StationGroupEntity getStationGroup() {
return this.stationGroup;
}
public void setStationGroup(StationGroupEntity stationGroup) {
this.stationGroup = stationGroup;
}
public List<StationGroupEntity> getStationGroups() {
return this.stationGroups;
}
public void setStationGroups(List<StationGroupEntity> stationGroups) {
this.stationGroups = stationGroups;
}
public StationGroupEntity addStationGroup(StationGroupEntity stationGroup) {
getStationGroups().add(stationGroup);
stationGroup.setStationGroup(this);
return stationGroup;
}
public StationGroupEntity removeStationGroup(StationGroupEntity stationGroup) {
getStationGroups().remove(stationGroup);
stationGroup.setStationGroup(null);
return stationGroup;
}
} | gpl-3.0 |
0x006EA1E5/oo6 | src/main/java/org/otherobjects/cms/controllers/DesignerController.java | 5683 | package org.otherobjects.cms.controllers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.otherobjects.cms.dao.DaoService;
import org.otherobjects.cms.jcr.UniversalJcrDao;
import org.otherobjects.cms.model.BaseNode;
import org.otherobjects.cms.model.Template;
import org.otherobjects.cms.model.TemplateBlockReference;
import org.otherobjects.cms.model.TemplateLayout;
import org.otherobjects.cms.model.TemplateRegion;
import org.otherobjects.cms.util.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* Controller that manages template design.
*
* @author rich
*/
@Controller
public class DesignerController
{
private final Logger logger = LoggerFactory.getLogger(DesignerController.class);
@Resource
private DaoService daoService;
/**
* Saves arrangmement of blocks on a template.
*/
@RequestMapping("/designer/saveArrangement/**")
public ModelAndView saveArrangement(HttpServletRequest request, HttpServletResponse response) throws Exception
{
UniversalJcrDao dao = (UniversalJcrDao) daoService.getDao(BaseNode.class);
String templateId = request.getParameter("templateId");
String arrangement = request.getParameter("arrangement");
logger.info("Arrangement: " + arrangement);
JSONArray regions = new JSONArray(arrangement);
// Load existing template
Template template = (Template) dao.get(templateId);
Map<String, TemplateBlockReference> blockRefs = new HashMap<String, TemplateBlockReference>();
// Gather all existing blockRefs
for (TemplateRegion tr : template.getRegions())
{
for (TemplateBlockReference trb : tr.getBlocks())
{
blockRefs.put(trb.getId(), trb);
}
tr.setBlocks(new ArrayList<TemplateBlockReference>());
}
// Re-insert blockRefs according to arrangement
for (int i = 0; i < regions.length(); i++)
{
JSONObject region = (JSONObject) regions.get(i);
TemplateRegion tr = template.getRegion((String) region.get("name"));
JSONArray blockIds = (JSONArray) region.get("blockIds");
for (int j = 0; j < blockIds.length(); j++)
{
String blockId = (String) blockIds.get(j);
tr.getBlocks().add(blockRefs.get(blockId));
blockRefs.remove(blockId);
}
}
dao.save(template, false);
// Delete removed blocks
// FIXME Need to remove deleted blocks from live
for (TemplateBlockReference ref : blockRefs.values())
{
dao.remove(ref.getId());
}
return null;
}
/**
* Saves arrangmement of blocks on a template.
*/
@RequestMapping("/designer/publishTemplate/**")
public ModelAndView publishTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception
{
UniversalJcrDao dao = (UniversalJcrDao) daoService.getDao(BaseNode.class);
String templateId = RequestUtils.getId(request);
// Load existing template
Template template = (Template) dao.get(templateId);
Map<String, TemplateBlockReference> blockRefs = new HashMap<String, TemplateBlockReference>();
// Gather all existing blockRefs
for (TemplateRegion tr : template.getRegions())
{
for (TemplateBlockReference trb : tr.getBlocks())
{
blockRefs.put(trb.getId(), trb);
}
}
// Check all blocks are published
for (TemplateBlockReference ref : blockRefs.values())
{
if (!ref.isPublished())
dao.publish(ref, null);
if (ref.getBlockData() != null && !ref.getBlockData().isPublished())
dao.publish(ref.getBlockData(), null);
}
// Publish template
dao.publish(template, null);
return null;
}
/**
* Creates a new template for specified type.
*/
@RequestMapping("/designer/createTemplate/**")
public ModelAndView createTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception
{
UniversalJcrDao dao = (UniversalJcrDao) daoService.getDao(BaseNode.class);
String resourceObjectId = RequestUtils.getId(request);
BaseNode resourceObject = dao.get(resourceObjectId);
String templateCode = request.getParameter("code");
String layoutId = request.getParameter("layout");
Template template = new Template();
template.setPath("/designer/templates/");
template.setCode(templateCode);
template.setLabel(resourceObject.getTypeDef().getLabel() + " Template");
TemplateLayout layout = (TemplateLayout) dao.get(layoutId);
template.setLayout(layout);
dao.save(template, false);
// FIXME Need to wrap linkPath
response.sendRedirect(resourceObject.getOoUrlPath());
return null;
}
/**
* Changes layout for specified template.
*/
@RequestMapping("/designer/changeLayout/**")
public ModelAndView changeLayout(HttpServletRequest request, HttpServletResponse response) throws Exception
{
return null;
}
}
| gpl-3.0 |
da-nrw/DNSCore | ContentBroker/src/main/java/de/uzk/hki/da/event/SystemEventFactory.java | 2827 | /*
DA-NRW Software Suite | ContentBroker
Copyright (C) 2015 LVRInfoKom
Landschaftsverband Rheinland
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General 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/>.
*/
/**
* @author jens Peters
* Factory for building events
*/
package de.uzk.hki.da.event;
import java.util.List;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.uzk.hki.da.model.Node;
import de.uzk.hki.da.model.SystemEvent;
import de.uzk.hki.da.service.HibernateUtil;
public class SystemEventFactory {
protected Logger logger = LoggerFactory.getLogger( this.getClass().getName() );
private Node localNode;
private String eventsPackage = "de.uzk.hki.da.event.";
public void buildStoredEvents() {
List<SystemEvent> ses = getEventsPerNode();
if (ses != null) {
for (SystemEvent se : ses) {
if (se.getType() == null)
continue;
AbstractSystemEvent ase = null;
try {
ase = (AbstractSystemEvent) Class.forName(eventsPackage + se.getType()).newInstance();
injectProperties(ase, se);
ase.run();
} catch (Exception e) {
logger.error("could not instantiate " + se.getType());
}
}
} else
logger.debug("no events to perform");
}
private void injectProperties(AbstractSystemEvent ase, SystemEvent se) {
ase.setNode(localNode);
ase.setOwner(se.getOwner());
ase.setStoredEvent(se);
}
@SuppressWarnings("unchecked")
private List<SystemEvent>getEventsPerNode() {
Session session = HibernateUtil.openSession();
List<SystemEvent> events=null;
try{
events = session
.createQuery("from SystemEvent e where e.node.id = ?1")
.setParameter("1", localNode.getId()).setCacheable(false).list();
if ((events == null) || (events.isEmpty())){
logger.trace("no systemevents found for " + localNode.getName());
session.close();
return null;
}
session.close();
}catch(Exception e){
session.close();
logger.error("Caught error in getEventsPerNode id: " + localNode.getId() + " " + e.getMessage(),e);
throw new RuntimeException(e.getMessage(), e);
}
return events;
}
public Node getLocalNode() {
return localNode;
}
public void setLocalNode(Node localNode) {
this.localNode = localNode;
}
}
| gpl-3.0 |
rivetlogic/liferay-elasticsearch-integration | webs/elasticsearch-web/docroot/WEB-INF/src/com/rivetlogic/portal/search/elasticsearch/indexer/document/ElasticsearchDocumentJSONBuilder.java | 7524 | /**
* Copyright (C) 2005-2014 Rivet Logic Corporation.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.rivetlogic.portal.search.elasticsearch.indexer.document;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.search.Document;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.util.portlet.PortletProps;
import com.rivetlogic.portal.search.elasticsearch.ElasticsearchIndexerConstants;
/**
* The Class ElasticsearchDocumentJSONBuilder.
*
*/
public class ElasticsearchDocumentJSONBuilder {
/**
* Init method.
*/
public void loadExcludedTypes() {
String cslExcludedType = PortletProps.get(ElasticsearchIndexerConstants.ES_KEY_EXCLUDED_INDEXTYPE);
if(Validator.isNotNull(cslExcludedType)){
excludedTypes = new HashSet<String>();
for(String excludedType : cslExcludedType.split(StringPool.COMMA)){
excludedTypes.add(excludedType);
}
if(_log.isDebugEnabled()){
_log.debug("Loaded Excluded index types are:"+cslExcludedType);
}
_log.info("Loaded Excluded index types are:"+cslExcludedType);
} else {
if(_log.isDebugEnabled()){
_log.debug("Excluded index types are not defined");
}
_log.info("Excluded index types are not defined");
}
}
/**
* Convert to json.
*
* @param document
* the document
* @return the string
*/
public ElasticserachJSONDocument convertToJSON(final Document document) {
Map<String, Field> fields = document.getFields();
ElasticserachJSONDocument elasticserachJSONDocument = new ElasticserachJSONDocument();
try {
XContentBuilder contentBuilder = XContentFactory.jsonBuilder().startObject();
Field classnameField = document.getField(ElasticsearchIndexerConstants.ENTRY_CLASSNAME);
String entryClassName = (classnameField == null)? "": classnameField.getValue();
/**
* Handle all error scenarios prior to conversion
*/
if(isDocumentHidden(document)){
elasticserachJSONDocument.setError(true);
elasticserachJSONDocument.setErrorMessage(ElasticserachJSONDocument.DocumentError.HIDDEN_DOCUMENT.toString());
return elasticserachJSONDocument;
}
if(entryClassName.isEmpty()){
elasticserachJSONDocument.setError(true);
elasticserachJSONDocument.setErrorMessage(ElasticserachJSONDocument.DocumentError.MISSING_ENTRYCLASSNAME.toString());
return elasticserachJSONDocument;
}
if(isExcludedType(entryClassName)){
elasticserachJSONDocument.setError(true);
elasticserachJSONDocument.setErrorMessage("Index Type:"+entryClassName+StringPool.COMMA+ElasticserachJSONDocument.DocumentError.EXCLUDED_TYPE.toString());
return elasticserachJSONDocument;
}
/**
* To avoid multiple documents for versioned assets such as Journal articles, DL entry etc
* the primary Id will be Indextype + Entry class PK. The primary Id is to maintain uniqueness
* in ES server database and nothing to do with UID or is not used for any other purpose.
*/
Field classPKField = document.getField(ElasticsearchIndexerConstants.ENTRY_CLASSPK);
String entryClassPK = (classPKField == null)? "": classPKField.getValue();
if(entryClassPK.isEmpty()){
elasticserachJSONDocument.setError(true);
elasticserachJSONDocument.setErrorMessage(ElasticserachJSONDocument.DocumentError.MISSING_CLASSPK.toString());
return elasticserachJSONDocument;
}
/** Replace '.' by '_' in Entry class name,since '.' is not recommended by Elasticsearch in Index type */
String indexType = entryClassName.replace(StringPool.PERIOD, StringPool.UNDERLINE);
elasticserachJSONDocument.setIndexType(indexType);
elasticserachJSONDocument.setId(indexType+entryClassPK);
/** Create a JSON string for remaining fields of document */
for (Iterator<Map.Entry<String, Field>> it = fields.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Field> entry = it.next();
Field field = entry.getValue();
contentBuilder.field(entry.getKey(), field.getValue());
}
contentBuilder.endObject();
elasticserachJSONDocument.setJsonDocument(contentBuilder.string());
if(_log.isDebugEnabled()){
_log.debug("Liferay Document converted to ESJSON document successfully:"+contentBuilder.string());
}
} catch (IOException e) {
_log.error("IO Error during converstion of Liferay Document to JSON format"+e.getMessage());
}
return elasticserachJSONDocument;
}
/**
* Check if liferay Document is of type hidden.
*
* @param document the document
* @return true, if is document hidden
*/
private boolean isDocumentHidden(Document document){
Field hiddenField = document.getField(ElasticsearchIndexerConstants.HIDDEN);
String hiddenFlag = (hiddenField == null)? "" : hiddenField.getValue();
if(StringPool.TRUE.equalsIgnoreCase(hiddenFlag)){
return true;
}
return false;
}
/**
* Check if EntryClassname is com.liferay.portal.kernel.plugin.PluginPackage/ExportImportHelper which need not be indexed
*
* @param indexType the index type
* @return true, if is excluded type
*/
private boolean isExcludedType(String indexType) {
if(indexType != null && excludedTypes != null) {
for(String excludedType : excludedTypes){
if(indexType.toLowerCase().contains(excludedType.toLowerCase())){
return true;
}
}
}
return false;
}
/** The Constant _log. */
private final static Log _log = LogFactoryUtil.getLog(ElasticsearchDocumentJSONBuilder.class);
/** The excluded types. */
private Set<String> excludedTypes;
}
| gpl-3.0 |
0x006EA1E5/oo6 | src/main/java/org/otherobjects/cms/model/Folder.java | 564 | package org.otherobjects.cms.model;
import java.io.Serializable;
import java.util.List;
import org.otherobjects.cms.types.TypeDef;
@SuppressWarnings("serial")
public abstract class Folder extends BaseNode implements Serializable
{
public abstract String getLabel();
public abstract void setLabel(String label);
abstract List<?> getAllowedTypes();
abstract void setAllowedTypes(List<String> allowedTypes);
abstract List<TypeDef> getAllAllowedTypes();
abstract String getCssClass();
abstract void setCssClass(String cssClass);
}
| gpl-3.0 |
QwertyManiac/seal-cdh4 | src/it/crs4/seal/demux/DemuxOutputFormat.java | 5848 | // Copyright (C) 2011-2012 CRS4.
//
// This file is part of Seal.
//
// Seal is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// Seal 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 Seal. If not, see <http://www.gnu.org/licenses/>.
package it.crs4.seal.demux;
import it.crs4.seal.common.SealToolParser; // for OUTPUT_FORMAT_CONF
import fi.tkk.ics.hadoop.bam.QseqOutputFormat.QseqRecordWriter;
import fi.tkk.ics.hadoop.bam.FastqOutputFormat.FastqRecordWriter;
import fi.tkk.ics.hadoop.bam.SequencedFragment;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.GzipCodec;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.util.ReflectionUtils;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
public class DemuxOutputFormat extends FileOutputFormat<Text, SequencedFragment>
{
protected static class DemuxMultiFileLineRecordWriter extends RecordWriter<Text,SequencedFragment> implements Configurable
{
protected static final String DEFAULT_OUTPUT_FORMAT = "qseq";
protected HashMap<Text,RecordWriter<Text, SequencedFragment>> outputs;
protected FileSystem fs;
protected Path outputPath;
protected Configuration conf;
protected boolean isCompressed;
protected CompressionCodec codec;
protected enum OutputFormatType {
Qseq,
Fastq;
};
protected OutputFormatType outputFormat;
public DemuxMultiFileLineRecordWriter(TaskAttemptContext task, FileSystem fs, Path defaultFile) throws IOException
{
conf = task.getConfiguration();
outputPath = defaultFile;
this.fs = outputPath.getFileSystem(conf);
isCompressed = FileOutputFormat.getCompressOutput(task);
if (isCompressed)
{
Class<? extends CompressionCodec> codecClass = FileOutputFormat.getOutputCompressorClass(task, GzipCodec.class);
codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf);
outputPath = outputPath.suffix(codec.getDefaultExtension());
}
outputs = new HashMap<Text,RecordWriter<Text,SequencedFragment>>(20);
// XXX: I don't think there's a better way to pass the desired output format
// into this object. If we go through the configuration object, we might as
// well re-use the OUTPUT_FORMAT_CONF property set by the SealToolParser.
String oformatName = conf.get(SealToolParser.OUTPUT_FORMAT_CONF, DEFAULT_OUTPUT_FORMAT);
if ("qseq".equalsIgnoreCase(oformatName))
this.outputFormat = OutputFormatType.Qseq;
else if ("fastq".equalsIgnoreCase(oformatName))
this.outputFormat = OutputFormatType.Fastq;
else
throw new RuntimeException("Unexpected output format " + oformatName);
}
public void setConf(Configuration conf) { this.conf = conf; }
public Configuration getConf() { return conf; }
public void write(Text key, SequencedFragment value) throws IOException , InterruptedException
{
if (value == null)
return;
if (key == null)
throw new RuntimeException("trying to output a null key. I don't know where to put that.");
RecordWriter<Text, SequencedFragment> writer = getOutputStream(key);
writer.write(null, value);
}
protected RecordWriter<Text, SequencedFragment> makeWriter(Path outputPath) throws IOException
{
DataOutputStream ostream;
if (isCompressed)
{
FSDataOutputStream fileOut = fs.create(outputPath, false);
ostream = new DataOutputStream(codec.createOutputStream(fileOut));
}
else
ostream = fs.create(outputPath, false);
if (outputFormat == OutputFormatType.Qseq)
return new QseqRecordWriter(conf, ostream);
else if (outputFormat == OutputFormatType.Fastq)
return new FastqRecordWriter(conf, ostream);
else
throw new RuntimeException("BUG! Unexpected outputFormat value " + outputFormat);
}
protected RecordWriter<Text, SequencedFragment> getOutputStream(Text key) throws IOException, InterruptedException
{
RecordWriter<Text, SequencedFragment> writer = outputs.get(key);
if (writer == null)
{
// create it
Path dir = new Path(outputPath.getParent(), key.toString());
Path file = new Path(dir, outputPath.getName());
if (!fs.exists(dir))
fs.mkdirs(dir);
// now create a new writer that will write to the desired file path
// (which should not already exist, since we didn't find it in our hash map)
writer = makeWriter(file);
outputs.put(key, writer); // insert the record writer into our map
}
return writer;
}
public synchronized void close(TaskAttemptContext context) throws IOException, InterruptedException
{
for (RecordWriter<Text, SequencedFragment> out: outputs.values())
out.close(null);
}
}
public RecordWriter<Text,SequencedFragment> getRecordWriter(TaskAttemptContext job) throws IOException
{
Path defaultFile = getDefaultWorkFile(job, "");
FileSystem fs = defaultFile.getFileSystem(job.getConfiguration());
return new DemuxMultiFileLineRecordWriter(job, fs, defaultFile);
}
}
| gpl-3.0 |
kinztechcom/OS-Cache-Suite | src/com/osrs/suite/cache/TextureImage.java | 289 | package com.osrs.suite.cache;
/**
* Created by Allen Kinzalow on 3/16/2015.
*/
public interface TextureImage {
int method21(int var1, int var2);
boolean method23(int var1, int var2);
boolean method24(int var1, int var2);
int[] getTexturePixels(int var1, int var2);
} | gpl-3.0 |
sensiasoft/lib-swe-common | swe-common-om/src/main/java/net/opengis/gml/v32/AbstractTimePrimitive.java | 1326 | /***************************** BEGIN LICENSE BLOCK ***************************
The contents of this file are subject to the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved.
******************************* END LICENSE BLOCK ***************************/
package net.opengis.gml.v32;
import net.opengis.OgcPropertyList;
/**
* POJO class for XML type AbstractTimePrimitiveType(@http://www.opengis.net/gml/3.2).
*
* This is a complex type.
*/
@SuppressWarnings("javadoc")
public interface AbstractTimePrimitive extends AbstractGML
{
/**
* Gets the list of relatedTime properties
*/
public OgcPropertyList<AbstractTimePrimitive> getRelatedTimeList();
/**
* Returns number of relatedTime properties
*/
public int getNumRelatedTimes();
/**
* Adds a new relatedTime property
*/
public void addRelatedTime(AbstractTimePrimitive relatedTime);
}
| mpl-2.0 |
seedstack/coffig | src/test/java/org/seedstack/coffig/mapper/ValueMapperTest.java | 2117 | /*
* Copyright © 2013-2021, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.coffig.mapper;
import org.junit.Test;
import org.seedstack.coffig.Coffig;
import org.seedstack.coffig.node.ValueNode;
import org.seedstack.coffig.spi.ConfigurationMapper;
import static org.assertj.core.api.Assertions.assertThat;
public class ValueMapperTest {
private ConfigurationMapper mapper = Coffig.basic().getMapper();
@Test
public void testMapValues() {
assertThat(mapper.map(new ValueNode("true"), Boolean.class)).isEqualTo(true);
assertThat(mapper.map(new ValueNode("false"), boolean.class)).isEqualTo(false);
assertThat(mapper.map(new ValueNode("101"), Byte.class)).isEqualTo((byte) 101);
assertThat(mapper.map(new ValueNode("101"), byte.class)).isEqualTo((byte) 101);
assertThat(mapper.map(new ValueNode("A"), Character.class)).isEqualTo('A');
assertThat(mapper.map(new ValueNode("A"), char.class)).isEqualTo('A');
assertThat(mapper.map(new ValueNode("3.14"), Double.class)).isEqualTo(3.14d);
assertThat(mapper.map(new ValueNode("3.14"), double.class)).isEqualTo(3.14d);
assertThat(mapper.map(new ValueNode("3.14"), Float.class)).isEqualTo(3.14f);
assertThat(mapper.map(new ValueNode("3.14"), float.class)).isEqualTo(3.14f);
assertThat(mapper.map(new ValueNode("3"), Integer.class)).isEqualTo(3);
assertThat(mapper.map(new ValueNode("3"), int.class)).isEqualTo(3);
assertThat(mapper.map(new ValueNode("3"), Long.class)).isEqualTo(3L);
assertThat(mapper.map(new ValueNode("3"), long.class)).isEqualTo(3L);
assertThat(mapper.map(new ValueNode("3"), Short.class)).isEqualTo((short) 3);
assertThat(mapper.map(new ValueNode("3"), short.class)).isEqualTo((short) 3);
assertThat(mapper.map(new ValueNode("abcd"), String.class)).isEqualTo("abcd");
}
}
| mpl-2.0 |
richardwilkes/gcs | com.trollworks.gcs/src/com/trollworks/gcs/expression/function/Log.java | 977 | /*
* Copyright ©1998-2022 by Richard A. Wilkes. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, version 2.0. If a copy of the MPL was not distributed with
* this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, version 2.0.
*/
package com.trollworks.gcs.expression.function;
import com.trollworks.gcs.expression.ArgumentTokenizer;
import com.trollworks.gcs.expression.EvaluationException;
import com.trollworks.gcs.expression.Evaluator;
public class Log implements ExpressionFunction {
@Override
public final String getName() {
return "log";
}
@Override
public final Object execute(Evaluator evaluator, String arguments) throws EvaluationException {
return Double.valueOf(Math.log(ArgumentTokenizer.getDoubleArgument(evaluator, arguments)));
}
}
| mpl-2.0 |
wx1988/strabon | runtime/src/main/java/eu/earthobservatory/runtime/generaldb/InvalidDatasetFormatFault.java | 410 | /**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (C) 2010, 2011, 2012, Pyravlos Team
*
* http://www.strabon.di.uoa.gr/
*/
package eu.earthobservatory.runtime.generaldb;
public class InvalidDatasetFormatFault extends Exception {
}
| mpl-2.0 |
jreneruiz/Impresor-de-etiquetas-zebra | src/com/modelo/Etiqueta.java | 1643 | package com.modelo;
import java.nio.charset.StandardCharsets;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.SimpleDoc;
/**
*
* Etiqueta class
* Clase donde se inicializa el tamaño de la letra y la posicion en la que van a
* estar los valores extraidos de la lista, ademas esta clase se ecargar de mandar
* estos valores a la impresora.
*
*
* @author Jose Rene Palacios Ruiz
* @version 1.0
* @since 19-06-2015
*/
public class Etiqueta {
/**
*
* Metodo encargada de imprimir la etiqueta; se le pasan
* ciertos parametros al mandarlo llamar
*
* @param printService Servicio de impresora al que se le va a mandar la informacion
* @param date Inicializador de la fecha
* @param mA Amperaje del archivo .cvs
* @return result
*/
public boolean impEtiqueta(PrintService printService, String date, String mA) {
if (printService == null || date == null || mA == null) {
return false;
}
String command = "^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR5,5~SD15^JUS^LRN^CI0^XZ^XA^MMT^PW203^LL0102^LS0^FT40,71^A0N,20,19^FH\\^FD"+date+"^FS^FT44,45^A0N,28,28^FH\\^FD"+mA+"^FS^PQ1,0,1,Y^XZ" ;
byte[] data;
data = command.getBytes(StandardCharsets.US_ASCII);
Doc doc = new SimpleDoc(data, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
boolean result = false;
try {
printService.createPrintJob().print(doc, null);
result = true;
} catch (PrintException e) {
e.printStackTrace();
}
return result;
}
}
| mpl-2.0 |
DevinZ1993/LeetCode-Solutions | java/522.java | 1490 | public class Solution {
public int findLUSlength(String[] strs) {
Arrays.sort(strs, new Comparator<String>(){
public int compare(String a, String b) {
if (a.length() != b.length()) {
return b.length()-a.length();
} else {
return a.compareTo(b);
}
}
});
for (int i=0; i<strs.length; i++) {
boolean flag = (i == strs.length-1 || !strs[i].equals(strs[i+1]));
if (flag) {
for (int j=i-1; j>=0; j--) {
if (isSub(strs[i], strs[j])) {
flag = false;
break;
}
}
}
if (flag) {
return strs[i].length();
}
}
return -1;
}
private boolean isSub(String a, String b) {
if (a.length() <= b.length()) {
for (int state=1, i=0; i<b.length(); i++) {
int next = 1;
for (int j=0; j<=i && j<a.length(); j++) {
if (0 != (state&(1<<j)) && a.charAt(j) == b.charAt(i)) {
if (j == a.length()-1) {
return true;
}
next |= (1<<(j+1));
}
}
state |= next;
}
}
return false;
}
}
| mpl-2.0 |
adrienlauer/business | core/src/test/java/org/seedstack/business/IdentityServiceIT.java | 2690 | /*
* Copyright © 2013-2019, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
*
*/
package org.seedstack.business;
import java.util.UUID;
import javax.inject.Inject;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.seedstack.business.domain.IdentityExistsException;
import org.seedstack.business.domain.IdentityService;
import org.seedstack.business.fixtures.identity.MyAggregate;
import org.seedstack.business.fixtures.identity.MyAggregateWithBadIdentityManagement;
import org.seedstack.business.fixtures.identity.MyAggregateWithConfiguration;
import org.seedstack.business.fixtures.identity.MyAggregateWithNoIdentityManagement;
import org.seedstack.business.internal.BusinessErrorCode;
import org.seedstack.business.internal.BusinessException;
import org.seedstack.seed.testing.junit4.SeedITRunner;
@RunWith(SeedITRunner.class)
public class IdentityServiceIT {
@Inject
private IdentityService identityService;
@Test
public void identify_entity() {
MyAggregate myAggregate = new MyAggregate();
identityService.identify(myAggregate);
Assertions.assertThat(myAggregate.getId())
.isNotNull();
}
@Test(expected = IdentityExistsException.class)
public void allready_identify_entity() {
MyAggregate myAggregate = new MyAggregate(UUID.randomUUID());
identityService.identify(myAggregate);
Assertions.fail("no exception occured");
}
@Test
public void identify_entity_with_configuration() {
MyAggregateWithConfiguration myAggregate = new MyAggregateWithConfiguration();
identityService.identify(myAggregate);
Assertions.assertThat(myAggregate.getId())
.isNotNull();
}
@Test
public void aggregate_with_bad_identity_Management() {
MyAggregateWithBadIdentityManagement myAggregate = new MyAggregateWithBadIdentityManagement();
try {
identityService.identify(myAggregate);
Assertions.fail("no exception occurred");
} catch (BusinessException e) {
Assertions.assertThat(e.getErrorCode())
.isEqualTo(BusinessErrorCode.INCOMPATIBLE_IDENTITY_TYPES);
}
}
@Test
public void aggregate_with_no_identity_Management() {
MyAggregateWithNoIdentityManagement myAggregate = new MyAggregateWithNoIdentityManagement();
identityService.identify(myAggregate);
}
}
| mpl-2.0 |
ekager/focus-android | app/src/androidTest/java/org/mozilla/focus/screenshots/ErrorPagesScreenshots.java | 3751 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.screenshots;
import android.os.Build;
import android.support.test.espresso.web.webdriver.Locator;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiSelector;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mozilla.focus.R;
import org.mozilla.focus.helpers.TestHelper;
import tools.fastlane.screengrab.Screengrab;
import tools.fastlane.screengrab.locale.LocaleTestRule;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.pressImeActionButton;
import static android.support.test.espresso.action.ViewActions.replaceText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.hasFocus;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.web.sugar.Web.onWebView;
import static android.support.test.espresso.web.webdriver.DriverAtoms.findElement;
import static android.support.test.espresso.web.webdriver.DriverAtoms.webClick;
import static android.support.test.espresso.web.webdriver.DriverAtoms.webScrollIntoView;
import static junit.framework.Assert.assertTrue;
@RunWith(AndroidJUnit4.class)
public class ErrorPagesScreenshots extends ScreenshotTest {
@ClassRule
public static final LocaleTestRule localeTestRule = new LocaleTestRule();
private enum ErrorTypes {
ERROR_UNKNOWN (-1),
ERROR_HOST_LOOKUP (-2),
ERROR_CONNECT (-6),
ERROR_TIMEOUT (-8),
ERROR_REDIRECT_LOOP (-9),
ERROR_UNSUPPORTED_SCHEME (-10),
ERROR_FAILED_SSL_HANDSHAKE (-11),
ERROR_BAD_URL (-12),
ERROR_TOO_MANY_REQUESTS (-15);
private int value;
ErrorTypes(int value) {
this.value = value;
}
}
@Test
public void takeScreenshotsOfErrorPages() {
for (ErrorTypes error: ErrorTypes.values()) {
onView(withId(R.id.urlView))
.check(matches(isDisplayed()))
.check(matches(hasFocus()))
.perform(click(), replaceText("error:" + error.value), pressImeActionButton());
assertTrue(TestHelper.webView.waitForExists(waitingTime));
assertTrue(TestHelper.progressBar.waitUntilGone(waitingTime));
// Android O has an issue with using Locator.ID
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
UiObject tryAgainBtn = device.findObject(new UiSelector()
.resourceId("errorTryAgain")
.clickable(true));
assertTrue(tryAgainBtn.waitForExists(waitingTime));
} else {
onWebView()
.withElement(findElement(Locator.ID, "errorTitle"))
.perform(webClick());
onWebView()
.withElement(findElement(Locator.ID, "errorTryAgain"))
.perform(webScrollIntoView());
}
Screengrab.screenshot(error.name());
onView(withId(R.id.display_url))
.check(matches(isDisplayed()))
.perform(click());
}
}
}
| mpl-2.0 |
wx1988/strabon | postgis/src/main/java/org/openrdf/sail/postgis/PostGISSqlTable.java | 1904 | /*
* Copyright Aduna (http://www.aduna-software.com/) (c) 2008.
*
* Licensed under the Aduna BSD-style license.
*/
package org.openrdf.sail.postgis;
import java.sql.SQLException;
import org.openrdf.sail.generaldb.GeneralDBSqlTable;
import eu.earthobservatory.constants.GeoConstants;
/**
* Converts table names to lower-case and include the analyse optimisation.
*
* @author James Leigh
*
*/
public class PostGISSqlTable extends GeneralDBSqlTable {
public PostGISSqlTable(String name) {
super(name.toLowerCase());
}
@Override
protected String buildOptimize()
throws SQLException
{
return "VACUUM ANALYZE " + getName();
}
@Override
protected String buildClear() {
return "TRUNCATE " + getName();
}
@Override
public String buildGeometryCollumn() {
return "SELECT AddGeometryColumn('','geo_values','strdfgeo',4326,'GEOMETRY',2)";
}
@Override
public String buildIndexOnGeometryCollumn() {
return "CREATE INDEX geoindex ON geo_values USING GIST (strdfgeo)";
}
@Override
public String buildInsertGeometryValue() {
Integer srid= GeoConstants.defaultSRID;
return " (id, strdfgeo,srid) VALUES (?,ST_Transform(ST_GeomFromWKB(?,?),"+srid+"),?)";
}
@Override
public String buildInsertValue(String type) {
return " (id, value) VALUES ( ?, ?) ";
}
@Override
protected String buildCreateTemporaryTable(CharSequence columns) {
StringBuilder sb = new StringBuilder();
sb.append("CREATE TEMPORARY TABLE ").append(getName());
sb.append(" (\n").append(columns).append(")");
return sb.toString();
}
@Override
public String buildDummyFromAndWhere(String fromDummy) {
StringBuilder sb = new StringBuilder(256);
sb.append(fromDummy);
sb.append("\nWHERE 1=0");
return sb.toString();
}
@Override
public String buildDynamicParameterInteger() {
return "?";
}
@Override
public String buildWhere() {
return " WHERE (1=1) ";
}
} | mpl-2.0 |
essar/prials-and-runs | src/test/java/uk/co/essarsoftware/par/engine/std/PlayerImplWithHandTest.java | 3147 | /*
* Copyright (c) 2012 Steve Roberts / Essar Software. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package uk.co.essarsoftware.par.engine.std;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uk.co.essarsoftware.games.cards.Card;
import uk.co.essarsoftware.games.cards.CardArray;
import uk.co.essarsoftware.games.cards.TestPack;
import uk.co.essarsoftware.par.engine.CardNotFoundException;
import uk.co.essarsoftware.par.engine.DuplicateCardException;
import uk.co.essarsoftware.par.engine.Player;
import uk.co.essarsoftware.par.engine.PlayerState;
import java.util.Arrays;
import static org.junit.Assert.*;
/**
* Created with IntelliJ IDEA.
* User: sroberts
* Date: 05/06/12
* Time: 13:14
* To change this template use File | Settings | File Templates.
*/
public class PlayerImplWithHandTest extends PlayerImplTest
{
private Card newCard1, newCard2;
private CardArray hand, newHand;
static {
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.ERROR);
Logger.getLogger(Player.class).setLevel(Level.DEBUG);
}
public PlayerImplWithHandTest() {
super();
newCard1 = Card.createCard(Card.Suit.SPADES, Card.Value.ACE);
newCard2 = Card.createCard(Card.Suit.DIAMONDS, Card.Value.FIVE);
// Register playCards with pack
TestPack tp = new TestPack();
tp.add(newCard1);
tp.add(newCard2);
newCard1 = tp.findCard(newCard1);
newCard2 = tp.findCard(newCard2);
hand = new CardArray();
hand.add(card);
newHand = new CardArray();
newHand.add(newCard1);
newHand.add(newCard2);
}
@Override@Before
public void setUp() {
super.setUp();
underTest.deal(hand);
assertEquals("setUp: hand", 1, underTest.getHandSize());
}
@Override@Test
public void testDefaultHand() {
assertEquals("Hand", 1, underTest.getHand().length);
assertEquals("Hand size", 1, underTest.getHandSize());
}
@Test
public void testDealHand() {
underTest.deal(newHand);
assertEquals("Hand size", 2, underTest.getHandSize());
assertNotContains("Old card no longer in hand", card, underTest.getHand());
assertContains("New card in hand", newCard1, underTest.getHand());
}
@Override@Test
public void testDiscard8C() throws CardNotFoundException {
underTest.discard(card);
assertNotContains("Card no longer in hand", card, underTest.getHand());
assertEquals("Hand size", 0, underTest.getHandSize());
}
@Override@Test(expected = DuplicateCardException.class)
public void testPickup8C() throws DuplicateCardException {
underTest.pickup(card);
fail("Picked up duplicate card, expected DuplicateCardException");
}
}
| mpl-2.0 |
tntim96/rhino-jscover-repackaged | src/jscover/mozilla/javascript/ast/IfStatement.java | 4530 | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package jscover.mozilla.javascript.ast;
import jscover.mozilla.javascript.Token;
/**
* If-else statement. Node type is {@link Token#IF}.<p>
*
* <pre><i>IfStatement</i> :
* <b>if</b> ( Expression ) Statement <b>else</b> Statement
* <b>if</b> ( Expression ) Statement</pre>
*/
public class IfStatement extends AstNode {
private AstNode condition;
private AstNode thenPart;
private int elsePosition = -1;
private AstNode elsePart;
private int lp = -1;
private int rp = -1;
{
type = Token.IF;
}
public IfStatement() {
}
public IfStatement(int pos) {
super(pos);
}
public IfStatement(int pos, int len) {
super(pos, len);
}
/**
* Returns if condition
*/
public AstNode getCondition() {
return condition;
}
/**
* Sets if condition.
* @throws IllegalArgumentException if {@code condition} is {@code null}.
*/
public void setCondition(AstNode condition) {
assertNotNull(condition);
this.condition = condition;
condition.setParent(this);
}
/**
* Returns statement to execute if condition is true
*/
public AstNode getThenPart() {
return thenPart;
}
/**
* Sets statement to execute if condition is true
* @throws IllegalArgumentException if thenPart is {@code null}
*/
public void setThenPart(AstNode thenPart) {
assertNotNull(thenPart);
this.thenPart = thenPart;
thenPart.setParent(this);
}
/**
* Returns statement to execute if condition is false
*/
public AstNode getElsePart() {
return elsePart;
}
/**
* Sets statement to execute if condition is false
* @param elsePart statement to execute if condition is false.
* Can be {@code null}.
*/
public void setElsePart(AstNode elsePart) {
this.elsePart = elsePart;
if (elsePart != null)
elsePart.setParent(this);
}
/**
* Returns position of "else" keyword, or -1
*/
public int getElsePosition() {
return elsePosition;
}
/**
* Sets position of "else" keyword, -1 if not present
*/
public void setElsePosition(int elsePosition) {
this.elsePosition = elsePosition;
}
/**
* Returns left paren offset
*/
public int getLp() {
return lp;
}
/**
* Sets left paren offset
*/
public void setLp(int lp) {
this.lp = lp;
}
/**
* Returns right paren position, -1 if missing
*/
public int getRp() {
return rp;
}
/**
* Sets right paren position, -1 if missing
*/
public void setRp(int rp) {
this.rp = rp;
}
/**
* Sets both paren positions
*/
public void setParens(int lp, int rp) {
this.lp = lp;
this.rp = rp;
}
@Override
public String toSource(int depth) {
String pad = makeIndent(depth);
StringBuilder sb = new StringBuilder(32);
sb.append(pad);
sb.append("if (");
sb.append(condition.toSource(0));
sb.append(") ");
if (thenPart.getType() != Token.BLOCK) {
sb.append("\n").append(makeIndent(depth + 1));
}
sb.append(thenPart.toSource(depth).trim());
if (elsePart != null) {
if (thenPart.getType() != Token.BLOCK) {
sb.append("\n").append(pad).append("else ");
} else {
sb.append(" else ");
}
if (elsePart.getType() != Token.BLOCK
&& elsePart.getType() != Token.IF) {
sb.append("\n").append(makeIndent(depth + 1));
}
sb.append(elsePart.toSource(depth).trim());
}
sb.append("\n");
return sb.toString();
}
/**
* Visits this node, the condition, the then-part, and
* if supplied, the else-part.
*/
@Override
public void visit(NodeVisitor v) {
if (v.visit(this)) {
condition.visit(v);
thenPart.visit(v);
if (elsePart != null) {
elsePart.visit(v);
}
}
}
}
| mpl-2.0 |
hserv/coordinated-entry | housing-matching/src/main/java/com/hserv/coordinatedentry/housingmatching/external/HousingUnitService.java | 553 | package com.hserv.coordinatedentry.housingmatching.external;
import java.util.List;
import com.hserv.coordinatedentry.housingmatching.model.EligibilityRequirementModel;
import com.hserv.coordinatedentry.housingmatching.model.HousingInventory;
import com.servinglynk.hmis.warehouse.core.model.Session;
public interface HousingUnitService {
List<HousingInventory> getHousingInventoryList(Session session, String trustedAppId);
List<EligibilityRequirementModel> getEligibilityRequirements(Session session, String trustedAppId);
}
| mpl-2.0 |
llggkk1117/TextFile | src/org/gene/modules/textFile/Test.java | 2697 | package org.gene.modules.textFile;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Scanner;
public class Test
{
public static void fileRead1()
{
try{
FileInputStream fis = new FileInputStream(new File("resource/bible/Korean/개역개정/01창세기.txt"));
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
BufferedReader br = new BufferedReader(isr);
while(true){
String str = br.readLine();
if(str==null) break;
System.out.println(str);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void fileRead2()
{
Scanner s = null;
try{
s = new Scanner(new File("sample2.txt"),"UTF-8");
while(true){
String str = s.nextLine();
System.out.println(str);
}
}catch(Exception e){
s.close();
}
}
public static void fileRead3() throws IOException
{
RandomAccessFile file = new RandomAccessFile("sample2.txt", "rwd");
String line = file.readLine();
file.close();
// line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
line = new String(line.getBytes("8859_1"), "UTF-8");
System.out.println(line);
}
public static void fileWrite()
{
try {
String srcText = new String("UTF-8 파일을 생성합니다.");
File targetFile = new File("D:\\output.txt");
targetFile.createNewFile();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile.getPath()), "UTF8"));
output.write(srcText);
output.close();
} catch(UnsupportedEncodingException uee) {
uee.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
public static void fileWrite2(){
try {
File fileDir = new File("sample");
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileDir), "UTF8"));
out.append("으하하").append("\r\n");
out.flush();
out.close();
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws IOException
{
// fileRead3();
}
}
| mpl-2.0 |
Skelril/Skree | src/main/java/com/skelril/skree/content/registry/item/tool/axe/CrystalAxe.java | 1351 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.skelril.skree.content.registry.item.tool.axe;
import com.skelril.nitro.registry.ItemTier;
import com.skelril.nitro.registry.item.ItemTiers;
import com.skelril.nitro.registry.item.ItemToolTypes;
import com.skelril.nitro.registry.item.axe.CustomAxe;
import net.minecraft.item.ItemStack;
import static com.skelril.nitro.item.ItemStackFactory.newItemStack;
public class CrystalAxe extends CustomAxe {
@Override
public String __getType() {
return "crystal";
}
@Override
public ItemStack __getRepairItemStack() {
return (ItemStack) (Object) newItemStack("skree:sea_crystal");
}
@Override
public double __getHitPower() {
return ItemTiers.CRYSTAL.getDamage() + ItemToolTypes.AXE.getBaseDamage();
}
@Override
public int __getEnchantability() {
return ItemTiers.CRYSTAL.getEnchantability();
}
@Override
public ItemTier __getHarvestTier() {
return ItemTiers.CRYSTAL;
}
@Override
public float __getSpecializedSpeed() {
return ItemTiers.CRYSTAL.getEfficienyOnProperMaterial();
}
@Override
public int __getMaxUses() {
return ItemTiers.CRYSTAL.getDurability();
}
}
| mpl-2.0 |
tfearn/AdaptinetSDK | src/org/adaptinet/peer/PeerFile.java | 2831 | /**
* Copyright (C), 2012 Adaptinet.org (Todd Fearn, Anthony Graffeo)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
package org.adaptinet.peer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.adaptinet.peer.PeerRoot;
public class PeerFile {
private static final String DEFAULT = "DefaultPeers.xml";
private boolean bOpen = false;
private File file;
private boolean bDefault = false;
private boolean bDirty = false;
public boolean isOpen() {
return bOpen;
}
public void setOpen(boolean bOpen) {
this.bOpen = bOpen;
}
public boolean isDefault() {
return bDefault;
}
public void setDefault(boolean bDefault) {
this.bDefault = bDefault;
}
public boolean isDirty() {
return bDirty;
}
public void setDirty(boolean bDirty) {
this.bDirty = bDirty;
}
public void openFile(final String name) throws Exception {
}
public PeerRoot open() throws Exception {
this.bDefault = true;
return open(DEFAULT);
}
public PeerRoot open(String name) throws Exception {
if (name == null || name.length() == 0) {
return open();
}
PeerRoot tmpRoot = new PeerRoot();
FileInputStream fis = null;
try {
if (name.equalsIgnoreCase(DEFAULT)) {
File defaultfile = new File(name);
bDefault = true;
if (!file.exists()) {
throw new IOException(
"error Default peer file does not exist.");
}
fis = new FileInputStream(defaultfile);
} else {
file = new File(name);
if (!file.exists()) {
new File(name.substring(0, name
.lastIndexOf(File.separatorChar))).mkdirs();
file.createNewFile();
}
fis = new FileInputStream(file);
bOpen = true;
}
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
tmpRoot.parsePeers(bytes);
// Check to see if there are any peers if not go to the default
// peer file that should have been included in the installation
if (tmpRoot.count() < 1 && !bDefault) {
return open();
}
return tmpRoot;
} catch (IOException x) {
x.printStackTrace();
throw x;
} finally {
if (fis != null) {
fis.close();
}
}
}
public void close() {
bOpen = false;
}
public void save(String data) throws IOException {
FileOutputStream fos = null;
try {
file.renameTo(new File(file.getName() + "~"));
fos = new FileOutputStream(file);
fos.write(data.getBytes());
bDirty = false;
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.close();
}
}
}
| mpl-2.0 |
diging/qstore4s | QStore4S/src/main/java/edu/asu/qstore4s/search/elements/factory/impl/SearchConceptFactory.java | 737 | package edu.asu.qstore4s.search.elements.factory.impl;
import org.springframework.stereotype.Service;
import edu.asu.qstore4s.search.elements.ISearchConcept;
import edu.asu.qstore4s.search.elements.factory.ISearchConceptFactory;
import edu.asu.qstore4s.search.elements.impl.SearchConcept;
@Service
public class SearchConceptFactory implements ISearchConceptFactory {
@Override
public ISearchConcept createSearchConcept()
{
ISearchConcept conceptObject = new SearchConcept();
return conceptObject;
}
@Override
public ISearchConcept createSearchConcept(String sourceUri)
{
ISearchConcept conceptObject = new SearchConcept();
conceptObject.setSourceURI(sourceUri == null ? "" : sourceUri);
return conceptObject;
}
}
| mpl-2.0 |
CloudyPadmal/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/injection/component/ActivityComponent.java | 7297 | package com.mifos.mifosxdroid.injection.component;
import com.mifos.mifosxdroid.activity.pathtracking.PathTrackingActivity;
import com.mifos.mifosxdroid.activity.pinpointclient.PinpointClientActivity;
import com.mifos.mifosxdroid.dialogfragments.chargedialog.ChargeDialogFragment;
import com.mifos.mifosxdroid.dialogfragments.datatablerowdialog.DataTableRowDialogFragment;
import com.mifos.mifosxdroid.dialogfragments.documentdialog.DocumentDialogFragment;
import com.mifos.mifosxdroid.dialogfragments.identifierdialog.IdentifierDialogFragment;
import com.mifos.mifosxdroid.dialogfragments.loanaccountapproval.LoanAccountApproval;
import com.mifos.mifosxdroid.dialogfragments.loanaccountdisbursement.LoanAccountDisbursement;
import com.mifos.mifosxdroid.dialogfragments.loanchargedialog.LoanChargeDialogFragment;
import com.mifos.mifosxdroid.dialogfragments.savingsaccountapproval.SavingsAccountApproval;
import com.mifos.mifosxdroid.dialogfragments.syncclientsdialog.SyncClientsDialogFragment;
import com.mifos.mifosxdroid.dialogfragments.syncgroupsdialog.SyncGroupsDialogFragment;
import com.mifos.mifosxdroid.injection.PerActivity;
import com.mifos.mifosxdroid.injection.module.ActivityModule;
import com.mifos.mifosxdroid.login.LoginActivity;
import com.mifos.mifosxdroid.offline.offlinedashbarod.OfflineDashboardFragment;
import com.mifos.mifosxdroid.offline.syncclientpayloads.SyncClientPayloadsFragment;
import com.mifos.mifosxdroid.offline.syncgrouppayloads.SyncGroupPayloadsFragment;
import com.mifos.mifosxdroid.offline.syncloanrepaymenttransacition.SyncLoanRepaymentTransactionFragment;
import com.mifos.mifosxdroid.offline.syncsavingsaccounttransaction.SyncSavingsAccountTransactionFragment;
import com.mifos.mifosxdroid.online.centerlist.CenterListFragment;
import com.mifos.mifosxdroid.online.clientcharge.ClientChargeFragment;
import com.mifos.mifosxdroid.online.clientdetails.ClientDetailsFragment;
import com.mifos.mifosxdroid.online.clientidentifiers.ClientIdentifiersFragment;
import com.mifos.mifosxdroid.online.clientlist.ClientListFragment;
import com.mifos.mifosxdroid.online.datatablelistfragment.DataTableListFragment;
import com.mifos.mifosxdroid.online.search.SearchFragment;
import com.mifos.mifosxdroid.online.collectionsheet.CollectionSheetFragment;
import com.mifos.mifosxdroid.online.createnewcenter.CreateNewCenterFragment;
import com.mifos.mifosxdroid.online.createnewclient.CreateNewClientFragment;
import com.mifos.mifosxdroid.online.createnewgroup.CreateNewGroupFragment;
import com.mifos.mifosxdroid.online.datatabledata.DataTableDataFragment;
import com.mifos.mifosxdroid.online.documentlist.DocumentListFragment;
import com.mifos.mifosxdroid.online.generatecollectionsheet.GenerateCollectionSheetFragment;
import com.mifos.mifosxdroid.online.groupdetails.GroupDetailsFragment;
import com.mifos.mifosxdroid.online.grouplist.GroupListFragment;
import com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment;
import com.mifos.mifosxdroid.online.groupslist.GroupsListFragment;
import com.mifos.mifosxdroid.online.loanaccount.LoanAccountFragment;
import com.mifos.mifosxdroid.online.loanaccountsummary.LoanAccountSummaryFragment;
import com.mifos.mifosxdroid.online.loancharge.LoanChargeFragment;
import com.mifos.mifosxdroid.online.loanrepayment.LoanRepaymentFragment;
import com.mifos.mifosxdroid.online.loanrepaymentschedule.LoanRepaymentScheduleFragment;
import com.mifos.mifosxdroid.online.loantransactions.LoanTransactionsFragment;
import com.mifos.mifosxdroid.online.savingaccountsummary.SavingsAccountSummaryFragment;
import com.mifos.mifosxdroid.online.savingaccounttransaction.SavingsAccountTransactionFragment;
import com.mifos.mifosxdroid.online.savingsaccount.SavingsAccountFragment;
import com.mifos.mifosxdroid.online.surveylist.SurveyListFragment;
import com.mifos.mifosxdroid.online.surveysubmit.SurveySubmitFragment;
import dagger.Component;
/**
* @author Rajan Maurya
* This component inject dependencies to all Activities across the application
*/
@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {
void inject(LoginActivity loginActivity);
void inject(CenterListFragment centerListFragment);
void inject(ClientChargeFragment clientChargeFragment);
void inject(ClientListFragment clientListFragment);
void inject(ClientIdentifiersFragment clientIdentifiersFragment);
void inject(SearchFragment clientSearchFragment);
void inject(DocumentListFragment documentListFragment);
void inject(GroupListFragment groupListFragment);
void inject(GenerateCollectionSheetFragment generateCollectionSheetFragment);
void inject(CreateNewCenterFragment createNewCenterFragment);
void inject(CreateNewGroupFragment createNewGroupFragment);
void inject(CreateNewClientFragment createNewClientFragment);
void inject(DataTableDataFragment dataTableDataFragment);
void inject(GroupDetailsFragment groupDetailsFragment);
void inject(ClientDetailsFragment clientDetailsFragment);
void inject(LoanAccountSummaryFragment loanAccountSummaryFragment);
void inject(SavingsAccountSummaryFragment savingsAccountSummaryFragment);
void inject(LoanChargeFragment loanChargeFragment);
void inject(SavingsAccountTransactionFragment savingsAccountTransactionFragment);
void inject(CollectionSheetFragment collectionSheetFragment);
void inject(GroupsListFragment groupsListFragment);
void inject(LoanTransactionsFragment loanTransactionsFragment);
void inject(SavingsAccountFragment savingsAccountFragment);
void inject(LoanRepaymentFragment loanRepaymentFragment);
void inject(GroupLoanAccountFragment groupLoanAccountFragment);
void inject(LoanAccountFragment loanAccountFragment);
void inject(LoanRepaymentScheduleFragment loanRepaymentScheduleFragment);
void inject(SurveyListFragment surveyListFragment);
void inject(SurveySubmitFragment surveySubmitFragment);
void inject(PinpointClientActivity pinpointClientActivity);
void inject(ChargeDialogFragment chargeDialogFragment);
void inject(DataTableRowDialogFragment dataTableRowDialogFragment);
void inject(DataTableListFragment dataTableListFragment);
void inject(DocumentDialogFragment documentDialogFragment);
void inject(LoanAccountApproval loanAccountApproval);
void inject(LoanAccountDisbursement loanAccountDisbursement);
void inject(LoanChargeDialogFragment loanChargeDialogFragment);
void inject(SavingsAccountApproval savingsAccountApproval);
void inject(SyncClientPayloadsFragment syncPayloadsFragment);
void inject(SyncGroupPayloadsFragment syncGroupPayloadsFragment);
void inject(OfflineDashboardFragment offlineDashboardFragment);
void inject(SyncLoanRepaymentTransactionFragment syncLoanRepaymentTransactionFragment);
void inject(SyncClientsDialogFragment syncClientsDialogFragment);
void inject(SyncSavingsAccountTransactionFragment syncSavingsAccountTransactionFragment);
void inject(SyncGroupsDialogFragment syncGroupsDialogFragment);
void inject(IdentifierDialogFragment identifierDialogFragment);
void inject(PathTrackingActivity pathTrackingActivity);
}
| mpl-2.0 |
hintjens/Canvas | app/src/main/java/com/codejockey/canvas/helperfiles/Drawing.java | 23382 | package com.codejockey.canvas.com.codejockey.canvas.helperfiles;
/* Canvas Drawing class
Accepts touch events and draws curves on a canvas. Solves these
major problems:
* Smooths jagged lines by drawing b-spline curves between sample
points.
* Snaps curve start and end points to the border to make it easier
to draw closed areas.
* Snaps curve end to curve start, if user drew a shape, to make it
easier to draw closed shapes.
* Adjusts curve thickness based on drawing velocity, so that slow
drawing creates thinner lines.
* Smooths curve thickness by removing outliers (some devices have
peaky sample rates).
* Allows perfect shape filling by using 100% pixel colors (no anti-
aliasing).
* Draws on larger bitmap, scales down to view size, to allow
zooming and give better image quality.
Algorithm by Pieter Hintjens and Darrin Smith.
*/
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
// Import Magnet API
// import com.samsung.magnet.wrapper.MagnetAgent;
// import com.samsung.magnet.wrapper.MagnetAgentImpl;
// import com.samsung.magnet.wrapper.MagnetAgent.ChannelListener;
// import com.samsung.magnet.wrapper.MagnetAgent.MagnetListener;
// import com.samsung.magnet.wrapper.MagnetAgent.MagnetServiceListener;
// import com.samsung.allshare.canvas.QueueLinearFloodFiller;
public class Drawing
{
private static final String TAG = "CanvasDrawing";
private Context context;
private ImageView imageview;
private Bitmap bitmap;
private Canvas canvas = new Canvas ();
private Paint paint = new Paint ();
// Magnet interface
// private MagnetAgent magnet = new MagnetAgentImpl ();
private String device_id = "";
// Drawing state
private int width;
private int height;
private int ink;
private int paper;
// Ratio of height or width for snaps
private static final float SNAP_MARGIN = 0.04f;
// Snap methods
private static final int SNAP_NONE = 0;
private static final int SNAP_TO_EDGE = 1;
private static final int SNAP_TO_START = 2;
// Snap margins
private int snapmin_x, snapmin_y;
private int snapmax_x, snapmax_y;
// Current drawn curve
private Point curve_start; // Requested starting point
private Point curve_start_snap; // Snapped starting point
private Point curve_end; // Requested ending point
private Point curve_end_snap; // Snapped ending point
private float curve_width; // Current (median) width
private float curve_extent; // Maximum distance from start
// Curve drawing constants
// We vary paintbrush width by at most this much each stroke
// to reduce the effects of event time spikes (affects some devices)
private static final float OUTLIER_TOLERANCE = 0.1f;
// Number of steps we draw between points
private static final int CURVE_STEPS = 30;
// Weight of curve between points
private static final float CURVE_DENSITY = 5.0f;
// Starting point for event sample rate guess
private static final int DIFF_BASELINE = 40;
// Points in curve; we store last four knots
private Point [] knots = new Point [4];
private long last_knot_time = 0;
// Smart invalidation after drawing curve
private float minx, maxx, miny, maxy;
// Median event sample rate, using the baseline as initial guess
private long median_diff = DIFF_BASELINE;
// Replaying to UI, don't process input events
private boolean ui_locked;
// Did we snap the start of the line to the edge?
private boolean start_snapped;
// Each command represents one instruction
// We can replay these from first to last
class command {
// These are the command types we know
public static final int RESET = 1; // Reset drawing
public static final int PAPER = 2; // Set paper color
public static final int INK = 3; // Set ink color
public static final int ERASE = 4; // Erase canvas
public static final int DOWN = 5; // Start a line
public static final int MOVE = 6; // Draw the line
public static final int UP = 7; // Draw the line
public static final int FILL = 8; // Fill an area
private int type;
private int x;
private int y;
private int color;
public command (int type, Point point) {
this.type = type;
this.x = point.x;
this.y = point.y;
}
public command (int type, int x, int y) {
this.type = type;
this.x = x;
this.y = y;
}
public command (int type, int color) {
this.type = type;
this.color = color;
}
}
// List of commands since we started
private List commands = new ArrayList <command> (1000);
public Drawing (Context _context, ImageView _imageview)
{
// Store parent context
context = _context;
imageview = _imageview;
// Create our bitmap drawing area
reset (1200, 1600);
// Set-up paint brush
paint.setStyle (Paint.Style.STROKE);
paint.setStrokeJoin (Paint.Join.ROUND);
paint.setStrokeCap (Paint.Cap.SQUARE);
// Connect to the Magnet network
// magnet.initServiceWithCustomAction ("com.samsung.magnet.service.Canvas",
// context, service_listener);
// magnet.registerPublicChannelListener (channel_listener);
}
public void onTouchEvent (MotionEvent event)
{
if (!gesture_detector.onTouchEvent (event)) {
Point point = get_point (event);
switch (event.getAction ()) {
case MotionEvent.ACTION_DOWN:
commands.add (new command (command.DOWN, point));
down_headless (point);
break;
case MotionEvent.ACTION_MOVE:
commands.add (new command (command.MOVE, point));
move_headless (point);
rect_invalidate ();
break;
case MotionEvent.ACTION_UP:
commands.add (new command (command.UP, point));
up_headless (point);
rect_invalidate ();
break;
}
}
}
// Set the canvas size
public void reset (int _width, int _height)
{
commands.add (new command (command.RESET, _width, _height));
width = _width;
height = _height;
paper = Color.WHITE;
ink = Color.BLACK;
bitmap = Bitmap.createBitmap (width, height, Bitmap.Config.ARGB_8888);
// Calculate snap knots, each time the width/height changes
snapmin_x = (int) (width * SNAP_MARGIN);
snapmin_y = (int) (height * SNAP_MARGIN);
snapmax_x = width - snapmin_x;
snapmax_y = height - snapmin_y;
// Draw the bitmap on the image
canvas.setBitmap (bitmap);
canvas.drawColor (paper);
imageview.setImageBitmap (bitmap);
imageview.setScaleType (ImageView.ScaleType.FIT_XY);
imageview.invalidate ();
}
// Set the drawing ink color
public void setInk (int _ink)
{
commands.add (new command (command.INK, _ink));
ink = _ink;
}
// Set the drawing paper color
public void setPaper (int _paper)
{
commands.add (new command (command.PAPER, _paper));
paper = _paper;
}
// Reset the canvas to the current paper color
public void erase ()
{
commands.add (new command (command.ERASE, paper));
erase_headless ();
}
// Event handlers
// ---------------------------------------------------------------------
/*
private MagnetServiceListener service_listener = new MagnetServiceListener ()
{
@Override
public void onWifiConnectivity () {
device_id = magnet.getLocalName ();
Log.i (TAG, "Magnet onWifiConnectivity received for device ID: " + device_id);
}
@Override
public void onServiceTerminated () {
Log.i (TAG, "Magnet onServiceTerminated received");
}
@Override
public void onServiceNotFound () {
Log.i (TAG, "Magnet onServiceNotFound received");
}
@Override
public void onNoWifiConnectivity () {
Log.i (TAG, "Magnet onNoWifiConnectivity received");
}
@Override
public void onMagnetPeers () {
Log.i (TAG, "Magnet onMagnetPeers received");
}
@Override
public void onMagnetNoPeers () {
Log.i (TAG, "Magnet onMagnetNoPeers received");
}
@Override
public void onInvalidSdk () {
Log.i (TAG, "Magnet onInvalidSdk received");
}
};
private ChannelListener channel_listener = new ChannelListener ()
{
@Override
public void onFailure (int reason) {
Log.i (TAG, "Magnet onFailure received");
}
@Override
public void onFileReceived (
String fromNode, String fromChannel,
String originalName, String hash,
String exchangeId, String type,
long fileSize, String tmp_path) {
Log.i (TAG, "Magnet onFileReceived received");
}
@Override
public void onFileFailed (
String fromNode, String fromChannel,
String originalName, String hash,
String exchangeId, int reason) {
Log.i (TAG, "Magnet onFileFailed received");
}
@Override
public void onDataReceived (
String fromNode, String fromChannel, String type, List<byte[]> payload) {
Log.i (TAG, "Magnet onDataReceived received");
}
@Override
public void onChunkReceived (
String fromNode, String fromChannel,
String originalName, String hash, String exchangeId, String type,
long fileSize, long offset) {
Log.i (TAG, "Magnet onChunkReceived received");
}
@Override
public void onFileNotified (
String arg0, String arg1, String arg2,
String arg3, String arg4, String arg5,
long arg6, String arg7) {
Log.i (TAG, "Magnet onFileNotified received");
}
@Override
public void onJoinEvent (String fromNode, String fromChannel)
{
Log.i (TAG, "Magnet onJoinEvent received, node:" + fromNode + " channel:" + fromChannel);
if (device_id == null) {
Log.i (TAG, "onJoinEvent: E: NULL device ID");
device_id = magnet.getLocalName ();
}
}
@Override
public void onLeaveEvent (String fromNode, String fromChannel) {
Log.i (TAG, "Magnet onLeaveEvent received, node: " + fromNode + " channel: " + fromChannel);
}
};
*/
// Private methods
// ---------------------------------------------------------------------
private GestureDetector gesture_detector = new GestureDetector (
new GestureDetector.SimpleOnGestureListener () {
public boolean onSingleTapUp (MotionEvent event) {
Point point = get_point (event);
commands.add (new command (command.FILL, point));
fill_headless (point);
imageview.invalidate ();
vibrate ();
return true;
}
public void onLongPress (MotionEvent event) {
new replay_commands ().execute ("nothing");
}
}
);
// Headless methods do not create any command history
// Thus they can safely be called to replay commands
private void erase_headless ()
{
canvas.drawColor (paper);
}
// Start a new line
private void down_headless (Point point)
{
curve_start = point;
curve_start_snap = snap (point, SNAP_TO_EDGE);
curve_extent = 0;
if (curve_start.equals (curve_start_snap))
curve_open (curve_start);
else {
curve_open (curve_start_snap);
curve_move (curve_start);
}
}
// Continue the line
private void move_headless (Point point)
{
curve_move (point);
// Track the extent of the curve to help us decide whether to
// close the shape automatically.
float extent = distance (point, curve_start);
if (curve_extent < extent)
curve_extent = extent;
}
// End the line
private void up_headless (Point point)
{
// Snap the end of the curve back to the start if close enough
// but only if the start wasn't itself snapped to the edge.
curve_end = point;
if (curve_start.equals (curve_start_snap))
curve_end_snap = snap (point, SNAP_TO_START);
else
curve_end_snap = snap (point, SNAP_TO_EDGE);
if (curve_end.equals (curve_end_snap))
curve_close (curve_end);
else {
curve_move (curve_end);
curve_close (curve_end_snap);
}
}
// Fill the selected area with the current ink color
public void fill_headless (Point point)
{
int targetColor = bitmap.getPixel (point.x, point.y);
QueueLinearFloodFiller filler = new QueueLinearFloodFiller (bitmap, targetColor, ink);
filler.setTolerance (25);
filler.floodFill (point.x, point.y);
}
// Convert motion event coordinates into point in our drawing
private Point get_point (MotionEvent event)
{
Point point = new Point ();
point.x = (int) (event.getX () * width / imageview.getWidth ());
point.y = (int) (event.getY () * height / imageview.getHeight ());
return point;
}
// Return point with snap if requested
private Point snap (Point point, int mode)
{
if (mode == SNAP_TO_EDGE) {
if (point.x < snapmin_x)
point.x = 0;
else
if (point.x > snapmax_x)
point.x = width;
if (point.y < snapmin_y)
point.y = 0;
else
if (point.y > snapmax_y)
point.y = height;
}
else
if (mode == SNAP_TO_START) {
// Snap back to start if start didn't move to edge.
// We snap back if we're less than 50% of the curve
// extent away from the starting point, i.e. we made
// some kind of shape. Ending point must also be
// reasonably close to starting point.
float extent = distance (curve_start, point);
if (curve_start.equals (curve_start_snap)
&& extent < curve_extent / 2.0f
&& extent < snapmin_x + snapmin_y)
point = curve_start;
else
point = snap (point, SNAP_TO_EDGE);
}
return point;
}
// Calculate distance in pixels between two knots
private float distance (Point p1, Point p2)
{
float distance = (float) Math.sqrt (
(p2.x - p1.x) * (p2.x - p1.x)
+ (p2.y - p1.y) * (p2.y - p1.y));
return distance;
}
// Plots a b-spline curve through the last four knots of the curve
// Based on Section 4.2 of Ammeraal, L. (1998) Computer Graphics for
// Java Programmers, Chichester: John Wiley.
//
private void curve_open (Point knot)
{
// Load up our knots with our start position.
// This solves two problems; one that we need at least 4
// knots to draw a curve and two, that we lose the first
// point unless we repeat it three times.
knots [1] = knot;
knots [2] = knot;
knots [3] = knot;
last_knot_time = System.currentTimeMillis ();
curve_width = 2.0f;
}
private void curve_move (Point knot)
{
// Adds a knot and draws the curve. Since we've preloaded
// the knots in curve_open this will draw between two or
// more points (aka knot in b-spline jargon).
knots [0] = knots [1];
knots [1] = knots [2];
knots [2] = knots [3];
knots [3] = knot;
// Sample rates range from 60-100 msecs depending on the device
// We estimate a rolling median using the simple technique of
// taking each new value; if it's larger than sample rate, add
// 1 to sample rate and if it's smaller, subtract 1.
long this_knot_time = System.currentTimeMillis ();
long time_diff = this_knot_time - last_knot_time;
if (time_diff > 10)
median_diff += median_diff > time_diff? -1: 1;
last_knot_time = this_knot_time;
curve_plot ();
}
private void curve_close (Point knot)
{
// Close the curve, drawing the end three times to ensure
// the curve is fully connected; otherwise the actual end
// point won't be drawn (the curve will stop just short).
curve_move (knot);
curve_move (knot);
curve_move (knot);
}
// We always draw the last 4 knots
private void curve_plot ()
{
// We take DIFF_BASELINE msec as being our "normal" sample
// rate. On slower screens the lines will otherwise be too fat.
float compensation = (float)
median_diff / DIFF_BASELINE / CURVE_STEPS * CURVE_DENSITY;
float x1 = -1;
float y1 = -1;
float a0 = (knots [0].x + 4 * knots [1].x + knots [2].x) / 6;
float b0 = (knots [0].y + 4 * knots [1].y + knots [2].y) / 6;
float a1 = (knots [2].x - knots [0].x) / 2;
float b1 = (knots [2].y - knots [0].y) / 2;
float a2 = (knots [0].x - 2 * knots [1].x + knots [2].x) / 2;
float b2 = (knots [0].y - 2 * knots [1].y + knots [2].y) / 2;
float a3 = (knots [3].x - knots [0].x + 3 * (knots [1].x - knots [2].x)) / 6;
float b3 = (knots [3].y - knots [0].y + 3 * (knots [1].y - knots [2].y)) / 6;
rect_reset ();
for (int step = 0; step <= CURVE_STEPS; step++) {
float x0 = x1;
float y0 = y1;
float t = (float) step / (float) CURVE_STEPS;
x1 = ((a3 * t + a2) * t + a1) * t + a0;
y1 = ((b3 * t + b2) * t + b1) * t + b0;
if (x0 != -1) {
float distance = (float) Math.sqrt ((x1 - x0) * (x1 - x0)
+ (y1 - y0) * (y1 - y0));
if (distance > 0) {
float target_width = (float) distance / compensation + 1.0f;
if (target_width > curve_width)
curve_width += OUTLIER_TOLERANCE;
else
curve_width -= OUTLIER_TOLERANCE;
paint.setStrokeWidth (curve_width);
paint.setColor (ink);
canvas.drawLine (x0, y0, x1, y1, paint);
rect_stretch (x0, y0, x1, y1);
}
}
}
}
// Reset invalidation rectangle
private void rect_reset ()
{
minx = width;
maxx = -1;
miny = height;
maxy = -1;
}
private void rect_stretch (float x0, float y0, float x1, float y1)
{
if (minx > x0 - curve_width)
minx = x0 - curve_width;
if (miny > y0 - curve_width)
miny = y0 - curve_width;
if (maxx < x1 + curve_width)
maxx = x1 + curve_width;
if (maxy < y1 + curve_width)
maxy = y1 + curve_width;
}
private void rect_invalidate ()
{
// Adjust rectangle for imageview only the affected rectangle
minx = minx / width * imageview.getWidth ();
maxx = maxx / width * imageview.getWidth ();
miny = miny / height * imageview.getHeight ();
maxy = maxy / height * imageview.getHeight ();
if (maxx > minx && maxy > miny)
imageview.invalidate ((int) minx, (int) miny, (int) maxx, (int) maxy);
}
private void vibrate ()
{
Vibrator mVibrator;
mVibrator = (Vibrator) context.getSystemService (Context.VIBRATOR_SERVICE);
mVibrator.vibrate (10);
}
private class replay_commands extends AsyncTask <String, Bitmap, String> {
protected void onPreExecute () {
ui_locked = true;
}
protected String doInBackground (String... params) {
Bitmap offscreen = Bitmap.createBitmap (width, height, Bitmap.Config.ARGB_8888);
canvas.setBitmap (offscreen);
ListIterator iterator = commands.listIterator ();
while (iterator.hasNext ()) {
command cmd = (command) iterator.next ();
switch (cmd.type) {
case command.RESET:
erase_headless ();
break;
case command.PAPER:
paper = cmd.color;
break;
case command.INK:
ink = cmd.color;
break;
case command.ERASE:
erase_headless ();
break;
case command.DOWN:
down_headless (new Point (cmd.x, cmd.y));
break;
case command.MOVE:
move_headless (new Point (cmd.x, cmd.y));
break;
case command.UP:
up_headless (new Point (cmd.x, cmd.y));
break;
case command.FILL:
fill_headless (new Point (cmd.x, cmd.y));
break;
}
Bitmap onscreen = Bitmap.createBitmap (offscreen);
publishProgress (onscreen);
}
return null;
}
protected void onProgressUpdate (Bitmap... onscreen) {
imageview.setImageBitmap (onscreen [0]);
imageview.invalidate ();
}
protected void onPostExecute (String result) {
ui_locked = false;
}
}
private void trace (String s, Point p)
{
Log.d (TAG, s + " " + p.x + "/" + p.y);
}
}
| mpl-2.0 |
origocms/origo | modules/core/app/main/origo/core/utils/ExceptionUtil.java | 1459 | package main.origo.core.utils;
import main.origo.core.InitializationException;
import main.origo.core.ModuleException;
import play.Logger;
import play.Play;
public class ExceptionUtil {
/**
* Transforms a nested exception into a simple runtime exception and throws it if in DEV mode.
* Only logs the exception if in PROD mode.
* @param e
* @return
*/
public static void assertExceptionHandling(Exception e) {
if (Play.isDev()) {
Throwable thrown = e;
while(thrown instanceof RuntimeException && thrown.getCause() != null) {
thrown = thrown.getCause();
}
if (thrown instanceof RuntimeException) {
throw (RuntimeException)thrown;
}
throw new RuntimeException(thrown);
}
Logger.error("An exception occurred while loading: " + e.getMessage(), e);
}
public static RuntimeException getCause(Throwable e) {
Throwable thrown = e;
while(thrown.getCause() != null &&
(thrown instanceof InitializationException ||
thrown instanceof ModuleException ||
thrown instanceof RuntimeException)) {
thrown = thrown.getCause();
}
if (thrown instanceof RuntimeException) {
throw (RuntimeException)thrown;
} else {
throw new RuntimeException(thrown);
}
}
}
| mpl-2.0 |
WolframG/Rhino-Prov-Mod | src/org/mozilla/javascript/orginal/ast/ObjectProperty.java | 3013 | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript.orginal.ast;
import org.mozilla.javascript.orginal.Token;
/**
* AST node for a single name:value entry in an Object literal.
* For simple entries, the node type is {@link Token#COLON}, and
* the name (left side expression) is either a {@link Name}, a
* {@link StringLiteral} or a {@link NumberLiteral}.<p>
*
* This node type is also used for getter/setter properties in object
* literals. In this case the node bounds include the "get" or "set"
* keyword. The left-hand expression in this case is always a
* {@link Name}, and the overall node type is {@link Token#GET} or
* {@link Token#SET}, as appropriate.<p>
*
* The {@code operatorPosition} field is meaningless if the node is
* a getter or setter.<p>
*
* <pre><i>ObjectProperty</i> :
* PropertyName <b>:</b> AssignmentExpression
* <i>PropertyName</i> :
* Identifier
* StringLiteral
* NumberLiteral</pre>
*/
public class ObjectProperty extends InfixExpression {
{
type = Token.COLON;
}
/**
* Sets the node type. Must be one of
* {@link Token#COLON}, {@link Token#GET}, or {@link Token#SET}.
* @throws IllegalArgumentException if {@code nodeType} is invalid
*/
public void setNodeType(int nodeType) {
if (nodeType != Token.COLON
&& nodeType != Token.GET
&& nodeType != Token.SET)
throw new IllegalArgumentException("invalid node type: "
+ nodeType);
setType(nodeType);
}
public ObjectProperty() {
}
public ObjectProperty(int pos) {
super(pos);
}
public ObjectProperty(int pos, int len) {
super(pos, len);
}
/**
* Marks this node as a "getter" property.
*/
public void setIsGetter() {
type = Token.GET;
}
/**
* Returns true if this is a getter function.
*/
public boolean isGetter() {
return type == Token.GET;
}
/**
* Marks this node as a "setter" property.
*/
public void setIsSetter() {
type = Token.SET;
}
/**
* Returns true if this is a setter function.
*/
public boolean isSetter() {
return type == Token.SET;
}
@Override
public String toSource(int depth) {
StringBuilder sb = new StringBuilder();
sb.append(makeIndent(depth));
if (isGetter()) {
sb.append("get ");
} else if (isSetter()) {
sb.append("set ");
}
sb.append(left.toSource(0));
if (type == Token.COLON) {
sb.append(": ");
}
sb.append(right.toSource(0));
return sb.toString();
}
}
| mpl-2.0 |
michaelknigge/afpbox | afpbox/src/test/java/de/textmode/afpbox/ptoca/SetTextColorTest.java | 1497 | package de.textmode.afpbox.ptoca;
/*
* Copyright 2019 Michael Knigge
*
* 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.
*/
/**
* Unit-Tests for the class {@link SetTextColor}.
*/
public final class SetTextColorTest extends PtocaControlSequenceTest<SetTextColor> {
/**
* Checks if a faulty STC is determined.
*/
public void testFaulty() throws Exception {
this.parseAndExpectFailure("2BD3067400000000",
"PTOCA control sequence STC has invalid length of 6 bytes (expected 4 or 5 bytes)");
}
/**
* Checks some correct STCs.
*/
public void testHappyFlow() throws Exception {
final SetTextColor stc1 = this.parse("2BD30474FF01");
assertEquals(0xFF01, stc1.getForegroundColor());
assertEquals(0x00, stc1.getPrecision());
final SetTextColor stc2 = this.parse("2BD30575010201");
assertEquals(0x0102, stc2.getForegroundColor());
assertEquals(0x01, stc2.getPrecision());
}
}
| mpl-2.0 |
threadly/threadly_benchmarks | src/main/java/org/threadly/concurrent/benchmark/jmh/ImmediateListenableFutureMicro.java | 2460 | package org.threadly.concurrent.benchmark.jmh;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.threadly.concurrent.DoNothingRunnable;
import org.threadly.concurrent.SameThreadSubmitterExecutor;
import org.threadly.concurrent.future.ImmediateFailureListenableFuture;
import org.threadly.concurrent.future.ImmediateResultListenableFuture;
@Fork(MicroBenchmarkRunner.FORKS)
@Warmup(iterations = MicroBenchmarkRunner.WARMUP_ITERATIONS,
time = MicroBenchmarkRunner.WARMUP_SECONDS, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = MicroBenchmarkRunner.RUN_ITERATIONS,
time = MicroBenchmarkRunner.RUN_SECONDS, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.Throughput)
public class ImmediateListenableFutureMicro extends AbstractListenableFutureMicro {
private static final ImmediateResultListenableFuture<Void> RESULT_FUTURE =
new ImmediateResultListenableFuture<>(null);
private static final ImmediateFailureListenableFuture<Void> FAILURE_FUTURE =
new ImmediateFailureListenableFuture<>(FAILURE);
@Benchmark
public void listener_called() {
RESULT_FUTURE.listener(DoNothingRunnable.instance());
}
@Benchmark
public void listener_executed() {
RESULT_FUTURE.listener(DoNothingRunnable.instance(), SameThreadSubmitterExecutor.instance());
}
@Benchmark
public void resultCallback_called() {
RESULT_FUTURE.resultCallback(RESULT_CALLBACK);
}
@Benchmark
public void resultCallback_executed() {
RESULT_FUTURE.resultCallback(RESULT_CALLBACK, SameThreadSubmitterExecutor.instance());
}
@Benchmark
public void map_resultMapped() {
RESULT_FUTURE.map(MAPPRER);
}
@Benchmark
public void map_resultMapExecuted() {
RESULT_FUTURE.map(MAPPRER, SameThreadSubmitterExecutor.instance());
}
@Benchmark
public void map_failureMapped() {
FAILURE_FUTURE.mapFailure(Exception.class, FAILURE_MAPPRER);
}
@Benchmark
public void map_failureMappedExecuted() {
FAILURE_FUTURE.mapFailure(Exception.class, FAILURE_MAPPRER, SameThreadSubmitterExecutor.instance());
}
}
| mpl-2.0 |
OpenSpaceDev/OpenSpaceDVR | src/org/jcodec/containers/mp4/boxes/EditListBox.java | 1602 | package org.jcodec.containers.mp4.boxes;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.jcodec.common.tools.ToJSON;
/**
* This class is part of JCodec ( www.jcodec.org ) This software is distributed
* under FreeBSD License
*
* @author The JCodec project
*
*/
public class EditListBox extends FullBox {
private List<Edit> edits;
public static String fourcc() {
return "elst";
}
public EditListBox(Header atom) {
super(atom);
}
public EditListBox() {
this(new Header(fourcc()));
}
public EditListBox(List<Edit> edits) {
this();
this.edits = edits;
}
public void parse(ByteBuffer input) {
super.parse(input);
edits = new ArrayList<Edit>();
long num = input.getInt();
for (int i = 0; i < num; i++) {
int duration = input.getInt();
int mediaTime = input.getInt();
float rate = input.getInt() / 65536f;
edits.add(new Edit(duration, mediaTime, rate));
}
}
protected void doWrite(ByteBuffer out) {
super.doWrite(out);
out.putInt(edits.size());
for (Edit edit : edits) {
out.putInt((int) edit.getDuration());
out.putInt((int) edit.getMediaTime());
out.putInt((int) (edit.getRate() * 65536));
}
}
public List<Edit> getEdits() {
return edits;
}
public void dump(StringBuilder sb) {
super.dump(sb);
sb.append(": ");
ToJSON.toJSON(this, sb, "edits");
}
}
| mpl-2.0 |
tbouvet/seed | web/websocket/src/it/java/org/seedstack/seed/web/ChatClientEndpoint2.java | 1244 | /**
* Copyright (c) 2013-2015, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.seed.web;
import org.seedstack.seed.web.internal.SeedClientEndpointConfigurator;
import javax.websocket.ClientEndpoint;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
/**
* @author pierre.thirouin@ext.mpsa.com
* Date: 19/12/13
*/
@ClientEndpoint(configurator = SeedClientEndpointConfigurator.class)
public class ChatClientEndpoint2 {
public static final String TEXT = "Client2 joins";
public static CountDownLatch latch;
public static String response;
@OnOpen
public void onOpen(Session session) {
try {
session.getBasicRemote().sendText(TEXT);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
@OnMessage
public void processMessage(String message) {
response = message;
latch.countDown();
}
} | mpl-2.0 |
hyb1996/NoRootScriptDroid | app/src/main/java/org/autojs/autojs/model/script/PathChecker.java | 1807 | package org.autojs.autojs.model.script;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.widget.Toast;
import java.io.File;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
/**
* Created by Stardust on 2017/4/1.
*/
public class PathChecker {
public static final int CHECK_RESULT_OK = 0;
private Context mContext;
public PathChecker(Context context) {
mContext = context;
}
public static int check(final String path) {
if (TextUtils.isEmpty(path))
return com.stardust.autojs.R.string.text_path_is_empty;
if (!new File(path).exists())
return com.stardust.autojs.R.string.text_file_not_exists;
return CHECK_RESULT_OK;
}
public boolean checkAndToastError(String path) {
int result = checkWithStoragePermission(path);
if (result != CHECK_RESULT_OK) {
Toast.makeText(mContext, mContext.getString(result) + ":" + path, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private int checkWithStoragePermission(String path) {
if (mContext instanceof Activity && !hasStorageReadPermission((Activity) mContext)) {
return com.stardust.autojs.R.string.text_no_file_rw_permission;
}
return check(path);
}
private static boolean hasStorageReadPermission(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
activity.checkSelfPermission(READ_EXTERNAL_STORAGE) == PERMISSION_GRANTED;
}
return true;
}
}
| mpl-2.0 |
SilverDav/Silverpeas-Core | core-library/src/main/java/org/silverpeas/core/contribution/content/form/displayers/AbstractFileFieldDisplayer.java | 11829 | /*
* 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.contribution.content.form.displayers;
import org.apache.commons.fileupload.FileItem;
import org.silverpeas.core.contribution.attachment.AttachmentServiceProvider;
import org.silverpeas.core.contribution.attachment.model.DocumentType;
import org.silverpeas.core.contribution.attachment.model.HistorisedDocument;
import org.silverpeas.core.contribution.attachment.model.SimpleAttachment;
import org.silverpeas.core.contribution.attachment.model.SimpleDocument;
import org.silverpeas.core.contribution.attachment.model.SimpleDocumentPK;
import org.silverpeas.core.contribution.content.form.Field;
import org.silverpeas.core.contribution.content.form.FieldTemplate;
import org.silverpeas.core.contribution.content.form.FormException;
import org.silverpeas.core.contribution.content.form.PagesContext;
import org.silverpeas.core.contribution.content.form.Util;
import org.silverpeas.core.contribution.content.form.field.FileField;
import org.silverpeas.core.util.StringUtil;
import org.silverpeas.core.util.WebEncodeHelper;
import org.silverpeas.core.util.file.FileUploadUtil;
import org.silverpeas.core.util.file.FileUtil;
import org.silverpeas.core.util.logging.SilverLogger;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author ehugonnet
*/
public abstract class AbstractFileFieldDisplayer extends AbstractFieldDisplayer<FileField> {
protected static final String OPERATION_KEY = "Operation";
/**
* The different kinds of operation that can be applied into an attached file.
*/
protected enum Operation {
ADD, UPDATE, DELETION
}
protected SimpleDocument createSimpleDocument(String objectId, String componentId, FileItem item,
String fileName, String userId, boolean versionned) throws IOException {
SimpleDocumentPK documentPk = new SimpleDocumentPK(null, componentId);
SimpleAttachment attachment = SimpleAttachment.builder()
.setFilename(fileName)
.setSize(item.getSize())
.setContentType(FileUtil.getMimeType(fileName))
.setCreationData(userId, new Date())
.build();
SimpleDocument document;
if (versionned) {
document = new HistorisedDocument(documentPk, objectId, 0, attachment);
} else {
document = new SimpleDocument(documentPk, objectId, 0, false, null, attachment);
}
document.setDocumentType(DocumentType.form);
try (InputStream in = item.getInputStream()) {
return AttachmentServiceProvider.getAttachmentService()
.createAttachment(document, in, false);
}
}
/**
* Deletes the specified attachment, identified by its unique identifier.?
*
* @param attachmentId the unique identifier of the attachment to delete.
* @param pageContext the context of the page.
*/
protected void deleteAttachment(String attachmentId, PagesContext pageContext) {
SimpleDocumentPK pk = new SimpleDocumentPK(attachmentId, pageContext.getComponentId());
SimpleDocument doc = AttachmentServiceProvider.getAttachmentService().searchDocumentById(pk,
pageContext.getContentLanguage());
if (doc != null) {
AttachmentServiceProvider.getAttachmentService().deleteAttachment(doc);
}
}
/**
* Returns the name of the managed types.
*/
public String[] getManagedTypes() {
return new String[]{FileField.TYPE};
}
/**
* Prints the javascripts which will be used to control the new value given to the named field.
* The error messages may be adapted to a local language. The FieldTemplate gives the field type
* and constraints. The FieldTemplate gives the local labeld too. Never throws an Exception but
* log a silvertrace and writes an empty string when :
* <ul>
* <li>the fieldName is unknown by the template.</li>
* <li>the field type is not a managed type.</li>
* </ul>
*/
@Override
public void displayScripts(final PrintWriter out, final FieldTemplate template,
final PagesContext pageContext) {
checkFieldType(template.getTypeName(), "AbstractFileFieldDisplayer.displayScripts");
String language = pageContext.getLanguage();
String fieldName = template.getFieldName();
String label = WebEncodeHelper.javaStringToJsString(template.getLabel(language));
if (template.isMandatory() && pageContext.useMandatory()) {
out.append(" if (!ignoreMandatory && isWhitespace(stripInitialWhitespace(field.value))) {\n")
.append(" var ").append(fieldName).append("Value = document.getElementById('")
.append(fieldName).append(FileField.PARAM_ID_SUFFIX).append("').value;\n")
.append(" var ").append(fieldName).append("Operation = document.")
.append(pageContext.getFormName()).append(".")
.append(fieldName).append(OPERATION_KEY).append(".value;\n")
.append(" if (").append(fieldName).append("Value=='' || ")
.append(fieldName).append("Operation=='").append(Operation.DELETION.name()).append(
"') {\n")
.append(" errorMsg+=\" - '")
.append(label).append("' ")
.append(Util.getString("GML.MustBeFilled", language)).append("\\n\";\n")
.append(" errorNb++;\n")
.append(" }\n")
.append(" }\n");
}
if (!template.isReadOnly()) {
Util.includeFileNameLengthChecker(template, pageContext, out);
Util.getJavascriptChecker(template.getFieldName(), pageContext, out);
}
}
@Override
public List<String> update(List<FileItem> items, FileField field, FieldTemplate template,
PagesContext pageContext) throws FormException {
List<String> attachmentIds = new ArrayList<>();
String attachmentId = processInput(items, field, pageContext);
attachmentIds.addAll(update(attachmentId, field, template, pageContext));
return attachmentIds;
}
protected String processInput(List<FileItem> items, FileField field, PagesContext pageContext) {
try {
String currentAttachmentId = field.getAttachmentId();
String inputName = Util.getFieldOccurrenceName(field.getName(), field.getOccurrence());
String attachmentId = processUploadedFile(items, inputName, pageContext);
Operation operation = Operation.valueOf(FileUploadUtil.getParameter(items, inputName
+ OPERATION_KEY));
if (!StringUtil.isDefined(attachmentId)) {
// Trying to verify if a link is performed instead of uploading a real file
String fileLinkOnApplication = FileUploadUtil.getParameter(items, inputName
+ Field.FILE_PARAM_NAME_SUFFIX);
if (StringUtil.startsWith(fileLinkOnApplication, "/")) {
// The identifier is a link to a file of an application.
// The attachment identifier becomes the file link.
attachmentId =
isDeletion(operation, fileLinkOnApplication) ? null : fileLinkOnApplication;
}
}
if (!pageContext.isCreation()) {
boolean isDeletionOfCurrent = isDeletion(operation, currentAttachmentId);
boolean isUpdate = StringUtil.isDefined(currentAttachmentId) && StringUtil.isDefined(
attachmentId) && !currentAttachmentId.equals(attachmentId);
boolean isAddOrUpdate = StringUtil.isDefined(attachmentId);
if ((isDeletionOfCurrent || isUpdate) && !StringUtil.startsWith(currentAttachmentId, "/")) {
// Current attachment identifier is a real one and is not a link to a resource of an
// application. So, deleting the previous attachment.
deleteAttachment(currentAttachmentId, pageContext);
} else if (!isAddOrUpdate) {
// Same value
return currentAttachmentId;
}
}
// Add, update, delete or no value
return attachmentId;
} catch (IOException ex) {
SilverLogger.getLogger(this).error(ex);
}
return null;
}
@Override
public List<String> update(String attachmentId, FileField field, FieldTemplate template,
PagesContext pagesContext) throws FormException {
List<String> updated = new ArrayList<>();
if (FileField.TYPE.equals(field.getTypeName())) {
if (!StringUtil.isDefined(attachmentId)) {
field.setNull();
} else {
field.setAttachmentId(attachmentId);
updated.add(attachmentId);
}
} else {
throw new FormException("FileFieldDisplayer.update", "form.EX_NOT_CORRECT_VALUE",
FileField.TYPE);
}
return updated;
}
/**
* Is the specified operation is a deletion?
*
* @param operation the operation.
* @param attachmentId the identifier of the attachment on which the operation is.
* @return true if the operation is a deletion, false otherwise.
*/
protected boolean isDeletion(final Operation operation, final String attachmentId) {
return StringUtil.isDefined(attachmentId) && operation == Operation.DELETION;
}
/**
* Is the specified operation is an update?
*
* @param operation the operation.
* @param attachmentId the identifier of the attachment on which the operation is.
* @return true if the operation is an update, false otherwise.
*/
protected boolean isUpdate(final Operation operation, final String attachmentId) {
return StringUtil.isDefined(attachmentId) && operation == Operation.UPDATE;
}
protected String processUploadedFile(List<FileItem> items, String parameterName,
PagesContext pagesContext) throws IOException {
String attachmentId = null;
FileItem item = FileUploadUtil.getFile(items, parameterName);
if (item != null && !item.isFormField()) {
String componentId = pagesContext.getComponentId();
String userId = pagesContext.getUserId();
String objectId = pagesContext.getObjectId();
if (StringUtil.isDefined(item.getName())) {
String fileName = FileUtil.getFilename(item.getName());
long size = item.getSize();
if (size > 0L) {
SimpleDocument document = createSimpleDocument(objectId, componentId, item, fileName,
userId, false);
attachmentId = document.getId();
}
}
}
return attachmentId;
}
@Override
public boolean isDisplayedMandatory() {
return true;
}
/**
* Checks the type of the field is as expected. The field must be of type file.
*
* @param typeName the name of the type.
* @param contextCall the context of the call: which is the caller of this method. This parameter
* is used for trace purpose.
*/
protected void checkFieldType(final String typeName, final String contextCall) {
// nothing for instance
}
}
| agpl-3.0 |
MCPhoton/Photon-MC1.8 | src/org/mcphoton/util/YamlHelper.java | 19387 | /*
* Copyright (C) 2015 ElectronWill
*
* 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.mcphoton.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
/**
* A utility class to use SnakeYAML easily. It can use path with multiple parts, in particular.
* <h3>How to use paths:</h3>
* <li>A path refer to a key in the Yaml map. The nodes are separated by a char called the
* "separator".
* <li>The separator is a dot '.' by default. Path example: "a.b.keyC"
* <li>"a.b.keyC" refers to a value "keyC" that is in the map "b" that is in an other map "a", that
* is in the global map of the Yaml data:<br>
* a:<br>
* __b:<br>
* ____keyC: keyC's value<br>
* </li>
*
* @see https://code.google.com/p/snakeyaml/wiki/Documentation
* @author ElectronWill
*/
public final class YamlHelper {
/**
* Returns true if the data contains the given path.
*
* @param data root Map containing all values
* @param path value's path
* @return true if the Map contains the value, false otherwise.
*/
public static boolean contains(Map<String, Object> data, String path) {
return contains(data, path, '.');
}
/**
* Returns true if the data contains the given path.
*
* @param data root Map containing all values
* @param path value's path
* @param separator the separator used to parse the path
* @return true if the Map contains the value, false otherwise.
*/
public static boolean contains(Map<String, Object> data, String path, char separator) {
String[] parts = split(path, separator);
if (parts.length == 0) {
Object o = data.get(path);
if (o == null) {
return data.containsKey(path);
}
return true;
}
for (int i = 0; i < parts.length; i++) {
String part = parts[i];
Object o = data.get(part);
if (i == parts.length - 1) {
if (o == null) {
return data.containsKey(part);
}
return true;
}
if (o == null) {
return false;
}
if (o instanceof Map) {
data = (Map<String, Object>) o;
} else {
return false;
}
}
return false;
}
/**
* Returns the requested Object by path, or def if not found.
*
* @param data root Map
* @param path value's path
* @param separator path's separator
* @param def value returned if not found
* @return the value of the given path, or def
*/
public static Object get(Map<String, Object> data, String path, char separator, Object def) {
String[] parts = split(path, separator);
if (parts.length == 0) {
Object o = data.get(path);
if (o == null) {
return data.containsKey(path) ? null : def;
}
return o;
}
for (int i = 0; i < parts.length; i++) {
String part = parts[i];
Object o = data.get(part);
if (i == parts.length - 1) {
if (o == null) {
return data.containsKey(part) ? null : def;
}
return o;
}
if (o == null) {
return def;
}
if (o instanceof Map) {
data = (Map<String, Object>) o;
} else {
return def;
}
}
return def;
}
/**
* Returns the requested Object by path, or null if not found.
*
* @param data root Map
* @param path value's path
* @return the value of the given path, or null
*/
public static Object get(Map<String, Object> data, String path) {
return get(data, path, '.', null);
}
/**
* Returns the requested Date by path, or def if not found.
*
* @param data
* @param path
* @param separator
* @param def
* @return
*/
public static Date getDate(Map<String, Object> data, String path, char separator, Object def) {
return (Date) get(data, path, separator, def);
}
/**
* Returns the requested Date by path, or null if not found.
*
* @param data
* @param path
* @return
*/
public static Date getDate(Map<String, Object> data, String path) {
return (Date) get(data, path, '.', null);
}
/**
* Returns the requested float by path, or def if not found.
*
* @param data
* @param path
* @param separator
* @param def
* @return
*/
public static float getFloat(Map<String, Object> data, String path, char separator, float def) {
return (Float) get(data, path, separator, def);
}
/**
* Returns the requested float by path, or -1 if not found.
*
* @param data
* @param path
* @return
*/
public static float getFloat(Map<String, Object> data, String path) {
return (Float) get(data, path, '.', -1);
}
/**
* Returns the requested int by path, or def if not found.
*
* @param data
* @param path
* @param separator
* @param def
* @return
*/
public static int getInteger(Map<String, Object> data, String path, char separator, int def) {
return (Integer) get(data, path, separator, def);
}
/**
* Returns the requested int by path, or -1 if not found.
*
* @param data
* @param path
* @return
*/
public static int getInteger(Map<String, Object> data, String path) {
return (Integer) get(data, path, '.', -1);
}
/**
* Returns the requested {@code List<Integer>} by path, or def if not found.
*
* @param data
* @param path
* @param separator
* @param def
* @return
*/
public static List<Integer> getIntegerList(Map<String, Object> data, String path, char separator, List<Integer> def) {
return (List<Integer>) get(data, path, separator, def);
}
/**
* Returns the requested {@code List<Integer>} by path, or null if not found.
*
* @param data
* @param path
* @return
*/
public static List<Integer> getIntegerList(Map<String, Object> data, String path) {
return (List<Integer>) get(data, path, '.', null);
}
/**
* Returns the requested {@code List} by path, or def if not found.
*
* @param data
* @param path
* @param separator
* @param def
* @return
*/
public static List getList(Map<String, Object> data, String path, char separator, List def) {
return (List) get(data, path, separator, def);
}
/**
* Returns the requested {@code List} by path, or null if not found.
*
* @param data
* @param path
* @return
*/
public static List getList(Map<String, Object> data, String path) {
return (List) get(data, path, '.', null);
}
/**
* Returns the requested {@code Map<>} by path, or def if not found.
*
* @param data
* @param path
* @param separator
* @param def
* @return
*/
public static Map<String, Object> getMap(Map<String, Object> data, String path, char separator, Map<String, Object> def) {
return (Map<String, Object>) get(data, path, separator, def);
}
/**
* Returns the requested {@code Map} by path, or null if not found.
*
* @param data
* @param path
* @return
*/
public static Map<String, Object> getMap(Map<String, Object> data, String path) {
return (Map<String, Object>) get(data, path, '.', null);
}
/**
* Returns the requested String by path, or def if not found.
*
* @param data
* @param path
* @param separator
* @param def
* @return
*/
public static String getString(Map<String, Object> data, String path, char separator, String def) {
return (String) get(data, path, separator, def);
}
/**
* Returns the requested String by path, or null if not found.
*
* @param data
* @param path
* @return
*/
public static String getString(Map<String, Object> data, String path) {
return (String) get(data, path, '.', null);
}
/**
* Returns the requested {@code List<String>} by path, or def if not found.
*
* @param data
* @param path
* @param separator
* @param def
* @return
*/
public static List<String> getStringList(Map<String, Object> data, String path, char separator, List<String> def) {
return (List<String>) get(data, path, separator, def);
}
/**
* Returns the requested {@code List<String>} by path, or null if not found.
*
* @param data
* @param path
* @return
*/
public static List<String> getStringList(Map<String, Object> data, String path) {
return (List<String>) get(data, path, '.', null);
}
/**
* Returns {@code true} if the given path refers to an existing Date value.
*
* @param data
* @param path
* @return
*/
public static boolean isDate(Map<String, Object> data, String path) {
return get(data, path) instanceof Date;
}
/**
* Returns {@code true} if the given path refers to an existing Date value.
*
* @param data
* @param path
* @param separator
* @return
*/
public static boolean isDate(Map<String, Object> data, String path, char separator) {
return get(data, path, separator, null) instanceof Date;
}
/**
* Returns {@code true} if the given path refers to an existing float value.
*
* @param data
* @param path
* @return
*/
public static boolean isFloat(Map<String, Object> data, String path) {
return get(data, path) instanceof Float;
}
/**
* Returns {@code true} if the given path refers to an existing float value.
*
* @param data
* @param path
* @param separator
* @return
*/
public static boolean isFloat(Map<String, Object> data, String path, char separator) {
return get(data, path, separator, null) instanceof Float;
}
/**
* Returns {@code true} if the given path refers to an existing int value.
*
* @param data
* @param path
* @return
*/
public static boolean isInteger(Map<String, Object> data, String path) {
return get(data, path) instanceof Integer;
}
/**
* Returns {@code true} if the given path refers to an existing int value.
*
* @param data
* @param path
* @param separator
* @return
*/
public static boolean isInteger(Map<String, Object> data, String path, char separator) {
return get(data, path, separator, null) instanceof Integer;
}
/**
* Returns {@code true} if the given path refers to an existing List value.
*
* @param data
* @param path
* @return
*/
public static boolean isList(Map<String, Object> data, String path) {
return get(data, path) instanceof List;
}
/**
* Returns {@code true} if the given path refers to an existing List value.
*
* @param data
* @param path
* @param separator
* @return
*/
public static boolean isList(Map<String, Object> data, String path, char separator) {
return get(data, path, separator, null) instanceof List;
}
/**
* Returns {@code true} if the given path refers to an existing String value.
*
* @param data
* @param path
* @return
*/
public static boolean isString(Map<String, Object> data, String path) {
return get(data, path) instanceof String;
}
/**
* Returns {@code true} if the given path refers to an existing String value.
*
* @param data
* @param path
* @param separator
* @return
*/
public static boolean isString(Map<String, Object> data, String path, char separator) {
return get(data, path, separator, null) instanceof String;
}
/**
* Sets the specified path to the given value.
*
* @param data
* @param path
* @param separator
* @param value
* @return the old value, if any.
*/
public static Object set(Map<String, Object> data, String path, char separator, Object value) {
String[] parts = split(path, separator);
if (parts.length == 0) {
return data.put(path, value);
}
for (int i = 0; i < parts.length; i++) {
String part = parts[i];
Object o = data.get(part);
if (i == parts.length - 1) {
return data.put(part, value);
}
if (o == null) {
throw new YAMLException("The part " + part + " of the path " + path + " does not exist");
}
if (o instanceof Map) {
data = (Map<String, Object>) o;
} else {
throw new YAMLException("The part " + part + " of the path " + path + " is not a Map<String, Object>");
}
}
throw new YAMLException("Unable to set the value at " + path);
}
/**
* Sets the specified path to the given value.
*
* @param data
* @param path
* @param value
* @return the old value, if any.
*/
public static Object set(Map<String, Object> data, String path, Object value) {
return set(data, path, '.', value);
}
/**
* Split a String in several parts, each part delimited by the given separator.
*
* @param str
* @param separator
* @return
*/
public static String[] split(String str, char separator) {
ArrayList<String> list = new ArrayList<>(4);
int i;
while ((i = str.indexOf(separator)) != -1) {
str = str.substring(i);
list.add(str);
}
return list.toArray(new String[list.size()]);
}
private final Map<String, Object> data;
private char separator = '.';
/**
* Creates a new YamlHelper with the given yaml data.
*
* @param ymlData
*/
public YamlHelper(String ymlData) {
Yaml yaml = new Yaml();
data = (Map) yaml.load(ymlData);
}
/**
* Creates a new YamlHelper that will read the file to get yaml data.
*
* @param file
* @throws java.io.FileNotFoundException
*/
public YamlHelper(File file) throws FileNotFoundException {
Yaml yaml = new Yaml();
data = (Map<String, Object>) yaml.load(new FileReader(file));
}
/**
* Creates a new YamlHelper with the given yaml data.
*
* @param yaml
* @param ymlData
*/
public YamlHelper(Yaml yaml, String ymlData) {
data = (Map) yaml.load(ymlData);
}
/**
* Creates a new YamlHelper that will read the file to get yaml data.
*
* @param yaml
* @param file
* @throws java.io.FileNotFoundException
*/
public YamlHelper(Yaml yaml, File file) throws FileNotFoundException {
data = (Map<String, Object>) yaml.load(new FileReader(file));
}
/**
* Creates a new YamlHelper with the given data Map.
*
* @param data
*/
public YamlHelper(Map<String, Object> data) {
this.data = data;
}
/**
* Returns true if the data contains the given path.
*
* @param path
* @return
*/
public boolean contains(String path) {
return contains(data, path, separator);
}
/**
* Returns the requested Object by path, or def if not found.
*
* @param path
* @param def
* @return
*/
public Object get(String path, Object def) {
return get(data, path, separator, def);
}
/**
* Returns the requested Object by path, or null if not found.
*
* @param path
* @return
*/
public Object get(String path) {
return get(data, path, separator, null);
}
/**
* Returns the requested Date by path, or def if not found.
*
* @param path
* @param def
* @return
*/
public Date getDate(String path, Date def) {
return getDate(data, path, separator, def);
}
/**
* Returns the requested Date by path, or null if not found.
*
* @param path
* @return
*/
public Date getDate(String path) {
return getDate(data, path, separator, null);
}
/**
* Returns the requested String by path, or def if not found.
*
* @param path
* @param def
* @return
*/
public String getString(String path, String def) {
return getString(data, path, separator, def);
}
/**
* Returns the requested String by path, or null if not found.
*
* @param path
* @return
*/
public String getString(String path) {
return getString(data, path, separator, null);
}
/**
* Returns the requested float by path, or def if not found.
*
* @param path
* @param def
* @return
*/
public float getFloat(String path, float def) {
return getFloat(data, path, separator, def);
}
/**
* Returns the requested float by path, or -1 if not found.
*
* @param path
* @return
*/
public float getFloat(String path) {
return getFloat(data, path, separator, -1);
}
/**
* Returns the requested int by path, or def if not found.
*
* @param path
* @param def
* @return
*/
public int getInteger(String path, int def) {
return getInteger(data, path, separator, def);
}
/**
* Returns the requested int by path, or -1 if not found.
*
* @param path
* @return
*/
public int getInteger(String path) {
return getInteger(data, path, separator, -1);
}
/**
* Returns the requested List by path, or def if not found.
*
* @param path
* @param def
* @return
*/
public List getList(String path, List def) {
return getList(data, path, separator, def);
}
/**
* Returns the requested List by path, or null if not found.
*
* @param path
* @return
*/
public List getList(String path) {
return getList(data, path, separator, null);
}
/**
* Returns the requested Map by path, or def if not found.
*
* @param path
* @param def
* @return
*/
public Map<String, Object> getMap(String path, Map<String, Object> def) {
return getMap(data, path, separator, def);
}
/**
* Returns the requested Map by path, or null if not found.
*
* @param path
* @return
*/
public Map<String, Object> getMap(String path) {
return getMap(data, path, separator, null);
}
/**
* Returns the current path separator.
*
* @return
*/
public char getSeparator() {
return separator;
}
/**
* Sets the path separator.
*
* @param separator
*/
public void setSeparator(char separator) {
this.separator = separator;
}
/**
* Returns the requested {@code List<String>} by path, or def if not found.
*
* @param path
* @param def
* @return
*/
public List getStringList(String path, List<String> def) {
return getStringList(data, path, separator, def);
}
/**
* Returns the requested {@code List<String>} by path, or null if not found.
*
* @param path
* @return
*/
public List getStringList(String path) {
return getStringList(data, path, separator, null);
}
/**
* Returns {@code true} if the given path refers to an existing Date value.
*
* @param path
* @return
*/
public boolean isDate(String path) {
return isDate(data, path, separator);
}
/**
* Returns {@code true} if the given path refers to an existing float value.
*
* @param path
* @return
*/
public boolean isFloat(String path) {
return isFloat(data, path, separator);
}
/**
* Returns {@code true} if the given path refers to an existing int value.
*
* @param path
* @return
*/
public boolean isInteger(String path) {
return isInteger(data, path, separator);
}
/**
* Returns {@code true} if the given path refers to an existing List value.
*
* @param path
* @return
*/
public boolean isList(String path) {
return isList(data, path, separator);
}
/**
* Returns {@code true} if the given path refers to an existing String value.
*
* @param path
* @return
*/
public boolean isString(String path) {
return isString(data, path, separator);
}
/**
* Sets the specified path to the given value.
*
* @param path
* @param value
* @return
*/
public Object set(String path, Object value) {
return set(data, path, separator, value);
}
}
| agpl-3.0 |
DISSIDIA-986/toolbar | effectivejava/src/main/java/org/effectivejava/examples/chapter03/item08/composition/Point.java | 513 | // Simple immutable two-dimensional integer point class - Page 37
package org.effectivejava.examples.chapter03.item08.composition;
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Point))
return false;
Point p = (Point) o;
return p.x == x && p.y == y;
}
// See Item 9
@Override
public int hashCode() {
return 31 * x + y;
}
}
| agpl-3.0 |
shenan4321/BIMplatform | generated/cn/dlb/bim/models/ifc2x3tc1/IfcStateEnum.java | 8123 | /**
* 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;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Ifc State Enum</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see cn.dlb.bim.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcStateEnum()
* @model
* @generated
*/
public enum IfcStateEnum implements Enumerator {
/**
* The '<em><b>NULL</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #NULL_VALUE
* @generated
* @ordered
*/
NULL(0, "NULL", "NULL"),
/**
* The '<em><b>READWRITE</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #READWRITE_VALUE
* @generated
* @ordered
*/
READWRITE(1, "READWRITE", "READWRITE"),
/**
* The '<em><b>LOCKED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #LOCKED_VALUE
* @generated
* @ordered
*/
LOCKED(2, "LOCKED", "LOCKED"),
/**
* The '<em><b>READWRITELOCKED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #READWRITELOCKED_VALUE
* @generated
* @ordered
*/
READWRITELOCKED(3, "READWRITELOCKED", "READWRITELOCKED"),
/**
* The '<em><b>READONLYLOCKED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #READONLYLOCKED_VALUE
* @generated
* @ordered
*/
READONLYLOCKED(4, "READONLYLOCKED", "READONLYLOCKED"),
/**
* The '<em><b>READONLY</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #READONLY_VALUE
* @generated
* @ordered
*/
READONLY(5, "READONLY", "READONLY");
/**
* The '<em><b>NULL</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>NULL</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #NULL
* @model
* @generated
* @ordered
*/
public static final int NULL_VALUE = 0;
/**
* The '<em><b>READWRITE</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>READWRITE</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #READWRITE
* @model
* @generated
* @ordered
*/
public static final int READWRITE_VALUE = 1;
/**
* The '<em><b>LOCKED</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>LOCKED</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #LOCKED
* @model
* @generated
* @ordered
*/
public static final int LOCKED_VALUE = 2;
/**
* The '<em><b>READWRITELOCKED</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>READWRITELOCKED</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #READWRITELOCKED
* @model
* @generated
* @ordered
*/
public static final int READWRITELOCKED_VALUE = 3;
/**
* The '<em><b>READONLYLOCKED</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>READONLYLOCKED</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #READONLYLOCKED
* @model
* @generated
* @ordered
*/
public static final int READONLYLOCKED_VALUE = 4;
/**
* The '<em><b>READONLY</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>READONLY</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #READONLY
* @model
* @generated
* @ordered
*/
public static final int READONLY_VALUE = 5;
/**
* An array of all the '<em><b>Ifc State Enum</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final IfcStateEnum[] VALUES_ARRAY = new IfcStateEnum[] { NULL, READWRITE, LOCKED, READWRITELOCKED, READONLYLOCKED, READONLY, };
/**
* A public read-only list of all the '<em><b>Ifc State Enum</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<IfcStateEnum> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Ifc State Enum</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static IfcStateEnum get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
IfcStateEnum result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Ifc State Enum</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static IfcStateEnum getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
IfcStateEnum result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Ifc State Enum</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static IfcStateEnum get(int value) {
switch (value) {
case NULL_VALUE:
return NULL;
case READWRITE_VALUE:
return READWRITE;
case LOCKED_VALUE:
return LOCKED;
case READWRITELOCKED_VALUE:
return READWRITELOCKED;
case READONLYLOCKED_VALUE:
return READONLYLOCKED;
case READONLY_VALUE:
return READONLY;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private IfcStateEnum(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //IfcStateEnum
| agpl-3.0 |
quikkian-ua-devops/will-financials | kfs-core/src/main/java/org/kuali/kfs/sys/service/impl/KfsBusinessObjectMetaDataServiceImpl.java | 10695 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, 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/>.
*/
package org.kuali.kfs.sys.service.impl;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.ojb.broker.metadata.ClassDescriptor;
import org.apache.ojb.broker.metadata.ClassNotPersistenceCapableException;
import org.kuali.kfs.coreservice.framework.parameter.ParameterService;
import org.kuali.kfs.kns.service.BusinessObjectMetaDataService;
import org.kuali.kfs.kns.service.DataDictionaryService;
import org.kuali.kfs.krad.bo.DataObjectRelationship;
import org.kuali.kfs.krad.datadictionary.AttributeDefinition;
import org.kuali.kfs.krad.datadictionary.BusinessObjectEntry;
import org.kuali.kfs.krad.service.BusinessObjectService;
import org.kuali.kfs.krad.service.KRADServiceLocatorWeb;
import org.kuali.kfs.krad.service.LookupService;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.businessobject.BusinessObjectComponent;
import org.kuali.kfs.sys.businessobject.BusinessObjectProperty;
import org.kuali.kfs.sys.dataaccess.BusinessObjectMetaDataDao;
import org.kuali.kfs.sys.service.KfsBusinessObjectMetaDataService;
import org.kuali.kfs.sys.service.NonTransactional;
import org.kuali.rice.krad.bo.BusinessObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
@NonTransactional
public class KfsBusinessObjectMetaDataServiceImpl implements KfsBusinessObjectMetaDataService {
private Logger LOG = Logger.getLogger(KfsBusinessObjectMetaDataServiceImpl.class);
private DataDictionaryService dataDictionaryService;
private ParameterService parameterService;
private BusinessObjectService businessObjectService;
private BusinessObjectMetaDataService businessObjectMetaDataService;
private BusinessObjectMetaDataDao businessObjectMetaDataDao;
private LookupService lookupService;
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
protected BusinessObjectComponent getBusinessObjectComponent(Class<?> componentClass) {
return new BusinessObjectComponent(KRADServiceLocatorWeb.getKualiModuleService().getNamespaceCode(componentClass), (org.kuali.kfs.kns.datadictionary.BusinessObjectEntry) dataDictionaryService.getDataDictionary().getBusinessObjectEntry(componentClass.getName()));
}
@Override
public BusinessObjectProperty getBusinessObjectProperty(String componentClass, String propertyName) {
try {
return new BusinessObjectProperty(getBusinessObjectComponent(Class.forName(componentClass)), dataDictionaryService.getDataDictionary().getBusinessObjectEntry(componentClass).getAttributeDefinition(propertyName));
} catch (ClassNotFoundException ex) {
LOG.error("Unable to resolve component class name: " + componentClass);
}
return null;
}
@Override
public List<BusinessObjectComponent> findBusinessObjectComponents(String namespaceCode, String componentLabel) {
Map<Class, BusinessObjectComponent> matchingBusinessObjectComponents = new HashMap<Class, BusinessObjectComponent>();
Pattern componentLabelRegex = null;
if (StringUtils.isNotBlank(componentLabel)) {
String patternStr = componentLabel.replace("*", ".*").toUpperCase();
try {
componentLabelRegex = Pattern.compile(patternStr);
} catch (PatternSyntaxException ex) {
LOG.error("KfsBusinessObjectMetaDataServiceImpl unable to parse componentLabel pattern, ignoring.", ex);
}
}
for (BusinessObjectEntry businessObjectEntry : dataDictionaryService.getDataDictionary().getBusinessObjectEntries().values()) {
if ((StringUtils.isBlank(namespaceCode) || namespaceCode.equals(KRADServiceLocatorWeb.getKualiModuleService().getNamespaceCode(businessObjectEntry.getBusinessObjectClass())))
&& ((componentLabelRegex == null) || (StringUtils.isNotBlank(businessObjectEntry.getObjectLabel()) && componentLabelRegex.matcher(businessObjectEntry.getObjectLabel().toUpperCase()).matches()))) {
matchingBusinessObjectComponents.put(businessObjectEntry.getBusinessObjectClass(), new BusinessObjectComponent(KRADServiceLocatorWeb.getKualiModuleService().getNamespaceCode(businessObjectEntry.getBusinessObjectClass()), (org.kuali.kfs.kns.datadictionary.BusinessObjectEntry) businessObjectEntry));
}
}
return new ArrayList<BusinessObjectComponent>(matchingBusinessObjectComponents.values());
}
@Override
public List<BusinessObjectProperty> findBusinessObjectProperties(String namespaceCode, String componentLabel, String propertyLabel) {
List<BusinessObjectComponent> businessObjectComponents = findBusinessObjectComponents(namespaceCode, componentLabel);
Pattern propertyLabelRegex = null;
if (StringUtils.isNotBlank(propertyLabel)) {
String patternStr = propertyLabel.replace("*", ".*").toUpperCase();
try {
propertyLabelRegex = Pattern.compile(patternStr);
} catch (PatternSyntaxException ex) {
LOG.error("KfsBusinessObjectMetaDataServiceImpl unable to parse propertyLabel pattern, ignoring.", ex);
}
}
List<BusinessObjectProperty> matchingBusinessObjectProperties = new ArrayList<BusinessObjectProperty>();
for (BusinessObjectComponent businessObjectComponent : businessObjectComponents) {
for (AttributeDefinition attributeDefinition : dataDictionaryService.getDataDictionary().getBusinessObjectEntry(businessObjectComponent.getComponentClass().toString()).getAttributes()) {
if (!attributeDefinition.getName().endsWith(KFSPropertyConstants.VERSION_NUMBER) && !attributeDefinition.getName().endsWith(KFSPropertyConstants.OBJECT_ID) && ((propertyLabelRegex == null) || propertyLabelRegex.matcher(attributeDefinition.getLabel().toUpperCase()).matches())) {
matchingBusinessObjectProperties.add(new BusinessObjectProperty(businessObjectComponent, attributeDefinition));
}
}
}
return matchingBusinessObjectProperties;
}
@Override
public boolean isMatch(String componentClass, String propertyName, String tableNameSearchCriterion, String fieldNameSearchCriterion) {
ClassDescriptor classDescriptor = null;
try {
classDescriptor = org.apache.ojb.broker.metadata.MetadataManager.getInstance().getGlobalRepository().getDescriptorFor(componentClass);
Pattern tableNameRegex = null;
if (StringUtils.isNotBlank(tableNameSearchCriterion)) {
String patternStr = tableNameSearchCriterion.replace("*", ".*").toUpperCase();
try {
tableNameRegex = Pattern.compile(patternStr);
} catch (PatternSyntaxException ex) {
LOG.error("DataMappingFieldDefinitionLookupableHelperServiceImpl unable to parse tableName pattern, ignoring.", ex);
}
}
Pattern fieldNameRegex = null;
if (StringUtils.isNotBlank(fieldNameSearchCriterion)) {
String patternStr = fieldNameSearchCriterion.replace("*", ".*").toUpperCase();
try {
fieldNameRegex = Pattern.compile(patternStr);
} catch (PatternSyntaxException ex) {
LOG.error("DataMappingFieldDefinitionLookupableHelperServiceImpl unable to parse fieldName pattern, ignoring.", ex);
}
}
return ((tableNameRegex == null) || tableNameRegex.matcher(classDescriptor.getFullTableName().toUpperCase()).matches()) && ((fieldNameRegex == null) || ((classDescriptor.getFieldDescriptorByName(propertyName) != null) && fieldNameRegex.matcher(classDescriptor.getFieldDescriptorByName(propertyName).getColumnName().toUpperCase()).matches()));
} catch (ClassNotPersistenceCapableException e) {
return StringUtils.isBlank(tableNameSearchCriterion) && StringUtils.isBlank(fieldNameSearchCriterion);
}
}
@Override
public String getReferenceComponentLabel(Class componentClass, String propertyName) {
DataObjectRelationship relationship = null;
try {
relationship = businessObjectMetaDataService.getBusinessObjectRelationship((BusinessObject) componentClass.newInstance(), propertyName);
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug("KfsBusinessObjectMetadataServiceImpl unable to instantiate componentClass: " + componentClass, e);
}
}
if (relationship != null) {
return dataDictionaryService.getDataDictionary().getBusinessObjectEntry(relationship.getRelatedClass().getName()).getObjectLabel();
}
return "";
}
public void setDataDictionaryService(DataDictionaryService dataDictionaryService) {
this.dataDictionaryService = dataDictionaryService;
}
public void setBusinessObjectService(BusinessObjectService businessObjectService) {
this.businessObjectService = businessObjectService;
}
public void setBusinessObjectMetaDataService(BusinessObjectMetaDataService businessObjectMetaDataService) {
this.businessObjectMetaDataService = businessObjectMetaDataService;
}
public void setBusinessObjectMetaDataDao(BusinessObjectMetaDataDao businessObjectMetaDataDao) {
this.businessObjectMetaDataDao = businessObjectMetaDataDao;
}
public void setLookupService(LookupService lookupService) {
this.lookupService = lookupService;
}
}
| agpl-3.0 |
Asqatasun/Asqatasun | rules/rules-accessiweb2.2/src/test/java/org/asqatasun/rules/accessiweb22/Aw22Rule06011Test.java | 49488 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This file is part of Asqatasun.
*
* Asqatasun 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.accessiweb22;
import org.asqatasun.entity.audit.ProcessRemark;
import org.asqatasun.entity.audit.ProcessResult;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.rules.accessiweb22.test.Aw22RuleImplementationTestCase;
import org.asqatasun.rules.keystore.RemarkMessageStore;
/**
*
* @author jkowalczyk
*/
public class Aw22Rule06011Test extends Aw22RuleImplementationTestCase {
public Aw22Rule06011Test(String testName) {
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.asqatasun.rules.accessiweb22.Aw22Rule06011");
}
@Override
protected void setUpWebResourceMap() {
getWebResourceMap().put("AW22.Test.06.01.01-2Failed-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-2Failed-01.html"));
getWebResourceMap().put("AW22.Test.06.01.01-2Failed-02",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-2Failed-02.html"));
getWebResourceMap().put("AW22.Test.06.01.01-2Failed-03",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-2Failed-03.html"));
getWebResourceMap().put("AW22.Test.06.01.01-2Failed-04",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-2Failed-04.html"));
getWebResourceMap().put("AW22.Test.06.01.01-2Failed-05",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-2Failed-05.html"));
getWebResourceMap().put("AW22.Test.06.01.01-2Failed-06",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-2Failed-06.html"));
getWebResourceMap().put("AW22.Test.06.01.01-2Failed-07",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-2Failed-07.html"));
getWebResourceMap().put("AW22.Test.06.01.01-2Failed-08",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-2Failed-08.html"));
getWebResourceMap().put("AW22.Test.06.01.01-3NMI-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-3NMI-01.html"));
getWebResourceMap().put("AW22.Test.06.01.01-3NMI-02",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-3NMI-02.html"));
getWebResourceMap().put("AW22.Test.06.01.01-3NMI-03",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-3NMI-03.html"));
getWebResourceMap().put("AW22.Test.06.01.01-3NMI-05",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-3NMI-05.html"));
getWebResourceMap().put("AW22.Test.06.01.01-3NMI-06",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-3NMI-06.html"));
getWebResourceMap().put("AW22.Test.06.01.01-3NMI-07",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-3NMI-07.html"));
getWebResourceMap().put("AW22.Test.06.01.01-4NA-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-4NA-01.html"));
getWebResourceMap().put("AW22.Test.06.01.01-4NA-02",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-4NA-02.html"));
getWebResourceMap().put("AW22.Test.06.01.01-4NA-03",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-4NA-03.html"));
getWebResourceMap().put("AW22.Test.06.01.01-4NA-04",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-4NA-04.html"));
getWebResourceMap().put("AW22.Test.06.01.01-4NA-05",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06011/AW22.Test.06.01.01-4NA-05.html"));
//06.01.02 testcases
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-01.html"));
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-02",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-02.html"));
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-03",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-03.html"));
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-04",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-04.html"));
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-05",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-05.html"));
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-06",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-06.html"));
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-07",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-07.html"));
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-08",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-08.html"));
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-09",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-09.html"));
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-10",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-10.html"));
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-11",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-11.html"));
getWebResourceMap().put("AW22.Test.06.01.02-2Failed-12",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-2Failed-12.html"));
getWebResourceMap().put("AW22.Test.06.01.02-3NMI-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-3NMI-01.html"));
getWebResourceMap().put("AW22.Test.06.01.02-3NMI-02",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-3NMI-02.html"));
getWebResourceMap().put("AW22.Test.06.01.02-3NMI-03",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-3NMI-03.html"));
getWebResourceMap().put("AW22.Test.06.01.02-3NMI-05",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-3NMI-05.html"));
getWebResourceMap().put("AW22.Test.06.01.02-3NMI-06",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06012/AW22.Test.06.01.02-3NMI-06.html"));
//06.01.03 testcases
getWebResourceMap().put("AW22.Test.06.01.03-2Failed-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-2Failed-01.html"));
getWebResourceMap().put("AW22.Test.06.01.03-2Failed-02",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-2Failed-02.html"));
getWebResourceMap().put("AW22.Test.06.01.03-2Failed-03",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-2Failed-03.html"));
getWebResourceMap().put("AW22.Test.06.01.03-2Failed-04",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-2Failed-04.html"));
getWebResourceMap().put("AW22.Test.06.01.03-2Failed-05",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-2Failed-05.html"));
getWebResourceMap().put("AW22.Test.06.01.03-2Failed-06",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-2Failed-06.html"));
getWebResourceMap().put("AW22.Test.06.01.03-2Failed-07",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-2Failed-07.html"));
getWebResourceMap().put("AW22.Test.06.01.03-2Failed-08",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-2Failed-08.html"));
getWebResourceMap().put("AW22.Test.06.01.03-3NMI-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-3NMI-01.html"));
getWebResourceMap().put("AW22.Test.06.01.03-3NMI-02",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-3NMI-02.html"));
getWebResourceMap().put("AW22.Test.06.01.03-3NMI-03",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-3NMI-03.html"));
getWebResourceMap().put("AW22.Test.06.01.03-3NMI-05",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-3NMI-05.html"));
getWebResourceMap().put("AW22.Test.06.01.03-3NMI-06",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-3NMI-06.html"));
getWebResourceMap().put("AW22.Test.06.01.03-3NMI-07",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06013/AW22.Test.06.01.03-3NMI-07.html"));
//06.01.04 testcases
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-01.html"));
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-02",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-02.html"));
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-03",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-03.html"));
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-04",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-04.html"));
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-05",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-05.html"));
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-06",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-06.html"));
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-07",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-07.html"));
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-08",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-08.html"));
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-09",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-09.html"));
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-10",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-10.html"));
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-11",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-11.html"));
getWebResourceMap().put("AW22.Test.06.01.04-2Failed-12",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-2Failed-12.html"));
getWebResourceMap().put("AW22.Test.06.01.04-3NMI-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-3NMI-01.html"));
getWebResourceMap().put("AW22.Test.06.01.04-3NMI-02",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-3NMI-02.html"));
getWebResourceMap().put("AW22.Test.06.01.04-3NMI-03",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-3NMI-03.html"));
getWebResourceMap().put("AW22.Test.06.01.04-3NMI-04",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-3NMI-04.html"));
getWebResourceMap().put("AW22.Test.06.01.04-3NMI-05",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06014/AW22.Test.06.01.04-3NMI-05.html"));
//06.06.01 testcases -> empty links
getWebResourceMap().put("AW22.Test.06.06.01-2Failed-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06061/AW22.Test.06.06.01-2Failed-01.html"));
getWebResourceMap().put("AW22.Test.06.06.01-2Failed-02",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06061/AW22.Test.06.06.01-2Failed-02.html"));
getWebResourceMap().put("AW22.Test.06.06.01-2Failed-03",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06061/AW22.Test.06.06.01-2Failed-03.html"));
getWebResourceMap().put("AW22.Test.06.06.01-2Failed-04",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06061/AW22.Test.06.06.01-2Failed-04.html"));
getWebResourceMap().put("AW22.Test.06.06.01-2Failed-05",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06061/AW22.Test.06.06.01-2Failed-05.html"));
getWebResourceMap().put("AW22.Test.06.06.01-4NA-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule06061/AW22.Test.06.06.01-4NA-01.html"));
}
@Override
protected void setProcess() {
ProcessResult processResult =
processPageTest("AW22.Test.06.01.01-2Failed-01");
assertEquals(TestSolution.FAILED,processResult.getValue());
assertEquals(2, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.FAILED,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode());
assertEquals(TestSolution.FAILED,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-2Failed-02");
assertEquals(TestSolution.FAILED,processResult.getValue());
assertEquals(2, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.FAILED,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode());
assertEquals(TestSolution.FAILED,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-2Failed-03");
assertEquals(TestSolution.FAILED,processResult.getValue());
assertEquals(1, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.FAILED,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-2Failed-04");
assertEquals(TestSolution.FAILED,processResult.getValue());
assertEquals(2, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.FAILED,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode());
assertEquals(TestSolution.FAILED,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-2Failed-05");
assertEquals(TestSolution.FAILED,processResult.getValue());
assertEquals(2, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.FAILED,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_WITH_CONTEXT_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-2Failed-06");
assertEquals(TestSolution.FAILED,processResult.getValue());
assertEquals(2, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.FAILED,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_WITH_CONTEXT_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-2Failed-07");
assertEquals(TestSolution.FAILED,processResult.getValue());
assertEquals(2, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.FAILED,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_WITH_CONTEXT_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-2Failed-08");
assertEquals(TestSolution.FAILED,processResult.getValue());
assertEquals(2, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.FAILED,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_WITH_CONTEXT_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-3NMI-01");
assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue());
assertEquals(2, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_WITH_CONTEXT_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_WITH_CONTEXT_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-3NMI-02");
assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue());
assertEquals(2, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_WITH_CONTEXT_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_WITH_CONTEXT_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[1]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-3NMI-03");
assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue());
assertEquals(1, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.UNEXPLICIT_LINK_WITH_CONTEXT_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-3NMI-05");
assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue());
assertEquals(1, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.CHECK_LINK_WITH_CONTEXT_PERTINENCE_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-3NMI-06");
assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue());
assertEquals(1, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.CHECK_LINK_WITH_CONTEXT_PERTINENCE_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-3NMI-07");
assertEquals(TestSolution.NEED_MORE_INFO,processResult.getValue());
assertEquals(1, processResult.getRemarkSet().size());
assertEquals(RemarkMessageStore.CHECK_LINK_WITH_CONTEXT_PERTINENCE_MSG,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO,
((ProcessRemark)processResult.getRemarkSet().toArray()[0]).getIssue());
processResult = processPageTest("AW22.Test.06.01.01-4NA-01");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.01-4NA-02");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.01-4NA-03");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.01-4NA-04");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.01-4NA-05");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
// 06.01.02 testcases : All is Not Applicable
processResult = processPageTest("AW22.Test.06.01.02-2Failed-01");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-2Failed-02");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-2Failed-03");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-2Failed-04");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-2Failed-05");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-2Failed-06");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-2Failed-07");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-2Failed-08");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-2Failed-09");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-2Failed-10");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-2Failed-11");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-2Failed-12");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-3NMI-01");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-3NMI-02");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-3NMI-03");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-3NMI-05");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.02-3NMI-06");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
// 06.01.03 testcases : All is Not Applicable
processResult = processPageTest("AW22.Test.06.01.03-2Failed-01");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-2Failed-02");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-2Failed-03");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-2Failed-04");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-2Failed-05");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-2Failed-06");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-2Failed-07");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-2Failed-08");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-3NMI-01");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-3NMI-02");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-3NMI-03");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-3NMI-05");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-3NMI-06");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.03-3NMI-07");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
// 06.01.04 testcases : All is Not Applicable
processResult = processPageTest("AW22.Test.06.01.04-2Failed-01");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-2Failed-02");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-2Failed-03");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-2Failed-04");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-2Failed-05");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-2Failed-06");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-2Failed-07");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-2Failed-08");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-2Failed-09");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-2Failed-10");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-2Failed-11");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-2Failed-12");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-3NMI-01");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-3NMI-02");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-3NMI-03");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-3NMI-04");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.01.04-3NMI-05");
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
assertNull(processResult.getRemarkSet());
// 06.06.01 testcases : All is Not Applicable
processResult = processPageTest("AW22.Test.06.06.01-2Failed-01");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.06.01-2Failed-02");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.06.01-2Failed-03");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.06.01-2Failed-04");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.06.01-2Failed-05");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
processResult = processPageTest("AW22.Test.06.06.01-4NA-01");
assertEquals(TestSolution.NOT_APPLICABLE,processResult.getValue());
assertNull(processResult.getRemarkSet());
}
@Override
protected void setConsolidate() {
assertEquals(TestSolution.FAILED,
consolidate("AW22.Test.06.01.01-2Failed-01").getValue());
assertEquals(TestSolution.FAILED,
consolidate("AW22.Test.06.01.01-2Failed-02").getValue());
assertEquals(TestSolution.FAILED,
consolidate("AW22.Test.06.01.01-2Failed-03").getValue());
assertEquals(TestSolution.FAILED,
consolidate("AW22.Test.06.01.01-2Failed-04").getValue());
assertEquals(TestSolution.FAILED,
consolidate("AW22.Test.06.01.01-2Failed-05").getValue());
assertEquals(TestSolution.FAILED,
consolidate("AW22.Test.06.01.01-2Failed-06").getValue());
assertEquals(TestSolution.FAILED,
consolidate("AW22.Test.06.01.01-2Failed-07").getValue());
assertEquals(TestSolution.FAILED,
consolidate("AW22.Test.06.01.01-2Failed-08").getValue());
assertEquals(TestSolution.NEED_MORE_INFO,
consolidate("AW22.Test.06.01.01-3NMI-01").getValue());
assertEquals(TestSolution.NEED_MORE_INFO,
consolidate("AW22.Test.06.01.01-3NMI-02").getValue());
assertEquals(TestSolution.NEED_MORE_INFO,
consolidate("AW22.Test.06.01.01-3NMI-03").getValue());
assertEquals(TestSolution.NEED_MORE_INFO,
consolidate("AW22.Test.06.01.01-3NMI-05").getValue());
assertEquals(TestSolution.NEED_MORE_INFO,
consolidate("AW22.Test.06.01.01-3NMI-06").getValue());
assertEquals(TestSolution.NEED_MORE_INFO,
consolidate("AW22.Test.06.01.01-3NMI-07").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.01-4NA-01").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.01-4NA-02").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.01-4NA-03").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.01-4NA-04").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.01-4NA-05").getValue());
// 06.01.02 testcases : All is Not Applicable
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-01").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-02").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-03").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-04").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-05").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-06").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-07").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-08").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-09").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-10").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-11").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-2Failed-12").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-3NMI-01").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-3NMI-02").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-3NMI-03").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-3NMI-05").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.02-3NMI-06").getValue());
// 06.01.03 testcases : All is Not Applicable
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-2Failed-01").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-2Failed-02").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-2Failed-03").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-2Failed-04").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-2Failed-05").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-2Failed-06").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-2Failed-07").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-2Failed-08").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-3NMI-01").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-3NMI-02").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-3NMI-03").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-3NMI-05").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-3NMI-06").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.03-3NMI-07").getValue());
// 06.01.04 testcases : All is Not Applicable
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-01").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-02").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-03").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-04").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-05").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-06").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-07").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-08").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-09").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-10").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-11").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-2Failed-12").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-3NMI-01").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-3NMI-02").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-3NMI-03").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-3NMI-04").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.01.04-3NMI-05").getValue());
// 06.06.01 testcases : All is Not Applicable
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.06.01-2Failed-01").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.06.01-2Failed-02").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.06.01-2Failed-03").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.06.01-2Failed-04").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.06.01-2Failed-05").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("AW22.Test.06.06.01-4NA-01").getValue());
}
}
| agpl-3.0 |
SilverDav/Silverpeas-Core | core-api/src/test/java/org/silverpeas/core/variables/VariableTest.java | 4378 | /*
* 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/Lib
* Open Source Software ("FLOSS") applications as described in Silverpeas
* FLOSS exception. You should have received a copy of the text describin
* 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 Licen
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.silverpeas.core.variables;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.silverpeas.core.admin.user.model.User;
import org.silverpeas.core.date.Period;
import org.silverpeas.core.persistence.Transaction;
import org.silverpeas.core.test.TestBeanContainer;
import org.silverpeas.core.test.extension.EnableSilverTestEnv;
import org.silverpeas.core.test.extension.RequesterProvider;
import org.silverpeas.core.test.extension.TestManagedMock;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;
@EnableSilverTestEnv
class VariableTest {
@TestManagedMock
VariableScheduledValueRepository valuesRepository;
@TestManagedMock
VariablesRepository variablesRepository;
@RequesterProvider
User getCurrentUser() {
User user = mock(User.class);
when(user.getId()).thenReturn("1");
when(user.getFirstName()).thenReturn("John");
when(user.getLastName()).thenReturn("Doo");
return user;
}
@BeforeEach
void setUpMocks() {
Transaction transaction = new Transaction();
when(TestBeanContainer.getMockedBeanContainer()
.getBeanByType(Transaction.class)).thenReturn(transaction);
}
@Test
void propertiesOfAVariableWithoutValueAreCorrectlySet() {
Variable variable = new Variable("Var1", "My variable var1");
assertThat(variable.getLabel(), is("Var1"));
assertThat(variable.getDescription(), is("My variable var1"));
assertThat(variable.getNumberOfValues(), is(0));
assertThat(variable.getVariableValues().isEmpty(), is(true));
}
@Test
void propertiesOfAVariableWithTwoValuesAreCorrectlySet() {
Variable variable = new Variable("Var1", "My variable var1");
VariableScheduledValue value1 = new VariableScheduledValue("value1", Period.indefinite());
VariableScheduledValue value2 = new VariableScheduledValue("value2", Period.indefinite());
variable.getVariableValues().add(value1);
variable.getVariableValues().add(value2);
assertThat(variable.getLabel(), is("Var1"));
assertThat(variable.getDescription(), is("My variable var1"));
assertThat(variable.getNumberOfValues(), is(2));
assertThat(variable.getVariableValues().size(), is(2));
assertThat(variable.getVariableValues().contains(value1), is(true));
assertThat(variable.getVariableValues().contains(value2), is(true));
}
@Test
void saveAVariableWithoutAnyValue() {
Variable variable = new Variable("Var1", "My variable var1");
variable.save();
verify(variablesRepository).save(variable);
}
@Test
void saveAVariableWithValue() {
Variable variable = new Variable("Var1", "My variable var1");
VariableScheduledValue value = new VariableScheduledValue("value", Period.indefinite());
variable.getVariableValues().add(value);
variable.save();
verify(variablesRepository).save(variable);
}
@Test
void saveExplicitlyAValueOfAVariable() {
Variable variable = new Variable("Var1", "My variable var1");
VariableScheduledValue value = new VariableScheduledValue("value", Period.indefinite());
variable.getVariableValues().addAndSave(value);
verify(valuesRepository).save(value);
}
}
| agpl-3.0 |
y0ke/actor-platform | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/calls/peers/PeerConnectionCallback.java | 1172 | package im.actor.core.modules.calls.peers;
import im.actor.runtime.webrtc.WebRTCMediaStream;
/**
* Peer Connection Callback
*/
public interface PeerConnectionCallback {
/**
* Called when offer need to be sent to other peer
*
* @param sdp sdp of the offer
*/
void onOffer(long sessionId, String sdp);
/**
* Called when answer need to be sent to other peer
*
* @param sdp sdp of the answer
*/
void onAnswer(long sessionId, String sdp);
/**
* Called when new ICE candidate was found
*
* @param mdpIndex index in source SDP line
* @param id id of candidate
* @param sdp sdp of candidate
*/
void onCandidate(int mdpIndex, String id, String sdp);
/**
* Called when negotiation finished successfully
*/
void onNegotiationSuccessful(long sessionId);
/**
* Called when peer stream was added
*
* @param stream added stream
*/
void onStreamAdded(WebRTCMediaStream stream);
/**
* Called when peer was removed
*
* @param stream removed stream
*/
void onStreamRemoved(WebRTCMediaStream stream);
}
| agpl-3.0 |
opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/ifc4/IfcTelecomAddress.java | 12476 | /**
* 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 org.bimserver.models.ifc4;
/******************************************************************************
* 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 org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Ifc Telecom Address</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.bimserver.models.ifc4.IfcTelecomAddress#getTelephoneNumbers <em>Telephone Numbers</em>}</li>
* <li>{@link org.bimserver.models.ifc4.IfcTelecomAddress#getFacsimileNumbers <em>Facsimile Numbers</em>}</li>
* <li>{@link org.bimserver.models.ifc4.IfcTelecomAddress#getPagerNumber <em>Pager Number</em>}</li>
* <li>{@link org.bimserver.models.ifc4.IfcTelecomAddress#getElectronicMailAddresses <em>Electronic Mail Addresses</em>}</li>
* <li>{@link org.bimserver.models.ifc4.IfcTelecomAddress#getWWWHomePageURL <em>WWW Home Page URL</em>}</li>
* <li>{@link org.bimserver.models.ifc4.IfcTelecomAddress#getMessagingIDs <em>Messaging IDs</em>}</li>
* </ul>
*
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcTelecomAddress()
* @model
* @generated
*/
public interface IfcTelecomAddress extends IfcAddress {
/**
* Returns the value of the '<em><b>Telephone Numbers</b></em>' attribute list.
* The list contents are of type {@link java.lang.String}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Telephone Numbers</em>' attribute list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Telephone Numbers</em>' attribute list.
* @see #isSetTelephoneNumbers()
* @see #unsetTelephoneNumbers()
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcTelecomAddress_TelephoneNumbers()
* @model unique="false" unsettable="true"
* @generated
*/
EList<String> getTelephoneNumbers();
/**
* Unsets the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getTelephoneNumbers <em>Telephone Numbers</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetTelephoneNumbers()
* @see #getTelephoneNumbers()
* @generated
*/
void unsetTelephoneNumbers();
/**
* Returns whether the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getTelephoneNumbers <em>Telephone Numbers</em>}' attribute list is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Telephone Numbers</em>' attribute list is set.
* @see #unsetTelephoneNumbers()
* @see #getTelephoneNumbers()
* @generated
*/
boolean isSetTelephoneNumbers();
/**
* Returns the value of the '<em><b>Facsimile Numbers</b></em>' attribute list.
* The list contents are of type {@link java.lang.String}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Facsimile Numbers</em>' attribute list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Facsimile Numbers</em>' attribute list.
* @see #isSetFacsimileNumbers()
* @see #unsetFacsimileNumbers()
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcTelecomAddress_FacsimileNumbers()
* @model unique="false" unsettable="true"
* @generated
*/
EList<String> getFacsimileNumbers();
/**
* Unsets the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getFacsimileNumbers <em>Facsimile Numbers</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetFacsimileNumbers()
* @see #getFacsimileNumbers()
* @generated
*/
void unsetFacsimileNumbers();
/**
* Returns whether the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getFacsimileNumbers <em>Facsimile Numbers</em>}' attribute list is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Facsimile Numbers</em>' attribute list is set.
* @see #unsetFacsimileNumbers()
* @see #getFacsimileNumbers()
* @generated
*/
boolean isSetFacsimileNumbers();
/**
* Returns the value of the '<em><b>Pager Number</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Pager Number</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Pager Number</em>' attribute.
* @see #isSetPagerNumber()
* @see #unsetPagerNumber()
* @see #setPagerNumber(String)
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcTelecomAddress_PagerNumber()
* @model unsettable="true"
* @generated
*/
String getPagerNumber();
/**
* Sets the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getPagerNumber <em>Pager Number</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Pager Number</em>' attribute.
* @see #isSetPagerNumber()
* @see #unsetPagerNumber()
* @see #getPagerNumber()
* @generated
*/
void setPagerNumber(String value);
/**
* Unsets the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getPagerNumber <em>Pager Number</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetPagerNumber()
* @see #getPagerNumber()
* @see #setPagerNumber(String)
* @generated
*/
void unsetPagerNumber();
/**
* Returns whether the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getPagerNumber <em>Pager Number</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Pager Number</em>' attribute is set.
* @see #unsetPagerNumber()
* @see #getPagerNumber()
* @see #setPagerNumber(String)
* @generated
*/
boolean isSetPagerNumber();
/**
* Returns the value of the '<em><b>Electronic Mail Addresses</b></em>' attribute list.
* The list contents are of type {@link java.lang.String}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Electronic Mail Addresses</em>' attribute list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Electronic Mail Addresses</em>' attribute list.
* @see #isSetElectronicMailAddresses()
* @see #unsetElectronicMailAddresses()
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcTelecomAddress_ElectronicMailAddresses()
* @model unique="false" unsettable="true"
* @generated
*/
EList<String> getElectronicMailAddresses();
/**
* Unsets the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getElectronicMailAddresses <em>Electronic Mail Addresses</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetElectronicMailAddresses()
* @see #getElectronicMailAddresses()
* @generated
*/
void unsetElectronicMailAddresses();
/**
* Returns whether the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getElectronicMailAddresses <em>Electronic Mail Addresses</em>}' attribute list is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Electronic Mail Addresses</em>' attribute list is set.
* @see #unsetElectronicMailAddresses()
* @see #getElectronicMailAddresses()
* @generated
*/
boolean isSetElectronicMailAddresses();
/**
* Returns the value of the '<em><b>WWW Home Page URL</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>WWW Home Page URL</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>WWW Home Page URL</em>' attribute.
* @see #isSetWWWHomePageURL()
* @see #unsetWWWHomePageURL()
* @see #setWWWHomePageURL(String)
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcTelecomAddress_WWWHomePageURL()
* @model unsettable="true"
* @generated
*/
String getWWWHomePageURL();
/**
* Sets the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getWWWHomePageURL <em>WWW Home Page URL</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>WWW Home Page URL</em>' attribute.
* @see #isSetWWWHomePageURL()
* @see #unsetWWWHomePageURL()
* @see #getWWWHomePageURL()
* @generated
*/
void setWWWHomePageURL(String value);
/**
* Unsets the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getWWWHomePageURL <em>WWW Home Page URL</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetWWWHomePageURL()
* @see #getWWWHomePageURL()
* @see #setWWWHomePageURL(String)
* @generated
*/
void unsetWWWHomePageURL();
/**
* Returns whether the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getWWWHomePageURL <em>WWW Home Page URL</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>WWW Home Page URL</em>' attribute is set.
* @see #unsetWWWHomePageURL()
* @see #getWWWHomePageURL()
* @see #setWWWHomePageURL(String)
* @generated
*/
boolean isSetWWWHomePageURL();
/**
* Returns the value of the '<em><b>Messaging IDs</b></em>' attribute list.
* The list contents are of type {@link java.lang.String}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Messaging IDs</em>' attribute list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Messaging IDs</em>' attribute list.
* @see #isSetMessagingIDs()
* @see #unsetMessagingIDs()
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcTelecomAddress_MessagingIDs()
* @model unique="false" unsettable="true"
* @generated
*/
EList<String> getMessagingIDs();
/**
* Unsets the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getMessagingIDs <em>Messaging IDs</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetMessagingIDs()
* @see #getMessagingIDs()
* @generated
*/
void unsetMessagingIDs();
/**
* Returns whether the value of the '{@link org.bimserver.models.ifc4.IfcTelecomAddress#getMessagingIDs <em>Messaging IDs</em>}' attribute list is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Messaging IDs</em>' attribute list is set.
* @see #unsetMessagingIDs()
* @see #getMessagingIDs()
* @generated
*/
boolean isSetMessagingIDs();
} // IfcTelecomAddress
| agpl-3.0 |
automenta/java_dann | src/syncleus/dann/math/random/ConstRandomizer.java | 1627 | /*
* 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.math.random;
/**
* A randomizer that will create always set the random number to a const value,
* used mainly for testing.
*/
public class ConstRandomizer extends BasicRandomizer {
/**
* The constant value.
*/
private final double value;
/**
* Construct a range randomizer.
*
* @param value The constant value.
*/
public ConstRandomizer(final double value) {
this.value = value;
}
/**
* Generate a random number based on the range specified in the constructor.
*
* @param d The range randomizer ignores this value.
* @return The random number.
*/
@Override
public double randomize(final double d) {
return this.value;
}
}
| agpl-3.0 |
opensourceBIM/bimql | BimQL/src/nl/wietmazairac/bimql/set/attribute/SetAttributeSubIfcRelAssociatesApproval.java | 2678 | package nl.wietmazairac.bimql.set.attribute;
/******************************************************************************
* Copyright (C) 2009-2017 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 org.bimserver.models.ifc2x3tc1.IfcRelAssociatesApproval;
public class SetAttributeSubIfcRelAssociatesApproval {
// fields
private Object object;
private String attributeName;
private String attributeNewValue;
// constructors
public SetAttributeSubIfcRelAssociatesApproval() {
}
public SetAttributeSubIfcRelAssociatesApproval(Object object, String attributeName, String attributeNewValue) {
this.object = object;
this.attributeName = attributeName;
this.attributeNewValue = attributeNewValue;
}
// methods
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public String getAttributeName() {
return attributeName;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public String getAttributeNewValue() {
return attributeNewValue;
}
public void setAttributeNewValue(String attributeNewValue) {
this.attributeNewValue = attributeNewValue;
}
public void setAttribute() {
if (attributeName.equals("RelatingApproval")) {
//1NoEList
//1void
//1IfcApproval
}
else if (attributeName.equals("GlobalId")) {
//5NoEList
//5void
//5IfcGloballyUniqueId
}
else if (attributeName.equals("OwnerHistory")) {
//5NoEList
//5void
//5IfcOwnerHistory
}
else if (attributeName.equals("Name")) {
//5NoEList
((IfcRelAssociatesApproval) object).setName(attributeNewValue);
//5void
//5String
}
else if (attributeName.equals("Description")) {
//5NoEList
((IfcRelAssociatesApproval) object).setDescription(attributeNewValue);
//5void
//5String
}
else {
}
}
}
| agpl-3.0 |
jph-axelor/axelor-business-suite | axelor-base/src/main/java/com/axelor/apps/report/engine/EmbeddedReportSettings.java | 1672 | /**
* 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.report.engine;
import java.io.IOException;
import org.eclipse.birt.core.exception.BirtException;
import com.axelor.app.internal.AppFilter;
import com.axelor.exception.AxelorException;
import com.axelor.exception.db.IException;
import com.axelor.inject.Beans;
import com.axelor.report.ReportGenerator;
public class EmbeddedReportSettings extends ReportSettings {
public EmbeddedReportSettings(String rptdesign, String outputName) {
super(rptdesign, outputName);
}
@Override
public EmbeddedReportSettings generate() throws AxelorException {
super.generate();
try {
final ReportGenerator generator = Beans.get(ReportGenerator.class);
this.output = generator.generate(rptdesign, format, params, AppFilter.getLocale());
this.attach();
} catch(IOException | BirtException e) {
throw new AxelorException(e.getCause(), IException.CONFIGURATION_ERROR);
}
return this;
}
}
| agpl-3.0 |
phenotips/phenotips | components/gene-panels/api/src/main/java/org/phenotips/panels/internal/DefaultGenePanelFactoryImpl.java | 3561 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.phenotips.panels.internal;
import org.phenotips.data.Patient;
import org.phenotips.panels.GenePanel;
import org.phenotips.panels.GenePanelFactory;
import org.phenotips.vocabulary.VocabularyManager;
import org.phenotips.vocabulary.VocabularyTerm;
import org.xwiki.component.annotation.Component;
import java.util.Collection;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.commons.lang3.Validate;
/**
* Default implementation of the {@link GenePanelFactory}.
*
* @version $Id$
* @since 1.3
*/
@Component
@Singleton
public class DefaultGenePanelFactoryImpl implements GenePanelFactory
{
/** The vocabulary manager required for accessing the available vocabularies. */
@Inject
private VocabularyManager vocabularyManager;
/** Is false by default. Iff set to true, will result in a panel that keeps count of number of genes for terms. */
private boolean generateMatchCount;
@Override
public GenePanelFactory withMatchCount(final boolean generate)
{
this.generateMatchCount = generate;
return this;
}
@Override
public GenePanel build(
@Nonnull final Collection<VocabularyTerm> presentTerms,
@Nonnull final Collection<VocabularyTerm> absentTerms)
{
Validate.notNull(presentTerms);
Validate.notNull(absentTerms);
return new DefaultGenePanelImpl(presentTerms, absentTerms, this.generateMatchCount, this.vocabularyManager);
}
@Override
public GenePanel build(
@Nonnull final Collection<VocabularyTerm> presentTerms,
@Nonnull final Collection<VocabularyTerm> absentTerms,
@Nonnull final Collection<VocabularyTerm> rejectedGenes)
{
Validate.notNull(presentTerms);
Validate.notNull(absentTerms);
Validate.notNull(rejectedGenes);
return new DefaultGenePanelImpl(presentTerms, absentTerms, rejectedGenes, this.generateMatchCount,
this.vocabularyManager);
}
@Override
public GenePanel build(@Nonnull final Patient patient)
{
return build(patient, true);
}
@Override
public GenePanel build(@Nonnull final Patient patient, final boolean excludeRejectedGenes)
{
Validate.notNull(patient);
final PatientDataAdapter dataAdapter = excludeRejectedGenes
? new PatientDataAdapter.AdapterBuilder(patient, this.vocabularyManager).withRejectedGenes().build()
: new PatientDataAdapter.AdapterBuilder(patient, this.vocabularyManager).build();
return new DefaultGenePanelImpl(dataAdapter.getPresentTerms(), dataAdapter.getAbsentTerms(),
dataAdapter.getRejectedGenes(), this.generateMatchCount, this.vocabularyManager);
}
}
| agpl-3.0 |
SilverDav/Silverpeas-Core | core-services/workflow/src/test/java/org/silverpeas/core/workflow/engine/user/TestContext.java | 5406 | /*
* 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.workflow.engine.user;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.mockito.invocation.InvocationOnMock;
import org.silverpeas.core.cache.service.CacheServiceProvider;
import org.silverpeas.core.date.Period;
import org.silverpeas.core.test.rule.CommonAPITestRule;
import org.silverpeas.core.test.util.JpaMocker;
import org.silverpeas.core.util.Mutable;
import org.silverpeas.core.workflow.api.UserManager;
import org.silverpeas.core.workflow.api.WorkflowException;
import org.silverpeas.core.workflow.api.user.Replacement;
import org.silverpeas.core.workflow.api.user.User;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Context of unit tests on the delegation API.
* @author mmoquillon
*/
public class TestContext extends CommonAPITestRule {
static final String WORKFLOW_ID = "workflow42";
private final User anIncumbent;
private final User aSubstitute;
// The actual replacement that is saved in the context of a given unit test
final Mutable<ReplacementImpl> savedReplacement = Mutable.empty();
public TestContext(final User anIncumbent, final User aSubstitute) {
super();
this.aSubstitute = anIncumbent;
this.anIncumbent = aSubstitute;
}
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
init();
base.evaluate();
}
};
}
public void init() {
try {
CacheServiceProvider.clearAllThreadCaches();
mockUserManager();
mockReplacementConstructor();
mockReplacementPersistence();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static User aUser(final String userId) {
User user = mock(User.class);
when(user.getUserId()).thenReturn(userId);
return user;
}
private void mockReplacementConstructor() {
injectIntoMockedBeanContainer(new ReplacementConstructor());
}
private void mockReplacementPersistence() {
JpaMocker jpa = new JpaMocker(this);
jpa.mockJPA(savedReplacement, ReplacementImpl.class);
mockReplacementRepository(jpa, savedReplacement);
}
private void mockReplacementRepository(final JpaMocker jpaMocker,
final Mutable<ReplacementImpl> savedReplacement) {
// Mocking persistence repository of delegations...
ReplacementRepository repository =
jpaMocker.mockRepository(ReplacementRepository.class, savedReplacement);
when(repository.findAllByIncumbentAndByWorkflow(any(User.class), anyString())).thenAnswer(
invocation -> computeReplacementsFor(invocation, aSubstitute));
when(repository.findAllBySubstituteAndByWorkflow(any(User.class), anyString())).thenAnswer(
invocation -> computeReplacementsFor(invocation, anIncumbent));
injectIntoMockedBeanContainer(repository);
}
private UserManager mockUserManager() throws WorkflowException {
// Mocking the User providing mechanism
UserManager userManager = mock(UserManager.class);
when(userManager.getUser(anyString())).thenAnswer(invocation -> {
String id = invocation.getArgument(0);
if (aSubstitute.getUserId().equals(id)) {
return aSubstitute;
} else if (anIncumbent.getUserId().equals(id)) {
return anIncumbent;
} else {
return aUser(id);
}
});
injectIntoMockedBeanContainer(userManager);
return userManager;
}
private Object computeReplacementsFor(final InvocationOnMock invocation,
final User concernedUser) {
LocalDate today = LocalDate.now();
List<ReplacementImpl> replacements = new ArrayList<>();
User user = invocation.getArgument(0);
String workflowId = invocation.getArgument(1);
if (concernedUser.getUserId().equals(user.getUserId()) && WORKFLOW_ID.equals(workflowId)) {
replacements.add(Replacement.between(aSubstitute, anIncumbent)
.inWorkflow(workflowId)
.during(Period.between(today.plusDays(1), today.plusDays(8))));
}
return replacements;
}
}
| agpl-3.0 |
MartinGijsen/PowerTools | power-tools-parent/power-tools-database/src/main/java/org/powertools/database/Table.java | 1220 | package org.powertools.database;
public abstract class Table extends Source {
public final String _tableName;
// TODO: use reflection to determine name?
public final String _instanceName;
public Table(String tableName, String instanceName) {
this._tableName = tableName;
this._instanceName = instanceName;
}
// TODO: use reflection to determine name?
protected final Column createColumn(String name) {
return new Column (this, name);
}
public final Selectable asterisk() {
return new Asterisk (this);
}
@Override
boolean hasName(String name) {
return _instanceName.equals (name);
}
@Override
String getName() {
return _instanceName;
}
@Override
public String getFullName () {
if (hasDefaultName ()) {
return _tableName;
} else {
return _tableName + " " + _instanceName;
}
}
final boolean hasDefaultName() {
return _tableName.equals (_instanceName);
}
@Override
public final String toString() {
return getFullName ();
}
}
| agpl-3.0 |
moparisthebest/MoparScape | clients/client508/src/main/java/Class1_Sub7.java | 11760 | /* Class1_Sub7 - Decompiled by JODE
* Visit http://jode.sourceforge.net/
*/
public class Class1_Sub7 extends Animable {
public static RSString aRSString_2590
= RSString.newRsString("Schlie-8en");
public static int anInt2591;
public int anInt2592;
public static int anInt2593;
public static int anInt2594;
public int anInt2595;
public int anInt2596;
public static int anInt2597;
public int anInt2598 = -1;
public int anInt2599;
public static int anInt2600;
public static RSString aRSString_2601;
public int anInt2602;
public int anInt2603;
public int anInt2604;
public Class92_Sub1 aClass92_Sub1_2605 = null;
public int anInt2606;
public static int anInt2607;
public static int anInt2608;
public int anInt2609;
public static int anInt2610;
public static RSString aRSString_2611;
public static boolean aBoolean2612;
public static RSString aRSString_2613 = RSString.newRsString("green:");
public int anInt2614;
public static int anInt2615;
public static int anInt2616;
public Class55 aClass55_2617;
public static Class21renamed aClass21_2618;
public static int anInt2619;
public static RSString method165(int i, int i_0_) {
if (i_0_ != -17516)
return null;
anInt2610++;
return (Class68_Sub20_Sub13_Sub2.method1166
(i_0_ ^ ~0x4469,
(new RSString[]
{Class68_Sub13_Sub24.method816(0xff & i >> -1240357992, 0),
Class75_Sub3_Sub1.aRSString_4596,
Class68_Sub13_Sub24.method816(0xff & i >> -1005336016, 0),
Class75_Sub3_Sub1.aRSString_4596,
Class68_Sub13_Sub24.method816((0xffc7 & i) >> 918212456,
0),
Class75_Sub3_Sub1.aRSString_4596,
Class68_Sub13_Sub24.method816(i & 0xff, 0)})));
}
public Animable method166(int i) {
if (i != 675116226)
return null;
anInt2591++;
return method167(false, 2);
}
public Animable method167(boolean bool, int i) {
anInt2608++;
boolean bool_1_ = (Class74.anIntArrayArrayArray1335
!= Class68_Sub20_Sub12.anIntArrayArrayArray4353);
Class116 class116 = Class1_Sub5.method140(i + 89, anInt2595);
if (class116.anIntArray1994 != null)
class116 = class116.method1710(i + -3);
if (class116 == null)
return null;
int i_2_ = anInt2604 & 0x3;
int i_3_;
int i_4_;
if (i_2_ == 1 || i_2_ == 3) {
i_4_ = class116.anInt1988;
i_3_ = class116.anInt1987;
} else {
i_3_ = class116.anInt1988;
i_4_ = class116.anInt1987;
}
int i_5_ = anInt2609 - -(i_3_ >> 1952131809);
int i_6_ = (i_4_ >> -580821599) + anInt2614;
int i_7_ = anInt2609 - -(i_3_ - -1 >> -1235910239);
int i_8_ = anInt2614 - -(1 + i_4_ >> 1627324641);
method171(i_5_ * 128, i_6_ * 128, (byte) -95);
boolean bool_9_ = (!bool_1_ && class116.aBoolean2018
&& ((anInt2598 ^ 0xffffffff) != (class116.anInt2031
^ 0xffffffff)
|| (anInt2603 != anInt2599
&& Class68_Sub13_Sub26.anInt3876 >= 2)));
if (bool && !bool_9_)
return null;
int[][] is = Class68_Sub20_Sub12.anIntArrayArrayArray4353[anInt2596];
int i_10_ = (anInt2609 << 1876830119) + (i_3_ << 135097254);
int i_11_ = (i_4_ << 1252249254) + (anInt2614 << 1882080487);
boolean bool_12_ = aClass92_Sub1_2605 == null;
int i_13_ = (is[i_7_][i_8_] + is[i_5_][i_8_] + (is[i_5_][i_6_]
+ is[i_7_][i_6_])
>> 675116226);
int[][] is_14_ = null;
if (!bool_1_) {
if (anInt2596 < 3)
is_14_ = (Class68_Sub20_Sub12.anIntArrayArrayArray4353
[1 + anInt2596]);
} else
is_14_ = Class74.anIntArrayArrayArray1335[0];
Class44 class44;
if (aClass55_2617 != null)
class44 = class116.method1714((!bool_12_ ? aClass92_Sub1_2605
: (Class68_Sub20_Sub16
.aClass92_Sub1_4425)),
aClass55_2617, bool_9_, i_10_,
i_13_, anInt2603, anInt2604, is_14_,
is, 65535, i_11_, anInt2602);
else
class44 = class116.method1702(anInt2602,
(!bool_12_ ? aClass92_Sub1_2605
: (Class68_Sub20_Sub16
.aClass92_Sub1_4425)),
bool_9_, (byte) -10, false, i_13_,
anInt2604, is, i_11_, is_14_, i_10_);
if (i != 2)
method171(13, 52, (byte) -73);
if (class44 == null)
return null;
return class44.aClass1_746;
}
public static void method168(int i) {
aRSString_2611 = null;
aRSString_2613 = null;
aRSString_2601 = null;
aRSString_2590 = null;
aClass21_2618 = null;
if (i > -44)
method168(-90);
}
public static void method169(int i, int i_15_, int i_16_, int i_17_,
Animable class1, long l, Animable class1_18_,
Animable class1_19_) {
Class57 class57 = new Class57();
class57.aClass1_1083 = class1;
class57.anInt1074 = i_15_ * 128 + 64;
class57.anInt1075 = i_16_ * 128 + 64;
class57.anInt1085 = i_17_;
class57.aLong1071 = l;
class57.aClass1_1073 = class1_18_;
class57.aClass1_1078 = class1_19_;
int i_20_ = 0;
Class68_Sub1 class68_sub1
= Class22.aClass68_Sub1ArrayArrayArray484[i][i_15_][i_16_];
if (class68_sub1 != null) {
for (int i_21_ = 0; i_21_ < class68_sub1.anInt2771; i_21_++) {
Class69 class69 = class68_sub1.aClass69Array2772[i_21_];
if ((class69.aLong1243 & 0x400000L) == 4194304L) {
int i_22_ = class69.aClass1_1242.method56();
if (i_22_ != -32768 && i_22_ < i_20_)
i_20_ = i_22_;
}
}
}
class57.anInt1069 = -i_20_;
if (Class22.aClass68_Sub1ArrayArrayArray484[i][i_15_][i_16_] == null)
Class22.aClass68_Sub1ArrayArrayArray484[i][i_15_][i_16_]
= new Class68_Sub1(i, i_15_, i_16_);
Class22.aClass68_Sub1ArrayArrayArray484[i][i_15_][i_16_].aClass57_2759
= class57;
}
public static void method170(int i) {
if (i != 255)
aClass21_2618 = null;
anInt2593++;
if (Class33.aClass86_581 != null) {
synchronized (Class33.aClass86_581) {
Class33.aClass86_581 = null;
}
}
}
public int method56() {
anInt2600++;
return anInt2592;
}
public void method51(int i, int i_23_, int i_24_, int i_25_, int i_26_,
int i_27_, int i_28_, int i_29_, long l) {
Animable class1 = method166(675116226);
anInt2607++;
if (class1 != null) {
class1.method51(i, i_23_, i_24_, i_25_, i_26_, i_27_, i_28_, i_29_,
l);
anInt2592 = class1.method56();
}
}
public void method60(int i, int i_30_, int i_31_, int i_32_, int i_33_) {
anInt2594++;
method171(128 * ((i_33_ + -i_30_ >> -315085247) + i_30_) + 64,
64 + (i_32_ - -(i + -i_32_ >> -159060191)) * 128,
(byte) -59);
if (i_31_ < 96)
anInt2604 = 5;
}
public void method171(int i, int i_34_, byte i_35_) {
anInt2615++;
if (aClass55_2617 != null) {
int i_36_ = Class68_Sub3.anInt2812 + -anInt2606;
if ((i_36_ ^ 0xffffffff) < -101 && aClass55_2617.anInt2072 > 0) {
int i_37_;
for (i_37_ = (-aClass55_2617.anInt2072
+ aClass55_2617.anIntArray2035.length);
((anInt2603 ^ 0xffffffff) > (i_37_ ^ 0xffffffff)
&& i_36_ > aClass55_2617.anIntArray2058[anInt2603]);
anInt2603++)
i_36_ -= aClass55_2617.anIntArray2058[anInt2603];
if (anInt2603 >= i_37_) {
int i_38_ = 0;
for (int i_39_ = i_37_;
((aClass55_2617.anIntArray2035.length ^ 0xffffffff)
< (i_39_ ^ 0xffffffff));
i_39_++)
i_38_ += aClass55_2617.anIntArray2058[i_39_];
i_36_ %= i_38_;
}
}
while ((i_36_ ^ 0xffffffff)
< (aClass55_2617.anIntArray2058[anInt2603] ^ 0xffffffff)) {
Class44.method489(false, anInt2603, i, aClass55_2617, false,
i_34_);
i_36_ -= aClass55_2617.anIntArray2058[anInt2603];
anInt2603++;
if (anInt2603 >= aClass55_2617.anIntArray2035.length) {
anInt2603 -= aClass55_2617.anInt2072;
if (anInt2603 < 0
|| ((aClass55_2617.anIntArray2035.length ^ 0xffffffff)
>= (anInt2603 ^ 0xffffffff))) {
aClass55_2617 = null;
break;
}
}
}
anInt2606 = -i_36_ + Class68_Sub3.anInt2812;
}
if (i_35_ >= -25)
anInt2598 = 24;
}
public Class1_Sub7(int i, int i_40_, int i_41_, int i_42_, int i_43_,
int i_44_, int i_45_, boolean bool, Animable class1) {
anInt2599 = -1;
anInt2592 = -32768;
anInt2609 = i_43_;
anInt2614 = i_44_;
anInt2602 = i_40_;
anInt2596 = i_42_;
anInt2595 = i;
anInt2604 = i_41_;
if (i_45_ != -1) {
aClass55_2617 = Class64.method624((byte) -36, i_45_);
anInt2606 = -1 + Class68_Sub3.anInt2812;
anInt2603 = 0;
if ((aClass55_2617.anInt2061 ^ 0xffffffff) == -1 && class1 != null
&& class1 instanceof Class1_Sub7) {
Class1_Sub7 class1_sub7_46_ = (Class1_Sub7) class1;
if (class1_sub7_46_.aClass55_2617 == aClass55_2617) {
anInt2603 = class1_sub7_46_.anInt2603;
anInt2606 = class1_sub7_46_.anInt2606;
return;
}
}
if (bool && aClass55_2617.anInt2072 != -1) {
anInt2603
= (int) ((double) aClass55_2617.anIntArray2035.length
* Math.random());
anInt2606 -= (int) (Math.random()
* (double) (aClass55_2617.anIntArray2058
[anInt2603]));
}
}
}
static {
aBoolean2612 = false;
aRSString_2611 = aRSString_2613;
aRSString_2601 = aRSString_2613;
anInt2597 = 0;
}
}
| agpl-3.0 |
stephaneperry/Silverpeas-Core | lib-core/src/main/java/com/silverpeas/admin/components/ComponentsInstanciatorIntf.java | 2779 | /**
* Copyright (C) 2000 - 2011 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://repository.silverpeas.com/legal/licensing"
*
* 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.admin.components;
import java.sql.Connection;
/**
* Interface for the instanciator component class. An instanciator creates and deletes components on
* a space for a user.
* @author Joaquim Vieira
*/
public interface ComponentsInstanciatorIntf {
/**
* The name of the component descriptor parameter holding the process file name
*/
public static final String PROCESS_XML_FILE_NAME = "XMLFileName";
/**
* Create a new instance of the component for a requested user and space.
* @param connection - Connection to the database used to save the create information.
* @param spaceId - Identity of the space where the component will be instancied.
* @param componentId - Identity of the component to instanciate.
* @param userId - Identity of the user who want the component
* @throws InstanciationException
* @roseuid 3B82286B0236
*/
public void create(Connection connection, String spaceId, String componentId,
String userId) throws InstanciationException;
/**
* Delete the component instance created for the user on the requested space.
* @param connection - Connection to the database where the create information will be destroyed.
* @param spaceId - Identity of the space where the instanced component will be deleted.
* @param componentId - Identity of the instanced component
* @param userId - Identity of the user who have instantiate the component.
* @throws InstanciationException
* @roseuid 3B8228740117
*/
public void delete(Connection connection, String spaceId, String componentId,
String userId) throws InstanciationException;
}
| agpl-3.0 |
Cineca/OrcidHub | src/main/java/it/cineca/pst/huborcid/web/rest/exception/TokenNotFoundException.java | 1148 | /**
* This file is part of huborcid.
*
* huborcid 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.
*
* huborcid 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 huborcid. If not, see <http://www.gnu.org/licenses/>.
*/
package it.cineca.pst.huborcid.web.rest.exception;
public class TokenNotFoundException extends Exception {
/**
*
*/
private static final long serialVersionUID = 4044790109623763501L;
String token = null;
public TokenNotFoundException(String token) {
super("token: "+token +" not found!");
this.token = token;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
| agpl-3.0 |
lonangel/adl-designer | designer/src/main/java/org/openehr/designer/repository/AbstractFileBasedArchetypeRepository.java | 10086 | /*
* ADL Designer
* Copyright (c) 2013-2014 Marand d.o.o. (www.marand.com)
*
* This file is part of ADL2-tools.
*
* ADL2-tools 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.openehr.designer.repository;
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import org.openehr.adl.am.ArchetypeIdInfo;
import org.openehr.adl.parser.AdlDeserializer;
import org.openehr.adl.parser.BomSupportingReader;
import org.openehr.adl.serializer.ArchetypeSerializer;
import org.openehr.designer.ArchetypeInfo;
import org.openehr.designer.WtUtils;
import org.openehr.jaxb.am.Archetype;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* @author markopi
*/
abstract public class AbstractFileBasedArchetypeRepository extends AbstractArchetypeRepository {
public static final Logger LOG = LoggerFactory.getLogger(AbstractFileBasedArchetypeRepository.class);
protected final AdlDeserializer deserializer = new AdlDeserializer();
private List<LocalArchetypeInfo> localArchetypeInfoList;
private Function<Archetype, Path> newArchetypeFileLocationGenerator = (archetype) -> {
ArchetypeIdInfo aidi = ArchetypeIdInfo.parse(archetype.getArchetypeId().getValue());
return Paths.get(aidi.toInterfaceString() + ".adls");
};
protected LocalArchetypeInfo createLocalArchetypeInfo(Path path, Archetype archetype) {
LocalArchetypeInfo result = new LocalArchetypeInfo();
result.setInfo(createArchetypeInfo(archetype));
String interfaceArchetypeId = ArchetypeIdInfo.parse(result.getInfo().getArchetypeId()).toInterfaceString();
result.setInterfaceArchetypeId(interfaceArchetypeId);
result.setPath(path);
return result;
}
@Nullable
protected LocalArchetypeInfo getLocalArchetypeInfo(String archetypeId) {
for (LocalArchetypeInfo localArchetypeInfo : localArchetypeInfoList) {
if (localArchetypeInfo.getInfo().getArchetypeId().equals(archetypeId)
|| localArchetypeInfo.getInterfaceArchetypeId().equals(archetypeId)) {
return localArchetypeInfo;
}
}
return null;
}
protected abstract Path getRepositoryLocation();
public Function<Archetype, Path> getNewArchetypeFileLocator() {
return newArchetypeFileLocationGenerator;
}
public void setNewArchetypeFileLocationGenerator(Function<Archetype, Path> newArchetypeFileLocationGenerator) {
this.newArchetypeFileLocationGenerator = newArchetypeFileLocationGenerator;
}
protected void parseRepository() throws IOException {
localArchetypeInfoList = parseRepositoryArchetypes();
}
private List<LocalArchetypeInfo> parseRepositoryArchetypes() throws IOException {
List<LocalArchetypeInfo> result = new ArrayList<>();
List<Path> adlFiles = new ArrayList<>();
Path repositoryPath = getRepositoryLocation();
addAdlFilesRecursively(adlFiles, repositoryPath);
for (Path adlFile : adlFiles) {
Path relativeArchetypePath = repositoryPath.relativize(adlFile);
try {
LOG.info("Parsing archetype file " + relativeArchetypePath);
String adlContent = readArchetype(adlFile);
Archetype archetype = deserializer.parse(adlContent);
LocalArchetypeInfo info = createLocalArchetypeInfo(relativeArchetypePath, archetype);
result.add(info);
// sourceArchetypes.put(info.getArchetypeId(), archetype);
// sourceArchetypes.put(interfaceArchetypeId, archetype);
} catch (Exception e) {
LOG.error("Error parsing archetype from file " + relativeArchetypePath + ". Archetype will be ignored", e);
}
}
return result;
}
private String readArchetype(Path adlFile) {
try {
return CharStreams.toString(new BomSupportingReader(
Files.newInputStream(adlFile),
Charsets.UTF_8));
} catch (IOException e) {
throw new ArchetypeRepositoryException("Could not read archetype from file " + adlFile, e);
}
}
protected void addAdlFilesRecursively(List<Path> target, Path directory) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
for (Path path : stream) {
if (Files.isDirectory(path)) {
if (acceptDirectory(path)) {
addAdlFilesRecursively(target, path);
}
} else if (path.getFileName().toString().endsWith(".adls")) {
target.add(path);
}
}
}
}
protected boolean acceptDirectory(Path dir) {
return !dir.getFileName().toString().startsWith(".");
}
protected Path getArchetypeFileLocation(@Nullable LocalArchetypeInfo info, Archetype archetype) {
if (info == null) {
// new archetype
return newArchetypeFileLocationGenerator.apply(archetype);
} else {
return info.getPath();
}
}
protected LocalArchetypeInfo addArchetype(Archetype archetype, String adl) throws IOException {
final Path archetypePath = getArchetypeFileLocation(null, archetype);
LOG.info("Saving new archetype in file {}", archetypePath);
LocalArchetypeInfo localArchetypeInfo = createLocalArchetypeInfo(archetypePath, archetype);
localArchetypeInfoList.add(localArchetypeInfo);
Path absolutePath = getRepositoryLocation().resolve(archetypePath);
Files.createDirectories(absolutePath.getParent());
Files.write(absolutePath, adl.getBytes(Charsets.UTF_8));
return localArchetypeInfo;
}
protected LocalArchetypeInfo updateArchetype(Archetype archetype, String adl) throws IOException {
LocalArchetypeInfo existingArchetypeInfo = getLocalArchetypeInfo(archetype.getArchetypeId().getValue());
checkNotNull(existingArchetypeInfo, "Archetype does not exist");
LOG.info("Updating archetype in file {}", existingArchetypeInfo.getPath());
LocalArchetypeInfo newLocalArchetypeInfo = createLocalArchetypeInfo(existingArchetypeInfo.getPath(), archetype);
int archetypeInfoIndex = WtUtils.indexOf(localArchetypeInfoList, (t) -> t == existingArchetypeInfo);
localArchetypeInfoList.set(archetypeInfoIndex, newLocalArchetypeInfo);
final Path archetypePath = getRepositoryLocation().resolve(newLocalArchetypeInfo.getPath());
Files.write(getRepositoryLocation().resolve(archetypePath), adl.getBytes(Charsets.UTF_8));
return newLocalArchetypeInfo;
}
protected LocalArchetypeInfo saveArchetypeToFile(Archetype archetype) {
checkArgument(archetype.isIsDifferential(), "Must be a differential archetype");
String adl = ArchetypeSerializer.serialize(archetype);
archetype = deserializer.parse(adl); // checks if the serialization is readable
LocalArchetypeInfo localArchetypeInfo = getLocalArchetypeInfo(archetype.getArchetypeId().getValue());
try {
//ArchetypeInfo info = createArchetypeInfo(archetype);
if (localArchetypeInfo == null) {
return addArchetype(archetype, adl);
} else {
return updateArchetype(archetype, adl);
}
} catch (ArchetypeRepositoryException e) {
throw e;
} catch (Exception e) {
throw new ArchetypeRepositoryException("Could not archetype to file", e);
}
}
protected Archetype loadDifferentialArchetype(String archetypeId) {
LocalArchetypeInfo localArchetypeInfo = getLocalArchetypeInfo(archetypeId);
if (localArchetypeInfo == null) {
throw new ArchetypeNotFoundException(archetypeId);
}
String adl = readArchetype(getRepositoryLocation().resolve(localArchetypeInfo.getPath()));
return deserializer.parse(adl);
}
@Override
public List<ArchetypeInfo> getArchetypeInfos() {
return localArchetypeInfoList.stream().map(LocalArchetypeInfo::getInfo)
.collect(Collectors.toList());
}
protected static class LocalArchetypeInfo {
private Path path;
private String interfaceArchetypeId;
private ArchetypeInfo info;
public String getInterfaceArchetypeId() {
return interfaceArchetypeId;
}
public void setInterfaceArchetypeId(String interfaceArchetypeId) {
this.interfaceArchetypeId = interfaceArchetypeId;
}
public Path getPath() {
return path;
}
public void setPath(Path path) {
this.path = path;
}
public ArchetypeInfo getInfo() {
return info;
}
public void setInfo(ArchetypeInfo info) {
this.info = info;
}
}
}
| agpl-3.0 |
clintonhealthaccess/lmis-moz-mobile | app/src/main/java/org/openlmis/core/network/model/UserResponse.java | 288 | package org.openlmis.core.network.model;
import org.openlmis.core.model.Program;
import org.openlmis.core.model.User;
import java.util.List;
import lombok.Data;
@Data
public class UserResponse {
private User userInformation;
private List<Program> facilitySupportedPrograms;
}
| agpl-3.0 |
ktunaxa/rms | map/src/main/java/org/ktunaxa/referral/client/form/DiscussEvaluationForm.java | 2031 | /*
* Ktunaxa Referral Management System.
*
* Copyright (C) see version control system
*
* 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.ktunaxa.referral.client.form;
import java.util.HashMap;
import java.util.Map;
import org.ktunaxa.bpm.KtunaxaBpmConstant;
import org.ktunaxa.referral.server.dto.TaskDto;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;
/**
* Empty task form, not requiring input of any values.
*
* @author Joachim Van der Auwera
*/
public class DiscussEvaluationForm extends AbstractTaskForm {
private CheckboxItem finalDecisionConsistent = new CheckboxItem();
public DiscussEvaluationForm() {
super();
finalDecisionConsistent.setName("finalDecisionConsistent");
finalDecisionConsistent.setTitle("Consistent decision");
finalDecisionConsistent.setPrompt("Provincial decision is consistent with KLRA response");
setFields(finalDecisionConsistent);
}
@Override
public void refresh(TaskDto task) {
super.refresh(task);
finalDecisionConsistent.setValue(task.getVariables().
get(KtunaxaBpmConstant.VAR_FINAL_DECISION_CONSISTENT));
}
@Override
public Map<String, String> getVariables() {
Map<String, String> result = new HashMap<String, String>();
result.put(KtunaxaBpmConstant.VAR_FINAL_DECISION_CONSISTENT + KtunaxaBpmConstant.SET_BOOLEAN,
nullSafeToString(finalDecisionConsistent.getValue()));
return result;
}
}
| agpl-3.0 |
AdrianLxM/AndroidAPS | app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java | 1763 | package info.nightscout.androidaps.events;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
/**
* Created by mike on 19.02.2017.
*/
public class EventPumpStatusChanged {
public static final int CONNECTING = 0;
public static final int CONNECTED = 1;
public static final int PERFORMING = 2;
public static final int DISCONNECTING = 3;
public static final int DISCONNECTED = 4;
public int sStatus = DISCONNECTED;
public int sSecondsElapsed = 0;
public String sPerfomingAction = "";
public static String error = "";
public EventPumpStatusChanged(int status) {
sStatus = status;
sSecondsElapsed = 0;
error = "";
}
public EventPumpStatusChanged(int status, int secondsElapsed) {
sStatus = status;
sSecondsElapsed = secondsElapsed;
error = "";
}
public EventPumpStatusChanged(int status, String error) {
sStatus = status;
sSecondsElapsed = 0;
this.error = error;
}
public EventPumpStatusChanged(String action) {
sStatus = PERFORMING;
sSecondsElapsed = 0;
sPerfomingAction = action;
}
public String textStatus() {
if (sStatus == CONNECTING)
return String.format(MainApp.sResources.getString(R.string.danar_history_connectingfor), sSecondsElapsed);
else if (sStatus == CONNECTED)
return MainApp.sResources.getString(R.string.connected);
else if (sStatus == PERFORMING)
return sPerfomingAction;
else if (sStatus == DISCONNECTING)
return MainApp.sResources.getString(R.string.disconnecting);
else if (sStatus == DISCONNECTED)
return "";
return "";
}
}
| agpl-3.0 |
CecileBONIN/Silverpeas-Core | lib-core/src/main/java/com/silverpeas/thumbnail/control/ThumbnailDummyHandledFile.java | 3231 | /*
* 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 recieved 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.thumbnail.control;
import com.silverpeas.thumbnail.model.ThumbnailDetail;
import com.silverpeas.util.FileUtil;
import com.stratelia.webactiv.util.WAPrimaryKey;
import org.apache.commons.io.FileUtils;
import org.silverpeas.process.io.file.AbstractDummyHandledFile;
import java.io.File;
/**
* User: Yohann Chastagnier
* Date: 25/10/13
*/
public class ThumbnailDummyHandledFile extends AbstractDummyHandledFile {
private final ThumbnailDetail thumbnail;
private final File thumbnailFile;
private boolean deleted = false;
private WAPrimaryKey targetPK = null;
public ThumbnailDummyHandledFile(final ThumbnailDetail thumbnail, final File thumbnailFile) {
this(thumbnail, thumbnailFile, false);
}
/**
* Default constructor.
* @param thumbnail
* @param targetPK
*/
public ThumbnailDummyHandledFile(final ThumbnailDetail thumbnail, final File thumbnailFile,
final WAPrimaryKey targetPK) {
this(thumbnail, thumbnailFile);
this.targetPK = targetPK;
}
/**
* Default constructor.
* @param thumbnail
* @param deleted
*/
public ThumbnailDummyHandledFile(final ThumbnailDetail thumbnail, final File thumbnailFile,
final boolean deleted) {
this.thumbnail = thumbnail;
this.thumbnailFile = thumbnailFile;
this.deleted = deleted;
}
@Override
public String getComponentInstanceId() {
if (targetPK != null) {
return targetPK.getInstanceId();
}
return thumbnail.getInstanceId();
}
@Override
public String getPath() {
return thumbnailFile.getPath();
}
@Override
public String getName() {
return thumbnailFile.getName();
}
@Override
public long getSize() {
if (!thumbnailFile.exists()) {
return 0;
}
return FileUtils.sizeOf(thumbnailFile);
}
@Override
public String getMimeType() {
if (thumbnailFile.exists() && thumbnailFile.isFile()) {
return FileUtil.getMimeType(thumbnailFile.getPath());
}
return thumbnail.getMimeType();
}
@Override
public boolean isDeleted() {
return deleted;
}
}
| agpl-3.0 |
VietOpenCPS/opencps-v2 | modules/backend-dossiermgt/backend-dossiermgt-service/src/main/java/org/opencps/dossiermgt/scheduler/DossierSyncUtils.java | 1518 | package org.opencps.dossiermgt.scheduler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONObject;
public class DossierSyncUtils {
public static final String dossierId = "dossierId";
public static final String dossierSyncId = "dossierSyncId";
public static final String method = "method";
public static ArrayList<DossierSyncOrderedModel> convertToModel(JSONArray array) {
ArrayList<DossierSyncOrderedModel> dossierSyncModels = new ArrayList<DossierSyncOrderedModel>();
for (int i = 0; i < array.length(); i++) {
JSONObject jsElm = array.getJSONObject(i);
DossierSyncOrderedModel dsm = new DossierSyncOrderedModel(jsElm.getLong(dossierSyncId),
jsElm.getLong(dossierId), jsElm.getInt(method));
dossierSyncModels.add(dsm);
}
return dossierSyncModels;
}
public static void orderSync(ArrayList<DossierSyncOrderedModel> origin) {
Collections.sort(origin, new Comparator<DossierSyncOrderedModel>() {
@Override
public int compare(DossierSyncOrderedModel obj1, DossierSyncOrderedModel obj2) {
Long dossierId1 = obj1.getDossierId();
Long dossierId2 = obj2.getDossierId();
int didComp = dossierId1.compareTo(dossierId2);
if (didComp != 0) {
return didComp;
} else {
Integer method1 = obj1.getMethodId();
Integer method2 = obj2.getMethodId();
return method2.compareTo(method1);
}
}
});
}
}
| agpl-3.0 |
ANBAL534/EORA | src/rattingadvisor/DbUtils.java | 10711 | /*
* DbUtils.java
EVE Online Ratting Advisor
Copyright (C) 2016 Anibal Muñoz Calero
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 rattingadvisor;
import java.sql.*;
import javax.swing.JTextArea;
/**
*
* @author Anibal
*/
public class DbUtils {
JTextArea textArea;
String dbName;
Connection conn;
Shared shared;
public DbUtils(String databaseName, JTextArea logArea) {
textArea = logArea;
dbName = databaseName;
conn = null;
try {
Class.forName("org.sqlite.JDBC");
} catch (Exception ex) {
log(ex.getMessage());
}
}
public void log(String log){
textArea.append("\n" + log);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
public void closeDb(){
try {
conn.close();
} catch (SQLException ex) {
log(ex.getMessage());
}
}
public void newOpenDb(){
boolean exists;
Statement stmt = null;
try {
exists = new FileManager().FileExist(dbName);
conn = DriverManager.getConnection("jdbc:sqlite:" + dbName);
stmt = conn.createStatement();
log("Opened " + dbName + " database successfully.");
if(!exists){//If db didn't exist we create the tables
String sql = "CREATE TABLE DEKLEIN "
+ "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "ORIGIN TEXT NOT NULL,"
+ "CONNECTION1 TEXT,"
+ "CONNECTION2 TEXT,"
+ "CONNECTION3 TEXT,"
+ "CONNECTION4 TEXT,"
+ "CONNECTION5 TEXT,"
+ "CONNECTION6 TEXT,"
+ "CONNECTION7 TEXT,"
+ "CONNECTION8 TEXT,"
+ "CONNECTION9 TEXT,"
+ "CONNECTION10 TEXT)";
//TODO: Add more regions in the future
stmt.executeUpdate(sql);
log("Region tables created successfully in the new empty database.");
}
stmt.close();
} catch (SQLException ex) {
log(ex.getMessage());
}
}
public int getIdFromOrigin(String systemName){
int id = -1;
try {
Statement stmt = null;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM DEKLEIN;");
while (rs.next()) {
if(rs.getString("ORIGIN").equals(systemName)){
id = rs.getInt("ID");
break;
}
}
stmt.close();
} catch (SQLException ex) {
log(ex.getMessage());
}
return id;
}
public String getSystemFromId(int id){
String systemName = "";
try {
Statement stmt = null;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM DEKLEIN;");
while (rs.next()) {
if(rs.getInt("ID") == id){
systemName = rs.getString("ORIGIN");
break;
}
}
stmt.close();
} catch (SQLException ex) {
log(ex.getMessage());
}
return systemName;
}
public void addSaveToDb(String origin, String[] connections){
try{
Statement stmt = null;
if(getIdFromOrigin(origin) == -1){//If there is no entry insert the values
stmt = conn.createStatement();
String sql = "INSERT INTO DEKLEIN (ORIGIN,CONNECTION1,CONNECTION2,CONNECTION3,CONNECTION4,CONNECTION5,CONNECTION6,CONNECTION7,CONNECTION8,CONNECTION9,CONNECTION10) "
+ "VALUES ('" + origin + "','" + connections[0] + "','" + connections[1] + "','" + connections[2] + "','" + connections[3] + "','" + connections[4] + "','" + connections[5] + "','" + connections[6] + "','" + connections[7] + "','" + connections[8] + "','" + connections[9] + "');";
stmt.executeUpdate(sql);
stmt.close();
log("Connections of " + origin + " newly created in the database successfully.");
}else{//If there is the entry update the values
int id = getIdFromOrigin(origin);
stmt = conn.createStatement();
String sql = "UPDATE DEKLEIN set CONNECTION1='" + connections[0] + "' where ID=" + id;
stmt.executeUpdate(sql);
sql = "UPDATE DEKLEIN set CONNECTION2='" + connections[1] + "' where ID=" + id;
stmt.executeUpdate(sql);
sql = "UPDATE DEKLEIN set CONNECTION3='" + connections[2] + "' where ID=" + id;
stmt.executeUpdate(sql);
sql = "UPDATE DEKLEIN set CONNECTION4='" + connections[3] + "' where ID=" + id;
stmt.executeUpdate(sql);
sql = "UPDATE DEKLEIN set CONNECTION5='" + connections[4] + "' where ID=" + id;
stmt.executeUpdate(sql);
sql = "UPDATE DEKLEIN set CONNECTION6='" + connections[5] + "' where ID=" + id;
stmt.executeUpdate(sql);
sql = "UPDATE DEKLEIN set CONNECTION7='" + connections[6] + "' where ID=" + id;
stmt.executeUpdate(sql);
sql = "UPDATE DEKLEIN set CONNECTION8='" + connections[7] + "' where ID=" + id;
stmt.executeUpdate(sql);
sql = "UPDATE DEKLEIN set CONNECTION9='" + connections[8] + "' where ID=" + id;
stmt.executeUpdate(sql);
sql = "UPDATE DEKLEIN set CONNECTION10='" + connections[9] + "' where ID=" + id;
stmt.executeUpdate(sql);
stmt.close();
log("Connections of " + origin + " updated in the database successfully.");
}
}catch(Exception e){
log(e.getMessage());
}
}
public String[] getRowFromOrigin(String systemName){
String[] result = new String[11];
int id = getIdFromOrigin(systemName);
try {
Statement stmt = null;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM DEKLEIN;");
while (rs.next()) {
if(rs.getInt("ID") == id){
result[0] = rs.getString("ORIGIN");
result[1] = rs.getString("CONNECTION1");
result[2] = rs.getString("CONNECTION2");
result[3] = rs.getString("CONNECTION3");
result[4] = rs.getString("CONNECTION4");
result[5] = rs.getString("CONNECTION5");
result[6] = rs.getString("CONNECTION6");
result[7] = rs.getString("CONNECTION7");
result[8] = rs.getString("CONNECTION8");
result[9] = rs.getString("CONNECTION9");
result[10] = rs.getString("CONNECTION10");
//log("Connections data from " + systemName + " found.");
break;
}
}
stmt.close();
} catch (SQLException ex) {
log(ex.getMessage());
}
if(id == -1)
log("Connections data from " + systemName + " NOT found.");
return result;
}
public String[] getRowFromId(int id){
String[] result = new String[11];
try {
Statement stmt = null;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM DEKLEIN;");
while (rs.next()) {
if(rs.getInt("ID") == id){
result[0] = rs.getString("ORIGIN");
result[1] = rs.getString("CONNECTION1");
result[2] = rs.getString("CONNECTION2");
result[3] = rs.getString("CONNECTION3");
result[4] = rs.getString("CONNECTION4");
result[5] = rs.getString("CONNECTION5");
result[6] = rs.getString("CONNECTION6");
result[7] = rs.getString("CONNECTION7");
result[8] = rs.getString("CONNECTION8");
result[9] = rs.getString("CONNECTION9");
result[10] = rs.getString("CONNECTION10");
//log("Connections data from ID: " + id + " (" + result[0] + ") found.");
break;
}
}
stmt.close();
} catch (SQLException ex) {
log(ex.getMessage());
}
if(id == -1)
log("Connections data from ID: " + id + "(" + result[0] + ") NOT found.");
return result;
}
}
| agpl-3.0 |
ua-eas/ua-kfs-5.3 | work/src/org/kuali/kfs/module/endow/batch/service/HoldingHistoryMarketValuesUpdateService.java | 1088 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* 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.kuali.kfs.module.endow.batch.service;
public interface HoldingHistoryMarketValuesUpdateService {
/**
* Updates Holding History Market Values
*/
public boolean updateHoldingHistoryMarketValues();
}
| agpl-3.0 |
oleaamot/grouse | src/main/java/no/kdrs/grouse/service/interfaces/IRequirementService.java | 428 | package no.kdrs.grouse.service.interfaces;
import no.kdrs.grouse.model.Requirement;
import java.util.List;
/**
* Created by tsodring on 9/25/17.
*/
public interface IRequirementService {
List<Requirement> findAll();
Requirement findById(String id);
Requirement save(Requirement requirement);
Requirement update(String requirementId, Requirement requirement) throws Exception;
void delete(String id);
}
| agpl-3.0 |
aborg0/rapidminer-vega | src/com/rapidminer/gui/look/ui/TableUI.java | 1350 | /*
* RapidMiner
*
* Copyright (C) 2001-2011 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.look.ui;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicTableUI;
/**
* The UI for tables. Simply uses the basic table UI.
*
* @author Ingo Mierswa
*/
public class TableUI extends BasicTableUI {
public static ComponentUI createUI(JComponent c) {
return new BasicTableUI();
}
@Override
protected void installDefaults() {
super.installDefaults();
}
}
| agpl-3.0 |
Asqatasun/Asqatasun | engine/contentloader/src/test/java/org/asqatasun/contentloader/FileContentLoaderFactoryImplTest.java | 2028 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This file is part of Asqatasun.
*
* Asqatasun 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.contentloader;
import java.util.Map;
import junit.framework.TestCase;
import org.asqatasun.entity.service.audit.ContentDataService;
import org.asqatasun.util.factory.DateFactory;
/**
*
* @author jkowalczyk
*/
public class FileContentLoaderFactoryImplTest extends TestCase {
public FileContentLoaderFactoryImplTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of create method, of class FileContentLoaderFactoryImpl.
*/
public void testCreate() {
System.out.println("create");
ContentDataService contentDataService = null;
Map<String, String> fileMap = null;
FileContentLoaderFactoryImpl instance = new FileContentLoaderFactoryImpl(contentDataService);
ContentLoader contentLoader = instance.create(fileMap, new DateFactory());
assertTrue(contentLoader instanceof FileContentLoaderImpl);
}
}
| agpl-3.0 |
opencadc/core | cadc-keygen/src/main/java/ca/nrc/cadc/keygen/Main.java | 6662 | /*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2011. (c) 2011.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 5 $
*
************************************************************************
*/
package ca.nrc.cadc.keygen;
import ca.nrc.cadc.util.ArgumentMap;
import ca.nrc.cadc.util.Log4jInit;
import ca.nrc.cadc.util.RsaSignatureGenerator;
import java.io.File;
import java.util.List;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
/**
* Simple utility to call RsaSignatureGenerator.genKeyPair(...).
*
* @author pdowler
*/
public class Main {
private static final Logger log = Logger.getLogger(Main.class);
public static void main(String[] args) {
try {
ArgumentMap am = new ArgumentMap(args);
if (am.isSet("h") || am.isSet("help")) {
usage();
}
Level level = Level.WARN;
if (am.isSet("d") || am.isSet("debug")) {
level = Level.DEBUG;
} else if (am.isSet("v") || am.isSet("verbose")) {
level = Level.INFO;
}
Log4jInit.setLevel("ca.nrc.cadc.keygen", level);
Log4jInit.setLevel("ca.nrc.cadc.util", level);
int keylen = 1024;
String slen = am.getValue("len");
if (slen != null) {
keylen = Integer.parseInt(slen);
}
List<String> out = am.getPositionalArgs();
if (out.size() != 2) {
usage();
System.exit(1);
}
File pub = new File(out.get(0));
File priv = new File(out.get(1));
Main m = new Main(pub, priv, keylen);
m.run();
} catch (Throwable t) {
log.error("FAIL", t);
}
}
private static void usage() {
System.out.println("usage: cadc-keygen [-v|--verbose|-d|--debug] [--len=<key length>] <pubkey> <privkey>");
System.out.println(" --len=<key length> [default: 1024]");
System.exit(1);
}
private File pubKey;
private File privKey;
private int len;
private Main() {
}
private Main(File pub, File priv, int len) {
this.pubKey = pub;
this.privKey = priv;
this.len = len;
}
public void run() {
try {
log.info("generating " + pubKey.getAbsolutePath() + " / " + privKey.getAbsolutePath() + " ...");
RsaSignatureGenerator.genKeyPair(pubKey, privKey, len);
log.info("generating " + pubKey.getAbsolutePath() + " / " + privKey.getAbsolutePath() + " ... [OK]");
} catch (Exception ex) {
log.error("failed to generate key pair", ex);
log.info("generating " + pubKey.getAbsolutePath() + " / " + privKey.getAbsolutePath() + " ... [FAIL]");
}
}
}
| agpl-3.0 |
RestComm/jss7 | map/map-api/src/main/java/org/restcomm/protocols/ss7/map/api/service/callhandling/CallDiversionTreatmentIndicator.java | 1497 | /*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* 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.map.api.service.callhandling;
import java.io.Serializable;
/**
* CallDiversionTreatmentIndicator ::= OCTET STRING (SIZE(1)) -- callDiversionAllowed (xxxx xx01) -- callDiversionNotAllowed
* (xxxx xx10) -- network default is call diversion allowed
*
* @author cristian veliscu
*
*/
public interface CallDiversionTreatmentIndicator extends Serializable {
int getData();
CallDiversionTreatmentIndicatorValue getCallDiversionTreatmentIndicatorValue();
}
| agpl-3.0 |
lpellegr/scheduling-portal | scheduler-portal/src/test/java/org/ow2/proactive_grid_cloud_portal/scheduler/client/SchedulerModelImplTest.java | 6556 | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2015 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive_grid_cloud_portal.scheduler.client;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.model.ExecutionsModel;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.model.JobsModel;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.model.OutputModel;
public class SchedulerModelImplTest {
private static final String STYLE_FOR_TASK_NAME = "<span style='color:gray;'>";
private OutputModel outputModel;
protected SchedulerModelImpl schedulerModel;
protected ExecutionsModel executionsModel;
protected JobsModel jobsModel;
@Before
public void setUp() throws Exception {
this.schedulerModel = new SchedulerModelImpl();
this.executionsModel = new ExecutionsModel(schedulerModel);
this.schedulerModel.setExecutionsModel(executionsModel);
outputModel = new OutputModel(this.schedulerModel);
this.schedulerModel.setOutputModel(outputModel);
this.jobsModel = new JobsModel(executionsModel);
this.executionsModel.setJobsModel(jobsModel);
}
// PORTAL-244 PORTAL-243
@Test
public void testSetTaskOutput_LinuxLineBreak() {
addJob(42);
Task task = new Task();
outputModel.setTaskOutput("42", task, "[Compute1@192.168.1.168;16:07:40] first line\n[Compute1@192.168.1.168;16:07:40] second line");
JobOutput jobOutput = outputModel.getJobOutput("42", false);
String firstLine = jobOutput.getLines(task).get(0);
String secondLine = jobOutput.getLines(task).get(1);
assertTrue(firstLine.contains("first"));
assertTrue(firstLine.contains(STYLE_FOR_TASK_NAME));
assertTrue(secondLine.contains("second"));
assertTrue(secondLine.contains(STYLE_FOR_TASK_NAME));
}
// PORTAL-244 PORTAL-243
@Test
public void testSetTaskOutput_WindowsLineBreak() {
addJob(42);
Task task = new Task();
outputModel.setTaskOutput("42", task, "[Compute1@192.168.1.168;16:07:40] first line\r\n[Compute1@192.168.1.168;16:07:40] second line");
JobOutput jobOutput = outputModel.getJobOutput("42", false);
String firstLine = jobOutput.getLines(task).get(0);
String secondLine = jobOutput.getLines(task).get(1);
assertTrue(firstLine.contains("first"));
assertTrue(firstLine.contains(STYLE_FOR_TASK_NAME));
assertTrue(secondLine.contains("second"));
assertTrue(secondLine.contains(STYLE_FOR_TASK_NAME));
}
// PORTAL-244 PORTAL-243
@Test
public void testAppendLiveOutput_LinuxLineBreak() {
addJob(42);
JobOutput out = outputModel.getJobOutput("42", true);
outputModel.setCurrentOutput(out);
outputModel.getCurrentOutput().setLive(true);
outputModel.appendLiveOutput("42", "[Compute1@192.168.1.168;16:07:40] first line\n[Compute1@192.168.1.168;16:07:40] second line");
Collection<List<String>> jobOutput = outputModel.getCurrentOutput().getLines();
List<String> output = jobOutput.iterator().next();
assertTrue(output.get(0).contains("first"));
assertTrue(output.get(0).contains(STYLE_FOR_TASK_NAME));
assertTrue(output.get(1).contains("second"));
assertTrue(output.get(1).contains(STYLE_FOR_TASK_NAME));
}
// PORTAL-244 PORTAL-243
@Test
public void testAppendLiveOutput_WindowsLineBreak() {
addJob(42);
JobOutput out = outputModel.getJobOutput("42", true);
outputModel.setCurrentOutput(out);
outputModel.getCurrentOutput().setLive(true);
outputModel.appendLiveOutput("42", "[Compute1@192.168.1.168;16:07:40] first line\r\n[Compute1@192.168.1.168;16:07:40] second line");
Collection<List<String>> jobOutput = outputModel.getCurrentOutput().getLines();
List<String> output = jobOutput.iterator().next();
assertTrue(output.get(0).contains("first"));
assertTrue(output.get(0).contains(STYLE_FOR_TASK_NAME));
assertTrue(output.get(1).contains("second"));
assertTrue(output.get(1).contains(STYLE_FOR_TASK_NAME));
}
@Test
public void testAppendLiveOutput_WrongFormat() {
addJob(42);
JobOutput out = outputModel.getJobOutput("42", true);
outputModel.setCurrentOutput(out);
outputModel.getCurrentOutput().setLive(true);
outputModel.appendLiveOutput("42", "first line\r\nsecond line");
Collection<List<String>> jobOutput = outputModel.getCurrentOutput().getLines();
List<String> output = jobOutput.iterator().next();
assertTrue(output.isEmpty());
}
private void addJob(int jobId) {
Job job = new Job(jobId);
job.setStatus(JobStatus.RUNNING);
this.jobsModel.setJobs(new LinkedHashMap<Integer, Job>(Collections.singletonMap(jobId, job)), 1, 1);
}
}
| agpl-3.0 |
acontes/scheduling | src/resource-manager/src/org/ow2/proactive/resourcemanager/selection/SelectionManager.java | 21348 | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.resourcemanager.selection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.api.PAFuture;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.utils.NamedThreadFactory;
import org.ow2.proactive.resourcemanager.authentication.Client;
import org.ow2.proactive.resourcemanager.core.RMCore;
import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties;
import org.ow2.proactive.resourcemanager.exception.NotConnectedException;
import org.ow2.proactive.resourcemanager.rmnode.RMNode;
import org.ow2.proactive.resourcemanager.selection.policies.ShufflePolicy;
import org.ow2.proactive.resourcemanager.selection.topology.TopologyHandler;
import org.ow2.proactive.scripting.Script;
import org.ow2.proactive.scripting.ScriptException;
import org.ow2.proactive.scripting.ScriptResult;
import org.ow2.proactive.scripting.SelectionScript;
import org.ow2.proactive.utils.Criteria;
import org.ow2.proactive.utils.NodeSet;
import org.ow2.proactive.utils.appenders.MultipleFileAppender;
/**
* An interface of selection manager which is responsible for
* nodes selection from a pool of free nodes for further scripts execution.
*
*/
public abstract class SelectionManager {
private final static Logger logger = Logger.getLogger(SelectionManager.class);
private RMCore rmcore;
private static final int SELECTION_THEADS_NUMBER = PAResourceManagerProperties.RM_SELECTION_MAX_THREAD_NUMBER
.getValueAsInt();
private ExecutorService scriptExecutorThreadPool;
private Set<String> inProgress;
// the policy for arranging nodes
private SelectionPolicy selectionPolicy;
public SelectionManager() {
}
public SelectionManager(RMCore rmcore) {
this.rmcore = rmcore;
this.scriptExecutorThreadPool = Executors.newFixedThreadPool(SELECTION_THEADS_NUMBER,
new NamedThreadFactory("Selection manager threadpool"));
this.inProgress = Collections.synchronizedSet(new HashSet<String>());
String policyClassName = PAResourceManagerProperties.RM_SELECTION_POLICY.getValueAsString();
try {
Class<?> policyClass = Class.forName(policyClassName);
selectionPolicy = (SelectionPolicy) policyClass.newInstance();
} catch (Exception e) {
logger.error("Cannot use the specified policy class: " + policyClassName, e);
logger.warn("Using the default class: " + ShufflePolicy.class.getName());
selectionPolicy = new ShufflePolicy();
}
}
/**
* Arranges nodes for script execution based on some criteria
* for example previous execution statistics.
*
* @param nodes - nodes list for script execution
* @param scripts - set of selection scripts
* @return collection of arranged nodes
*/
public abstract List<RMNode> arrangeNodesForScriptExecution(final List<RMNode> nodes,
List<SelectionScript> scripts);
/**
* Predicts script execution result. Allows to avoid duplicate script execution
* on the same node.
*
* @param script - script to execute
* @param rmnode - target node
* @return true if script will pass on the node
*/
public abstract boolean isPassed(SelectionScript script, RMNode rmnode);
/**
* Processes script result and updates knowledge base of
* selection manager at the same time.
*
* @param script - executed script
* @param scriptResult - obtained script result
* @param rmnode - node on which script has been executed
* @return whether node is selected
*/
public abstract boolean processScriptResult(SelectionScript script, ScriptResult<Boolean> scriptResult,
RMNode rmnode);
public NodeSet selectNodes(Criteria criteria, Client client) {
if (criteria.getComputationDescriptors() != null) {
// logging selection script execution into tasks logs
MDC.getContext().put(MultipleFileAppender.FILE_NAMES, criteria.getComputationDescriptors());
}
boolean hasScripts = criteria.getScripts() != null && criteria.getScripts().size() > 0;
logger.info(client + " requested " + criteria.getSize() + " nodes with " + criteria.getTopology());
if (logger.isDebugEnabled()) {
if (hasScripts) {
logger.debug("Selection scripts:");
for (SelectionScript s : criteria.getScripts()) {
logger.debug(s);
}
}
if (criteria.getBlackList() != null && criteria.getBlackList().size() > 0) {
logger.debug("Black list nodes:");
for (Node n : criteria.getBlackList()) {
logger.debug(n);
}
}
}
// can throw Exception if topology is disabled
TopologyHandler handler = RMCore.topologyManager.getHandler(criteria.getTopology());
List<RMNode> freeNodes = rmcore.getFreeNodes();
// filtering out the "free node list"
// removing exclusion and checking permissions
List<RMNode> filteredNodes = filterOut(freeNodes, criteria.getBlackList(), client);
if (filteredNodes.size() == 0) {
return new NodeSet();
}
// arranging nodes according to the selection policy
// if could be shuffling or node source priorities
List<RMNode> afterPolicyNodes = selectionPolicy.arrangeNodes(criteria.getSize(), filteredNodes,
client);
// arranging nodes for script execution
List<RMNode> arrangedNodes = arrangeNodesForScriptExecution(afterPolicyNodes, criteria.getScripts());
List<Node> matchedNodes = null;
if (criteria.getTopology().isTopologyBased()) {
// run scripts on all available nodes
matchedNodes = runScripts(arrangedNodes, criteria.getScripts());
} else {
// run scripts not on all nodes, but always on missing number of nodes
// until required node set is found
matchedNodes = new LinkedList<Node>();
while (matchedNodes.size() < criteria.getSize()) {
int requiredNodesNumber = criteria.getSize() - matchedNodes.size();
int numberOfNodesForScriptExecution = requiredNodesNumber;
if (numberOfNodesForScriptExecution < SELECTION_THEADS_NUMBER) {
// we can run "SELECTION_THEADS_NUMBER" scripts in parallel
// in case when we need less nodes it still useful to
// the full capacity of the thread pool to find nodes quicker
// it is not important if we find more nodes than needed
// subset will be selected later (topology handlers)
numberOfNodesForScriptExecution = SELECTION_THEADS_NUMBER;
}
List<RMNode> subset = arrangedNodes.subList(0, Math.min(numberOfNodesForScriptExecution,
arrangedNodes.size()));
matchedNodes.addAll(runScripts(subset, criteria.getScripts()));
// removing subset of arrangedNodes
subset.clear();
if (arrangedNodes.size() == 0) {
break;
}
}
}
if (hasScripts) {
logger.debug(matchedNodes.size() + " nodes found after scripts execution for " + client);
}
// now we have a list of nodes which match to selection scripts
// selecting subset according to topology requirements
// TopologyHandler handler = RMCore.topologyManager.getHandler(topologyDescriptor);
if (criteria.getTopology().isTopologyBased()) {
logger.debug("Filtering nodes with topology " + criteria.getTopology());
}
NodeSet selectedNodes = handler.select(criteria.getSize(), matchedNodes);
if (selectedNodes.size() < criteria.getSize() && !criteria.isBestEffort()) {
selectedNodes.clear();
if (selectedNodes.getExtraNodes() != null) {
selectedNodes.getExtraNodes().clear();
}
}
// the nodes are selected, now mark them as busy.
for (Node node : new LinkedList<Node>(selectedNodes)) {
try {
// Synchronous call
rmcore.setBusyNode(node.getNodeInformation().getURL(), client);
} catch (NotConnectedException e) {
// client has disconnected during getNodes request
logger.warn(e.getMessage(), e);
return null;
} catch (NodeException e) {
// if something happened with node after scripts were executed
// just return less nodes and do not restart the search
selectedNodes.remove(node);
rmcore.setDownNode(node.getNodeInformation().getURL());
}
}
// marking extra selected nodes as busy
if (selectedNodes.size() > 0 && selectedNodes.getExtraNodes() != null) {
for (Node node : new LinkedList<Node>(selectedNodes.getExtraNodes())) {
try {
// synchronous call
rmcore.setBusyNode(node.getNodeInformation().getURL(), client);
} catch (NotConnectedException e) {
// client has disconnected during getNodes request
logger.warn(e.getMessage(), e);
return null;
} catch (NodeException e) {
selectedNodes.getExtraNodes().remove(node);
rmcore.setDownNode(node.getNodeInformation().getURL());
}
}
}
String extraNodes = selectedNodes.getExtraNodes() != null && selectedNodes.getExtraNodes().size() > 0 ? "and " +
selectedNodes.getExtraNodes().size() + " extra nodes"
: "";
logger.info(client + " will get " + selectedNodes.size() + " nodes " + extraNodes);
if (logger.isDebugEnabled()) {
for (Node n : selectedNodes) {
logger.debug(n.getNodeInformation().getURL());
}
}
MDC.getContext().remove(MultipleFileAppender.FILE_NAMES);
return selectedNodes;
}
/**
* Runs scripts on given set of nodes and returns matched nodes.
* It blocks until all results are obtained.
*
* @param candidates nodes to execute scripts on
* @param scripts set of scripts to execute on each node
* @return nodes matched to all scripts
*/
private List<Node> runScripts(List<RMNode> candidates, List<SelectionScript> scripts) {
List<Node> matched = new LinkedList<Node>();
if (candidates.size() == 0) {
return matched;
}
// creating script executors object to be run in dedicated thread pool
List<Callable<Node>> scriptExecutors = new LinkedList<Callable<Node>>();
synchronized (inProgress) {
if (inProgress.size() > 0) {
logger.warn(inProgress.size() + " nodes are in process of script execution");
for (String nodeName : inProgress) {
logger.warn(nodeName);
}
logger.warn("Something is wrong on these nodes");
}
for (RMNode node : candidates) {
if (!inProgress.contains(node.getNodeURL())) {
inProgress.add(node.getNodeURL());
scriptExecutors.add(new ScriptExecutor(node, scripts, this));
}
}
}
ScriptException scriptException = null;
try {
// launching
Collection<Future<Node>> matchedNodes = scriptExecutorThreadPool.invokeAll(scriptExecutors,
PAResourceManagerProperties.RM_SELECT_SCRIPT_TIMEOUT.getValueAsInt(),
TimeUnit.MILLISECONDS);
int index = 0;
// waiting for the results
for (Future<Node> futureNode : matchedNodes) {
if (!futureNode.isCancelled()) {
Node node = null;
try {
node = futureNode.get();
if (node != null) {
matched.add(node);
}
} catch (InterruptedException e) {
logger.warn("Interrupting the selection manager");
return matched;
} catch (ExecutionException e) {
// SCHEDULING-954 : an exception in script call is considered as an exception
// thrown by the script itself.
scriptException = new ScriptException("Exception occurs in selection script call", e
.getCause());
}
} else {
// no script result was obtained
logger.warn("Timeout on " + scriptExecutors.get(index));
// in this case scriptExecutionFinished may not be called
scriptExecutionFinished(((ScriptExecutor) scriptExecutors.get(index)).getRMNode()
.getNodeURL());
}
index++;
}
} catch (InterruptedException e1) {
logger.warn("Interrupting the selection manager");
}
// if the script passes on some nodes ignore the exception
if (scriptException != null && matched.size() == 0) {
throw scriptException;
}
return matched;
}
/**
* Removes exclusion nodes and nodes not accessible for the client
*
* @param freeNodes
* @param exclusion
* @param client
* @return
*/
private List<RMNode> filterOut(List<RMNode> freeNodes, NodeSet exclusion, Client client) {
List<RMNode> filteredList = new ArrayList<RMNode>();
for (RMNode node : freeNodes) {
// checking the permission
try {
client.checkPermission(node.getUserPermission(), client +
" is not authorized to get the node " + node.getNodeURL() + " from " +
node.getNodeSource().getName());
} catch (SecurityException e) {
// client does not have an access to this node
logger.debug(e.getMessage());
continue;
}
if (!contains(exclusion, node)) {
filteredList.add(node);
}
}
return filteredList;
}
public <T> List<ScriptResult<T>> executeScript(final Script<T> script, final Collection<RMNode> nodes) {
// TODO: add a specific timeout for script execution
final int timeout = PAResourceManagerProperties.RM_EXECUTE_SCRIPT_TIMEOUT.getValueAsInt();
final ArrayList<Callable<ScriptResult<T>>> scriptExecutors = new ArrayList<Callable<ScriptResult<T>>>(
nodes.size());
// Execute the script on each selected node
for (final RMNode node : nodes) {
scriptExecutors.add(new Callable<ScriptResult<T>>() {
@Override
public ScriptResult<T> call() throws Exception {
// Execute with a timeout the script by the remote handler
// and always async-unlock the node, exceptions will be treated as ExecutionException
try {
ScriptResult<T> res = node.executeScript(script);
PAFuture.waitFor(res, timeout);
return res;
//return PAFuture.getFutureValue(res, timeout);
} finally {
// cleaning the node
try {
node.clean();
} catch (Throwable ex) {
logger.error("Cannot clean the node " + node.getNodeURL(), ex);
}
SelectionManager.this.rmcore.unlockNodes(Collections.singleton(node.getNodeURL()));
}
}
@Override
public String toString() {
return "executing script on " + node.getNodeURL();
}
});
}
// Invoke all Callables and get the list of futures
List<Future<ScriptResult<T>>> futures = null;
try {
futures = this.scriptExecutorThreadPool
.invokeAll(scriptExecutors, timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
logger.warn("Interrupted while waiting, unable to execute all scripts", e);
Thread.currentThread().interrupt();
}
final List<ScriptResult<T>> results = new LinkedList<ScriptResult<T>>();
int index = 0;
// waiting for the results
for (final Future<ScriptResult<T>> future : futures) {
final String description = scriptExecutors.get(index++).toString();
ScriptResult<T> result = null;
try {
result = future.get();
} catch (CancellationException e) {
result = new ScriptResult<T>(new ScriptException("Cancelled due to timeout expiration when " +
description, e));
} catch (InterruptedException e) {
result = new ScriptResult<T>(new ScriptException("Cancelled due to interruption when " +
description));
} catch (ExecutionException e) {
// Unwrap the root exception
Throwable rex = e.getCause();
result = new ScriptResult<T>(new ScriptException("Exception occured in script call when " +
description, rex));
}
results.add(result);
}
return results;
}
/**
* Indicates that script execution is finished for the node with specified url.
*/
public void scriptExecutionFinished(String nodeUrl) {
synchronized (inProgress) {
inProgress.remove(nodeUrl);
}
}
/**
* Handles shut down of the selection manager
*/
public void shutdown() {
// shutdown the thread pool without waiting for script execution completions
scriptExecutorThreadPool.shutdownNow();
PAActiveObject.terminateActiveObject(false);
}
/**
* Return true if node contains the node set.
*
* @param nodeset - a list of nodes to inspect
* @param node - a node to find
* @return true if node contains the node set.
*/
private boolean contains(NodeSet nodeset, RMNode node) {
if (nodeset == null)
return false;
for (Node n : nodeset) {
try {
if (n.getNodeInformation().getURL().equals(node.getNodeURL())) {
return true;
}
} catch (Exception e) {
continue;
}
}
return false;
}
}
| agpl-3.0 |
inter6/jHears | jhears-server/src/main/java/org/jhears/server/SegmentCacheSearch.java | 9028 | /*
* jHears, acoustic fingerprinting framework.
* Copyright (C) 2009-2010 Juha Heljoranta.
*
* This file is part of jHears.
*
* jHears 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.
*
* jHears 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 jHears. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jhears.server;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.configuration.Configuration;
import org.jhears.cache.ISegmentCache;
import org.jhears.cache.ISegmentCacheValue;
import org.jhears.cache.SegmentCacheValue;
import org.jhears.cnf.Cnf.FingerprintKey;
import org.jhears.cnf.Cnf.SearchKey;
import org.jhears.data.FingerprintDataObj;
import org.jhears.seq.FSeq;
import org.jhears.web.rs.Segment;
/**
* Searches cache for {@link #minimumHits} pieces of {@link Segment}s which are
* apart from each other by {@link #maxAllowedGap} at maximum.
* <p>
* This class is thread safe.
*/
public class SegmentCacheSearch {
/**
* Encapsulates state variables making the parent class thread safe.
* <p>
* Algorithm description: All query entries are put into {@link #seMap} at
* first. If the {@link #seMap} contains enough entries associated to single
* fingerprint then the entry is moved into {@link #retval}. If the entry
* doesn't have enough segments within #maxAllowedGap range then it is
* removed from {@link #seMap}.
*/
private class Worker {
/**
* Tracks position of a query. Starts with zero and ends with
* {@link FSeq#getLength()} - {@link FSeq#getSegmentLength()}.
*/
private int currentPos;
/**
* Map of search entries which had matches enough hits separated by the
* {@link #maxAllowedGap} at some point in the query string.
* <p>
* Map keys are values of {@link FingerprintDataObj#getId()}.
*/
private final Map<Long, SearchEntry> retval;
/**
* Search entries which are not yet considered as potential hits. Eldest
* entry of the map is removed if (
* {@link SearchEntry#getPositionLastSeen()} + {@link #maxAllowedGap} <
* {@link #currentPos}). If the eldest entry has high enough score when
* removed it is placed on {@link #retval} map.
* <p>
* Map keys are values of {@link FingerprintDataObj#getId()}.
*/
private final Map<Long, SearchEntry> seMap;
public Worker() {
retval = new HashMap<Long, SearchEntry>();
seMap = createLinkedHashMap();
}
/**
* Adds segment and cache entry for match tracking.
* <p>
* Update {@link SearchEntry#setPositionLastSeen(int)} and record
* {@link PotentialMatch}.
*
* @param querySegment
* @param ce
*/
private void addToSearchResults(Segment querySegment,
final ISegmentCacheValue ce) {
SearchEntry se = getOrCreateSearchEntry(Long.valueOf(ce
.getFingerprintId()), querySegment.getPosition());
// reconstruct segment object stored into cache
Segment cacheSegment = new Segment(querySegment.getData(), ce
.getSegmentPosition());
List<PotentialMatch> potentialMatches = se.getMap().get(
cacheSegment);
if (potentialMatches == null) {
potentialMatches = new ArrayList<PotentialMatch>();
se.getMap().put(cacheSegment, potentialMatches);
}
/*
* Segments which have exactly the same position are unique. Key
* used to fetch the list is unique for each entry in cache who have
* the same audioId. Therefore the list cannot have duplicates.
*/
// refresh last known matching position
se.setPositionLastSeen(querySegment.getPosition());
int relativePosition = querySegment.getPosition()
- cacheSegment.getPosition();
potentialMatches.add(new PotentialMatch(querySegment,
relativePosition));
}
/**
* Delegates a call {@link LinkedHashMap#removeEldestEntry(Entry)} to
* {@link #removeEldestEntry(Entry)}.
*
* @return
*/
@SuppressWarnings("serial")
private Map<Long, SearchEntry> createLinkedHashMap() {
return new LinkedHashMap<Long, SearchEntry>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(
java.util.Map.Entry<Long, SearchEntry> eldest) {
return Worker.this.removeEldestEntry(eldest);
}
};
}
/**
* Fetches {@link SegmentCacheValue}s matching the query segment and
* starts tracking found entries.
*
* @param querySegment
*/
private void fetchMatchingCacheEntries(Segment querySegment) {
Set<ISegmentCacheValue> ceList = cache.get(querySegment.getData());
for (final ISegmentCacheValue ce : ceList) {
addToSearchResults(querySegment, ce);
}
}
/**
* Fetches search entry by using fingerprint id from cache. If there is
* no search entry for the finger print then a new search entry is
* created.
* <p>
* Perform match tracking indirectly by allowing {@link #seMap} to throw
* out eldest entry. See {@link #removeEldestEntry(Entry)}
*
* @param fingerprintId
* @param lastSeen
* Position from query segment. .
* @return
*/
private SearchEntry getOrCreateSearchEntry(final Long fingerprintId,
int lastSeen) {
SearchEntry se = seMap.get(fingerprintId);
if (se == null) {
se = retval.get(fingerprintId);
if (se == null) {
/*
* SearchEntry must have the last seen position set
* correctly before adding it into map, otherwise the
* removeEldestEntry might throw it out immediately.
*/
se = new SearchEntry(lastSeen);
seMap.put(fingerprintId, se);
}
}
return se;
}
/**
* Adds search entry to potential hits map if it has
* {@link #minimumHits} or more matches.
*
* @param id
* fingerprint identifier
* @param se
* search entry associated to the fingerprint identifier
*/
private void potentiaHit(Long id, SearchEntry se) {
if (se.getMap().size() >= minimumHits) {
retval.put(id, se);
}
}
/**
* Query cache for matching entries.
*
* @param querySegments
* @return Map keys are fingerprint identifiers. The values are search
* entries.
*/
public Map<Long, SearchEntry> query(List<Segment> querySegments) {
for (Segment querySegment : querySegments) {
currentPos = querySegment.getPosition();
fetchMatchingCacheEntries(querySegment);
}
// check remaining seMap entries.
// seMap is access ordered and would throw a
// ConcurrentModificationException on get() method. making a copy
// prevents this.
HashMap<Long, SearchEntry> copy = new HashMap<Long, SearchEntry>(
seMap);
for (Map.Entry<Long, SearchEntry> entry : copy.entrySet()) {
potentiaHit(entry.getKey(), entry.getValue());
}
return retval;
}
/**
* Returns true if the search entry has not been updated since last
* {@link #maxAllowedGap} positions while searching the fingerprint.
*
* @param eldest
* @return
*/
private boolean removeEldestEntry(Entry<Long, SearchEntry> eldest) {
SearchEntry val = eldest.getValue();
if (val.getPositionLastSeen() + maxAllowedGap < currentPos) {
potentiaHit(eldest.getKey(), eldest.getValue());
return true;
}
return false;
}
}
/**
* Maximum allowed stretch in search string.
*/
private static final double THREE_PRECENT = 0.03;
private final ISegmentCache cache;
private final int maxAllowedGap;
private final int minimumHits;
private final int seglen;
public SegmentCacheSearch(ISegmentCache cache, Configuration fpConf,
Configuration searchConf) {
seglen = fpConf.getInt(FingerprintKey.SEGMENT_LENGTH);
minimumHits = searchConf.getInt(SearchKey.MINIMUM_HITS);
maxAllowedGap = minimumHits * seglen
+ (int) Math.ceil((minimumHits * seglen) * THREE_PRECENT);
this.cache = cache;
}
public void add(Long fpId, List<Segment> segments) {
for (Segment segment : segments) {
SegmentCacheValue ce = new SegmentCacheValue(fpId.longValue(),
segment.getPosition());
cache.add(segment.getData(), ce);
}
}
public void delete(long fpId, List<Segment> segments) {
for (Segment s : segments) {
SegmentCacheValue ce = new SegmentCacheValue(fpId, s.getPosition());
cache.delete(s.getData(), ce);
}
}
/**
*
* @param querySegments
* @return Map which key set represent values from
* {@link FingerprintDataObj#getId()}.
*/
public Map<Long, SearchEntry> query(List<Segment> querySegments) {
return new Worker().query(querySegments);
}
}
| agpl-3.0 |
ColostateResearchServices/kc | coeus-impl/src/test/java/org/kuali/kra/award/printing/service/impl/AwardPrintingServiceImplTest.java | 8656 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2016 Kuali, 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/>.
*/
package org.kuali.kra.award.printing.service.impl;
import static org.junit.Assert.*;
import java.sql.Timestamp;
import java.util.*;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.concurrent.Synchroniser;
import org.junit.Before;
import org.junit.Test;
import org.kuali.coeus.common.framework.print.AttachmentDataSource;
import org.kuali.coeus.common.framework.unit.UnitService;
import org.kuali.coeus.common.framework.unit.admin.UnitAdministrator;
import org.kuali.coeus.common.framework.unit.admin.UnitAdministratorType;
import org.kuali.coeus.common.impl.print.PrintingServiceImpl;
import org.kuali.kra.award.document.AwardDocument;
import org.kuali.kra.award.home.Award;
import org.kuali.kra.award.printing.AwardPrintParameters;
import org.kuali.kra.award.printing.AwardPrintType;
import org.kuali.kra.award.printing.print.AwardNoticePrint;
import org.kuali.kra.award.printing.xmlstream.AwardNoticeXmlStream;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.printing.schema.AwardType;
import org.kuali.rice.core.api.config.property.ConfigurationService;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.krad.util.KRADConstants;
public class AwardPrintingServiceImplTest {
private Mockery context;
private PrintingServiceImpl printService;
private UnitService unitService;
@Before
public void setUp() throws Exception {
context = new JUnit4Mockery() {
{
setThreadingPolicy(new Synchroniser());
}
};
printService = new PrintingServiceImpl();
final DateTimeService dateTimeService = context.mock(DateTimeService.class);
final Date now = new Date();
context.checking(new Expectations() {
{
oneOf(dateTimeService).getCurrentTimestamp();
will(returnValue(new Timestamp(now.getYear(), now.getMonth(), now.getDay(), now.getHours(), now.getMinutes(), now.getSeconds(), 0)));
}
});
context.checking(new Expectations() {
{
oneOf(dateTimeService).getCurrentDate();
will(returnValue(now));
}
});
context.checking(new Expectations() {
{
oneOf(dateTimeService).getCurrentCalendar();
will(returnValue(new GregorianCalendar()));
}
});
printService.setDateTimeService(dateTimeService);
final ConfigurationService configurationService = context.mock(ConfigurationService.class);
context.checking(new Expectations() {
{
oneOf(configurationService).getPropertyValueAsBoolean(Constants.PRINT_LOGGING_ENABLE);
will(returnValue(false));
oneOf(configurationService).getPropertyValueAsBoolean(Constants.PRINT_PDF_LOGGING_ENABLE);
will(returnValue(false));
oneOf(configurationService).getPropertyValueAsString(KRADConstants.APPLICATION_URL_KEY);
will(returnValue("foo"));
oneOf(configurationService).getPropertyValueAsString(Constants.KRA_EXTERNALIZABLE_IMAGES_URI_KEY);
will(returnValue("foo"));
}
});
printService.setKualiConfigurationService(configurationService);
unitService = context.mock(UnitService.class);
context.checking(new Expectations() {
{
oneOf(unitService).retrieveUnitAdministratorsByUnitNumber("123456");
UnitAdministrator admin = new UnitAdministrator();
admin.setUnitNumber("123456");
UnitAdministratorType type = new UnitAdministratorType();
type.setCode(UnitAdministratorType.ADMINISTRATIVE_OFFICER_TYPE_CODE);
type.setDefaultGroupFlag("Bleh");
admin.setUnitAdministratorTypeCode(UnitAdministratorType.ADMINISTRATIVE_OFFICER_TYPE_CODE);
admin.setUnitAdministratorType(type);
will(returnValue(Collections.singletonList(admin)));
}
});
}
@Test
public void testPrintAward1() {
AwardPrintingServiceImpl awardPrintingService = new AwardPrintingServiceImpl();
AwardNoticePrint awardNoticePrint = new AwardNoticePrint();
TestableAwardNoticePrintStream printStream = new TestableAwardNoticePrintStream();
printStream.setDateTimeService(printService.getDateTimeService());
awardNoticePrint.setXmlStream(printStream);
awardPrintingService.setAwardNoticePrint(awardNoticePrint);
awardPrintingService.setPrintingService(printService);
Map<String, Object> reportParameters = getReportParameters();
AttachmentDataSource ads = awardPrintingService.printAwardReport(createAward(), AwardPrintType.AWARD_NOTICE_REPORT, reportParameters);
assertTrue(ads.getData().length > 0);
}
@Test
public void testPrintAward2() {
AwardPrintingServiceImpl awardPrintingService = new AwardPrintingServiceImpl();
AwardNoticePrint awardNoticePrint = new AwardNoticePrint();
TestableAwardNoticePrintStream printStream = new TestableAwardNoticePrintStream();
printStream.setDateTimeService(printService.getDateTimeService());
awardNoticePrint.setXmlStream(printStream);
awardPrintingService.setAwardNoticePrint(awardNoticePrint);
awardPrintingService.setPrintingService(printService);
Map<String, Object> reportParameters = getReportParameters();
reportParameters.put(AwardPrintParameters.CLOSEOUT.getAwardPrintParameter(), true);
AttachmentDataSource ads = awardPrintingService.printAwardReport(createAward(), AwardPrintType.AWARD_NOTICE_REPORT, reportParameters);
assertTrue(ads.getData().length > 0);
}
private Map<String, Object> getReportParameters() {
Map<String, Object> reportParameters = new HashMap<String, Object>();
reportParameters.put(AwardPrintParameters.ADDRESS_LIST.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.FOREIGN_TRAVEL.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.REPORTING.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.FUNDING_SUMMARY.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.SPECIAL_REVIEW.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.COMMENTS.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.HIERARCHY_INFO.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.SUBCONTRACT.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.COST_SHARING.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.KEYWORDS.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.TECHNICAL_REPORTING.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.EQUIPMENT.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.OTHER_DATA.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.TERMS.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.FA_COST.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.PAYMENT.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.FLOW_THRU.getAwardPrintParameter(), true);
reportParameters.put(AwardPrintParameters.PROPOSAL_DUE.getAwardPrintParameter(), false);
reportParameters.put(AwardPrintParameters.SIGNATURE_REQUIRED.getAwardPrintParameter(), true);
return reportParameters;
}
private Award createAward() {
Award award = new Award();
award.setAwardNumber("000001-00001");
AwardDocument ad = new AwardDocument();
ad.setDocumentNumber("123");
ad.setAward(award);
award.setAwardDocument(ad);
award.setUnitNumber("123456");
award.setUnitService(unitService);
return award;
}
private class TestableAwardNoticePrintStream extends AwardNoticeXmlStream {
@Override
public String getNSFDescription(String nsfCode) {
return "";
}
@Override
protected AwardType getAward() {
AwardType at = org.kuali.kra.printing.schema.AwardType.Factory.newInstance();
return at;
}
}
}
| agpl-3.0 |
a-gogo/agogo | AMW_maia_federation/generated-sources/main/java/ch/mobi/xml/datatype/ch/mobi/maia/amw/maiaamwfederationservicetypes/v1_0/Message.java | 2678 |
package ch.mobi.xml.datatype.ch.mobi.maia.amw.maiaamwfederationservicetypes.v1_0;
import ch.mobi.xml.datatype.common.commons.v3.MessageSeverity;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Message complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Message">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="severity" type="{http://xml.mobi.ch/datatype/common/Commons/v3}MessageSeverity"/>
* <element name="humanReadableMessage" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Message", propOrder = {
"severity",
"humanReadableMessage"
})
public class Message {
@XmlElement(required = true)
protected MessageSeverity severity;
@XmlElement(required = true)
protected String humanReadableMessage;
/**
* Default no-arg constructor
*
*/
public Message() {
super();
}
/**
* Fully-initialising value constructor
*
*/
public Message(final MessageSeverity severity, final String humanReadableMessage) {
this.severity = severity;
this.humanReadableMessage = humanReadableMessage;
}
/**
* Gets the value of the severity property.
*
* @return
* possible object is
* {@link MessageSeverity }
*
*/
public MessageSeverity getSeverity() {
return severity;
}
/**
* Sets the value of the severity property.
*
* @param value
* allowed object is
* {@link MessageSeverity }
*
*/
public void setSeverity(MessageSeverity value) {
this.severity = value;
}
/**
* Gets the value of the humanReadableMessage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHumanReadableMessage() {
return humanReadableMessage;
}
/**
* Sets the value of the humanReadableMessage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHumanReadableMessage(String value) {
this.humanReadableMessage = value;
}
}
| agpl-3.0 |
semantic-web-software/dynagent | Common/src/dynagent/common/basicobjects/EssentialProperty.java | 1653 | package dynagent.common.basicobjects;
public class EssentialProperty implements Cloneable{
private Integer uTask=null;
private Integer idto=null;
private Integer prop=null;
private String uTaskName=null;
private String idtoName=null;
private String propName=null;
public EssentialProperty(Integer uTask, Integer idto, Integer prop){
this.uTask=uTask;
this.idto=idto;
this.prop=prop;
}
public EssentialProperty(){
}
public Integer getIdto() {
return idto;
}
public void setIdto(Integer aliasClass) {
this.idto = aliasClass;
}
public Integer getProp() {
return prop;
}
public void setProp(Integer prop) {
this.prop = prop;
}
public Integer getUTask() {
return uTask;
}
public void setUTask(Integer task) {
uTask = task;
}
public String toString(){
return "(ESSENTIALPROPERTY (IDTO "+this.idto+") (PROP "+this.prop+") (UTASK "+this.uTask+") "+
"(IDTO NAME "+ this.idtoName+") (PROP NAME "+this.propName+") (UTASK NAME "+this.uTaskName+"))";
}
public String getIdtoName() {
return idtoName;
}
public void setIdtoName(String idtoName) {
this.idtoName = idtoName;
}
public String getPropName() {
return propName;
}
public void setPropName(String propName) {
this.propName = propName;
}
public String getUTaskName() {
return uTaskName;
}
public void setUTaskName(String taskName) {
uTaskName = taskName;
}
@Override
public Object clone() throws CloneNotSupportedException {
EssentialProperty a=new EssentialProperty();
a.setIdto(idto);
a.setIdtoName(idtoName);
a.setProp(prop);
a.setPropName(propName);
a.setUTask(uTask);
a.setUTaskName(uTaskName);
return a;
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_organization_assemble_personal/src/main/java/com/x/organization/assemble/personal/jaxrs/password/ExceptionOldPasswordNotMatch.java | 338 | package com.x.organization.assemble.personal.jaxrs.password;
import com.x.base.core.project.exception.LanguagePromptException;
class ExceptionOldPasswordNotMatch extends LanguagePromptException {
private static final long serialVersionUID = -3885997486474873786L;
ExceptionOldPasswordNotMatch() {
super("原密码错误.");
}
}
| agpl-3.0 |
opensourceBIM/BIMserver | BimServer/src/org/bimserver/notifications/ChangeProgressTopicOnRevisionTopic.java | 1976 | package org.bimserver.notifications;
/******************************************************************************
* 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 org.bimserver.BimserverDatabaseException;
import org.bimserver.endpoints.EndPoint;
import org.bimserver.shared.exceptions.ServerException;
import org.bimserver.shared.exceptions.UserException;
public class ChangeProgressTopicOnRevisionTopic extends Topic {
private ChangeProgressTopicOnRevisionTopicKey key;
public ChangeProgressTopicOnRevisionTopic(NotificationsManager notificationsManager, ChangeProgressTopicOnRevisionTopicKey key) {
super(notificationsManager);
this.key = key;
}
public void notifyOfNewTopic(final NewProgressTopicOnRevisionNotification notification) throws UserException, ServerException, BimserverDatabaseException {
map(new Mapper(){
@Override
public void map(final EndPoint endPoint) throws UserException, ServerException {
endPoint.getNotificationInterface().newProgressOnRevisionTopic(notification.getPoid(), notification.getRoid(), notification.getTopicId());
}
});
}
@Override
public void remove() {
getNotificationsManager().removeChangeProgressTopicOnRevision(key);
}
}
| agpl-3.0 |