code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
// $Id: ActionAddClientDependencyAction.java 41 2010-04-03 20:04:12Z marcusvnac $
// Copyright (c) 2007 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.ui.foundation.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.argouml.i18n.Translator;
import org.argouml.kernel.ProjectManager;
import org.argouml.model.Model;
import org.argouml.uml.ui.AbstractActionAddModelElement2;
/**
* An Action to add client dependencies to some modelelement.
*
* @author Michiel
*/
public class ActionAddClientDependencyAction extends
AbstractActionAddModelElement2 {
/**
* The constructor.
*/
public ActionAddClientDependencyAction() {
super();
setMultiSelect(true);
}
/*
* Constraint: This code only deals with 1 supplier per dependency!
* TODO: How to support more?
*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#doIt(java.util.List)
*/
protected void doIt(Collection selected) {
Set oldSet = new HashSet(getSelected());
for (Object client : selected) {
if (oldSet.contains(client)) {
oldSet.remove(client); //to be able to remove dependencies later
} else {
Model.getCoreFactory().buildDependency(getTarget(), client);
}
}
Collection toBeDeleted = new ArrayList();
Collection dependencies = Model.getFacade().getClientDependencies(
getTarget());
for (Object dependency : dependencies) {
if (oldSet.containsAll(Model.getFacade().getSuppliers(dependency))) {
toBeDeleted.add(dependency);
}
}
ProjectManager.getManager().getCurrentProject()
.moveToTrash(toBeDeleted);
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getChoices()
*/
protected List getChoices() {
List ret = new ArrayList();
Object model =
ProjectManager.getManager().getCurrentProject().getModel();
if (getTarget() != null) {
ret.addAll(Model.getModelManagementHelper()
.getAllModelElementsOfKind(model,
"org.omg.uml.foundation.core.ModelElement"));
ret.remove(getTarget());
}
return ret;
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getDialogTitle()
*/
protected String getDialogTitle() {
return Translator.localize("dialog.title.add-client-dependency");
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getSelected()
*/
protected List getSelected() {
List v = new ArrayList();
Collection c = Model.getFacade().getClientDependencies(getTarget());
for (Object cd : c) {
v.addAll(Model.getFacade().getSuppliers(cd));
}
return v;
}
}
| ckaestne/LEADT | workspace/argouml_critics/argouml-app/src/org/argouml/uml/ui/foundation/core/ActionAddClientDependencyAction.java | Java | gpl-3.0 | 4,569 |
package fr.ybo.transportscommun.activity.commun;
import android.widget.ImageButton;
public interface ChangeIconActionBar {
public void changeIconActionBar(ImageButton imageButton);
}
| ybonnel/TransportsRennes | TransportsCommun/src/fr/ybo/transportscommun/activity/commun/ChangeIconActionBar.java | Java | gpl-3.0 | 188 |
package net.einsteinsci.betterbeginnings.items;
import net.einsteinsci.betterbeginnings.register.IBBName;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import java.util.HashSet;
import java.util.Set;
public abstract class ItemKnife extends ItemTool implements IBBName
{
public static final float DAMAGE = 3.0f;
public ItemKnife(ToolMaterial material)
{
super(DAMAGE, material, getBreakable());
}
public static Set getBreakable()
{
Set<Block> s = new HashSet<>();
// s.add(Blocks.log);
// s.add(Blocks.log2);
// s.add(Blocks.planks);
s.add(Blocks.pumpkin);
s.add(Blocks.lit_pumpkin);
s.add(Blocks.melon_block);
s.add(Blocks.clay);
s.add(Blocks.grass);
s.add(Blocks.mycelium);
s.add(Blocks.leaves);
s.add(Blocks.leaves2);
s.add(Blocks.brown_mushroom_block);
s.add(Blocks.red_mushroom_block);
s.add(Blocks.glass);
s.add(Blocks.glass_pane);
s.add(Blocks.soul_sand);
s.add(Blocks.stained_glass);
s.add(Blocks.stained_glass_pane);
s.add(Blocks.cactus);
return s;
}
@Override
public boolean shouldRotateAroundWhenRendering()
{
return true;
}
@Override
public int getHarvestLevel(ItemStack stack, String toolClass)
{
return toolMaterial.getHarvestLevel();
}
@Override
public Set<String> getToolClasses(ItemStack stack)
{
Set<String> res = new HashSet<>();
res.add("knife");
return res;
}
// ...which also requires this...
@Override
public ItemStack getContainerItem(ItemStack itemStack)
{
ItemStack result = itemStack.copy();
result.setItemDamage(itemStack.getItemDamage() + 1);
return result;
}
// Allows durability-based crafting.
@Override
public boolean hasContainerItem(ItemStack stack)
{
return true;
}
@Override
public abstract String getName();
}
| Leviathan143/betterbeginnings | src/main/java/net/einsteinsci/betterbeginnings/items/ItemKnife.java | Java | gpl-3.0 | 1,851 |
package es.ucm.fdi.emf.model.ed2.diagram.sheet;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.viewers.BaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.graphics.Image;
import es.ucm.fdi.emf.model.ed2.diagram.navigator.Ed2NavigatorGroup;
import es.ucm.fdi.emf.model.ed2.diagram.part.Ed2VisualIDRegistry;
import es.ucm.fdi.emf.model.ed2.diagram.providers.Ed2ElementTypes;
/**
* @generated
*/
public class Ed2SheetLabelProvider extends BaseLabelProvider implements
ILabelProvider {
/**
* @generated
*/
public String getText(Object element) {
element = unwrap(element);
if (element instanceof Ed2NavigatorGroup) {
return ((Ed2NavigatorGroup) element).getGroupName();
}
IElementType etype = getElementType(getView(element));
return etype == null ? "" : etype.getDisplayName();
}
/**
* @generated
*/
public Image getImage(Object element) {
IElementType etype = getElementType(getView(unwrap(element)));
return etype == null ? null : Ed2ElementTypes.getImage(etype);
}
/**
* @generated
*/
private Object unwrap(Object element) {
if (element instanceof IStructuredSelection) {
return ((IStructuredSelection) element).getFirstElement();
}
return element;
}
/**
* @generated
*/
private View getView(Object element) {
if (element instanceof View) {
return (View) element;
}
if (element instanceof IAdaptable) {
return (View) ((IAdaptable) element).getAdapter(View.class);
}
return null;
}
/**
* @generated
*/
private IElementType getElementType(View view) {
// For intermediate views climb up the containment hierarchy to find the one associated with an element type.
while (view != null) {
int vid = Ed2VisualIDRegistry.getVisualID(view);
IElementType etype = Ed2ElementTypes.getElementType(vid);
if (etype != null) {
return etype;
}
view = view.eContainer() instanceof View ? (View) view.eContainer()
: null;
}
return null;
}
}
| RubenM13/E-EDD-2.0 | es.ucm.fdi.ed2.emf.diagram/src/es/ucm/fdi/emf/model/ed2/diagram/sheet/Ed2SheetLabelProvider.java | Java | gpl-3.0 | 2,246 |
/*
* Copyright © 2013-2020, 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.i18n.rest.internal.infrastructure.csv;
import com.google.common.collect.Sets;
import org.seedstack.i18n.rest.internal.locale.LocaleFinder;
import org.seedstack.i18n.rest.internal.locale.LocaleRepresentation;
import org.seedstack.io.spi.Template;
import org.seedstack.io.spi.TemplateLoader;
import org.seedstack.io.supercsv.Column;
import org.seedstack.io.supercsv.SuperCsvTemplate;
import org.seedstack.jpa.JpaUnit;
import org.seedstack.seed.transaction.Transactional;
import org.supercsv.cellprocessor.Optional;
import javax.inject.Inject;
import java.util.List;
import java.util.Set;
/**
* @author pierre.thirouin@ext.mpsa.com
*/
public class I18nCSVTemplateLoader implements TemplateLoader {
public static final String I18N_CSV_TEMPLATE = "i18nTranslations";
public static final String KEY = "key";
@Inject
private LocaleFinder localeFinder;
@JpaUnit("seed-i18n-domain")
@Transactional
@Override
public Template load(String name) {
List<LocaleRepresentation> availableLocales = localeFinder.findAvailableLocales();
SuperCsvTemplate superCsvTemplate = new SuperCsvTemplate(name);
superCsvTemplate.addColumn(new Column(KEY, KEY, new Optional(), new Optional()));
for (LocaleRepresentation availableLocale : availableLocales) {
superCsvTemplate.addColumn(new Column(availableLocale.getCode(), availableLocale.getCode(), new Optional(), new Optional()));
}
return superCsvTemplate;
}
@Override
public Set<String> names() {
return Sets.newHashSet(I18N_CSV_TEMPLATE);
}
@Override
public boolean contains(String name) {
return names().contains(name);
}
@Override
public String templateRenderer() {
return I18nCSVRenderer.I18N_RENDERER;
}
@Override
public String templateParser() {
return CSVParser.I18N_PARSER;
}
}
| seedstack/i18n-function | rest/src/main/java/org/seedstack/i18n/rest/internal/infrastructure/csv/I18nCSVTemplateLoader.java | Java | mpl-2.0 | 2,205 |
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ResponseMode.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ResponseMode">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="D"/>
* <enumeration value="I"/>
* <enumeration value="Q"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ResponseMode")
@XmlEnum
public enum ResponseMode {
D,
I,
Q;
public String value() {
return name();
}
public static ResponseMode fromValue(String v) {
return valueOf(v);
}
}
| jembi/openhim-encounter-orchestrator | src/main/java/org/hl7/v3/ResponseMode.java | Java | mpl-2.0 | 754 |
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated: 12/10/2015, 13:28
*
*/
package ims.core.clinical.domain.objects;
/**
*
* @author John MacEnri
* Generated.
*/
public class NonUniqueTaxonomyMap extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable {
public static final int CLASSID = 1003100071;
private static final long serialVersionUID = 1003100071L;
public static final String CLASSVERSION = "${ClassVersion}";
@Override
public boolean shouldCapQuery()
{
return true;
}
private ims.domain.lookups.LookupInstance taxonomyName;
private String taxonomyCode;
private java.util.Date effectiveFrom;
private java.util.Date effectiveTo;
/** SystemInformation */
private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation();
public NonUniqueTaxonomyMap (Integer id, int ver)
{
super(id, ver);
isComponentClass=true;
}
public NonUniqueTaxonomyMap ()
{
super();
isComponentClass=true;
}
public NonUniqueTaxonomyMap (Integer id, int ver, Boolean includeRecord)
{
super(id, ver, includeRecord);
isComponentClass=true;
}
public Class getRealDomainClass()
{
return ims.core.clinical.domain.objects.NonUniqueTaxonomyMap.class;
}
public ims.domain.lookups.LookupInstance getTaxonomyName() {
return taxonomyName;
}
public void setTaxonomyName(ims.domain.lookups.LookupInstance taxonomyName) {
this.taxonomyName = taxonomyName;
}
public String getTaxonomyCode() {
return taxonomyCode;
}
public void setTaxonomyCode(String taxonomyCode) {
if ( null != taxonomyCode && taxonomyCode.length() > 30 ) {
throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for taxonomyCode. Tried to set value: "+
taxonomyCode);
}
this.taxonomyCode = taxonomyCode;
}
public java.util.Date getEffectiveFrom() {
return effectiveFrom;
}
public void setEffectiveFrom(java.util.Date effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
public java.util.Date getEffectiveTo() {
return effectiveTo;
}
public void setEffectiveTo(java.util.Date effectiveTo) {
this.effectiveTo = effectiveTo;
}
public ims.domain.SystemInformation getSystemInformation() {
if (systemInformation == null) systemInformation = new ims.domain.SystemInformation();
return systemInformation;
}
/**
* isConfigurationObject
* Taken from the Usage property of the business object, this method will return
* a boolean indicating whether this is a configuration object or not
* Configuration = true, Instantiation = false
*/
public static boolean isConfigurationObject()
{
if ( "Instantiation".equals("Configuration") )
return true;
else
return false;
}
public int getClassId() {
return CLASSID;
}
public String getClassVersion()
{
return CLASSVERSION;
}
public String toAuditString()
{
StringBuffer auditStr = new StringBuffer();
auditStr.append("\r\n*taxonomyName* :");
if (taxonomyName != null)
auditStr.append(taxonomyName.getText());
auditStr.append("; ");
auditStr.append("\r\n*taxonomyCode* :");
auditStr.append(taxonomyCode);
auditStr.append("; ");
auditStr.append("\r\n*effectiveFrom* :");
auditStr.append(effectiveFrom);
auditStr.append("; ");
auditStr.append("\r\n*effectiveTo* :");
auditStr.append(effectiveTo);
auditStr.append("; ");
return auditStr.toString();
}
public String toXMLString()
{
return toXMLString(new java.util.HashMap());
}
public String toXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
sb.append("<class type=\"" + this.getClass().getName() + "\" ");
sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" ");
sb.append(" classVersion=\"" + this.getClassVersion() + "\" ");
sb.append(" component=\"" + this.getIsComponentClass() + "\" >");
if (domMap.get(this) == null)
{
domMap.put(this, this);
sb.append(this.fieldsToXMLString(domMap));
}
sb.append("</class>");
return sb.toString();
}
public String fieldsToXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
if (this.getTaxonomyName() != null)
{
sb.append("<taxonomyName>");
sb.append(this.getTaxonomyName().toXMLString());
sb.append("</taxonomyName>");
}
if (this.getTaxonomyCode() != null)
{
sb.append("<taxonomyCode>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getTaxonomyCode().toString()));
sb.append("</taxonomyCode>");
}
if (this.getEffectiveFrom() != null)
{
sb.append("<effectiveFrom>");
sb.append(new ims.framework.utils.DateTime(this.getEffectiveFrom()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</effectiveFrom>");
}
if (this.getEffectiveTo() != null)
{
sb.append("<effectiveTo>");
sb.append(new ims.framework.utils.DateTime(this.getEffectiveTo()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</effectiveTo>");
}
return sb.toString();
}
public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception
{
if (list == null)
list = new java.util.ArrayList();
fillListFromXMLString(list, el, factory, domMap);
return list;
}
public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception
{
if (set == null)
set = new java.util.HashSet();
fillSetFromXMLString(set, el, factory, domMap);
return set;
}
private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!set.contains(domainObject))
set.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = set.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
set.remove(iter.next());
}
}
private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
int domIdx = list.indexOf(domainObject);
if (domIdx == -1)
{
list.add(i, domainObject);
}
else if (i != domIdx && i < list.size())
{
Object tmp = list.get(i);
list.set(i, list.get(domIdx));
list.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=list.size();
while (i1 > size)
{
list.remove(i1-1);
i1=list.size();
}
}
public static NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml));
return getNonUniqueTaxonomyMapfromXML(doc.getRootElement(), factory, domMap);
}
public static NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return null;
String className = el.attributeValue("type");
if (!NonUniqueTaxonomyMap.class.getName().equals(className))
{
Class clz = Class.forName(className);
if (!NonUniqueTaxonomyMap.class.isAssignableFrom(clz))
throw new Exception("Element of type = " + className + " cannot be imported using the NonUniqueTaxonomyMap class");
String shortClassName = className.substring(className.lastIndexOf(".")+1);
String methodName = "get" + shortClassName + "fromXML";
java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class});
return (NonUniqueTaxonomyMap)m.invoke(null, new Object[]{el, factory, domMap});
}
String impVersion = el.attributeValue("classVersion");
if(!impVersion.equals(NonUniqueTaxonomyMap.CLASSVERSION))
{
throw new Exception("Incompatible class structure found. Cannot import instance.");
}
NonUniqueTaxonomyMap ret = null;
if (ret == null)
{
ret = new NonUniqueTaxonomyMap();
}
fillFieldsfromXML(el, factory, ret, domMap);
return ret;
}
public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, NonUniqueTaxonomyMap obj, java.util.HashMap domMap) throws Exception
{
org.dom4j.Element fldEl;
fldEl = el.element("taxonomyName");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setTaxonomyName(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
fldEl = el.element("taxonomyCode");
if(fldEl != null)
{
obj.setTaxonomyCode(new String(fldEl.getTextTrim()));
}
fldEl = el.element("effectiveFrom");
if(fldEl != null)
{
obj.setEffectiveFrom(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
fldEl = el.element("effectiveTo");
if(fldEl != null)
{
obj.setEffectiveTo(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
}
public static String[] getCollectionFields()
{
return new String[]{
};
}
/**
equals
*/
public boolean equals(Object obj)
{
if (null == obj)
{
return false;
}
if(!(obj instanceof NonUniqueTaxonomyMap))
{
return false;
}
NonUniqueTaxonomyMap compareObj=(NonUniqueTaxonomyMap)obj;
if((taxonomyCode==null ? compareObj.taxonomyCode == null : taxonomyCode.equals(compareObj.taxonomyCode))&&
(taxonomyName==null ? compareObj.taxonomyName==null : taxonomyName.equals(compareObj.taxonomyName))&&
(effectiveFrom==null? compareObj.effectiveFrom==null : effectiveFrom.equals(compareObj.effectiveFrom))&&
(effectiveTo==null? compareObj.effectiveTo==null : effectiveTo.equals(compareObj.effectiveTo)))
return true;
return super.equals(obj);
}
/**
toString
*/
public String toString()
{
StringBuffer objStr = new StringBuffer();
if (taxonomyName != null)
objStr.append(taxonomyName.getText() + "-");
objStr.append(taxonomyCode);
return objStr.toString();
}
/**
hashcode
*/
public int hashCode()
{
int hash = 0;
if (taxonomyName!= null) hash += taxonomyName.hashCode()* 10011;
if (taxonomyCode!= null) hash += taxonomyCode.hashCode();
if (effectiveFrom!= null) hash += effectiveFrom.hashCode();
if (effectiveTo!= null) hash += effectiveTo.hashCode();
return hash;
}
public static class FieldNames
{
public static final String ID = "id";
public static final String TaxonomyName = "taxonomyName";
public static final String TaxonomyCode = "taxonomyCode";
public static final String EffectiveFrom = "effectiveFrom";
public static final String EffectiveTo = "effectiveTo";
}
}
| IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/DomainObjects/src/ims/core/clinical/domain/objects/NonUniqueTaxonomyMap.java | Java | agpl-3.0 | 14,623 |
/*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.plotter.mathplot;
import org.math.plot.Plot3DPanel;
import org.math.plot.PlotPanel;
import com.rapidminer.datatable.DataTable;
import com.rapidminer.gui.plotter.PlotterConfigurationModel;
/** The abstract super class for all 3D plotters using the JMathPlot library.
*
* @author Ingo Mierswa
*/
public abstract class JMathPlotter3D extends JMathPlotter {
private static final long serialVersionUID = -8695197842788069313L;
public JMathPlotter3D(PlotterConfigurationModel settings) {
super(settings);
}
public JMathPlotter3D(PlotterConfigurationModel settings, DataTable dataTable) {
super(settings, dataTable);
}
@Override
public PlotPanel createPlotPanel() { return new Plot3DPanel(); }
@Override
public int getNumberOfOptionIcons() {
return 5;
}
}
| rapidminer/rapidminer-5 | src/com/rapidminer/gui/plotter/mathplot/JMathPlotter3D.java | Java | agpl-3.0 | 1,676 |
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.analysis;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.analysis.Analyzer;
import org.elasticsearch.ElasticSearchIllegalArgumentException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.component.CloseableComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.AbstractIndexComponent;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.indices.analysis.IndicesAnalysisService;
import java.util.Map;
import static com.google.common.collect.Maps.newHashMap;
/**
*
*/
public class AnalysisService extends AbstractIndexComponent implements CloseableComponent {
private final ImmutableMap<String, NamedAnalyzer> analyzers;
private final ImmutableMap<String, TokenizerFactory> tokenizers;
private final ImmutableMap<String, CharFilterFactory> charFilters;
private final ImmutableMap<String, TokenFilterFactory> tokenFilters;
private final NamedAnalyzer defaultAnalyzer;
private final NamedAnalyzer defaultIndexAnalyzer;
private final NamedAnalyzer defaultSearchAnalyzer;
private final NamedAnalyzer defaultSearchQuoteAnalyzer;
public AnalysisService(Index index) {
this(index, ImmutableSettings.Builder.EMPTY_SETTINGS, null, null, null, null, null);
}
@Inject
public AnalysisService(Index index, @IndexSettings Settings indexSettings, @Nullable IndicesAnalysisService indicesAnalysisService,
@Nullable Map<String, AnalyzerProviderFactory> analyzerFactoryFactories,
@Nullable Map<String, TokenizerFactoryFactory> tokenizerFactoryFactories,
@Nullable Map<String, CharFilterFactoryFactory> charFilterFactoryFactories,
@Nullable Map<String, TokenFilterFactoryFactory> tokenFilterFactoryFactories) {
super(index, indexSettings);
Map<String, TokenizerFactory> tokenizers = newHashMap();
if (tokenizerFactoryFactories != null) {
Map<String, Settings> tokenizersSettings = indexSettings.getGroups("index.analysis.tokenizer");
for (Map.Entry<String, TokenizerFactoryFactory> entry : tokenizerFactoryFactories.entrySet()) {
String tokenizerName = entry.getKey();
TokenizerFactoryFactory tokenizerFactoryFactory = entry.getValue();
Settings tokenizerSettings = tokenizersSettings.get(tokenizerName);
if (tokenizerSettings == null) {
tokenizerSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
TokenizerFactory tokenizerFactory = tokenizerFactoryFactory.create(tokenizerName, tokenizerSettings);
tokenizers.put(tokenizerName, tokenizerFactory);
tokenizers.put(Strings.toCamelCase(tokenizerName), tokenizerFactory);
}
}
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltTokenizerFactoryFactory> entry : indicesAnalysisService.tokenizerFactories().entrySet()) {
String name = entry.getKey();
if (!tokenizers.containsKey(name)) {
tokenizers.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!tokenizers.containsKey(name)) {
tokenizers.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
this.tokenizers = ImmutableMap.copyOf(tokenizers);
Map<String, CharFilterFactory> charFilters = newHashMap();
if (charFilterFactoryFactories != null) {
Map<String, Settings> charFiltersSettings = indexSettings.getGroups("index.analysis.char_filter");
for (Map.Entry<String, CharFilterFactoryFactory> entry : charFilterFactoryFactories.entrySet()) {
String charFilterName = entry.getKey();
CharFilterFactoryFactory charFilterFactoryFactory = entry.getValue();
Settings charFilterSettings = charFiltersSettings.get(charFilterName);
if (charFilterSettings == null) {
charFilterSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
CharFilterFactory tokenFilterFactory = charFilterFactoryFactory.create(charFilterName, charFilterSettings);
charFilters.put(charFilterName, tokenFilterFactory);
charFilters.put(Strings.toCamelCase(charFilterName), tokenFilterFactory);
}
}
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltCharFilterFactoryFactory> entry : indicesAnalysisService.charFilterFactories().entrySet()) {
String name = entry.getKey();
if (!charFilters.containsKey(name)) {
charFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!charFilters.containsKey(name)) {
charFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
this.charFilters = ImmutableMap.copyOf(charFilters);
Map<String, TokenFilterFactory> tokenFilters = newHashMap();
if (tokenFilterFactoryFactories != null) {
Map<String, Settings> tokenFiltersSettings = indexSettings.getGroups("index.analysis.filter");
for (Map.Entry<String, TokenFilterFactoryFactory> entry : tokenFilterFactoryFactories.entrySet()) {
String tokenFilterName = entry.getKey();
TokenFilterFactoryFactory tokenFilterFactoryFactory = entry.getValue();
Settings tokenFilterSettings = tokenFiltersSettings.get(tokenFilterName);
if (tokenFilterSettings == null) {
tokenFilterSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
TokenFilterFactory tokenFilterFactory = tokenFilterFactoryFactory.create(tokenFilterName, tokenFilterSettings);
tokenFilters.put(tokenFilterName, tokenFilterFactory);
tokenFilters.put(Strings.toCamelCase(tokenFilterName), tokenFilterFactory);
}
}
// pre initialize the globally registered ones into the map
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltTokenFilterFactoryFactory> entry : indicesAnalysisService.tokenFilterFactories().entrySet()) {
String name = entry.getKey();
if (!tokenFilters.containsKey(name)) {
tokenFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!tokenFilters.containsKey(name)) {
tokenFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
this.tokenFilters = ImmutableMap.copyOf(tokenFilters);
Map<String, AnalyzerProvider> analyzerProviders = newHashMap();
if (analyzerFactoryFactories != null) {
Map<String, Settings> analyzersSettings = indexSettings.getGroups("index.analysis.analyzer");
for (Map.Entry<String, AnalyzerProviderFactory> entry : analyzerFactoryFactories.entrySet()) {
String analyzerName = entry.getKey();
AnalyzerProviderFactory analyzerFactoryFactory = entry.getValue();
Settings analyzerSettings = analyzersSettings.get(analyzerName);
if (analyzerSettings == null) {
analyzerSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
AnalyzerProvider analyzerFactory = analyzerFactoryFactory.create(analyzerName, analyzerSettings);
analyzerProviders.put(analyzerName, analyzerFactory);
}
}
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltAnalyzerProviderFactory> entry : indicesAnalysisService.analyzerProviderFactories().entrySet()) {
String name = entry.getKey();
if (!analyzerProviders.containsKey(name)) {
analyzerProviders.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!analyzerProviders.containsKey(name)) {
analyzerProviders.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
if (!analyzerProviders.containsKey("default")) {
analyzerProviders.put("default", new StandardAnalyzerProvider(index, indexSettings, null, "default", ImmutableSettings.Builder.EMPTY_SETTINGS));
}
if (!analyzerProviders.containsKey("default_index")) {
analyzerProviders.put("default_index", analyzerProviders.get("default"));
}
if (!analyzerProviders.containsKey("default_search")) {
analyzerProviders.put("default_search", analyzerProviders.get("default"));
}
if (!analyzerProviders.containsKey("default_search_quoted")) {
analyzerProviders.put("default_search_quoted", analyzerProviders.get("default_search"));
}
Map<String, NamedAnalyzer> analyzers = newHashMap();
for (AnalyzerProvider analyzerFactory : analyzerProviders.values()) {
if (analyzerFactory instanceof CustomAnalyzerProvider) {
((CustomAnalyzerProvider) analyzerFactory).build(this);
}
Analyzer analyzerF = analyzerFactory.get();
if (analyzerF == null) {
throw new ElasticSearchIllegalArgumentException("analyzer [" + analyzerFactory.name() + "] created null analyzer");
}
NamedAnalyzer analyzer;
// if we got a named analyzer back, use it...
if (analyzerF instanceof NamedAnalyzer) {
analyzer = (NamedAnalyzer) analyzerF;
} else {
analyzer = new NamedAnalyzer(analyzerFactory.name(), analyzerFactory.scope(), analyzerF);
}
analyzers.put(analyzerFactory.name(), analyzer);
analyzers.put(Strings.toCamelCase(analyzerFactory.name()), analyzer);
String strAliases = indexSettings.get("index.analysis.analyzer." + analyzerFactory.name() + ".alias");
if (strAliases != null) {
for (String alias : Strings.commaDelimitedListToStringArray(strAliases)) {
analyzers.put(alias, analyzer);
}
}
String[] aliases = indexSettings.getAsArray("index.analysis.analyzer." + analyzerFactory.name() + ".alias");
for (String alias : aliases) {
analyzers.put(alias, analyzer);
}
}
defaultAnalyzer = analyzers.get("default");
if (defaultAnalyzer == null) {
throw new ElasticSearchIllegalArgumentException("no default analyzer configured");
}
defaultIndexAnalyzer = analyzers.containsKey("default_index") ? analyzers.get("default_index") : analyzers.get("default");
defaultSearchAnalyzer = analyzers.containsKey("default_search") ? analyzers.get("default_search") : analyzers.get("default");
defaultSearchQuoteAnalyzer = analyzers.containsKey("default_search_quote") ? analyzers.get("default_search_quote") : defaultSearchAnalyzer;
this.analyzers = ImmutableMap.copyOf(analyzers);
}
public void close() {
for (NamedAnalyzer analyzer : analyzers.values()) {
if (analyzer.scope() == AnalyzerScope.INDEX) {
try {
analyzer.close();
} catch (NullPointerException e) {
// because analyzers are aliased, they might be closed several times
// an NPE is thrown in this case, so ignore....
} catch (Exception e) {
logger.debug("failed to close analyzer " + analyzer);
}
}
}
}
public NamedAnalyzer analyzer(String name) {
return analyzers.get(name);
}
public NamedAnalyzer defaultAnalyzer() {
return defaultAnalyzer;
}
public NamedAnalyzer defaultIndexAnalyzer() {
return defaultIndexAnalyzer;
}
public NamedAnalyzer defaultSearchAnalyzer() {
return defaultSearchAnalyzer;
}
public NamedAnalyzer defaultSearchQuoteAnalyzer() {
return defaultSearchQuoteAnalyzer;
}
public TokenizerFactory tokenizer(String name) {
return tokenizers.get(name);
}
public CharFilterFactory charFilter(String name) {
return charFilters.get(name);
}
public TokenFilterFactory tokenFilter(String name) {
return tokenFilters.get(name);
}
}
| exercitussolus/yolo | src/main/java/org/elasticsearch/index/analysis/AnalysisService.java | Java | agpl-3.0 | 14,624 |
/*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH
*
* 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 theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at trademark@heliumv.com).
*
* 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: developers@heliumv.com
******************************************************************************/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.12.03 at 10:12:07 AM MEZ
//
package com.lp.server.schema.opentrans.cc.orderresponse;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for _XML_XML_COST_CATEGORY_ID complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="_XML_XML_COST_CATEGORY_ID">
* <simpleContent>
* <extension base="<http://www.opentrans.org/XMLSchema/1.0>typeCOST_CATEGORY_ID">
* <attGroup ref="{http://www.opentrans.org/XMLSchema/1.0}ComIbmMrmNamespaceInfo154"/>
* <attribute name="type">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN">
* <minLength value="1"/>
* <maxLength value="32"/>
* <enumeration value="cost_center"/>
* <enumeration value="project"/>
* </restriction>
* </simpleType>
* </attribute>
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "_XML_XML_COST_CATEGORY_ID", propOrder = {
"value"
})
public class XMLXMLCOSTCATEGORYID {
@XmlValue
protected String value;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String type;
@XmlAttribute(name = "xsi_schemaLocation")
protected String xsiSchemaLocation;
@XmlAttribute(name = "xmlns_xsd")
protected String xmlnsXsd;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the xsiSchemaLocation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXsiSchemaLocation() {
if (xsiSchemaLocation == null) {
return "openbase_1_0.mxsd";
} else {
return xsiSchemaLocation;
}
}
/**
* Sets the value of the xsiSchemaLocation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXsiSchemaLocation(String value) {
this.xsiSchemaLocation = value;
}
/**
* Gets the value of the xmlnsXsd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXmlnsXsd() {
if (xmlnsXsd == null) {
return "http://www.w3.org/2001/XMLSchema";
} else {
return xmlnsXsd;
}
}
/**
* Sets the value of the xmlnsXsd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXmlnsXsd(String value) {
this.xmlnsXsd = value;
}
}
| erdincay/ejb | src/com/lp/server/schema/opentrans/cc/orderresponse/XMLXMLCOSTCATEGORYID.java | Java | agpl-3.0 | 5,991 |
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2019. (c) 2019.
* 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/>.
*
*
************************************************************************
*/
package org.opencadc.proxy;
import ca.nrc.cadc.auth.AuthMethod;
import ca.nrc.cadc.reg.client.RegistryClient;
import java.net.URI;
import java.net.URL;
import org.junit.Test;
import org.junit.Assert;
import static org.mockito.Mockito.*;
public class ProxyServletTest {
@Test
public void lookupServiceURL() throws Exception {
final RegistryClient mockRegistryClient = mock(RegistryClient.class);
final ProxyServlet testSubject = new ProxyServlet() {
/**
* Useful for overriding in tests.
*
* @return RegistryClient instance. Never null.
*/
@Override
RegistryClient getRegistryClient() {
return mockRegistryClient;
}
};
final URL lookedUpServiceURL = new URL("https://www.services.com/myservice");
final ServiceParameterMap serviceParameterMap = new ServiceParameterMap();
serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource");
serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard");
serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https");
serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "cookie");
when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"),
URI.create("ivo://cadc.nrc.ca/mystandard"),
AuthMethod.COOKIE,
URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn(
lookedUpServiceURL);
final URL result = testSubject.lookupServiceURL(serviceParameterMap);
Assert.assertEquals("URLs do not match.", lookedUpServiceURL, result);
}
@Test
public void lookupServiceURLWithPath() throws Exception {
final RegistryClient mockRegistryClient = mock(RegistryClient.class);
final ProxyServlet testSubject = new ProxyServlet() {
/**
* Useful for overriding in tests.
*
* @return RegistryClient instance. Never null.
*/
@Override
RegistryClient getRegistryClient() {
return mockRegistryClient;
}
};
final URL lookedUpServiceURL = new URL("https://www.services.com/myservice");
final ServiceParameterMap serviceParameterMap = new ServiceParameterMap();
serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource");
serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard");
serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https");
serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "anon");
serviceParameterMap.put(ServiceParameterName.EXTRA_PATH, "alt-site");
when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"),
URI.create("ivo://cadc.nrc.ca/mystandard"),
AuthMethod.ANON,
URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn(
lookedUpServiceURL);
final URL result = testSubject.lookupServiceURL(serviceParameterMap);
final URL expected = new URL("https://www.services.com/myservice/alt-site");
Assert.assertEquals("URLs do not match.", expected, result);
}
@Test
public void lookupServiceURLWithPathQuery() throws Exception {
final RegistryClient mockRegistryClient = mock(RegistryClient.class);
final ProxyServlet testSubject = new ProxyServlet() {
/**
* Useful for overriding in tests.
*
* @return RegistryClient instance. Never null.
*/
@Override
RegistryClient getRegistryClient() {
return mockRegistryClient;
}
};
final URL lookedUpServiceURL = new URL("https://www.services.com/myservice");
final ServiceParameterMap serviceParameterMap = new ServiceParameterMap();
serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource");
serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard");
serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https");
serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "anon");
serviceParameterMap.put(ServiceParameterName.EXTRA_PATH, "alt-site");
serviceParameterMap.put(ServiceParameterName.EXTRA_QUERY, "myquery=a&g=j");
when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"),
URI.create("ivo://cadc.nrc.ca/mystandard"),
AuthMethod.ANON,
URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn(
lookedUpServiceURL);
final URL result = testSubject.lookupServiceURL(serviceParameterMap);
final URL expected = new URL("https://www.services.com/myservice/alt-site?myquery=a&g=j");
Assert.assertEquals("URLs do not match.", expected, result);
}
}
| at88mph/web | cadc-web-util/src/test/java/org/opencadc/proxy/ProxyServletTest.java | Java | agpl-3.0 | 9,512 |
package org.osforce.connect.service.system;
import org.osforce.connect.entity.system.ProjectFeature;
/**
*
* @author gavin
* @since 1.0.0
* @create Feb 12, 2011 - 9:23:35 PM
* <a href="http://www.opensourceforce.org">开源力量</a>
*/
public interface ProjectFeatureService {
ProjectFeature getProjectFeature(Long featureId);
ProjectFeature getProjectFeature(String code, Long projectId);
void createProjectFeature(ProjectFeature feature);
void updateProjectFeature(ProjectFeature feature);
void deleteProjectFeature(Long featureId);
}
| shook2012/focus-sns | connect-service/src/main/java/org/osforce/connect/service/system/ProjectFeatureService.java | Java | agpl-3.0 | 562 |
package functionaltests.job;
import java.io.Serializable;
import org.ow2.proactive.scheduler.common.Scheduler;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.TaskFlowJob;
import org.ow2.proactive.scheduler.common.task.JavaTask;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.common.task.executable.JavaExecutable;
import org.junit.Test;
import functionaltests.utils.SchedulerFunctionalTest;
import static org.junit.Assert.*;
/**
* Test provokes scenario when task gets 'NOT_RESTARTED' status:
* - task is submitted and starts execution
* - user requests to restart task with some delay
* - before task was restarted job is killed
*
*/
public class TestTaskNotRestarted extends SchedulerFunctionalTest {
public static class TestJavaTask extends JavaExecutable {
@Override
public Serializable execute(TaskResult... results) throws Throwable {
Thread.sleep(Long.MAX_VALUE);
return "OK";
}
}
@Test
public void test() throws Exception {
Scheduler scheduler = schedulerHelper.getSchedulerInterface();
JobId jobId = scheduler.submit(createJob());
JobState jobState;
schedulerHelper.waitForEventTaskRunning(jobId, "task1");
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.RUNNING, jobState.getTasks().get(0).getStatus());
scheduler.restartTask(jobId, "task1", Integer.MAX_VALUE);
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.WAITING_ON_ERROR, jobState.getTasks().get(0).getStatus());
scheduler.killJob(jobId);
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.NOT_RESTARTED, jobState.getTasks().get(0).getStatus());
}
private TaskFlowJob createJob() throws Exception {
TaskFlowJob job = new TaskFlowJob();
job.setName(this.getClass().getSimpleName());
JavaTask javaTask = new JavaTask();
javaTask.setExecutableClassName(TestJavaTask.class.getName());
javaTask.setName("task1");
javaTask.setMaxNumberOfExecution(10);
job.addTask(javaTask);
return job;
}
}
| sandrineBeauche/scheduling | scheduler/scheduler-server/src/test/java/functionaltests/job/TestTaskNotRestarted.java | Java | agpl-3.0 | 2,532 |
/* This file is part of VoltDB.
* Copyright (C) 2008-2017 VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
import java.io.File;
/**
* This file isn't long for this world. It's just something I've been using
* to debug multi-process rejoin stuff.
*
*/
public class VLog {
static File m_logfile = new File("vlog.txt");
public synchronized static void setPortNo(int portNo) {
m_logfile = new File(String.format("vlog-%d.txt", portNo));
}
public synchronized static void log(String str) {
// turn off this stupid thing for now
/*try {
FileWriter log = new FileWriter(m_logfile, true);
log.write(str + "\n");
log.flush();
log.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
public static void log(String format, Object... args) {
log(String.format(format, args));
}
}
| migue/voltdb | src/frontend/org/voltdb/VLog.java | Java | agpl-3.0 | 1,623 |
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.enums;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
public enum BeaconIndexType implements EnumAsString {
LOG("Log"),
STATE("State");
private String value;
BeaconIndexType(String value) {
this.value = value;
}
@Override
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
public static BeaconIndexType get(String value) {
if(value == null)
{
return null;
}
// goes over BeaconIndexType defined values and compare the inner value with the given one:
for(BeaconIndexType item: values()) {
if(item.getValue().equals(value)) {
return item;
}
}
// in case the requested value was not found in the enum values, we return the first item as default.
return BeaconIndexType.values().length > 0 ? BeaconIndexType.values()[0]: null;
}
}
| kaltura/KalturaGeneratedAPIClientsJava | src/main/java/com/kaltura/client/enums/BeaconIndexType.java | Java | agpl-3.0 | 2,312 |
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 12/10/2015, 13:24
*
*/
package ims.admin.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Cornel Ventuneac
*/
public class ConfigLocationLiteVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.admin.vo.ConfigLocationLiteVo copy(ims.admin.vo.ConfigLocationLiteVo valueObjectDest, ims.admin.vo.ConfigLocationLiteVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_Location(valueObjectSrc.getID_Location());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// Name
valueObjectDest.setName(valueObjectSrc.getName());
// Type
valueObjectDest.setType(valueObjectSrc.getType());
// isActive
valueObjectDest.setIsActive(valueObjectSrc.getIsActive());
// Address
valueObjectDest.setAddress(valueObjectSrc.getAddress());
// IsVirtual
valueObjectDest.setIsVirtual(valueObjectSrc.getIsVirtual());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(java.util.Set domainObjectSet)
{
return createConfigLocationLiteVoCollectionFromLocation(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.admin.vo.ConfigLocationLiteVoCollection voList = new ims.admin.vo.ConfigLocationLiteVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) iterator.next();
ims.admin.vo.ConfigLocationLiteVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(java.util.List domainObjectList)
{
return createConfigLocationLiteVoCollectionFromLocation(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap map, java.util.List domainObjectList)
{
ims.admin.vo.ConfigLocationLiteVoCollection voList = new ims.admin.vo.ConfigLocationLiteVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) domainObjectList.get(i);
ims.admin.vo.ConfigLocationLiteVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.core.resource.place.domain.objects.Location set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractLocationSet(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection)
{
return extractLocationSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractLocationSet(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.admin.vo.ConfigLocationLiteVo vo = voCollection.get(i);
ims.core.resource.place.domain.objects.Location domainObject = ConfigLocationLiteVoAssembler.extractLocation(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.core.resource.place.domain.objects.Location list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractLocationList(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection)
{
return extractLocationList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractLocationList(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.admin.vo.ConfigLocationLiteVo vo = voCollection.get(i);
ims.core.resource.place.domain.objects.Location domainObject = ConfigLocationLiteVoAssembler.extractLocation(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.core.resource.place.domain.objects.Location object.
* @param domainObject ims.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.ConfigLocationLiteVo create(ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.core.resource.place.domain.objects.Location object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.admin.vo.ConfigLocationLiteVo create(DomainObjectMap map, ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.admin.vo.ConfigLocationLiteVo valueObject = (ims.admin.vo.ConfigLocationLiteVo) map.getValueObject(domainObject, ims.admin.vo.ConfigLocationLiteVo.class);
if ( null == valueObject )
{
valueObject = new ims.admin.vo.ConfigLocationLiteVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.ConfigLocationLiteVo insert(ims.admin.vo.ConfigLocationLiteVo valueObject, ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.ConfigLocationLiteVo insert(DomainObjectMap map, ims.admin.vo.ConfigLocationLiteVo valueObject, ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_Location(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// Name
valueObject.setName(domainObject.getName());
// Type
ims.domain.lookups.LookupInstance instance2 = domainObject.getType();
if ( null != instance2 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath());
}
color = instance2.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.LocationType voLookup2 = new ims.core.vo.lookups.LocationType(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color);
ims.core.vo.lookups.LocationType parentVoLookup2 = voLookup2;
ims.domain.lookups.LookupInstance parent2 = instance2.getParent();
while (parent2 != null)
{
if (parent2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent2.getColor();
if (color != null)
color.getValue();
parentVoLookup2.setParent(new ims.core.vo.lookups.LocationType(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color));
parentVoLookup2 = parentVoLookup2.getParent();
parent2 = parent2.getParent();
}
valueObject.setType(voLookup2);
}
// isActive
valueObject.setIsActive( domainObject.isIsActive() );
// Address
valueObject.setAddress(ims.core.vo.domain.PersonAddressAssembler.create(map, domainObject.getAddress()) );
// IsVirtual
valueObject.setIsVirtual( domainObject.isIsVirtual() );
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.core.resource.place.domain.objects.Location extractLocation(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVo valueObject)
{
return extractLocation(domainFactory, valueObject, new HashMap());
}
public static ims.core.resource.place.domain.objects.Location extractLocation(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_Location();
ims.core.resource.place.domain.objects.Location domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.core.resource.place.domain.objects.Location)domMap.get(valueObject);
}
// ims.admin.vo.ConfigLocationLiteVo ID_Location field is unknown
domainObject = new ims.core.resource.place.domain.objects.Location();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Location());
if (domMap.get(key) != null)
{
return (ims.core.resource.place.domain.objects.Location)domMap.get(key);
}
domainObject = (ims.core.resource.place.domain.objects.Location) domainFactory.getDomainObject(ims.core.resource.place.domain.objects.Location.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_Location());
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getName() != null && valueObject.getName().equals(""))
{
valueObject.setName(null);
}
domainObject.setName(valueObject.getName());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value2 = null;
if ( null != valueObject.getType() )
{
value2 =
domainFactory.getLookupInstance(valueObject.getType().getID());
}
domainObject.setType(value2);
domainObject.setIsActive(valueObject.getIsActive());
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.generic.domain.objects.Address value4 = null;
if ( null != valueObject.getAddress() )
{
if (valueObject.getAddress().getBoId() == null)
{
if (domMap.get(valueObject.getAddress()) != null)
{
value4 = (ims.core.generic.domain.objects.Address)domMap.get(valueObject.getAddress());
}
}
else
{
value4 = (ims.core.generic.domain.objects.Address)domainFactory.getDomainObject(ims.core.generic.domain.objects.Address.class, valueObject.getAddress().getBoId());
}
}
domainObject.setAddress(value4);
domainObject.setIsVirtual(valueObject.getIsVirtual());
return domainObject;
}
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/admin/vo/domain/ConfigLocationLiteVoAssembler.java | Java | agpl-3.0 | 19,428 |
package org.ownprofile.boundary.owner.client;
public class Result<T> {
private boolean isSuccess;
private T successValue;
private Fail fail;
public static Result<Void> success() {
return success(null);
}
public static <S> Result<S> success(S successValue) {
return new Result<S>(successValue);
}
public static <S> Result<S> fail(String message) {
return fail((Throwable)null, "%s", message);
}
public static <S> Result<S> fail(Throwable cause, String message) {
return fail(cause, "%s", message);
}
public static <S> Result<S> fail(String format, Object... args) {
return fail(null, format, args);
}
public static <S> Result<S> fail(Throwable cause, String format, Object... args) {
final Fail f = new Fail(cause, format, args);
return new Result<S>(f);
}
private Result(T successValue) {
this.isSuccess = true;
this.successValue = successValue;
}
private Result(Fail fail) {
this.isSuccess = false;
this.fail = fail;
}
public boolean isSuccess() {
return isSuccess;
}
public boolean isFail() {
return !isSuccess;
}
public T getSuccessValue() {
if (isSuccess) {
return successValue;
} else {
throw new IllegalStateException(String.format("Result is Fail: %s", fail));
}
}
public Fail getFail() {
if (isSuccess) {
throw new IllegalStateException(String.format("Result is Success"));
} else {
return fail;
}
}
@Override
public String toString() {
return String.format("%s: %s",
isSuccess ? "SUCCESS" : "FAIL",
isSuccess ? successValue : fail);
}
// ------------------------------
public static class Fail {
private String message;
private Throwable cause;
private Fail(Throwable cause, String message) {
this.cause = cause;
this.message = message;
}
private Fail(Throwable cause, String format, Object... args) {
this(cause, String.format(format, args));
}
public String getMessage() {
return message;
}
public Throwable getCause() {
return cause;
}
@Override
public String toString() {
return String.format("%s - %s", message, cause);
}
}
}
| mchlrch/ownprofile | org.ownprofile.node/src/main/java/org/ownprofile/boundary/owner/client/Result.java | Java | agpl-3.0 | 2,101 |
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.vitalsignstprbp;
import ims.framework.delegates.*;
abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode
{
abstract protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onChkLegendValueChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnViewClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onRadioButtongrpShowByValueChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnPrintClick() throws ims.framework.exceptions.PresentationLogicException;
public final void setContext(ims.framework.UIEngine engine, GenForm form)
{
this.engine = engine;
this.form = form;
this.form.setFormOpenEvent(new FormOpen()
{
private static final long serialVersionUID = 1L;
public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException
{
onFormOpen();
}
});
this.form.chkLegend().setValueChangedEvent(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onChkLegendValueChanged();
}
});
this.form.btnView().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnViewClick();
}
});
this.form.grpShowBy().setValueChangedEvent(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onRadioButtongrpShowByValueChanged();
}
});
this.form.btnPrint().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnPrintClick();
}
});
}
public void free()
{
this.engine = null;
this.form = null;
}
protected ims.framework.UIEngine engine;
protected GenForm form;
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Core/src/ims/core/forms/vitalsignstprbp/Handlers.java | Java | agpl-3.0 | 4,321 |
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.RefMan.vo.beans;
public class PatientDiagnosisStatusForReferralCodingVoBean extends ims.vo.ValueObjectBean
{
public PatientDiagnosisStatusForReferralCodingVoBean()
{
}
public PatientDiagnosisStatusForReferralCodingVoBean(ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean();
}
public ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo = null;
if(map != null)
vo = (ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.vo.LookupInstanceBean getStatus()
{
return this.status;
}
public void setStatus(ims.vo.LookupInstanceBean value)
{
this.status = value;
}
private Integer id;
private int version;
private ims.vo.LookupInstanceBean status;
}
| IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/refman/vo/beans/PatientDiagnosisStatusForReferralCodingVoBean.java | Java | agpl-3.0 | 3,988 |
/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2007 Funambol, Inc.
*
* 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 with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
package com.funambol.ctp.server.notification;
/**
*
* @version $Id: NotificationProviderException.java,v 1.2 2007-11-28 11:26:16 nichele Exp $
*/
public class NotificationProviderException extends Exception {
/**
* Creates a new instance of <code>NotificationProviderException</code> without
* detail message.
*/
public NotificationProviderException() {
super();
}
/**
* Constructs an instance of <code>NotificationProviderException</code> with the
* specified detail message.
*
* @param message the detail message.
*/
public NotificationProviderException(String message) {
super(message);
}
/**
* Constructs an instance of <code>NotificationProviderException</code> with the
* specified detail message and the given cause.
*
* @param message the detail message.
* @param cause the cause.
*/
public NotificationProviderException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs an instance of <code>NotificationProviderException</code> with the
* specified cause.
*
* @param cause the cause.
*/
public NotificationProviderException(Throwable cause) {
super(cause);
}
}
| accesstest3/cfunambol | ctp/ctp-server/src/main/java/com/funambol/ctp/server/notification/NotificationProviderException.java | Java | agpl-3.0 | 3,078 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.spinalinjuries.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class BaseSharedNewConcernImpl extends DomainImpl implements ims.spinalinjuries.domain.SharedNewConcern, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
public void validatesaveConcern(ims.core.vo.PatientCurrentConcernVo concern, ims.core.vo.PatientShort patient)
{
}
@SuppressWarnings("unused")
public void validatelistHcps(ims.core.vo.HcpFilter filter)
{
}
@SuppressWarnings("unused")
public void validatelistProbsOnAdmission(ims.core.vo.CareContextShortVo coClinicalContactShort)
{
}
@SuppressWarnings("unused")
public void validategetConcern(ims.core.clinical.vo.PatientConcernRefVo concernId)
{
}
}
| open-health-hub/openmaxims-linux | openmaxims_workspace/SpinalInjuries/src/ims/spinalinjuries/domain/base/impl/BaseSharedNewConcernImpl.java | Java | agpl-3.0 | 2,507 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5007.25751)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 16/04/2014, 12:31
*
*/
package ims.emergency.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Cornel Ventuneac
*/
public class TrackingLiteVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.emergency.vo.TrackingLiteVo copy(ims.emergency.vo.TrackingLiteVo valueObjectDest, ims.emergency.vo.TrackingLiteVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_Tracking(valueObjectSrc.getID_Tracking());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// CurrentArea
valueObjectDest.setCurrentArea(valueObjectSrc.getCurrentArea());
// isPrimaryCare
valueObjectDest.setIsPrimaryCare(valueObjectSrc.getIsPrimaryCare());
// isDischarged
valueObjectDest.setIsDischarged(valueObjectSrc.getIsDischarged());
// LastMovementDateTime
valueObjectDest.setLastMovementDateTime(valueObjectSrc.getLastMovementDateTime());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createTrackingLiteVoCollectionFromTracking(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(java.util.Set domainObjectSet)
{
return createTrackingLiteVoCollectionFromTracking(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.emergency.vo.TrackingLiteVoCollection voList = new ims.emergency.vo.TrackingLiteVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) iterator.next();
ims.emergency.vo.TrackingLiteVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(java.util.List domainObjectList)
{
return createTrackingLiteVoCollectionFromTracking(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(DomainObjectMap map, java.util.List domainObjectList)
{
ims.emergency.vo.TrackingLiteVoCollection voList = new ims.emergency.vo.TrackingLiteVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) domainObjectList.get(i);
ims.emergency.vo.TrackingLiteVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.emergency.domain.objects.Tracking set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractTrackingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection)
{
return extractTrackingSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractTrackingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.emergency.vo.TrackingLiteVo vo = voCollection.get(i);
ims.emergency.domain.objects.Tracking domainObject = TrackingLiteVoAssembler.extractTracking(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.emergency.domain.objects.Tracking list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractTrackingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection)
{
return extractTrackingList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractTrackingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.emergency.vo.TrackingLiteVo vo = voCollection.get(i);
ims.emergency.domain.objects.Tracking domainObject = TrackingLiteVoAssembler.extractTracking(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.Tracking object.
* @param domainObject ims.emergency.domain.objects.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo create(ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.Tracking object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.emergency.vo.TrackingLiteVo create(DomainObjectMap map, ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.emergency.vo.TrackingLiteVo valueObject = (ims.emergency.vo.TrackingLiteVo) map.getValueObject(domainObject, ims.emergency.vo.TrackingLiteVo.class);
if ( null == valueObject )
{
valueObject = new ims.emergency.vo.TrackingLiteVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo insert(ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo insert(DomainObjectMap map, ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_Tracking(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// CurrentArea
if (domainObject.getCurrentArea() != null)
{
if(domainObject.getCurrentArea() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already.
{
HibernateProxy p = (HibernateProxy) domainObject.getCurrentArea();
int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString());
valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(id, -1));
}
else
{
valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(domainObject.getCurrentArea().getId(), domainObject.getCurrentArea().getVersion()));
}
}
// isPrimaryCare
valueObject.setIsPrimaryCare( domainObject.isIsPrimaryCare() );
// isDischarged
valueObject.setIsDischarged( domainObject.isIsDischarged() );
// LastMovementDateTime
java.util.Date LastMovementDateTime = domainObject.getLastMovementDateTime();
if ( null != LastMovementDateTime )
{
valueObject.setLastMovementDateTime(new ims.framework.utils.DateTime(LastMovementDateTime) );
}
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.emergency.domain.objects.Tracking extractTracking(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVo valueObject)
{
return extractTracking(domainFactory, valueObject, new HashMap());
}
public static ims.emergency.domain.objects.Tracking extractTracking(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_Tracking();
ims.emergency.domain.objects.Tracking domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.emergency.domain.objects.Tracking)domMap.get(valueObject);
}
// ims.emergency.vo.TrackingLiteVo ID_Tracking field is unknown
domainObject = new ims.emergency.domain.objects.Tracking();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Tracking());
if (domMap.get(key) != null)
{
return (ims.emergency.domain.objects.Tracking)domMap.get(key);
}
domainObject = (ims.emergency.domain.objects.Tracking) domainFactory.getDomainObject(ims.emergency.domain.objects.Tracking.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_Tracking());
ims.emergency.configuration.domain.objects.TrackingArea value1 = null;
if ( null != valueObject.getCurrentArea() )
{
if (valueObject.getCurrentArea().getBoId() == null)
{
if (domMap.get(valueObject.getCurrentArea()) != null)
{
value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domMap.get(valueObject.getCurrentArea());
}
}
else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field
{
value1 = domainObject.getCurrentArea();
}
else
{
value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domainFactory.getDomainObject(ims.emergency.configuration.domain.objects.TrackingArea.class, valueObject.getCurrentArea().getBoId());
}
}
domainObject.setCurrentArea(value1);
domainObject.setIsPrimaryCare(valueObject.getIsPrimaryCare());
domainObject.setIsDischarged(valueObject.getIsDischarged());
ims.framework.utils.DateTime dateTime4 = valueObject.getLastMovementDateTime();
java.util.Date value4 = null;
if ( dateTime4 != null )
{
value4 = dateTime4.getJavaDate();
}
domainObject.setLastMovementDateTime(value4);
return domainObject;
}
}
| open-health-hub/openmaxims-linux | openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/TrackingLiteVoAssembler.java | Java | agpl-3.0 | 17,855 |
package com.sapienter.jbilling.client.jspc.payment;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import com.sapienter.jbilling.client.util.Constants;
public final class review_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.release();
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.release();
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n");
if (_jspx_meth_sess_005fexistsAttribute_005f0(_jspx_page_context))
return;
out.write('\r');
out.write('\n');
if (_jspx_meth_sess_005fexistsAttribute_005f1(_jspx_page_context))
return;
out.write("\r\n\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_sess_005fexistsAttribute_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// sess:existsAttribute
org.apache.taglibs.session.ExistsAttributeTag _jspx_th_sess_005fexistsAttribute_005f0 = (org.apache.taglibs.session.ExistsAttributeTag) _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.get(org.apache.taglibs.session.ExistsAttributeTag.class);
_jspx_th_sess_005fexistsAttribute_005f0.setPageContext(_jspx_page_context);
_jspx_th_sess_005fexistsAttribute_005f0.setParent(null);
// /payment/review.jsp(30,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_sess_005fexistsAttribute_005f0.setName("jsp_is_refund");
// /payment/review.jsp(30,0) name = value type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_sess_005fexistsAttribute_005f0.setValue(false);
int _jspx_eval_sess_005fexistsAttribute_005f0 = _jspx_th_sess_005fexistsAttribute_005f0.doStartTag();
if (_jspx_eval_sess_005fexistsAttribute_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n ");
if (_jspx_meth_tiles_005finsert_005f0(_jspx_th_sess_005fexistsAttribute_005f0, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = _jspx_th_sess_005fexistsAttribute_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_sess_005fexistsAttribute_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f0);
return true;
}
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f0);
return false;
}
private boolean _jspx_meth_tiles_005finsert_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_sess_005fexistsAttribute_005f0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// tiles:insert
org.apache.struts.taglib.tiles.InsertTag _jspx_th_tiles_005finsert_005f0 = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class);
_jspx_th_tiles_005finsert_005f0.setPageContext(_jspx_page_context);
_jspx_th_tiles_005finsert_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_sess_005fexistsAttribute_005f0);
// /payment/review.jsp(31,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f0.setDefinition("payment.review");
// /payment/review.jsp(31,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f0.setFlush(true);
int _jspx_eval_tiles_005finsert_005f0 = _jspx_th_tiles_005finsert_005f0.doStartTag();
if (_jspx_th_tiles_005finsert_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f0);
return true;
}
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f0);
return false;
}
private boolean _jspx_meth_sess_005fexistsAttribute_005f1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// sess:existsAttribute
org.apache.taglibs.session.ExistsAttributeTag _jspx_th_sess_005fexistsAttribute_005f1 = (org.apache.taglibs.session.ExistsAttributeTag) _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.get(org.apache.taglibs.session.ExistsAttributeTag.class);
_jspx_th_sess_005fexistsAttribute_005f1.setPageContext(_jspx_page_context);
_jspx_th_sess_005fexistsAttribute_005f1.setParent(null);
// /payment/review.jsp(33,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_sess_005fexistsAttribute_005f1.setName("jsp_is_refund");
int _jspx_eval_sess_005fexistsAttribute_005f1 = _jspx_th_sess_005fexistsAttribute_005f1.doStartTag();
if (_jspx_eval_sess_005fexistsAttribute_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n ");
if (_jspx_meth_tiles_005finsert_005f1(_jspx_th_sess_005fexistsAttribute_005f1, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = _jspx_th_sess_005fexistsAttribute_005f1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_sess_005fexistsAttribute_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f1);
return true;
}
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f1);
return false;
}
private boolean _jspx_meth_tiles_005finsert_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_sess_005fexistsAttribute_005f1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// tiles:insert
org.apache.struts.taglib.tiles.InsertTag _jspx_th_tiles_005finsert_005f1 = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class);
_jspx_th_tiles_005finsert_005f1.setPageContext(_jspx_page_context);
_jspx_th_tiles_005finsert_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_sess_005fexistsAttribute_005f1);
// /payment/review.jsp(34,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f1.setDefinition("refund.review");
// /payment/review.jsp(34,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f1.setFlush(true);
int _jspx_eval_tiles_005finsert_005f1 = _jspx_th_tiles_005finsert_005f1.doStartTag();
if (_jspx_th_tiles_005finsert_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f1);
return true;
}
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f1);
return false;
}
}
| maduhu/knx-jbilling2.2.0 | build/jsp-classes/com/sapienter/jbilling/client/jspc/payment/review_jsp.java | Java | agpl-3.0 | 11,647 |
//#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.notificationdialog;
public interface IFormUILogicCode
{
// No methods yet.
}
| open-health-hub/openmaxims-linux | openmaxims_workspace/Core/src/ims/core/forms/notificationdialog/IFormUILogicCode.java | Java | agpl-3.0 | 1,804 |
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Silviu Checherita using IMS Development Environment (version 1.80 build 5567.19951)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
package ims.scheduling.domain.impl;
import java.util.ArrayList;
import java.util.List;
import ims.domain.DomainFactory;
import ims.domain.lookups.LookupInstance;
import ims.scheduling.domain.base.impl.BaseReasonTextDialogImpl;
import ims.scheduling.vo.lookups.CancelAppointmentReason;
import ims.scheduling.vo.lookups.CancelAppointmentReasonCollection;
import ims.scheduling.vo.lookups.Status_Reason;
public class ReasonTextDialogImpl extends BaseReasonTextDialogImpl
{
private static final long serialVersionUID = 1L;
//WDEV-21736
public CancelAppointmentReasonCollection listReasons()
{
DomainFactory factory = getDomainFactory();
ArrayList markers = new ArrayList();
ArrayList values = new ArrayList();
String hql = "SELECT r FROM CancellationTypeReason AS t LEFT JOIN t.cancellationReason as r WHERE t.cancellationType.id = :cancellationType AND r.active = 1";
markers.add("cancellationType");
values.add(Status_Reason.HOSPITALCANCELLED.getID());
List results = factory.find(hql.toString(), markers,values);
if (results == null)
return null;
CancelAppointmentReasonCollection col = new CancelAppointmentReasonCollection();
for (int i=0; i<results.size(); i++)
{
CancelAppointmentReason reason = new CancelAppointmentReason(((LookupInstance) results.get(i)).getId(), ((LookupInstance) results.get(i)).getText(), ((LookupInstance) results.get(i)).isActive());
col.add(reason);
}
return col;
}
//WDEV-21736 ends here
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Scheduling/src/ims/scheduling/domain/impl/ReasonTextDialogImpl.java | Java | agpl-3.0 | 3,583 |
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.oncology.vo.lookups;
import ims.framework.cn.data.TreeNode;
import java.util.ArrayList;
import ims.framework.utils.Image;
import ims.framework.utils.Color;
public class GradeofDifferentation extends ims.vo.LookupInstVo implements TreeNode
{
private static final long serialVersionUID = 1L;
public GradeofDifferentation()
{
super();
}
public GradeofDifferentation(int id)
{
super(id, "", true);
}
public GradeofDifferentation(int id, String text, boolean active)
{
super(id, text, active, null, null, null);
}
public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image)
{
super(id, text, active, parent, image);
}
public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image, Color color)
{
super(id, text, active, parent, image, color);
}
public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image, Color color, int order)
{
super(id, text, active, parent, image, color, order);
}
public static GradeofDifferentation buildLookup(ims.vo.LookupInstanceBean bean)
{
return new GradeofDifferentation(bean.getId(), bean.getText(), bean.isActive());
}
public String toString()
{
if(getText() != null)
return getText();
return "";
}
public TreeNode getParentNode()
{
return (GradeofDifferentation)super.getParentInstance();
}
public GradeofDifferentation getParent()
{
return (GradeofDifferentation)super.getParentInstance();
}
public void setParent(GradeofDifferentation parent)
{
super.setParentInstance(parent);
}
public TreeNode[] getChildren()
{
ArrayList children = super.getChildInstances();
GradeofDifferentation[] typedChildren = new GradeofDifferentation[children.size()];
for (int i = 0; i < children.size(); i++)
{
typedChildren[i] = (GradeofDifferentation)children.get(i);
}
return typedChildren;
}
public int addChild(TreeNode child)
{
if (child instanceof GradeofDifferentation)
{
super.addChild((GradeofDifferentation)child);
}
return super.getChildInstances().size();
}
public int removeChild(TreeNode child)
{
if (child instanceof GradeofDifferentation)
{
super.removeChild((GradeofDifferentation)child);
}
return super.getChildInstances().size();
}
public Image getExpandedImage()
{
return super.getImage();
}
public Image getCollapsedImage()
{
return super.getImage();
}
public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection()
{
GradeofDifferentationCollection result = new GradeofDifferentationCollection();
return result;
}
public static GradeofDifferentation[] getNegativeInstances()
{
return new GradeofDifferentation[] {};
}
public static String[] getNegativeInstanceNames()
{
return new String[] {};
}
public static GradeofDifferentation getNegativeInstance(String name)
{
if(name == null)
return null;
// No negative instances found
return null;
}
public static GradeofDifferentation getNegativeInstance(Integer id)
{
if(id == null)
return null;
// No negative instances found
return null;
}
public int getTypeId()
{
return TYPE_ID;
}
public static final int TYPE_ID = 1251032;
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/oncology/vo/lookups/GradeofDifferentation.java | Java | agpl-3.0 | 5,476 |
/*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapid_i.deployment.update.client;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.rapid_i.deployment.update.client.listmodels.AbstractPackageListModel;
import com.rapidminer.deployment.client.wsimport.PackageDescriptor;
import com.rapidminer.deployment.client.wsimport.UpdateService;
import com.rapidminer.gui.RapidMinerGUI;
import com.rapidminer.gui.tools.ExtendedJScrollPane;
import com.rapidminer.gui.tools.ProgressThread;
import com.rapidminer.gui.tools.ResourceAction;
import com.rapidminer.gui.tools.SwingTools;
import com.rapidminer.gui.tools.dialogs.ButtonDialog;
import com.rapidminer.gui.tools.dialogs.ConfirmDialog;
import com.rapidminer.io.process.XMLTools;
import com.rapidminer.tools.FileSystemService;
import com.rapidminer.tools.I18N;
import com.rapidminer.tools.LogService;
import com.rapidminer.tools.ParameterService;
import com.rapidminer.tools.XMLException;
/**
* The Dialog is eventually shown at the start of RapidMiner, if the user purchased extensions online but haven't installed them yet.
*
* @author Dominik Halfkann
*/
public class PendingPurchasesInstallationDialog extends ButtonDialog {
private static final long serialVersionUID = 1L;
private final PackageDescriptorCache packageDescriptorCache = new PackageDescriptorCache();
private AbstractPackageListModel purchasedModel = new PurchasedNotInstalledModel(packageDescriptorCache);
JCheckBox neverAskAgain = new JCheckBox(I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.purchased_not_installed.not_check_on_startup"));
private final List<String> packages;
private boolean isConfirmed;
private LinkedList<PackageDescriptor> installablePackageList;
private JButton remindNeverButton;
private JButton remindLaterButton;
private JButton okButton;
private class PurchasedNotInstalledModel extends AbstractPackageListModel {
private static final long serialVersionUID = 1L;
public PurchasedNotInstalledModel(PackageDescriptorCache cache) {
super(cache, "gui.dialog.update.tab.no_packages");
}
@Override
public List<String> handleFetchPackageNames() {
return packages;
}
}
public PendingPurchasesInstallationDialog(List<String> packages) {
super("purchased_not_installed");
this.packages = packages;
remindNeverButton = remindNeverButton();
remindLaterButton = remindLaterButton();
okButton = makeOkButton("install_purchased");
layoutDefault(makeContentPanel(), NORMAL, okButton, remindNeverButton, remindLaterButton);
this.setPreferredSize(new Dimension(404, 430));
this.setMaximumSize(new Dimension(404, 430));
this.setMinimumSize(new Dimension(404, 300));
this.setSize(new Dimension(404, 430));
}
private JPanel makeContentPanel() {
BorderLayout layout = new BorderLayout(12, 12);
JPanel panel = new JPanel(layout);
panel.setBorder(new EmptyBorder(0, 12, 8, 12));
panel.add(createExtensionListScrollPane(purchasedModel), BorderLayout.CENTER);
purchasedModel.update();
JPanel southPanel = new JPanel(new BorderLayout(0, 7));
JLabel question = new JLabel(I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.purchased_not_installed.should_install"));
southPanel.add(question, BorderLayout.CENTER);
southPanel.add(neverAskAgain, BorderLayout.SOUTH);
panel.add(southPanel, BorderLayout.SOUTH);
return panel;
}
private JScrollPane createExtensionListScrollPane(AbstractPackageListModel model) {
final JList updateList = new JList(model);
updateList.setCellRenderer(new UpdateListCellRenderer(true));
JScrollPane extensionListScrollPane = new ExtendedJScrollPane(updateList);
extensionListScrollPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
return extensionListScrollPane;
}
private JButton remindLaterButton() {
Action Action = new ResourceAction("ask_later") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
wasConfirmed = false;
checkNeverAskAgain();
close();
}
};
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "CLOSE");
getRootPane().getActionMap().put("CLOSE", Action);
JButton button = new JButton(Action);
getRootPane().setDefaultButton(button);
return button;
}
private JButton remindNeverButton() {
Action Action = new ResourceAction("ask_never") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
wasConfirmed = false;
checkNeverAskAgain();
neverRemindAgain();
close();
}
};
JButton button = new JButton(Action);
getRootPane().setDefaultButton(button);
return button;
}
@Override
protected void ok() {
checkNeverAskAgain();
startUpdate(getPackageDescriptorList());
dispose();
}
public List<PackageDescriptor> getPackageDescriptorList() {
List<PackageDescriptor> packageList = new ArrayList<PackageDescriptor>();
for (int a = 0; a < purchasedModel.getSize(); a++) {
Object listItem = purchasedModel.getElementAt(a);
if (listItem instanceof PackageDescriptor) {
packageList.add((PackageDescriptor) listItem);
}
}
return packageList;
}
public void startUpdate(final List<PackageDescriptor> downloadList) {
final UpdateService service;
try {
service = UpdateManager.getService();
} catch (Exception e) {
SwingTools.showSimpleErrorMessage("failed_update_server", e, UpdateManager.getBaseUrl());
return;
}
new ProgressThread("resolving_dependencies", true) {
@Override
public void run() {
try {
getProgressListener().setTotal(100);
remindLaterButton.setEnabled(false);
remindNeverButton.setEnabled(false);
final HashMap<PackageDescriptor, HashSet<PackageDescriptor>> dependency = UpdateDialog.resolveDependency(downloadList, packageDescriptorCache);
getProgressListener().setCompleted(30);
installablePackageList = UpdateDialog.getPackagesforInstallation(dependency);
final HashMap<String, String> licenseNameToLicenseTextMap = UpdateDialog.collectLicenses(installablePackageList,getProgressListener(),100,30,100);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
isConfirmed = ConfirmLicensesDialog.confirm(dependency, licenseNameToLicenseTextMap);
new ProgressThread("installing_updates", true) {
@Override
public void run() {
try {
if (isConfirmed) {
getProgressListener().setTotal(100);
getProgressListener().setCompleted(20);
UpdateService service = UpdateManager.getService();
UpdateManager um = new UpdateManager(service);
List<PackageDescriptor> installedPackages = um.performUpdates(installablePackageList, getProgressListener());
getProgressListener().setCompleted(40);
if (installedPackages.size() > 0) {
int confirmation = SwingTools.showConfirmDialog((installedPackages.size() == 1 ? "update.complete_restart" : "update.complete_restart1"),
ConfirmDialog.YES_NO_OPTION, installedPackages.size());
if (confirmation == ConfirmDialog.YES_OPTION) {
RapidMinerGUI.getMainFrame().exit(true);
} else if (confirmation == ConfirmDialog.NO_OPTION) {
if (installedPackages.size() == installablePackageList.size()) {
dispose();
}
}
}
getProgressListener().complete();
}
} catch (Exception e) {
SwingTools.showSimpleErrorMessage("error_installing_update", e, e.getMessage());
} finally {
getProgressListener().complete();
}
}
}.start();
}
});
remindLaterButton.setEnabled(true);
remindNeverButton.setEnabled(true);
getProgressListener().complete();
} catch (Exception e) {
SwingTools.showSimpleErrorMessage("error_resolving_dependencies", e, e.getMessage());
}
}
}.start();
}
private void checkNeverAskAgain() {
if (neverAskAgain.isSelected()) {
ParameterService.setParameterValue(RapidMinerGUI.PROPERTY_RAPIDMINER_GUI_PURCHASED_NOT_INSTALLED_CHECK, "false");
ParameterService.saveParameters();
}
}
private void neverRemindAgain() {
LogService.getRoot().log(Level.CONFIG, "com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.saving_ignored_extensions_file");
Document doc;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.creating_xml_document_error",
e),
e);
return;
}
Element root = doc.createElement(UpdateManager.NEVER_REMIND_INSTALL_EXTENSIONS_FILE_NAME);
doc.appendChild(root);
for (String i : purchasedModel.fetchPackageNames()) {
Element entryElem = doc.createElement("extension_name");
entryElem.setTextContent(i);
root.appendChild(entryElem);
}
File file = FileSystemService.getUserConfigFile(UpdateManager.NEVER_REMIND_INSTALL_EXTENSIONS_FILE_NAME);
try {
XMLTools.stream(doc, file, null);
} catch (XMLException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.saving_ignored_extensions_file_error",
e),
e);
}
}
}
| rapidminer/rapidminer-5 | src/com/rapid_i/deployment/update/client/PendingPurchasesInstallationDialog.java | Java | agpl-3.0 | 11,249 |
//#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 12/10/2015, 13:25
*
*/
package ims.emergency.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Florin Blindu
*/
public class EDPartialAdmissionForDischargeDetailOutcomeVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo copy(ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObjectDest, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_EDPartialAdmission(valueObjectSrc.getID_EDPartialAdmission());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// DecisionToAdmitDateTime
valueObjectDest.setDecisionToAdmitDateTime(valueObjectSrc.getDecisionToAdmitDateTime());
// Specialty
valueObjectDest.setSpecialty(valueObjectSrc.getSpecialty());
// AllocatedStatus
valueObjectDest.setAllocatedStatus(valueObjectSrc.getAllocatedStatus());
// AllocatedBedType
valueObjectDest.setAllocatedBedType(valueObjectSrc.getAllocatedBedType());
// AuthoringInfo
valueObjectDest.setAuthoringInfo(valueObjectSrc.getAuthoringInfo());
// AllocatedDateTime
valueObjectDest.setAllocatedDateTime(valueObjectSrc.getAllocatedDateTime());
// AdmittingConsultant
valueObjectDest.setAdmittingConsultant(valueObjectSrc.getAdmittingConsultant());
// AccomodationRequestedType
valueObjectDest.setAccomodationRequestedType(valueObjectSrc.getAccomodationRequestedType());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(java.util.Set domainObjectSet)
{
return createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voList = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.emergency.domain.objects.EDPartialAdmission domainObject = (ims.emergency.domain.objects.EDPartialAdmission) iterator.next();
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(java.util.List domainObjectList)
{
return createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap map, java.util.List domainObjectList)
{
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voList = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.emergency.domain.objects.EDPartialAdmission domainObject = (ims.emergency.domain.objects.EDPartialAdmission) domainObjectList.get(i);
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.emergency.domain.objects.EDPartialAdmission set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractEDPartialAdmissionSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection)
{
return extractEDPartialAdmissionSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractEDPartialAdmissionSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = voCollection.get(i);
ims.emergency.domain.objects.EDPartialAdmission domainObject = EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.extractEDPartialAdmission(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.emergency.domain.objects.EDPartialAdmission list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractEDPartialAdmissionList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection)
{
return extractEDPartialAdmissionList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractEDPartialAdmissionList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = voCollection.get(i);
ims.emergency.domain.objects.EDPartialAdmission domainObject = EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.extractEDPartialAdmission(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.EDPartialAdmission object.
* @param domainObject ims.emergency.domain.objects.EDPartialAdmission
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo create(ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.EDPartialAdmission object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo create(DomainObjectMap map, ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject = (ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo) map.getValueObject(domainObject, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo.class);
if ( null == valueObject )
{
valueObject = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.EDPartialAdmission
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo insert(ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.EDPartialAdmission
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo insert(DomainObjectMap map, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_EDPartialAdmission(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// DecisionToAdmitDateTime
java.util.Date DecisionToAdmitDateTime = domainObject.getDecisionToAdmitDateTime();
if ( null != DecisionToAdmitDateTime )
{
valueObject.setDecisionToAdmitDateTime(new ims.framework.utils.DateTime(DecisionToAdmitDateTime) );
}
// Specialty
ims.domain.lookups.LookupInstance instance2 = domainObject.getSpecialty();
if ( null != instance2 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath());
}
color = instance2.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.Specialty voLookup2 = new ims.core.vo.lookups.Specialty(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color);
ims.core.vo.lookups.Specialty parentVoLookup2 = voLookup2;
ims.domain.lookups.LookupInstance parent2 = instance2.getParent();
while (parent2 != null)
{
if (parent2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent2.getColor();
if (color != null)
color.getValue();
parentVoLookup2.setParent(new ims.core.vo.lookups.Specialty(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color));
parentVoLookup2 = parentVoLookup2.getParent();
parent2 = parent2.getParent();
}
valueObject.setSpecialty(voLookup2);
}
// AllocatedStatus
ims.domain.lookups.LookupInstance instance3 = domainObject.getAllocatedStatus();
if ( null != instance3 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance3.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance3.getImage().getImageId(), instance3.getImage().getImagePath());
}
color = instance3.getColor();
if (color != null)
color.getValue();
ims.emergency.vo.lookups.AllocationStatus voLookup3 = new ims.emergency.vo.lookups.AllocationStatus(instance3.getId(),instance3.getText(), instance3.isActive(), null, img, color);
ims.emergency.vo.lookups.AllocationStatus parentVoLookup3 = voLookup3;
ims.domain.lookups.LookupInstance parent3 = instance3.getParent();
while (parent3 != null)
{
if (parent3.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent3.getImage().getImageId(), parent3.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent3.getColor();
if (color != null)
color.getValue();
parentVoLookup3.setParent(new ims.emergency.vo.lookups.AllocationStatus(parent3.getId(),parent3.getText(), parent3.isActive(), null, img, color));
parentVoLookup3 = parentVoLookup3.getParent();
parent3 = parent3.getParent();
}
valueObject.setAllocatedStatus(voLookup3);
}
// AllocatedBedType
ims.domain.lookups.LookupInstance instance4 = domainObject.getAllocatedBedType();
if ( null != instance4 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance4.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance4.getImage().getImageId(), instance4.getImage().getImagePath());
}
color = instance4.getColor();
if (color != null)
color.getValue();
ims.emergency.vo.lookups.AllocatedBedType voLookup4 = new ims.emergency.vo.lookups.AllocatedBedType(instance4.getId(),instance4.getText(), instance4.isActive(), null, img, color);
ims.emergency.vo.lookups.AllocatedBedType parentVoLookup4 = voLookup4;
ims.domain.lookups.LookupInstance parent4 = instance4.getParent();
while (parent4 != null)
{
if (parent4.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent4.getImage().getImageId(), parent4.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent4.getColor();
if (color != null)
color.getValue();
parentVoLookup4.setParent(new ims.emergency.vo.lookups.AllocatedBedType(parent4.getId(),parent4.getText(), parent4.isActive(), null, img, color));
parentVoLookup4 = parentVoLookup4.getParent();
parent4 = parent4.getParent();
}
valueObject.setAllocatedBedType(voLookup4);
}
// AuthoringInfo
valueObject.setAuthoringInfo(ims.core.vo.domain.AuthoringInformationVoAssembler.create(map, domainObject.getAuthoringInfo()) );
// AllocatedDateTime
java.util.Date AllocatedDateTime = domainObject.getAllocatedDateTime();
if ( null != AllocatedDateTime )
{
valueObject.setAllocatedDateTime(new ims.framework.utils.DateTime(AllocatedDateTime) );
}
// AdmittingConsultant
valueObject.setAdmittingConsultant(ims.core.vo.domain.HcpMinVoAssembler.create(map, domainObject.getAdmittingConsultant()) );
// AccomodationRequestedType
ims.domain.lookups.LookupInstance instance8 = domainObject.getAccomodationRequestedType();
if ( null != instance8 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance8.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance8.getImage().getImageId(), instance8.getImage().getImagePath());
}
color = instance8.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.AccomodationRequestedType voLookup8 = new ims.core.vo.lookups.AccomodationRequestedType(instance8.getId(),instance8.getText(), instance8.isActive(), null, img, color);
ims.core.vo.lookups.AccomodationRequestedType parentVoLookup8 = voLookup8;
ims.domain.lookups.LookupInstance parent8 = instance8.getParent();
while (parent8 != null)
{
if (parent8.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent8.getImage().getImageId(), parent8.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent8.getColor();
if (color != null)
color.getValue();
parentVoLookup8.setParent(new ims.core.vo.lookups.AccomodationRequestedType(parent8.getId(),parent8.getText(), parent8.isActive(), null, img, color));
parentVoLookup8 = parentVoLookup8.getParent();
parent8 = parent8.getParent();
}
valueObject.setAccomodationRequestedType(voLookup8);
}
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.emergency.domain.objects.EDPartialAdmission extractEDPartialAdmission(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject)
{
return extractEDPartialAdmission(domainFactory, valueObject, new HashMap());
}
public static ims.emergency.domain.objects.EDPartialAdmission extractEDPartialAdmission(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_EDPartialAdmission();
ims.emergency.domain.objects.EDPartialAdmission domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.emergency.domain.objects.EDPartialAdmission)domMap.get(valueObject);
}
// ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo ID_EDPartialAdmission field is unknown
domainObject = new ims.emergency.domain.objects.EDPartialAdmission();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_EDPartialAdmission());
if (domMap.get(key) != null)
{
return (ims.emergency.domain.objects.EDPartialAdmission)domMap.get(key);
}
domainObject = (ims.emergency.domain.objects.EDPartialAdmission) domainFactory.getDomainObject(ims.emergency.domain.objects.EDPartialAdmission.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_EDPartialAdmission());
ims.framework.utils.DateTime dateTime1 = valueObject.getDecisionToAdmitDateTime();
java.util.Date value1 = null;
if ( dateTime1 != null )
{
value1 = dateTime1.getJavaDate();
}
domainObject.setDecisionToAdmitDateTime(value1);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value2 = null;
if ( null != valueObject.getSpecialty() )
{
value2 =
domainFactory.getLookupInstance(valueObject.getSpecialty().getID());
}
domainObject.setSpecialty(value2);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value3 = null;
if ( null != valueObject.getAllocatedStatus() )
{
value3 =
domainFactory.getLookupInstance(valueObject.getAllocatedStatus().getID());
}
domainObject.setAllocatedStatus(value3);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value4 = null;
if ( null != valueObject.getAllocatedBedType() )
{
value4 =
domainFactory.getLookupInstance(valueObject.getAllocatedBedType().getID());
}
domainObject.setAllocatedBedType(value4);
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.clinical.domain.objects.AuthoringInformation value5 = null;
if ( null != valueObject.getAuthoringInfo() )
{
if (valueObject.getAuthoringInfo().getBoId() == null)
{
if (domMap.get(valueObject.getAuthoringInfo()) != null)
{
value5 = (ims.core.clinical.domain.objects.AuthoringInformation)domMap.get(valueObject.getAuthoringInfo());
}
}
else
{
value5 = (ims.core.clinical.domain.objects.AuthoringInformation)domainFactory.getDomainObject(ims.core.clinical.domain.objects.AuthoringInformation.class, valueObject.getAuthoringInfo().getBoId());
}
}
domainObject.setAuthoringInfo(value5);
ims.framework.utils.DateTime dateTime6 = valueObject.getAllocatedDateTime();
java.util.Date value6 = null;
if ( dateTime6 != null )
{
value6 = dateTime6.getJavaDate();
}
domainObject.setAllocatedDateTime(value6);
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.resource.people.domain.objects.Hcp value7 = null;
if ( null != valueObject.getAdmittingConsultant() )
{
if (valueObject.getAdmittingConsultant().getBoId() == null)
{
if (domMap.get(valueObject.getAdmittingConsultant()) != null)
{
value7 = (ims.core.resource.people.domain.objects.Hcp)domMap.get(valueObject.getAdmittingConsultant());
}
}
else
{
value7 = (ims.core.resource.people.domain.objects.Hcp)domainFactory.getDomainObject(ims.core.resource.people.domain.objects.Hcp.class, valueObject.getAdmittingConsultant().getBoId());
}
}
domainObject.setAdmittingConsultant(value7);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value8 = null;
if ( null != valueObject.getAccomodationRequestedType() )
{
value8 =
domainFactory.getLookupInstance(valueObject.getAccomodationRequestedType().getID());
}
domainObject.setAccomodationRequestedType(value8);
return domainObject;
}
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.java | Java | agpl-3.0 | 28,003 |
package com.sapienter.jbilling.client.jspc.user;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import com.sapienter.jbilling.client.util.Constants;
public final class listProcessSuccessfulUsersTop_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.release();
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.release();
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.release();
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n");
out.write("\r\n\r\n");
// html:messages
org.apache.struts.taglib.html.MessagesTag _jspx_th_html_005fmessages_005f0 = (org.apache.struts.taglib.html.MessagesTag) _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.get(org.apache.struts.taglib.html.MessagesTag.class);
_jspx_th_html_005fmessages_005f0.setPageContext(_jspx_page_context);
_jspx_th_html_005fmessages_005f0.setParent(null);
// /user/listProcessSuccessfulUsersTop.jsp(30,0) name = message type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_html_005fmessages_005f0.setMessage("true");
// /user/listProcessSuccessfulUsersTop.jsp(30,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_html_005fmessages_005f0.setId("myMessage");
int _jspx_eval_html_005fmessages_005f0 = _jspx_th_html_005fmessages_005f0.doStartTag();
if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
java.lang.String myMessage = null;
if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.pushBody();
_jspx_th_html_005fmessages_005f0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);
_jspx_th_html_005fmessages_005f0.doInitBody();
}
myMessage = (java.lang.String) _jspx_page_context.findAttribute("myMessage");
do {
out.write("\r\n\t<p>");
if (_jspx_meth_bean_005fwrite_005f0(_jspx_th_html_005fmessages_005f0, _jspx_page_context))
return;
out.write("</p>\r\n");
int evalDoAfterBody = _jspx_th_html_005fmessages_005f0.doAfterBody();
myMessage = (java.lang.String) _jspx_page_context.findAttribute("myMessage");
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.popBody();
}
}
if (_jspx_th_html_005fmessages_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.reuse(_jspx_th_html_005fmessages_005f0);
return;
}
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.reuse(_jspx_th_html_005fmessages_005f0);
out.write("\r\n\r\n");
out.write('\r');
out.write('\n');
// bean:define
org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_005fdefine_005f0 = (org.apache.struts.taglib.bean.DefineTag) _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.get(org.apache.struts.taglib.bean.DefineTag.class);
_jspx_th_bean_005fdefine_005f0.setPageContext(_jspx_page_context);
_jspx_th_bean_005fdefine_005f0.setParent(null);
// /user/listProcessSuccessfulUsersTop.jsp(36,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f0.setId("forward_from");
// /user/listProcessSuccessfulUsersTop.jsp(36,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f0.setValue(Constants.FORWARD_USER_VIEW);
// /user/listProcessSuccessfulUsersTop.jsp(36,0) name = toScope type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f0.setToScope("session");
int _jspx_eval_bean_005fdefine_005f0 = _jspx_th_bean_005fdefine_005f0.doStartTag();
if (_jspx_th_bean_005fdefine_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f0);
return;
}
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f0);
java.lang.String forward_from = null;
forward_from = (java.lang.String) _jspx_page_context.findAttribute("forward_from");
out.write("\r\n\r\n");
// bean:define
org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_005fdefine_005f1 = (org.apache.struts.taglib.bean.DefineTag) _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.get(org.apache.struts.taglib.bean.DefineTag.class);
_jspx_th_bean_005fdefine_005f1.setPageContext(_jspx_page_context);
_jspx_th_bean_005fdefine_005f1.setParent(null);
// /user/listProcessSuccessfulUsersTop.jsp(40,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f1.setId("forward_to");
// /user/listProcessSuccessfulUsersTop.jsp(40,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f1.setValue(Constants.FORWARD_USER_VIEW);
// /user/listProcessSuccessfulUsersTop.jsp(40,0) name = toScope type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f1.setToScope("session");
int _jspx_eval_bean_005fdefine_005f1 = _jspx_th_bean_005fdefine_005f1.doStartTag();
if (_jspx_th_bean_005fdefine_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f1);
return;
}
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f1);
java.lang.String forward_to = null;
forward_to = (java.lang.String) _jspx_page_context.findAttribute("forward_to");
out.write("\r\n\r\n");
// jbilling:genericList
com.sapienter.jbilling.client.list.GenericListTag _jspx_th_jbilling_005fgenericList_005f0 = (com.sapienter.jbilling.client.list.GenericListTag) _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.get(com.sapienter.jbilling.client.list.GenericListTag.class);
_jspx_th_jbilling_005fgenericList_005f0.setPageContext(_jspx_page_context);
_jspx_th_jbilling_005fgenericList_005f0.setParent(null);
// /user/listProcessSuccessfulUsersTop.jsp(44,0) name = setup type = java.lang.Boolean reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_jbilling_005fgenericList_005f0.setSetup(new Boolean(true));
// /user/listProcessSuccessfulUsersTop.jsp(44,0) name = type type = java.lang.String reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_jbilling_005fgenericList_005f0.setType(Constants.LIST_TYPE_PROCESS_RUN_SUCCESSFULL_USERS);
int _jspx_eval_jbilling_005fgenericList_005f0 = _jspx_th_jbilling_005fgenericList_005f0.doStartTag();
if (_jspx_th_jbilling_005fgenericList_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.reuse(_jspx_th_jbilling_005fgenericList_005f0);
return;
}
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.reuse(_jspx_th_jbilling_005fgenericList_005f0);
out.write(" \r\n \r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_bean_005fwrite_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_html_005fmessages_005f0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// bean:write
org.apache.struts.taglib.bean.WriteTag _jspx_th_bean_005fwrite_005f0 = (org.apache.struts.taglib.bean.WriteTag) _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.get(org.apache.struts.taglib.bean.WriteTag.class);
_jspx_th_bean_005fwrite_005f0.setPageContext(_jspx_page_context);
_jspx_th_bean_005fwrite_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_005fmessages_005f0);
// /user/listProcessSuccessfulUsersTop.jsp(31,4) name = name type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fwrite_005f0.setName("myMessage");
int _jspx_eval_bean_005fwrite_005f0 = _jspx_th_bean_005fwrite_005f0.doStartTag();
if (_jspx_th_bean_005fwrite_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.reuse(_jspx_th_bean_005fwrite_005f0);
return true;
}
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.reuse(_jspx_th_bean_005fwrite_005f0);
return false;
}
}
| maduhu/knx-jbilling2.2.0 | build/jsp-classes/com/sapienter/jbilling/client/jspc/user/listProcessSuccessfulUsersTop_jsp.java | Java | agpl-3.0 | 13,697 |
/*
* Concept profile generation tool suite
* Copyright (C) 2015 Biosemantics Group, Erasmus University Medical Center,
* Rotterdam, The Netherlands
*
* 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 JochemBuilder.KEGGcompound;
import org.erasmusmc.ontology.OntologyFileLoader;
import org.erasmusmc.ontology.OntologyStore;
import org.erasmusmc.ontology.ontologyutilities.OntologyCurator;
import org.erasmusmc.utilities.StringUtilities;
import JochemBuilder.SharedCurationScripts.CasperForJochem;
import JochemBuilder.SharedCurationScripts.CurateUsingManualCurationFile;
import JochemBuilder.SharedCurationScripts.RemoveDictAndCompanyNamesAtEndOfTerm;
import JochemBuilder.SharedCurationScripts.RewriteFurther;
import JochemBuilder.SharedCurationScripts.SaveOnlyCASandInchiEntries;
public class KEGGcompoundImport {
public static String date = "110809";
public static String home = "/home/khettne/Projects/Jochem";
public static String keggcImportFile = home+"/KEGG/Compound/compound";
public static String compoundToDrugMappingOutFile = home+"/KEGG/Compound/compoundToDrugMapping";
public static String keggcToInchiMappingFile = home+"/KEGG/Compound/compound.inchi";
public static String keggcDictionariesLog = home+"/KEGG/Compound/KEGGc_dictionaries_"+date+".log";
public static String keggcRewriteLog = home+"/KEGG/Compound/KEGGcCAS_casperFiltered_"+date+".log";
public static String keggcLowerCaseLog = home+"/KEGG/Compound/KEGGcCAS_lowerCase_"+date+".log";
public static String termsToRemove = "keggcTermsToRemove.txt";
public static String keggcCuratedOntologyPath = home+"/KEGG/Compound/KEGGcCAS_curated_"+date+".ontology";
public static String keggcCuratedLog = home+"/KEGG/Compound/KEGGcCAS_curated_"+date+".log";
public static void main(String[] args) {
OntologyStore ontology = new OntologyStore();
OntologyFileLoader loader = new OntologyFileLoader();
//Make unprocessed thesaurus
ChemicalsFromKEGGcompound keggchem = new ChemicalsFromKEGGcompound();
ontology = keggchem.run(keggcImportFile, compoundToDrugMappingOutFile);
RemoveDictAndCompanyNamesAtEndOfTerm remove = new RemoveDictAndCompanyNamesAtEndOfTerm();
ontology = remove.run(ontology, keggcDictionariesLog);
MapKEGGc2InChI mapOntology = new MapKEGGc2InChI();
ontology = mapOntology.map(ontology, keggcToInchiMappingFile);
// CAS and InChI
SaveOnlyCASandInchiEntries make = new SaveOnlyCASandInchiEntries();
ontology = make.run(ontology);
//Rewrite
CasperForJochem casper = new CasperForJochem();
casper.run(ontology, keggcRewriteLog);
// Make some entries lower case and filter further
RewriteFurther rewrite = new RewriteFurther();
ontology = rewrite.run(ontology, keggcLowerCaseLog);
//Remove terms based on medline frequency
CurateUsingManualCurationFile curate = new CurateUsingManualCurationFile();
ontology = curate.run(ontology, keggcCuratedLog,termsToRemove);
//Set default flags and save ontology
OntologyCurator curator = new OntologyCurator();
curator.curateAndPrepare(ontology);
loader.save(ontology,keggcCuratedOntologyPath);
System.out.println("Done! " + StringUtilities.now());
}
}
| BiosemanticsDotOrg/GeneDiseasePlosBio | java/DataImport/src/JochemBuilder/KEGGcompound/KEGGcompoundImport.java | Java | agpl-3.0 | 3,807 |
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.xpn.xwiki.objects;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import com.xpn.xwiki.web.Utils;
/**
* @version $Id$
*/
// TODO: shouldn't this be abstract? toFormString and toText
// will never work unless getValue is overriden
public class BaseProperty extends BaseElement implements PropertyInterface, Serializable, Cloneable
{
private BaseCollection object;
private int id;
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.PropertyInterface#getObject()
*/
public BaseCollection getObject()
{
return this.object;
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.PropertyInterface#setObject(com.xpn.xwiki.objects.BaseCollection)
*/
public void setObject(BaseCollection object)
{
this.object = object;
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.BaseElement#equals(java.lang.Object)
*/
@Override
public boolean equals(Object el)
{
// Same Java object, they sure are equal
if (this == el) {
return true;
}
// I hate this.. needed for hibernate to find the object
// when loading the collections..
if ((this.object == null) || ((BaseProperty) el).getObject() == null) {
return (hashCode() == el.hashCode());
}
if (!super.equals(el)) {
return false;
}
return (getId() == ((BaseProperty) el).getId());
}
public int getId()
{
// I hate this.. needed for hibernate to find the object
// when loading the collections..
if (this.object == null) {
return this.id;
} else {
return getObject().getId();
}
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.PropertyInterface#setId(int)
*/
public void setId(int id)
{
// I hate this.. needed for hibernate to find the object
// when loading the collections..
this.id = id;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
// I hate this.. needed for hibernate to find the object
// when loading the collections..
return ("" + getId() + getName()).hashCode();
}
public String getClassType()
{
return getClass().getName();
}
public void setClassType(String type)
{
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.BaseElement#clone()
*/
@Override
public Object clone()
{
BaseProperty property = (BaseProperty) super.clone();
property.setObject(getObject());
return property;
}
public Object getValue()
{
return null;
}
public void setValue(Object value)
{
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.PropertyInterface#toXML()
*/
public Element toXML()
{
Element el = new DOMElement(getName());
Object value = getValue();
el.setText((value == null) ? "" : value.toString());
return el;
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.PropertyInterface#toFormString()
*/
public String toFormString()
{
return Utils.formEncode(toText());
}
public String toText()
{
Object value = getValue();
return (value == null) ? "" : value.toString();
}
public String toXMLString()
{
Document doc = new DOMDocument();
doc.setRootElement(toXML());
OutputFormat outputFormat = new OutputFormat("", true);
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out, outputFormat);
try {
writer.write(doc);
return out.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return toXMLString();
}
public Object getCustomMappingValue()
{
return getValue();
}
}
| xwiki-contrib/sankoreorg | xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/objects/BaseProperty.java | Java | lgpl-2.1 | 5,379 |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2016, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -------------
* Effect3D.java
* -------------
* (C) Copyright 2002-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Nov-2002 : Version 1 (DG);
* 14-Nov-2002 : Modified to have independent x and y offsets (DG);
*
*/
package org.jfree.chart;
/**
* An interface that should be implemented by renderers that use a 3D effect.
* This allows the axes to mirror the same effect by querying the renderer.
*/
public interface Effect3D {
/**
* Returns the x-offset (in Java2D units) for the 3D effect.
*
* @return The offset.
*/
public double getXOffset();
/**
* Returns the y-offset (in Java2D units) for the 3D effect.
*
* @return The offset.
*/
public double getYOffset();
}
| simon04/jfreechart | src/main/java/org/jfree/chart/Effect3D.java | Java | lgpl-2.1 | 2,135 |
/*
* Created on 17-dic-2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.herac.tuxguitar.app.actions.layout;
import org.herac.tuxguitar.app.actions.Action;
import org.herac.tuxguitar.app.actions.ActionData;
import org.herac.tuxguitar.graphics.control.TGLayout;
/**
* @author julian
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class SetTablatureEnabledAction extends Action{
public static final String NAME = "action.view.layout-set-tablature-enabled";
public SetTablatureEnabledAction() {
super(NAME, AUTO_LOCK | AUTO_UNLOCK | AUTO_UPDATE | KEY_BINDING_AVAILABLE);
}
protected int execute(ActionData actionData){
TGLayout layout = getEditor().getTablature().getViewLayout();
layout.setStyle( ( layout.getStyle() ^ TGLayout.DISPLAY_TABLATURE ) );
if((layout.getStyle() & TGLayout.DISPLAY_TABLATURE) == 0 && (layout.getStyle() & TGLayout.DISPLAY_SCORE) == 0 ){
layout.setStyle( ( layout.getStyle() ^ TGLayout.DISPLAY_SCORE ) );
}
updateTablature();
return 0;
}
}
| yuan39/TuxGuitar | TuxGuitar/src/org/herac/tuxguitar/app/actions/layout/SetTablatureEnabledAction.java | Java | lgpl-2.1 | 1,189 |
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
/**
* Restricts the number of statements per line to one.
* <p>
* Rationale: It's very difficult to read multiple statements on one line.
* </p>
* <p>
* In the Java programming language, statements are the fundamental unit of
* execution. All statements except blocks are terminated by a semicolon.
* Blocks are denoted by open and close curly braces.
* </p>
* <p>
* OneStatementPerLineCheck checks the following types of statements:
* variable declaration statements, empty statements, assignment statements,
* expression statements, increment statements, object creation statements,
* 'for loop' statements, 'break' statements, 'continue' statements,
* 'return' statements, import statements.
* </p>
* <p>
* The following examples will be flagged as a violation:
* </p>
* <pre>
* //Each line causes violation:
* int var1; int var2;
* var1 = 1; var2 = 2;
* int var1 = 1; int var2 = 2;
* var1++; var2++;
* Object obj1 = new Object(); Object obj2 = new Object();
* import java.io.EOFException; import java.io.BufferedReader;
* ;; //two empty statements on the same line.
*
* //Multi-line statements:
* int var1 = 1
* ; var2 = 2; //violation here
* int o = 1, p = 2,
* r = 5; int t; //violation here
* </pre>
*
* @author Alexander Jesse
* @author Oliver Burn
* @author Andrei Selkin
*/
public final class OneStatementPerLineCheck extends Check {
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_KEY = "multiple.statements.line";
/**
* Hold the line-number where the last statement ended.
*/
private int lastStatementEnd = -1;
/**
* Hold the line-number where the last 'for-loop' statement ended.
*/
private int forStatementEnd = -1;
/**
* The for-header usually has 3 statements on one line, but THIS IS OK.
*/
private boolean inForHeader;
@Override
public int[] getDefaultTokens() {
return getAcceptableTokens();
}
@Override
public int[] getAcceptableTokens() {
return new int[]{
TokenTypes.SEMI, TokenTypes.FOR_INIT,
TokenTypes.FOR_ITERATOR,
};
}
@Override
public int[] getRequiredTokens() {
return getAcceptableTokens();
}
@Override
public void beginTree(DetailAST rootAST) {
inForHeader = false;
lastStatementEnd = -1;
forStatementEnd = -1;
}
@Override
public void visitToken(DetailAST ast) {
switch (ast.getType()) {
case TokenTypes.SEMI:
DetailAST currentStatement = ast;
if (isMultilineStatement(currentStatement)) {
currentStatement = ast.getPreviousSibling();
}
if (isOnTheSameLine(currentStatement, lastStatementEnd,
forStatementEnd) && !inForHeader) {
log(ast, MSG_KEY);
}
break;
case TokenTypes.FOR_ITERATOR:
forStatementEnd = ast.getLineNo();
break;
default:
inForHeader = true;
break;
}
}
@Override
public void leaveToken(DetailAST ast) {
switch (ast.getType()) {
case TokenTypes.SEMI:
lastStatementEnd = ast.getLineNo();
forStatementEnd = -1;
break;
case TokenTypes.FOR_ITERATOR:
inForHeader = false;
break;
default:
break;
}
}
/**
* Checks whether two statements are on the same line.
* @param ast token for the current statement.
* @param lastStatementEnd the line-number where the last statement ended.
* @param forStatementEnd the line-number where the last 'for-loop'
* statement ended.
* @return true if two statements are on the same line.
*/
private static boolean isOnTheSameLine(DetailAST ast, int lastStatementEnd,
int forStatementEnd) {
return lastStatementEnd == ast.getLineNo() && forStatementEnd != ast.getLineNo();
}
/**
* Checks whether statement is multiline.
* @param ast token for the current statement.
* @return true if one statement is distributed over two or more lines.
*/
private static boolean isMultilineStatement(DetailAST ast) {
final boolean multiline;
if (ast.getPreviousSibling() == null) {
multiline = false;
}
else {
final DetailAST prevSibling = ast.getPreviousSibling();
multiline = prevSibling.getLineNo() != ast.getLineNo()
&& ast.getParent() != null;
}
return multiline;
}
}
| jasonchaffee/checkstyle | src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheck.java | Java | lgpl-2.1 | 6,201 |
/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package org.kurento.tutorial.player;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.kurento.client.EndOfStreamEvent;
import org.kurento.client.EventListener;
import org.kurento.client.FaceOverlayFilter;
import org.kurento.client.HttpGetEndpoint;
import org.kurento.client.MediaPipeline;
import org.kurento.client.PlayerEndpoint;
import org.kurento.client.KurentoClient;
/**
* HTTP Player with Kurento; the media pipeline is composed by a PlayerEndpoint
* connected to a filter (FaceOverlay) and an HttpGetEnpoint; the default
* desktop web browser is launched to play the video.
*
* @author Micael Gallego (micael.gallego@gmail.com)
* @author Boni Garcia (bgarcia@gsyc.es)
* @since 5.0.0
*/
public class KurentoHttpPlayer {
public static void main(String[] args) throws IOException,
URISyntaxException, InterruptedException {
// Connecting to Kurento Server
KurentoClient kurento = KurentoClient
.create("ws://localhost:8888/kurento");
// Creating media pipeline
MediaPipeline pipeline = kurento.createMediaPipeline();
// Creating media elements
PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline,
"http://files.kurento.org/video/fiwarecut.mp4").build();
FaceOverlayFilter filter = new FaceOverlayFilter.Builder(pipeline)
.build();
filter.setOverlayedImage(
"http://files.kurento.org/imgs/mario-wings.png", -0.2F, -1.1F,
1.6F, 1.6F);
HttpGetEndpoint http = new HttpGetEndpoint.Builder(pipeline).build();
// Connecting media elements
player.connect(filter);
filter.connect(http);
// Reacting to events
player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
@Override
public void onEvent(EndOfStreamEvent event) {
System.out.println("The playing has finished");
System.exit(0);
}
});
// Playing media and opening the default desktop browser
player.play();
String videoUrl = http.getUrl();
Desktop.getDesktop().browse(new URI(videoUrl));
// Setting a delay to wait the EndOfStream event, previously subscribed
Thread.sleep(60000);
}
}
| oclab/howto-callme | kurento-http-player/src/main/java/org/kurento/tutorial/player/KurentoHttpPlayer.java | Java | lgpl-2.1 | 2,724 |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2016, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -----------------------------
* MeanAndStandardDeviation.java
* -----------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 05-Feb-2002 : Version 1 (DG);
* 05-Feb-2005 : Added equals() method and implemented Serializable (DG);
* 02-Oct-2007 : Added getMeanValue() and getStandardDeviationValue() methods
* for convenience, and toString() method for debugging (DG);
*
*/
package org.jfree.data.statistics;
import java.io.Serializable;
import org.jfree.util.ObjectUtilities;
/**
* A simple data structure that holds a mean value and a standard deviation
* value. This is used in the
* {@link org.jfree.data.statistics.DefaultStatisticalCategoryDataset} class.
*/
public class MeanAndStandardDeviation implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 7413468697315721515L;
/** The mean. */
private Number mean;
/** The standard deviation. */
private Number standardDeviation;
/**
* Creates a new mean and standard deviation record.
*
* @param mean the mean.
* @param standardDeviation the standard deviation.
*/
public MeanAndStandardDeviation(double mean, double standardDeviation) {
this(new Double(mean), new Double(standardDeviation));
}
/**
* Creates a new mean and standard deviation record.
*
* @param mean the mean ({@code null} permitted).
* @param standardDeviation the standard deviation ({@code null}
* permitted.
*/
public MeanAndStandardDeviation(Number mean, Number standardDeviation) {
this.mean = mean;
this.standardDeviation = standardDeviation;
}
/**
* Returns the mean.
*
* @return The mean.
*/
public Number getMean() {
return this.mean;
}
/**
* Returns the mean as a double primitive. If the underlying mean is
* {@code null}, this method will return {@code Double.NaN}.
*
* @return The mean.
*
* @see #getMean()
*
* @since 1.0.7
*/
public double getMeanValue() {
double result = Double.NaN;
if (this.mean != null) {
result = this.mean.doubleValue();
}
return result;
}
/**
* Returns the standard deviation.
*
* @return The standard deviation.
*/
public Number getStandardDeviation() {
return this.standardDeviation;
}
/**
* Returns the standard deviation as a double primitive. If the underlying
* standard deviation is {@code null}, this method will return
* {@code Double.NaN}.
*
* @return The standard deviation.
*
* @since 1.0.7
*/
public double getStandardDeviationValue() {
double result = Double.NaN;
if (this.standardDeviation != null) {
result = this.standardDeviation.doubleValue();
}
return result;
}
/**
* Tests this instance for equality with an arbitrary object.
*
* @param obj the object ({@code null} permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof MeanAndStandardDeviation)) {
return false;
}
MeanAndStandardDeviation that = (MeanAndStandardDeviation) obj;
if (!ObjectUtilities.equal(this.mean, that.mean)) {
return false;
}
if (!ObjectUtilities.equal(
this.standardDeviation, that.standardDeviation)
) {
return false;
}
return true;
}
/**
* Returns a string representing this instance.
*
* @return A string.
*
* @since 1.0.7
*/
@Override
public String toString() {
return "[" + this.mean + ", " + this.standardDeviation + "]";
}
} | simon04/jfreechart | src/main/java/org/jfree/data/statistics/MeanAndStandardDeviation.java | Java | lgpl-2.1 | 5,489 |
package com.digitalcraftinghabitat.forgemod.util;
import org.apache.logging.log4j.Level;
import cpw.mods.fml.relauncher.FMLRelaunchLog;
/**
* Created by christopher on 02/08/15.
*/
public class DCHLog {
public static final FMLRelaunchLog INSTANCE = FMLRelaunchLog.log;
private DCHLog(){
}
public static void warning( String format, Object... data )
{
log( Level.WARN, format, data );
}
private static void log( Level level, String format, Object... data )
{
FMLRelaunchLog.log( "DCH:", level, format, data );
}
public static void error( Throwable e )
{
severe( "Error: " + e.getClass().getName() + " : " + e.getMessage() );
e.printStackTrace();
}
public static void severe( String format, Object... data )
{
log( Level.ERROR, format, data );
}
public static void blockUpdate( int xCoord, int yCoord, int zCoord, String title)
{
info( title + " @ " + xCoord + ", " + yCoord + ", " + zCoord );
}
public static void info( String format, Object... data )
{
log( Level.INFO, format, data );
}
public static void crafting( String format, Object... data )
{
log( Level.INFO, format, data );
}
}
| digital-crafting-habitat/dch_forge_mod | src/main/java/com/digitalcraftinghabitat/forgemod/util/DCHLog.java | Java | lgpl-2.1 | 1,264 |
/**
* Encodes and decodes to and from Base64 notation.
*
* <p>
* Change Log:
* </p>
* <ul>
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
* some convenience methods for reading and writing to and from files.</li>
* <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
* with other encodings (like EBCDIC).</li>
* <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
* encoded data was a single byte.</li>
* <li>v2.0 - I got rid of methods that used booleans to set options.
* Now everything is more consolidated and cleaner. The code now detects
* when data that's being decoded is gzip-compressed and will decompress it
* automatically. Generally things are cleaner. You'll probably have to
* change some method calls that you were making to support the new
* options format (<tt>int</tt>s that you "OR" together).</li>
* <li>v1.5.1 - Fixed bug when decompressing and decoding to a
* byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
* Added the ability to "suspend" encoding in the Output Stream so
* you can turn on and off the encoding if you need to embed base64
* data in an otherwise "normal" stream (like an XML file).</li>
* <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
* This helps when using GZIP streams.
* Added the ability to GZip-compress objects before encoding them.</li>
* <li>v1.4 - Added helper methods to read/write files.</li>
* <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
* <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
* where last buffer being read, if not completely full, was not returned.</li>
* <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
* <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
* </ul>
*
* <p>
* I am placing this code in the Public Domain. Do with it as you will.
* This software comes with no guarantees or warranties but with
* plenty of well-wishing instead!
* Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
* periodically to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author rob@iharder.net
* @version 2.1
*/
public class Base64
{
/* ******** P U B L I C F I E L D S ******** */
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
/** Specify encoding. */
public final static int ENCODE = 1;
/** Specify decoding. */
public final static int DECODE = 0;
/** Specify that data should be gzip-compressed. */
public final static int GZIP = 2;
/** Don't break lines when encoding (violates strict Base64 specification) */
public final static int DONT_BREAK_LINES = 8;
/* ******** P R I V A T E F I E L D S ******** */
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte)'=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte)'\n';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "UTF-8";
/** The 64 valid Base64 values. */
private final static byte[] ALPHABET;
private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */
{
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
/** Determine which ALPHABET to use. */
static
{
byte[] __bytes;
try
{
__bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes( PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException use)
{
__bytes = _NATIVE_ALPHABET; // Fall back to native encoding
} // end catch
ALPHABET = __bytes;
} // end static
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] DECODABET =
{
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,-9,-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9,-9,-9, // Decimal 91 - 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
// I think I end up not using the BAD_ENCODING indicator.
//private final static byte BAD_ENCODING = -9; // Indicates error in encoding
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/** Defeats instantiation. */
private Base64(){}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Encodes up to the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
* The array <var>threeBytes</var> needs only be as big as
* <var>numSigBytes</var>.
* Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
*
* @param b4 A reusable byte array to reduce array instantiation
* @param threeBytes the array to convert
* @param numSigBytes the number of significant bytes in your array
* @return four byte array in Base64 notation.
* @since 1.5.1
*/
private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes )
{
encode3to4( threeBytes, 0, numSigBytes, b4, 0 );
return b4;
} // end encode3to4
/**
* Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset )
{
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
| ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
| ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
switch( numSigBytes )
{
case 3:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
return destination;
case 2:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
case 1:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = EQUALS_SIGN;
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object. If the object
* cannot be serialized or there is another error,
* the method will return <tt>null</tt>.
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject The object to encode
* @return The Base64-encoded object
* @since 1.4
*/
public static String encodeObject( java.io.Serializable serializableObject )
{
return encodeObject( serializableObject, NO_OPTIONS );
} // end encodeObject
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object. If the object
* cannot be serialized or there is another error,
* the method will return <tt>null</tt>.
* <p>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
* @param serializableObject The object to encode
* @param options Specified options
* @return The Base64-encoded object
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeObject( java.io.Serializable serializableObject, int options )
{
// Streams
java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.io.ObjectOutputStream oos = null;
java.util.zip.GZIPOutputStream gzos = null;
// Isolate options
int gzip = (options & GZIP);
int dontBreakLines = (options & DONT_BREAK_LINES);
try
{
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
// GZip?
if( gzip == GZIP )
{
gzos = new java.util.zip.GZIPOutputStream( b64os );
oos = new java.io.ObjectOutputStream( gzos );
} // end if: gzip
else
oos = new java.io.ObjectOutputStream( b64os );
oos.writeObject( serializableObject );
} // end try
catch( java.io.IOException e )
{
e.printStackTrace();
return null;
} // end catch
finally
{
try{ oos.close(); } catch( Exception e ){}
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
// Return value according to relevant encoding.
try
{
return new String( baos.toByteArray(), PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue)
{
return new String( baos.toByteArray() );
} // end catch
} // end encode
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @since 1.4
*/
public static String encodeBytes( byte[] source )
{
return encodeBytes( source, 0, source.length, NO_OPTIONS );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
*
* @param source The data to convert
* @param options Specified options
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeBytes( byte[] source, int options )
{
return encodeBytes( source, 0, source.length, options );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @since 1.4
*/
public static String encodeBytes( byte[] source, int off, int len )
{
return encodeBytes( source, off, len, NO_OPTIONS );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeBytes( byte[] source, int off, int len, int options )
{
// Isolate options
int dontBreakLines = ( options & DONT_BREAK_LINES );
int gzip = ( options & GZIP );
// Compress?
if( gzip == GZIP )
{
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
Base64.OutputStream b64os = null;
try
{
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
gzos = new java.util.zip.GZIPOutputStream( b64os );
gzos.write( source, off, len );
gzos.close();
} // end try
catch( java.io.IOException e )
{
e.printStackTrace();
return null;
} // end catch
finally
{
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
// Return value according to relevant encoding.
try
{
return new String( baos.toByteArray(), PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue)
{
return new String( baos.toByteArray() );
} // end catch
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else
{
// Convert option to boolean in way that code likes it.
boolean breakLines = dontBreakLines == 0;
int len43 = len * 4 / 3;
byte[] outBuff = new byte[ ( len43 ) // Main 4:3
+ ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
+ (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 )
{
encode3to4( source, d+off, 3, outBuff, e );
lineLength += 4;
if( breakLines && lineLength == MAX_LINE_LENGTH )
{
outBuff[e+4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len )
{
encode3to4( source, d+off, len - d, outBuff, e );
e += 4;
} // end if: some padding needed
// Return value according to relevant encoding.
try
{
return new String( outBuff, 0, e, PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue)
{
return new String( outBuff, 0, e );
} // end catch
} // end else: don't compress
} // end encodeBytes
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the number of decoded bytes converted
* @since 1.3
*/
private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset )
{
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN )
{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else
{
try{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}catch( Exception e){
System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) );
System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
return -1;
} //e nd catch
}
} // end decodeToBytes
/**
* Very low-level access to decoding ASCII characters in
* the form of a byte array. Does not support automatically
* gunzipping or any other "fancy" features.
*
* @param source The Base64 encoded data
* @param off The offset of where to begin decoding
* @param len The length of characters to decode
* @return decoded data
* @since 1.3
*/
public static byte[] decode( byte[] source, int off, int len )
{
int len34 = len * 3 / 4;
byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
int outBuffPosn = 0;
byte[] b4 = new byte[4];
int b4Posn = 0;
int i = 0;
byte sbiCrop = 0;
byte sbiDecode = 0;
for( i = off; i < off+len; i++ )
{
sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[ sbiCrop ];
if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
{
if( sbiDecode >= EQUALS_SIGN_ENC )
{
b4[ b4Posn++ ] = sbiCrop;
if( b4Posn > 3 )
{
outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn );
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if( sbiCrop == EQUALS_SIGN )
break;
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else
{
//System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
return null;
} // end else:
} // each input character
byte[] out = new byte[ outBuffPosn ];
System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @return the decoded data
* @since 1.4
*/
public static byte[] decode( String s )
{
byte[] bytes;
try
{
bytes = s.getBytes( PREFERRED_ENCODING );
} // end try
catch( java.io.UnsupportedEncodingException uee )
{
bytes = s.getBytes();
} // end catch
//</change>
// Decode
bytes = decode( bytes, 0, bytes.length );
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
if( bytes != null && bytes.length >= 4 )
{
int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head )
{
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length = 0;
try
{
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream( bytes );
gzis = new java.util.zip.GZIPInputStream( bais );
while( ( length = gzis.read( buffer ) ) >= 0 )
{
baos.write(buffer,0,length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch( java.io.IOException e )
{
// Just return originally-decoded bytes
} // end catch
finally
{
try{ baos.close(); } catch( Exception e ){}
try{ gzis.close(); } catch( Exception e ){}
try{ bais.close(); } catch( Exception e ){}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
} // end decode
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @since 1.5
*/
public static Object decodeToObject( String encodedObject )
{
// Decode and gunzip if necessary
byte[] objBytes = decode( encodedObject );
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try
{
bais = new java.io.ByteArrayInputStream( objBytes );
ois = new java.io.ObjectInputStream( bais );
obj = ois.readObject();
} // end try
catch( java.io.IOException e )
{
e.printStackTrace();
obj = null;
} // end catch
catch( java.lang.ClassNotFoundException e )
{
e.printStackTrace();
obj = null;
} // end catch
finally
{
try{ bais.close(); } catch( Exception e ){}
try{ ois.close(); } catch( Exception e ){}
} // end finally
return obj;
} // end decodeObject
/**
* Convenience method for encoding data to a file.
*
* @param dataToEncode byte array of data to encode in base64 form
* @param filename Filename for saving encoded data
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*
* @since 2.1
*/
public static boolean encodeToFile( byte[] dataToEncode, String filename )
{
boolean success = false;
Base64.OutputStream bos = null;
try
{
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.ENCODE );
bos.write( dataToEncode );
success = true;
} // end try
catch( java.io.IOException e )
{
success = false;
} // end catch: IOException
finally
{
try{ bos.close(); } catch( Exception e ){}
} // end finally
return success;
} // end encodeToFile
/**
* Convenience method for decoding data to a file.
*
* @param dataToDecode Base64-encoded data as a string
* @param filename Filename for saving decoded data
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*
* @since 2.1
*/
public static boolean decodeToFile( String dataToDecode, String filename )
{
boolean success = false;
Base64.OutputStream bos = null;
try
{
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.DECODE );
bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
success = true;
} // end try
catch( java.io.IOException e )
{
success = false;
} // end catch: IOException
finally
{
try{ bos.close(); } catch( Exception e ){}
} // end finally
return success;
} // end decodeToFile
/**
* Convenience method for reading a base64-encoded
* file and decoding it.
*
* @param filename Filename for reading encoded data
* @return decoded byte array or null if unsuccessful
*
* @since 2.1
*/
public static byte[] decodeFromFile( String filename )
{
byte[] decodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if( file.length() > Integer.MAX_VALUE )
{
System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." );
return null;
} // end if: file too big for int index
buffer = new byte[ (int)file.length() ];
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.DECODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
length += numBytes;
// Save in a variable to return
decodedData = new byte[ length ];
System.arraycopy( buffer, 0, decodedData, 0, length );
} // end try
catch( java.io.IOException e )
{
System.err.println( "Error decoding from file " + filename );
} // end catch: IOException
finally
{
try{ bis.close(); } catch( Exception e) {}
} // end finally
return decodedData;
} // end decodeFromFile
/**
* Convenience method for reading a binary file
* and base64-encoding it.
*
* @param filename Filename for reading binary data
* @return base64-encoded string or null if unsuccessful
*
* @since 2.1
*/
public static String encodeFromFile( String filename )
{
String encodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = new byte[ (int)(file.length() * 1.4) ];
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.ENCODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
length += numBytes;
// Save in a variable to return
encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
} // end try
catch( java.io.IOException e )
{
System.err.println( "Error encoding from file " + filename );
} // end catch: IOException
finally
{
try{ bis.close(); } catch( Exception e) {}
} // end finally
return encodedData;
} // end encodeFromFile
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
/**
* A {@link Base64.InputStream} will read data from another
* <tt>java.io.InputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream
{
private boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private byte[] buffer; // Small buffer holding converted data
private int bufferLength; // Length of buffer (3 or 4)
private int numSigBytes; // Number of meaningful bytes in the buffer
private int lineLength;
private boolean breakLines; // Break lines at less than 80 characters
/**
* Constructs a {@link Base64.InputStream} in DECODE mode.
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @since 1.3
*/
public InputStream( java.io.InputStream in )
{
this( in, DECODE );
} // end constructor
/**
* Constructs a {@link Base64.InputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DONT_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
*
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @param options Specified options
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public InputStream( java.io.InputStream in, int options )
{
super( in );
this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
this.encode = (options & ENCODE) == ENCODE;
this.bufferLength = encode ? 4 : 3;
this.buffer = new byte[ bufferLength ];
this.position = -1;
this.lineLength = 0;
} // end constructor
/**
* Reads enough of the input stream to convert
* to/from Base64 and returns the next byte.
*
* @return next byte
* @since 1.3
*/
public int read() throws java.io.IOException
{
// Do we need to get data?
if( position < 0 )
{
if( encode )
{
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for( int i = 0; i < 3; i++ )
{
try
{
int b = in.read();
// If end of stream, b is -1.
if( b >= 0 )
{
b3[i] = (byte)b;
numBinaryBytes++;
} // end if: not end of stream
} // end try: read
catch( java.io.IOException e )
{
// Only a problem if we got no data at all.
if( i == 0 )
throw e;
} // end catch
} // end for: each needed input byte
if( numBinaryBytes > 0 )
{
encode3to4( b3, 0, numBinaryBytes, buffer, 0 );
position = 0;
numSigBytes = 4;
} // end if: got data
else
{
return -1;
} // end else
} // end if: encoding
// Else decoding
else
{
byte[] b4 = new byte[4];
int i = 0;
for( i = 0; i < 4; i++ )
{
// Read four "meaningful" bytes:
int b = 0;
do{ b = in.read(); }
while( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC );
if( b < 0 )
break; // Reads a -1 if end of stream
b4[i] = (byte)b;
} // end for: each needed input byte
if( i == 4 )
{
numSigBytes = decode4to3( b4, 0, buffer, 0 );
position = 0;
} // end if: got four characters
else if( i == 0 ){
return -1;
} // end else if: also padded correctly
else
{
// Must have broken out from above.
throw new java.io.IOException( "Improperly padded Base64 input." );
} // end
} // end else: decode
} // end else: get data
// Got data?
if( position >= 0 )
{
// End of relevant data?
if( /*!encode &&*/ position >= numSigBytes )
return -1;
if( encode && breakLines && lineLength >= MAX_LINE_LENGTH )
{
lineLength = 0;
return '\n';
} // end if
else
{
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[ position++ ];
if( position >= bufferLength )
position = -1;
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else
{
// When JDK1.4 is more accepted, use an assertion here.
throw new java.io.IOException( "Error in Base64 code reading stream." );
} // end else
} // end read
/**
* Calls {@link #read()} repeatedly until the end of stream
* is reached or <var>len</var> bytes are read.
* Returns number of bytes read into array or -1 if
* end of stream is encountered.
*
* @param dest array to hold values
* @param off offset for array
* @param len max number of bytes to read into array
* @return bytes read into array or -1 if end of stream is encountered.
* @since 1.3
*/
public int read( byte[] dest, int off, int len ) throws java.io.IOException
{
int i;
int b;
for( i = 0; i < len; i++ )
{
b = read();
//if( b < 0 && i == 0 )
// return -1;
if( b >= 0 )
dest[off + i] = (byte)b;
else if( i == 0 )
return -1;
else
break; // Out of 'for' loop
} // end for: each byte read
return i;
} // end read
} // end inner class InputStream
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
/**
* A {@link Base64.OutputStream} will write data to another
* <tt>java.io.OutputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class OutputStream extends java.io.FilterOutputStream
{
private boolean encode;
private int position;
private byte[] buffer;
private int bufferLength;
private int lineLength;
private boolean breakLines;
private byte[] b4; // Scratch used in a few places
private boolean suspendEncoding;
/**
* Constructs a {@link Base64.OutputStream} in ENCODE mode.
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @since 1.3
*/
public OutputStream( java.io.OutputStream out )
{
this( out, ENCODE );
} // end constructor
/**
* Constructs a {@link Base64.OutputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DONT_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @param options Specified options.
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DONT_BREAK_LINES
* @since 1.3
*/
public OutputStream( java.io.OutputStream out, int options )
{
super( out );
this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
this.encode = (options & ENCODE) == ENCODE;
this.bufferLength = encode ? 3 : 4;
this.buffer = new byte[ bufferLength ];
this.position = 0;
this.lineLength = 0;
this.suspendEncoding = false;
this.b4 = new byte[4];
} // end constructor
/**
* Writes the byte to the output stream after
* converting to/from Base64 notation.
* When encoding, bytes are buffered three
* at a time before the output stream actually
* gets a write() call.
* When decoding, bytes are buffered four
* at a time.
*
* @param theByte the byte to write
* @since 1.3
*/
public void write(int theByte) throws java.io.IOException
{
// Encoding suspended?
if( suspendEncoding )
{
super.out.write( theByte );
return;
} // end if: supsended
// Encode?
if( encode )
{
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) // Enough to encode.
{
out.write( encode3to4( b4, buffer, bufferLength ) );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH )
{
out.write( NEW_LINE );
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else
{
// Meaningful Base64 character?
if( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC )
{
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) // Enough to output.
{
int len = Base64.decode4to3( buffer, 0, b4, 0 );
out.write( b4, 0, len );
//out.write( Base64.decode4to3( buffer ) );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC )
{
throw new java.io.IOException( "Invalid character in Base64 data." );
} // end else: not white space either
} // end else: decoding
} // end write
/**
* Calls {@link #write(int)} repeatedly until <var>len</var>
* bytes are written.
*
* @param theBytes array from which to read bytes
* @param off offset for array
* @param len max number of bytes to read into array
* @since 1.3
*/
public void write( byte[] theBytes, int off, int len ) throws java.io.IOException
{
// Encoding suspended?
if( suspendEncoding )
{
super.out.write( theBytes, off, len );
return;
} // end if: supsended
for( int i = 0; i < len; i++ )
{
write( theBytes[ off + i ] );
} // end for: each byte written
} // end write
/**
* Method added by PHIL. [Thanks, PHIL. -Rob]
* This pads the buffer without closing the stream.
*/
public void flushBase64() throws java.io.IOException
{
if( position > 0 )
{
if( encode )
{
out.write( encode3to4( b4, buffer, position ) );
position = 0;
} // end if: encoding
else
{
throw new java.io.IOException( "Base64 input not properly padded." );
} // end else: decoding
} // end if: buffer partially full
} // end flush
/**
* Flushes and closes (I think, in the superclass) the stream.
*
* @since 1.3
*/
public void close() throws java.io.IOException
{
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
} // end close
/**
* Suspends encoding of the stream.
* May be helpful if you need to embed a piece of
* base640-encoded data in a stream.
*
* @since 1.5.1
*/
public void suspendEncoding() throws java.io.IOException
{
flushBase64();
this.suspendEncoding = true;
} // end suspendEncoding
/**
* Resumes encoding of the stream.
* May be helpful if you need to embed a piece of
* base640-encoded data in a stream.
*
* @since 1.5.1
*/
public void resumeEncoding()
{
this.suspendEncoding = false;
} // end resumeEncoding
} // end inner class OutputStream
} // end class Base64
| Chandrashar/jradius | applet/src/main/java/Base64.java | Java | lgpl-2.1 | 53,360 |
package org.kevoree.modeling.memory.struct.map.impl;
import org.kevoree.modeling.memory.struct.map.BaseKLongLongHashMapTest;
import org.kevoree.modeling.memory.struct.map.KLongLongMap;
public class ArrayLongLongHashMapTest extends BaseKLongLongHashMapTest {
@Override
public KLongLongMap createKLongLongHashMap(int p_initalCapacity, float p_loadFactor) {
return new ArrayLongLongMap(p_initalCapacity, p_loadFactor);
}
}
| dukeboard/kevoree-modeling-framework | org.kevoree.modeling.microframework/src/test/java/org/kevoree/modeling/memory/struct/map/impl/ArrayLongLongHashMapTest.java | Java | lgpl-3.0 | 443 |
package com.samepage.view;
import java.util.List;
import com.samepage.model.EmpDTO;
public class EmpView {
public static void print(String title, List<EmpDTO> emplist){
System.out.println(title + ">>========== ¿©·¯°Ç Ãâ·Â ===========<<");
for (EmpDTO empDTO : emplist) {
System.out.println(empDTO);
}
}
public static void printOne(String title, EmpDTO empDTO){
System.out.println(title + ">>========== ÇÑ°Ç Ãâ·Â ===========<<");
System.out.println(empDTO);
}
public static void sysMessage(String message){
System.out.println(message);
}
}
| qfactor2013/BizStudyParallel | DB/Day5/src/com/samepage/view/EmpView.java | Java | lgpl-3.0 | 569 |
/*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003,2004 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.detect;
import java.util.*;
import edu.umd.cs.findbugs.*;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.visitclass.AnnotationVisitor;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.*;
import edu.umd.cs.findbugs.visitclass.Constants2;
import static edu.umd.cs.findbugs.visitclass.Constants2.*;
public class NoteSuppressedWarnings extends AnnotationVisitor
implements Detector, Constants2 {
private static Set<String> packages = new HashSet<String>();
private SuppressionMatcher suppressionMatcher;
private BugReporter bugReporter;
private AnalysisContext analysisContext;
private NoteSuppressedWarnings recursiveDetector;
public NoteSuppressedWarnings(BugReporter bugReporter) {
this(bugReporter, false);
}
public NoteSuppressedWarnings(BugReporter bugReporter, boolean recursive) {
if (!recursive) {
DelegatingBugReporter b = (DelegatingBugReporter) bugReporter;
BugReporter origBugReporter = b.getRealBugReporter();
suppressionMatcher = new SuppressionMatcher();
BugReporter filterBugReporter = new FilterBugReporter(origBugReporter, suppressionMatcher, false);
b.setRealBugReporter(filterBugReporter);
recursiveDetector = new NoteSuppressedWarnings(bugReporter,true);
recursiveDetector.suppressionMatcher =
suppressionMatcher;
}
this.bugReporter = bugReporter;
}
public void setAnalysisContext(AnalysisContext analysisContext) {
this.analysisContext = analysisContext;
}
public void visitClassContext(ClassContext classContext) {
classContext.getJavaClass().accept(this);
}
public void visit(JavaClass obj) {
if (recursiveDetector == null) return;
try {
if (getClassName().endsWith("package-info")) return;
String packageName = getPackageName().replace('/', '.');
if (!packages.add(packageName)) return;
String packageInfo = "package-info";
if (packageName.length() > 0)
packageInfo = packageName + "." + packageInfo;
JavaClass packageInfoClass = Repository.lookupClass(packageInfo);
recursiveDetector.visitJavaClass(packageInfoClass);
} catch (ClassNotFoundException e) {
// ignore
}
}
public void visitAnnotation(String annotationClass, Map<String, Object> map,
boolean runtimeVisible) {
if (!annotationClass.endsWith("SuppressWarnings")) return;
Object value = map.get("value");
if (value == null || !(value instanceof Object[])) {
suppressWarning(null);
return;
}
Object [] suppressedWarnings = (Object[]) value;
if (suppressedWarnings.length == 0)
suppressWarning(null);
else for(int i = 0; i < suppressedWarnings.length; i++)
suppressWarning((String)suppressedWarnings[i]);
}
private void suppressWarning(String pattern) {
String className = getDottedClassName();
ClassAnnotation clazz = new ClassAnnotation(getDottedClassName());
if (className.endsWith("package-info") && recursiveDetector == null)
suppressionMatcher.addPackageSuppressor(
new PackageWarningSuppressor(pattern,
getPackageName().replace('/', '.')));
else if (visitingMethod())
suppressionMatcher.addSuppressor(
new MethodWarningSuppressor(pattern,
clazz, MethodAnnotation.fromVisitedMethod(this)));
else if (visitingField())
suppressionMatcher.addSuppressor(
new FieldWarningSuppressor(pattern,
clazz, FieldAnnotation.fromVisitedField(this)));
else
suppressionMatcher.addSuppressor(
new ClassWarningSuppressor(pattern,
clazz));
}
public void report() {
}
}
| simeshev/parabuild-ci | 3rdparty/findbugs086src/src/java/edu/umd/cs/findbugs/detect/NoteSuppressedWarnings.java | Java | lgpl-3.0 | 4,473 |
package org.xacml4j.v30.pdp;
/*
* #%L
* Xacml4J Core Engine Implementation
* %%
* Copyright (C) 2009 - 2014 Xacml4J.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import java.util.ListIterator;
import org.xacml4j.v30.Expression;
import org.xacml4j.v30.ValueType;
import org.xacml4j.v30.spi.function.FunctionParamSpecVisitor;
public interface FunctionParamSpec
{
/**
* Validates if the "sequence" of expressions
* from the current position is valid according
* this specification. Iterator will be advanced to
* the next expression after "sequence"
*
* @param it an iterator
* @return {@code true} if sequence of
* expressions starting at the current position
* is valid according this spec
*/
boolean validate(ListIterator<Expression> it);
Expression getDefaultValue();
boolean isOptional();
/**
* Tests if instances of a given value type
* can be used as values for a function
* parameter specified by this specification
*
* @param type a value type
* @return {@code true}
*/
boolean isValidParamType(ValueType type);
/**
* Tests if this parameter is variadic
*
* @return {@code true} if a function
* parameter represented by this object is
* variadic
*/
boolean isVariadic();
void accept(FunctionParamSpecVisitor v);
}
| snmaher/xacml4j | xacml-core/src/main/java/org/xacml4j/v30/pdp/FunctionParamSpec.java | Java | lgpl-3.0 | 1,952 |
// Catalano Imaging Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2015
// diego.catalano at live.com
//
// Copyright © Andrew Kirillov, 2007-2008
// andrew.kirillov@gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
package Catalano.Imaging.Filters;
import Catalano.Core.IntRange;
import Catalano.Math.ComplexNumber;
/**
* Filtering of frequencies outside of specified range in complex Fourier transformed image.
* @author Diego Catalano
*/
public class FrequencyFilter {
private IntRange freq = new IntRange(0, 1024);
/**
* Initializes a new instance of the FrequencyFilter class.
*/
public FrequencyFilter() {}
/**
* Initializes a new instance of the FrequencyFilter class.
* @param min Minimum value for to keep.
* @param max Maximum value for to keep.
*/
public FrequencyFilter(int min, int max){
this.freq = new IntRange(min, max);
}
/**
* Initializes a new instance of the FrequencyFilter class.S
* @param range IntRange.
*/
public FrequencyFilter(IntRange range) {
this.freq = range;
}
/**
* Get range of frequencies to keep.
* @return IntRange.
*/
public IntRange getFrequencyRange() {
return freq;
}
/**
* Set range of frequencies to keep.
* @param freq IntRange.
*/
public void setFrequencyRange(IntRange freq) {
this.freq = freq;
}
/**
* Apply filter to an fourierTransform.
* @param fourierTransform Fourier transformed.
*/
public void ApplyInPlace(FourierTransform fourierTransform){
if (!fourierTransform.isFourierTransformed()) {
try {
throw new Exception("the image should be fourier transformed.");
} catch (Exception e) {
e.printStackTrace();
}
}
int width = fourierTransform.getWidth();
int height = fourierTransform.getHeight();
int halfWidth = width / 2;
int halfHeight = height / 2;
int min = freq.getMin();
int max = freq.getMax();
ComplexNumber[][] c = fourierTransform.getData();
for ( int i = 0; i < height; i++ ){
int y = i - halfHeight;
for ( int j = 0; j < width; j++ ){
int x = j - halfWidth;
int d = (int) Math.sqrt( x * x + y * y );
// filter values outside the range
if ( ( d > max ) || ( d < min ) ){
c[i][j].real = 0;
c[i][j].imaginary = 0;
}
}
}
}
}
| cswaroop/Catalano-Framework | Catalano.Image/src/Catalano/Imaging/Filters/FrequencyFilter.java | Java | lgpl-3.0 | 3,543 |
/*
* Copyright 2009-2014 PrimeTek.
*
* 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.primefaces.adamantium.view.data.datatable;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.primefaces.adamantium.domain.Car;
import org.primefaces.adamantium.service.CarService;
@ManagedBean(name="dtColumnsView")
@ViewScoped
public class ColumnsView implements Serializable {
private final static List<String> VALID_COLUMN_KEYS = Arrays.asList("id", "brand", "year", "color", "price");
private String columnTemplate = "id brand year";
private List<ColumnModel> columns;
private List<Car> cars;
private List<Car> filteredCars;
@ManagedProperty("#{carService}")
private CarService service;
@PostConstruct
public void init() {
cars = service.createCars(10);
createDynamicColumns();
}
public List<Car> getCars() {
return cars;
}
public List<Car> getFilteredCars() {
return filteredCars;
}
public void setFilteredCars(List<Car> filteredCars) {
this.filteredCars = filteredCars;
}
public void setService(CarService service) {
this.service = service;
}
public String getColumnTemplate() {
return columnTemplate;
}
public void setColumnTemplate(String columnTemplate) {
this.columnTemplate = columnTemplate;
}
public List<ColumnModel> getColumns() {
return columns;
}
private void createDynamicColumns() {
String[] columnKeys = columnTemplate.split(" ");
columns = new ArrayList<ColumnModel>();
for(String columnKey : columnKeys) {
String key = columnKey.trim();
if(VALID_COLUMN_KEYS.contains(key)) {
columns.add(new ColumnModel(columnKey.toUpperCase(), columnKey));
}
}
}
public void updateColumns() {
//reset table state
UIComponent table = FacesContext.getCurrentInstance().getViewRoot().findComponent(":form:cars");
table.setValueExpression("sortBy", null);
//update columns
createDynamicColumns();
}
static public class ColumnModel implements Serializable {
private String header;
private String property;
public ColumnModel(String header, String property) {
this.header = header;
this.property = property;
}
public String getHeader() {
return header;
}
public String getProperty() {
return property;
}
}
}
| salviof/SBJSFComp | htmlOffiline/Volverine/tag/src/main/java/org/primefaces/adamantium/view/data/datatable/ColumnsView.java | Java | lgpl-3.0 | 3,441 |
package es.uvigo.esei.sing.bdbm.gui.configuration;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.EventListener;
import java.util.EventObject;
import java.util.concurrent.Callable;
import javax.swing.AbstractAction;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import es.uvigo.esei.sing.bdbm.gui.BDBMGUIController;
public class ConfigurationPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final BDBMGUIController controller;
private final JTextField txtRepository;
private final JTextField txtBLAST;
private final JTextField txtEMBOSS;
private final JTextField txtBedTools;
private final JTextField txtSplign;
private final JTextField txtCompart;
private final JButton btnBuildRepository;
public ConfigurationPanel(BDBMGUIController controller) {
super();
this.controller = controller;
// this.setPreferredSize(new Dimension(600, 140));
final GroupLayout layout = new GroupLayout(this);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
this.setLayout(layout);
final JLabel lblRepository = new JLabel("Repository Path");
final JLabel lblBLAST = new JLabel("BLAST Path");
final JLabel lblEMBOSS = new JLabel("EMBOSS Path");
final JLabel lblBedTools = new JLabel("BedTools Path");
final JLabel lblSplign = new JLabel("Splign Path");
final JLabel lblCompart = new JLabel("Compart Path");
final File repositoryPath = this.controller.getEnvironment()
.getRepositoryPaths().getBaseDirectory();
final File blastBD = this.controller.getEnvironment()
.getBLASTBinaries().getBaseDirectory();
final File embossBD = this.controller.getEnvironment()
.getEMBOSSBinaries().getBaseDirectory();
final File bedToolsBD = this.controller.getEnvironment()
.getBedToolsBinaries().getBaseDirectory();
final File splignBD = this.controller.getEnvironment()
.getSplignBinaries().getBaseDirectory();
final File compartBD = this.controller.getEnvironment()
.getCompartBinaries().getBaseDirectory();
this.txtRepository = new JTextField(repositoryPath.getAbsolutePath());
this.txtBLAST = new JTextField(blastBD == null ? "" : blastBD.getAbsolutePath());
this.txtEMBOSS = new JTextField(embossBD == null ? "" : embossBD.getAbsolutePath());
this.txtBedTools = new JTextField(bedToolsBD == null ? "" : bedToolsBD.getAbsolutePath());
this.txtSplign = new JTextField(splignBD == null ? "" : splignBD.getAbsolutePath());
this.txtCompart = new JTextField(compartBD == null ? "" : compartBD.getAbsolutePath());
this.txtRepository.setEditable(false);
this.txtBLAST.setEditable(false);
this.txtEMBOSS.setEditable(false);
this.txtBedTools.setEditable(false);
this.txtSplign.setEditable(false);
this.txtCompart.setEditable(false);
final JButton btnRepository = new JButton("Select...");
final JButton btnBLASTSelect = new JButton("Select...");
final JButton btnEMBOSSSelect = new JButton("Select...");
final JButton btnBedToolsSelect = new JButton("Select...");
final JButton btnSplignSelect = new JButton("Select...");
final JButton btnCompartSelect = new JButton("Select...");
final JButton btnBLASTInPath = new JButton("In system path");
final JButton btnEMBOSSInPath = new JButton("In system path");
final JButton btnBedToolsInPath = new JButton("In system path");
final JButton btnSplignInPath = new JButton("In system path");
final JButton btnCompartInPath = new JButton("In system path");
this.btnBuildRepository = new JButton(new AbstractAction("Build") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
ConfigurationPanel.this.buildRepository();
}
});
this.btnBuildRepository.setEnabled(false);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(lblRepository, Alignment.CENTER)
.addComponent(this.txtRepository)
.addComponent(btnRepository)
.addComponent(this.btnBuildRepository)
)
.addGroup(layout.createParallelGroup()
.addComponent(lblBLAST, Alignment.CENTER)
.addComponent(this.txtBLAST)
.addComponent(btnBLASTSelect)
.addComponent(btnBLASTInPath)
)
.addGroup(layout.createParallelGroup()
.addComponent(lblEMBOSS, Alignment.CENTER)
.addComponent(this.txtEMBOSS)
.addComponent(btnEMBOSSSelect)
.addComponent(btnEMBOSSInPath)
)
.addGroup(layout.createParallelGroup()
.addComponent(lblBedTools, Alignment.CENTER)
.addComponent(this.txtBedTools)
.addComponent(btnBedToolsSelect)
.addComponent(btnBedToolsInPath)
)
.addGroup(layout.createParallelGroup()
.addComponent(lblSplign, Alignment.CENTER)
.addComponent(this.txtSplign)
.addComponent(btnSplignSelect)
.addComponent(btnSplignInPath)
)
.addGroup(layout.createParallelGroup()
.addComponent(lblCompart, Alignment.CENTER)
.addComponent(this.txtCompart)
.addComponent(btnCompartSelect)
.addComponent(btnCompartInPath)
)
);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(lblRepository)
.addComponent(lblBLAST)
.addComponent(lblEMBOSS)
.addComponent(lblBedTools)
.addComponent(lblSplign)
.addComponent(lblCompart)
)
.addGroup(layout.createParallelGroup()
.addComponent(this.txtRepository)
.addComponent(this.txtBLAST)
.addComponent(this.txtEMBOSS)
.addComponent(this.txtBedTools)
.addComponent(this.txtSplign)
.addComponent(this.txtCompart)
)
.addGroup(layout.createParallelGroup()
.addComponent(btnRepository)
.addComponent(btnBLASTSelect)
.addComponent(btnEMBOSSSelect)
.addComponent(btnBedToolsSelect)
.addComponent(btnSplignSelect)
.addComponent(btnCompartSelect)
)
.addGroup(layout.createParallelGroup()
.addComponent(this.btnBuildRepository)
.addComponent(btnBLASTInPath)
.addComponent(btnEMBOSSInPath)
.addComponent(btnBedToolsInPath)
.addComponent(btnSplignInPath)
.addComponent(btnCompartInPath)
)
);
final Callable<Boolean> callbackRepositorySelection = new Callable<Boolean>() {
@Override
public Boolean call() {
if (ConfigurationPanel.this.isValidRepositoryPath()) {
btnBuildRepository.setEnabled(false);
} else {
btnBuildRepository.setEnabled(true);
if (JOptionPane.showConfirmDialog(
ConfigurationPanel.this,
"Repository path does not exist or its structure is incomplete. Do you wish to build repository structure?",
"Invalid Repository",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
) == JOptionPane.YES_OPTION) {
ConfigurationPanel.this.buildRepository();
}
}
return true;
}
};
btnRepository.addActionListener(
new PathSelectionActionListener(this.txtRepository, callbackRepositorySelection)
);
final Callable<Boolean> callbackCheckBLAST = new Callable<Boolean>() {
@Override
public Boolean call() {
if (ConfigurationPanel.this.isValidBLASTPath()) {
return true;
} else {
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Invalid BLAST binaries path. Please, change the selected path",
"Invalid Path",
JOptionPane.ERROR_MESSAGE
);
return false;
}
}
};
btnBLASTSelect.addActionListener(
new PathSelectionActionListener(this.txtBLAST, callbackCheckBLAST)
);
btnBLASTInPath.addActionListener(
new SystemPathSelectionActionListener(this.txtBLAST, callbackCheckBLAST)
);
final Callable<Boolean> callbackCheckEMBOSS = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
if (ConfigurationPanel.this.isValidEMBOSSPath()) {
return true;
} else {
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Invalid EMBOSS binaries path. Please, change the selected path",
"Invalid Path",
JOptionPane.ERROR_MESSAGE
);
return false;
}
}
};
btnEMBOSSSelect.addActionListener(
new PathSelectionActionListener(this.txtEMBOSS, callbackCheckEMBOSS)
);
btnEMBOSSInPath.addActionListener(
new SystemPathSelectionActionListener(this.txtEMBOSS, callbackCheckEMBOSS)
);
final Callable<Boolean> callbackCheckBedTools = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
if (ConfigurationPanel.this.isValidBedToolsPath()) {
return true;
} else {
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Invalid bedtools binaries path. Please, change the selected path",
"Invalid Path",
JOptionPane.ERROR_MESSAGE
);
return false;
}
}
};
btnBedToolsSelect.addActionListener(
new PathSelectionActionListener(this.txtBedTools, callbackCheckBedTools)
);
btnBedToolsInPath.addActionListener(
new SystemPathSelectionActionListener(this.txtBedTools, callbackCheckBedTools)
);
final Callable<Boolean> callbackCheckSplign = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
if (ConfigurationPanel.this.isValidSplignPath()) {
return true;
} else {
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Invalid splign binaries path. Please, change the selected path",
"Invalid Path",
JOptionPane.ERROR_MESSAGE
);
return false;
}
}
};
btnSplignSelect.addActionListener(
new PathSelectionActionListener(this.txtSplign, callbackCheckSplign)
);
btnSplignInPath.addActionListener(
new SystemPathSelectionActionListener(this.txtSplign, callbackCheckSplign)
);
final Callable<Boolean> callbackCheckCompart = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
if (ConfigurationPanel.this.isValidCompartPath()) {
return true;
} else {
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Invalid compart binaries path. Please, change the selected path",
"Invalid Path",
JOptionPane.ERROR_MESSAGE
);
return false;
}
}
};
btnCompartSelect.addActionListener(
new PathSelectionActionListener(this.txtCompart, callbackCheckCompart)
);
btnCompartInPath.addActionListener(
new SystemPathSelectionActionListener(this.txtCompart, callbackCheckCompart)
);
}
public void addConfigurationChangeListener(ConfigurationChangeEventListener listener) {
this.listenerList.add(ConfigurationChangeEventListener.class, listener);
}
public void removeConfigurationChangeListener(ConfigurationChangeEventListener listener) {
this.listenerList.remove(ConfigurationChangeEventListener.class, listener);
}
protected void fireChangeEvent(ConfigurationChangeEvent event) {
final ConfigurationChangeEventListener[] listeners =
this.listenerList.getListeners(ConfigurationChangeEventListener.class);
for (ConfigurationChangeEventListener listener : listeners) {
listener.configurationChanged(event);
}
}
protected void fireChange() {
this.fireChangeEvent(new ConfigurationChangeEvent(this));
}
protected File getRepositoryDirectory() {
return new File(this.txtRepository.getText());
}
protected String getBLASTPath() {
return this.txtBLAST.getText().isEmpty() ?
null : new File(this.txtBLAST.getText()).getAbsolutePath();
}
protected String getEMBOSSPath() {
return this.txtEMBOSS.getText().isEmpty() ?
null : new File(this.txtEMBOSS.getText()).getAbsolutePath();
}
protected String getBedToolsPath() {
return this.txtBedTools.getText().isEmpty() ?
null : new File(this.txtBedTools.getText()).getAbsolutePath();
}
protected String getSplignPath() {
return this.txtSplign.getText().isEmpty() ?
null : new File(this.txtSplign.getText()).getAbsolutePath();
}
protected String getCompartPath() {
return this.txtCompart.getText().isEmpty() ?
null : new File(this.txtCompart.getText()).getAbsolutePath();
}
public boolean isValidRepositoryPath() {
return this.controller.getEnvironment()
.getRepositoryPaths()
.checkBaseDirectory(getRepositoryDirectory());
}
public boolean isValidBLASTPath() {
return this.controller.getManager().checkBLASTPath(getBLASTPath());
}
protected boolean isValidEMBOSSPath() {
return this.controller.getManager().checkEMBOSSPath(getEMBOSSPath());
}
protected boolean isValidBedToolsPath() {
return this.controller.getManager().checkBedToolsPath(getBedToolsPath());
}
protected boolean isValidSplignPath() {
return this.controller.getManager().checkSplignPath(getSplignPath());
}
protected boolean isValidCompartPath() {
return this.controller.getManager().checkCompartPath(getCompartPath());
}
protected void buildRepository() {
try {
this.controller.getEnvironment()
.getRepositoryPaths()
.buildBaseDirectory(this.getRepositoryDirectory());
this.btnBuildRepository.setEnabled(false);
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Repository structure was correctly built.",
"Repository Built",
JOptionPane.INFORMATION_MESSAGE
);
this.fireChange();
} catch (Exception e) {
this.btnBuildRepository.setEnabled(true);
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Error building repository. Please, check path and press 'Build' or change path",
"Repository Building Error",
JOptionPane.ERROR_MESSAGE
);
}
}
public PathsConfiguration getConfiguration() {
if (this.isValidRepositoryPath() && this.isValidBLASTPath()) {
final String blastPath = this.getBLASTPath();
final String embossPath = this.getEMBOSSPath();
final String bedToolsPath = this.getBedToolsPath();
final String splignPath = this.getSplignPath();
final String compartPath = this.getCompartPath();
return new PathsConfiguration(
this.getRepositoryDirectory(),
blastPath == null ? null : new File(blastPath),
embossPath == null ? null : new File(embossPath),
bedToolsPath == null ? null : new File(bedToolsPath),
splignPath == null ? null : new File(splignPath),
compartPath == null ? null : new File(compartPath)
);
} else {
return null;
}
}
private final class SystemPathSelectionActionListener implements
ActionListener {
private final JTextField txtAssociated;
private final Callable<Boolean> callback;
private SystemPathSelectionActionListener(JTextField txtAssociated, Callable<Boolean> callback) {
this.txtAssociated = txtAssociated;
this.callback = callback;
}
@Override
public void actionPerformed(ActionEvent e) {
final String previousPath = this.txtAssociated.getText();
this.txtAssociated.setText("");
try {
if (this.callback.call()) {
ConfigurationPanel.this.fireChange();
} else {
txtAssociated.setText(previousPath);
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
private final class PathSelectionActionListener implements ActionListener {
private final JTextField txtAssociated;
private final Callable<Boolean> callback;
private PathSelectionActionListener(JTextField txtAssociated, Callable<Boolean> callback) {
this.txtAssociated = txtAssociated;
this.callback = callback;
}
@Override
public void actionPerformed(ActionEvent e) {
final JFileChooser chooser = new JFileChooser(
new File(txtAssociated.getText())
);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setMultiSelectionEnabled(false);
if (chooser.showOpenDialog(ConfigurationPanel.this) == JFileChooser.APPROVE_OPTION) {
final String previousPath = txtAssociated.getText();
txtAssociated.setText(chooser.getSelectedFile().getAbsolutePath());
try {
if (this.callback.call()) {
ConfigurationPanel.this.fireChange();
} else {
txtAssociated.setText(previousPath);
}
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
}
}
public static class ConfigurationChangeEvent extends EventObject {
private static final long serialVersionUID = 1L;
private final PathsConfiguration configuration;
protected ConfigurationChangeEvent(ConfigurationPanel panel) {
this(panel, panel.getConfiguration());
}
public ConfigurationChangeEvent(Object source, PathsConfiguration configuration) {
super(source);
this.configuration = configuration;
}
public PathsConfiguration getConfiguration() {
return configuration;
}
}
public static interface ConfigurationChangeEventListener extends EventListener {
public void configurationChanged(ConfigurationChangeEvent event);
}
}
| mrjato/BDBM | gui/es/uvigo/esei/sing/bdbm/gui/configuration/ConfigurationPanel.java | Java | lgpl-3.0 | 16,988 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.batch;
import org.apache.commons.io.IOUtils;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.batch.protocol.input.GlobalRepositories;
import org.sonar.db.metric.MetricDto;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.db.DbSession;
import org.sonar.db.MyBatis;
import org.sonar.db.property.PropertiesDao;
import org.sonar.db.property.PropertyDto;
import org.sonar.server.db.DbClient;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.plugins.MimeTypes;
import org.sonar.server.user.UserSession;
public class GlobalAction implements BatchWsAction {
private final DbClient dbClient;
private final PropertiesDao propertiesDao;
private final UserSession userSession;
public GlobalAction(DbClient dbClient, PropertiesDao propertiesDao, UserSession userSession) {
this.dbClient = dbClient;
this.propertiesDao = propertiesDao;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("global")
.setDescription("Return metrics and global properties")
.setSince("4.5")
.setInternal(true)
.setHandler(this);
}
@Override
public void handle(Request request, Response response) throws Exception {
boolean hasScanPerm = userSession.hasGlobalPermission(GlobalPermissions.SCAN_EXECUTION);
boolean hasPreviewPerm = userSession.hasGlobalPermission(GlobalPermissions.PREVIEW_EXECUTION);
if (!hasPreviewPerm && !hasScanPerm) {
throw new ForbiddenException(Messages.NO_PERMISSION);
}
DbSession session = dbClient.openSession(false);
try {
GlobalRepositories ref = new GlobalRepositories();
addMetrics(ref, session);
addSettings(ref, hasScanPerm, hasPreviewPerm, session);
response.stream().setMediaType(MimeTypes.JSON);
IOUtils.write(ref.toJson(), response.stream().output());
} finally {
MyBatis.closeQuietly(session);
}
}
private void addMetrics(GlobalRepositories ref, DbSession session) {
for (MetricDto metric : dbClient.metricDao().selectEnabled(session)) {
ref.addMetric(
new org.sonar.batch.protocol.input.Metric(metric.getId(), metric.getKey(),
metric.getValueType(),
metric.getDescription(),
metric.getDirection(),
metric.getKey(),
metric.isQualitative(),
metric.isUserManaged(),
metric.getWorstValue(),
metric.getBestValue(),
metric.isOptimizedBestValue()));
}
}
private void addSettings(GlobalRepositories ref, boolean hasScanPerm, boolean hasPreviewPerm, DbSession session) {
for (PropertyDto propertyDto : propertiesDao.selectGlobalProperties(session)) {
String key = propertyDto.getKey();
String value = propertyDto.getValue();
if (isPropertyAllowed(key, hasScanPerm, hasPreviewPerm)) {
ref.addGlobalSetting(key, value);
}
}
}
private static boolean isPropertyAllowed(String key, boolean hasScanPerm, boolean hasPreviewPerm) {
return !key.contains(".secured") || hasScanPerm || (key.contains(".license") && hasPreviewPerm);
}
}
| ayondeep/sonarqube | server/sonar-server/src/main/java/org/sonar/server/batch/GlobalAction.java | Java | lgpl-3.0 | 4,163 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.ce.configuration;
import javax.annotation.ParametersAreNonnullByDefault;
| SonarSource/sonarqube | server/sonar-ce/src/main/java/org/sonar/ce/configuration/package-info.java | Java | lgpl-3.0 | 966 |
package spitter.web;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.view.InternalResourceView;
import spittr.Spittle;
import spittr.data.SpittleRepository;
import spittr.web.SpittleController;
public class SpittleControllerTest {
@Test
public void houldShowRecentSpittles() throws Exception {
List<Spittle> expectedSpittles = createSpittleList(20);
SpittleRepository mockRepository = mock(SpittleRepository.class);
when(mockRepository.findSpittles(Long.MAX_VALUE, 20))
.thenReturn(expectedSpittles);
SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller)
.setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
.build();
mockMvc.perform(get("/spittles"))
.andExpect(view().name("spittles"))
.andExpect(model().attributeExists("spittleList"))
.andExpect(model().attribute("spittleList",
hasItems(expectedSpittles.toArray())));
}
@Test
public void shouldShowPagedSpittles() throws Exception {
List<Spittle> expectedSpittles = createSpittleList(50);
SpittleRepository mockRepository = mock(SpittleRepository.class);
when(mockRepository.findSpittles(238900, 50))
.thenReturn(expectedSpittles);
SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller)
.setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
.build();
mockMvc.perform(get("/spittles?max=238900&count=50"))
.andExpect(view().name("spittles"))
.andExpect(model().attributeExists("spittleList"))
.andExpect(model().attribute("spittleList",
hasItems(expectedSpittles.toArray())));
}
@Test
public void testSpittle() throws Exception {
Spittle expectedSpittle = new Spittle("Hello", new Date());
SpittleRepository mockRepository = mock(SpittleRepository.class);
when(mockRepository.findOne(12345)).thenReturn(expectedSpittle);
SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller).build();
mockMvc.perform(get("/spittles/12345"))
.andExpect(view().name("spittle"))
.andExpect(model().attributeExists("spittle"))
.andExpect(model().attribute("spittle", expectedSpittle));
}
@Test
public void saveSpittle() throws Exception {
SpittleRepository mockRepository = mock(SpittleRepository.class);
SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller).build();
mockMvc.perform(post("/spittles")
.param("message", "Hello World") // this works, but isn't really testing what really happens
.param("longitude", "-81.5811668")
.param("latitude", "28.4159649")
)
.andExpect(redirectedUrl("/spittles"));
verify(mockRepository, atLeastOnce()).save(new Spittle(null, "Hello World", new Date(), -81.5811668, 28.4159649));
}
private List<Spittle> createSpittleList(int count) {
List<Spittle> spittles = new ArrayList<Spittle>();
for (int i=0; i < count; i++) {
spittles.add(new Spittle("Spittle " + i, new Date()));
}
return spittles;
}
}
| qiqjiao/study | spring/springinaction/SpringInActionExamples/Chapter_06/thymeleaf/src/test/java/spitter/web/SpittleControllerTest.java | Java | lgpl-3.0 | 3,786 |
/*
* Copyright (C) 2009 Christian Hujer.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* File Filtering.
* @author <a href="mailto:cher@riedquat.de">Christian Hujer</a>
* @since 0.1
*/
package net.sf.japi.util.filter.file;
| christianhujer/japi | historic2/src/prj/net/sf/japi/util/filter/file/package-info.java | Java | lgpl-3.0 | 936 |
/*
{{ jtdavids-reflex }}
Copyright (C) 2015 Jake Davidson
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.example.jake.jtdavids_reflex;
import android.content.SharedPreferences;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Jake on 28/09/2015.
*/
public class StatisticCalc {
List<Double> reaction_times = new ArrayList<Double>();
public StatisticCalc() {
}
public void add(double time){
reaction_times.add(time);
}
public void clear(){
reaction_times.clear();
}
public String getAllTimeMin(){
//gets the minimum time of all recorded reaction times
//if no reaction times are recored, return 'N/A'
if (reaction_times.size() != 0) {
double min = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i >= 0; i--) {
if (reaction_times.get(i) < min) {
min = reaction_times.get(i);
}
}
return String.valueOf(min);
} else{
return "N/A";
}
}
public String getSpecifiedTimeMin(int length){
//Gets the minimum reaction time of the last X reactions
//a negative value should not be passed into this method
//Since reactions are stored in a list, must iterate backwards through the list
//to retrieve reaction times in chronological order
if (reaction_times.size() != 0) {
if(reaction_times.size() < length){
length = reaction_times.size();
}
double min = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i > reaction_times.size()-length; i--) {
if (reaction_times.get(i) < min) {
min = reaction_times.get(i);
}
}
return String.valueOf(min);
} else{
return "N/A";
}
}
public String getAllTimeMax(){
//gets the maximum reaction time of all reactions
if (reaction_times.size() !=0 ) {
double max = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i >= 0; i--) {
if (reaction_times.get(i) > max) {
max = reaction_times.get(i);
}
}
return String.valueOf(max);
} else{
return "N/A";
}
}
public String getSpecifiedTimeMax(int length){
//Gets the maximum reaction time of the last X reactions
//a negative value should not be passed into this method
//Since reactions are stored in a list, must iterate backwards through the list
//to retrieve reaction times in chronological order
if (reaction_times.size() !=0 ) {
if(reaction_times.size() < length){
length = reaction_times.size();
}
double max = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i > reaction_times.size()-length; i--) {
if (reaction_times.get(i) > max) {
max = reaction_times.get(i);
}
}
return String.valueOf(max);
}
else{
return "N/A";
}
}
public String getAllTimeAvg(){
//gets the average reaction time of all reactions
if (reaction_times.size() !=0 ) {
double avg = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i >= 0; i--) {
avg = avg + reaction_times.get(i);
}
return String.valueOf((avg / reaction_times.size()));
} else{
return "N/A ";
}
}
public String getSpecifiedTimeAvg(int length){
//Gets the average reaction time of the last X reactions
//a negative value should not be passed into this method
//Since reactions are stored in a list, must iterate backwards through the list
//to retrieve reaction times in chronological order
if (reaction_times.size() !=0 ) {
if(reaction_times.size() < length){
length = reaction_times.size();
}
double avg = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i >= reaction_times.size()-length; i--) {
avg = avg + reaction_times.get(i);
}
return String.valueOf((avg / length));
}else{
return "N/A ";
}
}
public String getAllTimeMed(){
//gets the median reaction time of all reactions
if (reaction_times.size() !=0 ) {
List<Double> sorted_times = new ArrayList<Double>(reaction_times);
Collections.sort(sorted_times);
return String.valueOf((sorted_times.get(sorted_times.size() / 2)));
}
else{
return "N/A";
}
}
public String getSpecifiedTimeMed(int length){
//Gets the median reaction time of the last X reactions
//a negative value should not be passed into this method
if (reaction_times.size() != 0 ) {
if(reaction_times.size() < length){
length = reaction_times.size();
}
List<Double> sorted_times = new ArrayList<Double>(reaction_times.subList(0, length));
Collections.sort(sorted_times);
return String.valueOf((sorted_times.get(sorted_times.size() / 2)));
}else{
return "N/A";
}
}
public String getStatsMessage(SharedPreferences twoplayers_score, SharedPreferences threeplayers_score, SharedPreferences fourplayers_score){
return ("______SINGLEPLAYER______\n" +
" MIN TIME:\n" +
"All Time: " + getAllTimeMin() + "\nLast 10 times: " + getSpecifiedTimeMin(10) + "\nLast 100 times: " + getSpecifiedTimeMin(100) + "\n" +
" MAX TIME:\n" +
"All Time: " + getAllTimeMax() + "\nLast 10 times: " + getSpecifiedTimeMax(10) + "\nLast 100 times: " + getSpecifiedTimeMax(100) + "\n" +
" AVERAGE TIME:\n" +
"All Time: " + getAllTimeAvg() + "\nLast 10 times: " + getSpecifiedTimeAvg(10) + "\nLast 100 times: " + getSpecifiedTimeAvg(100) + "\n" +
" MEDIAN TIME:\n" +
"All Time: " + getAllTimeMed() + "\nLast 10 times: " + getSpecifiedTimeMed(10) + "\nLast 100 times: " + getSpecifiedTimeMed(100) + "\n" +
"______PARTY PLAY______\n" +
" 2 PLAYERS:\n" +
"Player 1: " + String.valueOf(twoplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(twoplayers_score.getInt("player2", 0)) + "\n" +
" 3 PLAYERS:\n" +
"Player 1: " + String.valueOf(threeplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(threeplayers_score.getInt("player2", 0)) + "\nPlayer 3: " + String.valueOf(threeplayers_score.getInt("player3", 0)) + "\n" +
" 4 PLAYERS:\n" +
"Player 1: " + String.valueOf(fourplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(fourplayers_score.getInt("player2", 0)) + "\nPlayer 3: " + String.valueOf(fourplayers_score.getInt("player3", 0)) + "\nPlayer 4: " + String.valueOf(fourplayers_score.getInt("player4", 0)) + "\n");
}
}
| jtdavids/jtdavids-reflex | jtdavids-reflex/src/main/java/com/example/jake/jtdavids_reflex/StatisticCalc.java | Java | lgpl-3.0 | 8,131 |
package org.cloudbus.cloudsim.examples.power.steady;
import java.io.IOException;
/**
* A simulation of a heterogeneous power aware data center that applies the
* Static Threshold (THR) VM allocation policy and Minimum Migration Time (MMT)
* VM selection policy.
*
* The remaining configuration parameters are in the Constants and
* SteadyConstants classes.
*
* If you are using any algorithms, policies or workload included in the power
* package please cite the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic
* Algorithms and Adaptive Heuristics for Energy and Performance Efficient
* Dynamic Consolidation of Virtual Machines in Cloud Data Centers", Concurrency
* and Computation: Practice and Experience (CCPE), Volume 24, Issue 13, Pages:
* 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since Jan 5, 2012
*/
public class ThrMmt {
/**
* The main method.
*
* @param args
* the arguments
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void main(String[] args) throws IOException {
boolean enableOutput = true;
boolean outputToFile = false;
String inputFolder = "";
String outputFolder = "";
String workload = "steady"; // Steady workload
String vmAllocationPolicy = "thr"; // Static Threshold (THR) VM
// allocation policy
String vmSelectionPolicy = "mmt"; // Minimum Migration Time (MMT) VM
// selection policy
String parameter = "0.8"; // the static utilization threshold
new SteadyRunner(enableOutput, outputToFile, inputFolder, outputFolder,
workload, vmAllocationPolicy, vmSelectionPolicy, parameter);
}
}
| swethapts/cloudsim | sources/org/cloudbus/cloudsim/examples/power/steady/ThrMmt.java | Java | lgpl-3.0 | 1,797 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package orgomg.cwm.analysis.olap.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList;
import org.eclipse.emf.ecore.util.InternalEList;
import orgomg.cwm.analysis.olap.HierarchyLevelAssociation;
import orgomg.cwm.analysis.olap.LevelBasedHierarchy;
import orgomg.cwm.analysis.olap.OlapPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Level Based Hierarchy</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link orgomg.cwm.analysis.olap.impl.LevelBasedHierarchyImpl#getHierarchyLevelAssociation <em>Hierarchy Level Association</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class LevelBasedHierarchyImpl extends HierarchyImpl implements LevelBasedHierarchy {
/**
* The cached value of the '{@link #getHierarchyLevelAssociation() <em>Hierarchy Level Association</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHierarchyLevelAssociation()
* @generated
* @ordered
*/
protected EList<HierarchyLevelAssociation> hierarchyLevelAssociation;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected LevelBasedHierarchyImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return OlapPackage.Literals.LEVEL_BASED_HIERARCHY;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<HierarchyLevelAssociation> getHierarchyLevelAssociation() {
if (hierarchyLevelAssociation == null) {
hierarchyLevelAssociation = new EObjectContainmentWithInverseEList<HierarchyLevelAssociation>(HierarchyLevelAssociation.class, this, OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION, OlapPackage.HIERARCHY_LEVEL_ASSOCIATION__LEVEL_BASED_HIERARCHY);
}
return hierarchyLevelAssociation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getHierarchyLevelAssociation()).basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
return ((InternalEList<?>)getHierarchyLevelAssociation()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
return getHierarchyLevelAssociation();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
getHierarchyLevelAssociation().clear();
getHierarchyLevelAssociation().addAll((Collection<? extends HierarchyLevelAssociation>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
getHierarchyLevelAssociation().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
return hierarchyLevelAssociation != null && !hierarchyLevelAssociation.isEmpty();
}
return super.eIsSet(featureID);
}
} //LevelBasedHierarchyImpl
| dresden-ocl/dresdenocl | plugins/org.dresdenocl.tools.CWM/src/orgomg/cwm/analysis/olap/impl/LevelBasedHierarchyImpl.java | Java | lgpl-3.0 | 4,857 |
package com.wavpack.decoder;
import java.io.RandomAccessFile;
/*
** WavpackContext.java
**
** Copyright (c) 2007 - 2008 Peter McQuillan
**
** All Rights Reserved.
**
** Distributed under the BSD Software License (see license.txt)
**
*/
public class WavpackContext {
WavpackConfig config = new WavpackConfig();
WavpackStream stream = new WavpackStream();
byte read_buffer[] = new byte[65536]; // was uchar in C
int[] temp_buffer = new int[Defines.SAMPLE_BUFFER_SIZE];
int[] temp_buffer2 = new int[Defines.SAMPLE_BUFFER_SIZE];
String error_message = "";
boolean error;
RandomAccessFile infile;
long total_samples, crc_errors, first_flags; // was uint32_t in C
int open_flags, norm_offset;
int reduced_channels = 0;
int lossy_blocks;
int status = 0; // 0 ok, 1 error
public boolean isError() {
return error;
}
public String getErrorMessage() {
return error_message;
}
} | jacky8hyf/musique | dependencies/wavpack/src/main/java/com/wavpack/decoder/WavpackContext.java | Java | lgpl-3.0 | 1,036 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.core.metamodel.facets.object.callbacks.remove;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.ImperativeFacet;
public class RemovingCallbackFacetViaMethod extends RemovingCallbackFacetAbstract implements ImperativeFacet {
private final List<Method> methods = new ArrayList<Method>();
public RemovingCallbackFacetViaMethod(final Method method, final FacetHolder holder) {
super(holder);
addMethod(method);
}
@Override
public void addMethod(final Method method) {
methods.add(method);
}
@Override
public boolean impliesResolve() {
return false;
}
@Override
public Intent getIntent(final Method method) {
return Intent.LIFECYCLE;
}
@Override
public boolean impliesObjectChanged() {
return false;
}
@Override
public List<Method> getMethods() {
return Collections.unmodifiableList(methods);
}
@Override
public void invoke(final ObjectAdapter adapter) {
ObjectAdapter.InvokeUtils.invokeAll(methods, adapter);
}
@Override
protected String toStringValues() {
return "methods=" + methods;
}
}
| kidaa/isis | core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/callbacks/remove/RemovingCallbackFacetViaMethod.java | Java | apache-2.0 | 2,249 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.jstorm.message.netty;
import backtype.storm.Config;
import backtype.storm.messaging.IConnection;
import backtype.storm.messaging.IContext;
import backtype.storm.utils.DisruptorQueue;
import backtype.storm.utils.Utils;
import com.alibaba.jstorm.callback.AsyncLoopThread;
import com.alibaba.jstorm.metric.MetricDef;
import com.alibaba.jstorm.utils.JStormUtils;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NettyContext implements IContext {
private final static Logger LOG = LoggerFactory.getLogger(NettyContext.class);
@SuppressWarnings("rawtypes")
private Map stormConf;
private NioClientSocketChannelFactory clientChannelFactory;
private ReconnectRunnable reconnector;
@SuppressWarnings("unused")
public NettyContext() {
}
/**
* initialization per Storm configuration
*/
@SuppressWarnings("rawtypes")
public void prepare(Map stormConf) {
this.stormConf = stormConf;
int maxWorkers = Utils.getInt(stormConf.get(Config.STORM_MESSAGING_NETTY_CLIENT_WORKER_THREADS));
ThreadFactory bossFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "boss");
ThreadFactory workerFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "worker");
if (maxWorkers > 0) {
clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
Executors.newCachedThreadPool(workerFactory), maxWorkers);
} else {
clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
Executors.newCachedThreadPool(workerFactory));
}
reconnector = new ReconnectRunnable();
new AsyncLoopThread(reconnector, true, Thread.MIN_PRIORITY, true);
}
@Override
public IConnection bind(String topologyId, int port, ConcurrentHashMap<Integer, DisruptorQueue> deserializedQueue,
DisruptorQueue recvControlQueue, boolean bstartRec, Set<Integer> workerTasks) {
IConnection retConnection = null;
try {
retConnection = new NettyServer(stormConf, port, deserializedQueue, recvControlQueue, bstartRec, workerTasks);
} catch (Throwable e) {
LOG.error("Failed to create NettyServer", e);
JStormUtils.halt_process(-1, "Failed to bind " + port);
}
return retConnection;
}
@Override
public IConnection connect(String topologyId, String host, int port) {
return new NettyClientAsync(stormConf, clientChannelFactory, host, port, reconnector, new HashSet<Integer>(), new HashSet<Integer>());
}
@Override
public IConnection connect(String topologyId, String host, int port, Set<Integer> sourceTasks, Set<Integer> targetTasks) {
return new NettyClientAsync(stormConf, clientChannelFactory, host, port, reconnector, sourceTasks, targetTasks);
}
/**
* terminate this context
*/
public void term() {
/* clientScheduleService.shutdown();
try {
clientScheduleService.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOG.error("Error when shutting down client scheduler", e);
}*/
clientChannelFactory.releaseExternalResources();
reconnector.shutdown();
}
}
| alibaba/jstorm | jstorm-core/src/main/java/com/alibaba/jstorm/message/netty/NettyContext.java | Java | apache-2.0 | 4,482 |
package org.jboss.resteasy.test.providers.multipart.resource;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "customer")
@XmlAccessorType(XmlAccessType.FIELD)
public class ContextProvidersCustomer {
@XmlElement
private String name;
public ContextProvidersCustomer() {
}
public ContextProvidersCustomer(final String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| awhitford/Resteasy | testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ContextProvidersCustomer.java | Java | apache-2.0 | 607 |
/*
* Copyright (C) 2013 nohana, 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 com.amalgam.database;
import android.annotation.TargetApi;
import android.database.Cursor;
import android.os.Build;
/**
* Utility for the {@link android.database.Cursor}
*/
@SuppressWarnings("unused") // public APIs
public final class CursorUtils {
private static final int TRUE = 1;
private CursorUtils() {
throw new AssertionError();
}
/**
* Close with null checks.
* @param cursor to close.
*/
public static void close(Cursor cursor) {
if (cursor == null) {
return;
}
cursor.close();
}
/**
* Read the boolean data for the column.
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the boolean value.
*/
public static boolean getBoolean(Cursor cursor, String columnName) {
return cursor != null && cursor.getInt(cursor.getColumnIndex(columnName)) == TRUE;
}
/**
* Read the int data for the column.
* @see android.database.Cursor#getInt(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the int value.
*/
public static int getInt(Cursor cursor, String columnName) {
if (cursor == null) {
return -1;
}
return cursor.getInt(cursor.getColumnIndex(columnName));
}
/**
* Read the String data for the column.
* @see android.database.Cursor#getString(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the String value.
*/
public static String getString(Cursor cursor, String columnName) {
if (cursor == null) {
return null;
}
return cursor.getString(cursor.getColumnIndex(columnName));
}
/**
* Read the short data for the column.
* @see android.database.Cursor#getShort(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the short value.
*/
public static short getShort(Cursor cursor, String columnName) {
if (cursor == null) {
return -1;
}
return cursor.getShort(cursor.getColumnIndex(columnName));
}
/**
* Read the long data for the column.
* @see android.database.Cursor#getLong(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the long value.
*/
public static long getLong(Cursor cursor, String columnName) {
if (cursor == null) {
return -1;
}
return cursor.getLong(cursor.getColumnIndex(columnName));
}
/**
* Read the double data for the column.
* @see android.database.Cursor#getDouble(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the double value.
*/
public static double getDouble(Cursor cursor, String columnName) {
if (cursor == null) {
return -1;
}
return cursor.getDouble(cursor.getColumnIndex(columnName));
}
/**
* Read the float data for the column.
* @see android.database.Cursor#getFloat(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the float value.
*/
public static float getFloat(Cursor cursor, String columnName) {
if (cursor == null) {
return -1;
}
return cursor.getFloat(cursor.getColumnIndex(columnName));
}
/**
* Read the blob data for the column.
* @see android.database.Cursor#getBlob(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the blob value.
*/
public static byte[] getBlob(Cursor cursor, String columnName) {
if (cursor == null) {
return null;
}
return cursor.getBlob(cursor.getColumnIndex(columnName));
}
/**
* Checks the type of the column.
* @see android.database.Cursor#getType(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the type of the column.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static int getType(Cursor cursor, String columnName) {
if (cursor == null) {
return Cursor.FIELD_TYPE_NULL;
}
return cursor.getType(cursor.getColumnIndex(columnName));
}
/**
* Checks if the column value is null or not.
* @see android.database.Cursor#isNull(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return true if the column value is null.
*/
public static boolean isNull(Cursor cursor, String columnName) {
return cursor != null && cursor.isNull(cursor.getColumnIndex(columnName));
}
}
| KeithYokoma/Amalgam | amalgam/src/main/java/com/amalgam/database/CursorUtils.java | Java | apache-2.0 | 5,998 |
/*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.irb;
import org.kuali.kra.irb.actions.submit.ProtocolSubmission;
import org.kuali.kra.irb.personnel.ProtocolPerson;
import org.kuali.kra.irb.personnel.ProtocolUnit;
import org.kuali.kra.irb.protocol.funding.ProtocolFundingSource;
import org.kuali.kra.irb.protocol.location.ProtocolLocation;
import org.kuali.kra.irb.protocol.research.ProtocolResearchArea;
import org.kuali.kra.protocol.CriteriaFieldHelper;
import org.kuali.kra.protocol.ProtocolBase;
import org.kuali.kra.protocol.ProtocolDaoOjbBase;
import org.kuali.kra.protocol.ProtocolLookupConstants;
import org.kuali.kra.protocol.actions.ProtocolActionBase;
import org.kuali.kra.protocol.actions.submit.ProtocolSubmissionBase;
import org.kuali.kra.protocol.personnel.ProtocolPersonBase;
import org.kuali.kra.protocol.personnel.ProtocolUnitBase;
import org.kuali.rice.krad.service.util.OjbCollectionAware;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
*
* This class is the implementation for ProtocolDao interface.
*/
class ProtocolDaoOjb extends ProtocolDaoOjbBase<Protocol> implements OjbCollectionAware, ProtocolDao {
/**
* The APPROVED_SUBMISSION_STATUS_CODE contains the status code of approved protocol submissions (i.e. 203).
*/
private static final Collection<String> APPROVED_SUBMISSION_STATUS_CODES = Arrays.asList(new String[] {"203"});
/**
* The ACTIVE_PROTOCOL_STATUS_CODES contains the various active status codes for a protocol.
* <li> 200 - Active, open to enrollment
* <li> 201 - Active, closed to enrollment
* <li> 202 - Active, data analysis only
*/
private static final Collection<String> ACTIVE_PROTOCOL_STATUS_CODES = Arrays.asList(new String[] {"200", "201", "202"});
/**
* The REVISION_REQUESTED_PROTOCOL_ACTION_TYPE_CODES contains the protocol action codes for the protocol revision requests.
* <li> 202 - Specific Minor Revision
* <li> 203 - Substantive Revision Requested
*/
private static final Collection<String> REVISION_REQUESTED_PROTOCOL_ACTION_TYPE_CODES = Arrays.asList(new String[] {"202", "203"});
/**
* The REVISION_REQUESTED_PROTOCOL_STATUS_CODES contains the various status codes for protocol revision requests.
* <li> 102 - Specific Minor Revision
* <li> 104 - Substantive Revision Requested
*/
private static final Collection<String> REVISION_REQUESTED_PROTOCOL_STATUS_CODES = Arrays.asList(new String[] {"102", "104"});
private static final Collection<String> PENDING_AMENDMENT_RENEWALS_STATUS_CODES = Arrays.asList(new String[]{"100", "101", "102", "103", "104", "105", "106"});
@Override
protected Collection<String> getApprovedSubmissionStatusCodesHook() {
return APPROVED_SUBMISSION_STATUS_CODES;
}
@Override
protected Collection<String> getActiveProtocolStatusCodesHook() {
return ACTIVE_PROTOCOL_STATUS_CODES;
}
@Override
protected Collection<String> getRevisionRequestedProtocolActionTypeCodesHook() {
return REVISION_REQUESTED_PROTOCOL_ACTION_TYPE_CODES;
}
@Override
protected Collection<String> getRevisionRequestedProtocolStatusCodesHook() {
return REVISION_REQUESTED_PROTOCOL_STATUS_CODES;
}
@Override
protected Class<? extends ProtocolActionBase> getProtocolActionBOClassHoook() {
return org.kuali.kra.irb.actions.ProtocolAction.class;
}
@Override
protected void initRoleListsHook(List<String> investigatorRoles, List<String> personRoles) {
investigatorRoles.add("PI");
investigatorRoles.add("COI");
personRoles.add("SP");
personRoles.add("CA");
personRoles.add("CRC");
}
@Override
protected Collection<String> getPendingAmendmentRenewalsProtocolStatusCodesHook() {
return PENDING_AMENDMENT_RENEWALS_STATUS_CODES;
}
@Override
protected Class<? extends ProtocolBase> getProtocolBOClassHook() {
return Protocol.class;
}
@Override
protected Class<? extends ProtocolPersonBase> getProtocolPersonBOClassHook() {
return ProtocolPerson.class;
}
@Override
protected Class<? extends ProtocolUnitBase> getProtocolUnitBOClassHook() {
return ProtocolUnit.class;
}
@Override
protected Class<? extends ProtocolSubmissionBase> getProtocolSubmissionBOClassHook() {
return ProtocolSubmission.class;
}
@Override
protected List<CriteriaFieldHelper> getCriteriaFields() {
List<CriteriaFieldHelper> criteriaFields = new ArrayList<CriteriaFieldHelper>();
criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.KEY_PERSON,
ProtocolLookupConstants.Property.PERSON_NAME,
ProtocolPerson.class));
criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.INVESTIGATOR,
ProtocolLookupConstants.Property.PERSON_NAME,
ProtocolPerson.class));
criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.FUNDING_SOURCE,
ProtocolLookupConstants.Property.FUNDING_SOURCE_NUMBER,
ProtocolFundingSource.class));
criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.PERFORMING_ORGANIZATION_ID,
ProtocolLookupConstants.Property.ORGANIZATION_ID,
ProtocolLocation.class));
criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.RESEARCH_AREA_CODE,
ProtocolLookupConstants.Property.RESEARCH_AREA_CODE,
ProtocolResearchArea.class));
return criteriaFields;
}
}
| vivantech/kc_fixes | src/main/java/org/kuali/kra/irb/ProtocolDaoOjb.java | Java | apache-2.0 | 6,383 |
/**
* Copyright (c) 2005-20010 springside.org.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* $Id: PropertyFilter.java 1205 2010-09-09 15:12:17Z calvinxiu $
*/
package com.snakerflow.framework.orm;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import com.snakerflow.framework.utils.ConvertUtils;
import com.snakerflow.framework.utils.ServletUtils;
import org.springframework.util.Assert;
/**
* 与具体ORM实现无关的属性过滤条件封装类, 主要记录页面中简单的搜索过滤条件.
*
* @author calvin
*/
public class PropertyFilter {
/** 多个属性间OR关系的分隔符. */
public static final String OR_SEPARATOR = "_OR_";
/** 属性比较类型. */
public enum MatchType {
EQ, LIKE, LT, GT, LE, GE;
}
/** 属性数据类型. */
public enum PropertyType {
S(String.class), I(Integer.class), L(Long.class), N(Double.class), D(Date.class), B(Boolean.class);
private Class<?> clazz;
private PropertyType(Class<?> clazz) {
this.clazz = clazz;
}
public Class<?> getValue() {
return clazz;
}
}
private MatchType matchType = null;
private Object matchValue = null;
private Class<?> propertyClass = null;
private String[] propertyNames = null;
public PropertyFilter() {
}
/**
* @param filterName 比较属性字符串,含待比较的比较类型、属性值类型及属性列表.
* eg. LIKES_NAME_OR_LOGIN_NAME
* @param value 待比较的值.
*/
public PropertyFilter(final String filterName, final String value) {
String firstPart = StringUtils.substringBefore(filterName, "_");
String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1);
String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length());
try {
matchType = Enum.valueOf(MatchType.class, matchTypeCode);
} catch (RuntimeException e) {
throw new IllegalArgumentException("filter名称" + filterName + "没有按规则编写,无法得到属性比较类型.", e);
}
try {
propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
} catch (RuntimeException e) {
throw new IllegalArgumentException("filter名称" + filterName + "没有按规则编写,无法得到属性值类型.", e);
}
String propertyNameStr = StringUtils.substringAfter(filterName, "_");
Assert.isTrue(StringUtils.isNotBlank(propertyNameStr), "filter名称" + filterName + "没有按规则编写,无法得到属性名称.");
propertyNames = StringUtils.splitByWholeSeparator(propertyNameStr, PropertyFilter.OR_SEPARATOR);
this.matchValue = ConvertUtils.convertStringToObject(value, propertyClass);
}
/**
* 从HttpRequest中创建PropertyFilter列表, 默认Filter属性名前缀为filter.
*
* @see #buildFromHttpRequest(HttpServletRequest, String)
*/
public static List<PropertyFilter> buildFromHttpRequest(final HttpServletRequest request) {
return buildFromHttpRequest(request, "filter");
}
/**
* 从HttpRequest中创建PropertyFilter列表
* PropertyFilter命名规则为Filter属性前缀_比较类型属性类型_属性名.
*
* eg.
* filter_EQS_name
* filter_LIKES_name_OR_email
*/
public static List<PropertyFilter> buildFromHttpRequest(final HttpServletRequest request, final String filterPrefix) {
List<PropertyFilter> filterList = new ArrayList<PropertyFilter>();
//从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map.
Map<String, Object> filterParamMap = ServletUtils.getParametersStartingWith(request, filterPrefix + "_");
//分析参数Map,构造PropertyFilter列表
for (Map.Entry<String, Object> entry : filterParamMap.entrySet()) {
String filterName = entry.getKey();
String value = (String) entry.getValue();
//如果value值为空,则忽略此filter.
if (StringUtils.isNotBlank(value)) {
PropertyFilter filter = new PropertyFilter(filterName, value);
filterList.add(filter);
}
}
return filterList;
}
/**
* 获取比较值的类型.
*/
public Class<?> getPropertyClass() {
return propertyClass;
}
/**
* 获取比较方式.
*/
public MatchType getMatchType() {
return matchType;
}
/**
* 获取比较值.
*/
public Object getMatchValue() {
return matchValue;
}
/**
* 获取比较属性名称列表.
*/
public String[] getPropertyNames() {
return propertyNames;
}
/**
* 获取唯一的比较属性名称.
*/
public String getPropertyName() {
Assert.isTrue(propertyNames.length == 1, "There are not only one property in this filter.");
return propertyNames[0];
}
/**
* 是否比较多个属性.
*/
public boolean hasMultiProperties() {
return (propertyNames.length > 1);
}
}
| snakerflow/snaker-web | src/main/java/com/snakerflow/framework/orm/PropertyFilter.java | Java | apache-2.0 | 4,884 |
/*
* Copyright 2019 MovingBlocks
*
* 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.terasology.gestalt.module.exceptions;
/**
* Exception for when metadata cannot be resolved for a module
*/
public class MissingModuleMetadataException extends RuntimeException {
public MissingModuleMetadataException() {
}
public MissingModuleMetadataException(String s) {
super(s);
}
public MissingModuleMetadataException(String s, Throwable throwable) {
super(s, throwable);
}
}
| immortius/gestalt | gestalt-module/src/main/java/org/terasology/gestalt/module/exceptions/MissingModuleMetadataException.java | Java | apache-2.0 | 1,036 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro;
/** Thrown for errors building schemas. */
public class SchemaBuilderException extends AvroRuntimeException {
public SchemaBuilderException(Throwable cause) {
super(cause);
}
public SchemaBuilderException(String message) {
super(message);
}
}
| apache/avro | lang/java/avro/src/main/java/org/apache/avro/SchemaBuilderException.java | Java | apache-2.0 | 1,094 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.fn.harness.state;
import static org.junit.Assert.assertArrayEquals;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.protobuf.ByteString;
import java.io.IOException;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link MultimapSideInput}. */
@RunWith(JUnit4.class)
public class MultimapSideInputTest {
@Test
public void testGet() throws Exception {
FakeBeamFnStateClient fakeBeamFnStateClient = new FakeBeamFnStateClient(ImmutableMap.of(
key("A"), encode("A1", "A2", "A3"),
key("B"), encode("B1", "B2")));
MultimapSideInput<String, String> multimapSideInput = new MultimapSideInput<>(
fakeBeamFnStateClient,
"instructionId",
"ptransformId",
"sideInputId",
ByteString.copyFromUtf8("encodedWindow"),
StringUtf8Coder.of(),
StringUtf8Coder.of());
assertArrayEquals(new String[]{ "A1", "A2", "A3" },
Iterables.toArray(multimapSideInput.get("A"), String.class));
assertArrayEquals(new String[]{ "B1", "B2" },
Iterables.toArray(multimapSideInput.get("B"), String.class));
assertArrayEquals(new String[]{ },
Iterables.toArray(multimapSideInput.get("unknown"), String.class));
}
private StateKey key(String id) throws IOException {
return StateKey.newBuilder().setMultimapSideInput(
StateKey.MultimapSideInput.newBuilder()
.setPtransformId("ptransformId")
.setSideInputId("sideInputId")
.setWindow(ByteString.copyFromUtf8("encodedWindow"))
.setKey(encode(id))).build();
}
private ByteString encode(String ... values) throws IOException {
ByteString.Output out = ByteString.newOutput();
for (String value : values) {
StringUtf8Coder.of().encode(value, out);
}
return out.toByteString();
}
}
| tgroh/incubator-beam | sdks/java/harness/src/test/java/org/apache/beam/fn/harness/state/MultimapSideInputTest.java | Java | apache-2.0 | 2,861 |
package com.mc.phonefinder.usersettings;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.mc.phonefinder.R;
import com.mc.phonefinder.login.FindPhoneActivity;
import com.mc.phonefinder.login.SampleApplication;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.io.Serializable;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
public class FindPhoneInterface extends ActionBarActivity {
/*
For the below: check if the setting is set for the user and if so let the user use the functionality.
View location - Referes to location column in Settings table
Show Phone finder image - Displays the image of the person who find the phone
View nearby users - Refers to otherUsers in Settings table
Alert my phone - Rings the phone to easily identify it
*/
static final boolean[] nearByUserSetting = new boolean[1];
static final boolean[] locationSetting = new boolean[1];
AtomicBoolean nearByUserSetting_check = new AtomicBoolean();
AtomicBoolean locPrefs_check = new AtomicBoolean();
public static String test = "Class";
static final String TAG="bharathdebug";
public void savePrefs(String key, boolean value)
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putBoolean(key, value);
edit.commit();
}
public boolean loadBoolPrefs(String key)
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean cbVal = sp.getBoolean(key, false);
return cbVal;
}
public void savePrefs(String key, String value)
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_phone_interface);
final String ObjectId = (String)this.getIntent().getSerializableExtra("userObjectId");
nearByUserSetting[0] = false;
locationSetting[0] = false;
savePrefs("nearByUserSetting", false);
savePrefs("locationSetting", false);
Log.i(TAG,"Before inner class"+test);
// final String ObjectId = (String)this.getIntent().getSerializableExtra("userObjectId");
ParseQuery<ParseObject> getSettings = new ParseQuery<ParseObject>("Settings");
getSettings.whereEqualTo("userObjectId", ObjectId);
getSettings.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
if (objects != null) {
Log.i(TAG, "Object not null");
if(objects.size()>0){
// nearByUserSetting[0] = objects.get(0).getBoolean("otherUser");
// locationSetting[0] = objects.get(0).getBoolean("location");
// test = "Inner class";
nearByUserSetting_check.set( objects.get(0).getBoolean("otherUser"));
locPrefs_check.set(objects.get(0).getBoolean("location"));
Log.i(TAG, "Inner class neary by " + String.valueOf(nearByUserSetting_check.get()));
Log.i(TAG,"Inner class Location pref "+ (String.valueOf(locPrefs_check.get())));
//
// savePrefs("nearByUserSetting", nearByUserSetting[0]);
// savePrefs("locationSetting", locationSetting[0]);
}
}
}
});
// nearByUserSetting_check=loadBoolPrefs("nearByUserSetting");
// locPrefs_check = loadBoolPrefs("locationSetting");
//
// Log.i(TAG,"Final val after inner class "+test);
// System.out.print("Camera Setting " + nearByUserSetting[0]);
Log.i(TAG,"Near by user "+ (String.valueOf(nearByUserSetting_check.get())));
Log.i(TAG,"Location pref "+ (String.valueOf(locPrefs_check.get())));
((Button) findViewById(R.id.nearbyUsers)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(nearByUserSetting_check.get()) {
Intent i = new Intent();
savePrefs("findPhoneId", ObjectId);
Log.i(TAG, "FindPhoneInterface Object id " + ObjectId);
i.setClass(FindPhoneInterface.this, NearbyUserView.class);
//i.putExtra("userObjectId", ObjectId);
startActivity(i);
startActivity(new Intent(FindPhoneInterface.this, NearbyUserView.class));
}
else
{
Toast.makeText(FindPhoneInterface.this, "Find nearby user service not set ", Toast.LENGTH_SHORT).show();
}
}
});
((Button) findViewById(R.id.viewLocation)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(locPrefs_check.get()) {
Toast.makeText(FindPhoneInterface.this, "Getting Your Location", Toast.LENGTH_LONG)
.show();
String ObjectId = (String) FindPhoneInterface.this.getIntent().getSerializableExtra("userObjectId");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Location");
if (!ObjectId.equals(null) && !ObjectId.equals("")) {
query.whereEqualTo("userId", ObjectId);
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
ParseGeoPoint userLocation;
for (int i = 0; i < objects.size(); i++) {
userLocation = objects.get(i).getParseGeoPoint("location");
String uri = String.format(Locale.ENGLISH, "geo:%f,%f?q=%f,%f", userLocation.getLatitude(), userLocation.getLongitude(), userLocation.getLatitude(), userLocation.getLongitude());
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:%f,%f?q=%f,%f",userLocation.getLatitude(), userLocation.getLongitude(),userLocation.getLatitude(), userLocation.getLongitude()));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
Toast.makeText(FindPhoneInterface.this, "Opening Maps", Toast.LENGTH_LONG)
.show();
}
}
});
}
}
else {
Toast.makeText(FindPhoneInterface.this, "Location Preference service not set ", Toast.LENGTH_SHORT).show();
}
}});
//Bharath - View image of person who picked phone
((Button) findViewById(R.id.btn_phonepicker)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Starts an intent of the log in activity
Log.i(TAG,"Find face object id "+ObjectId);
savePrefs("findfaceObjId",ObjectId);
startActivity(new Intent(FindPhoneInterface.this, ShowPhoneFinderImage.class));
}
});
//Change ringer alert
((Button) findViewById(R.id.triggerAlert)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Settings");
query.whereEqualTo("userObjectId", ObjectId);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> scoreList, ParseException e) {
//get current user
ParseUser user = ParseUser.getCurrentUser();
if (e == null) {
if (scoreList != null) {
if (scoreList.size() > 0) {
//store the location of the user with the objectId of the user
scoreList.get(0).put("alertPhone", true);
scoreList.get(0).saveInBackground();
Toast.makeText(FindPhoneInterface.this, "Phone Alerted", Toast.LENGTH_LONG)
.show();
}
} else {
ParseObject alertVal = new ParseObject("Settings");
alertVal.put("userObjectId", ObjectId);
alertVal.put("alertPhone", true);
scoreList.get(0).saveInBackground();
Toast.makeText(FindPhoneInterface.this, "Phone Alerted", Toast.LENGTH_LONG)
.show();
}
}
}
});
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_find_phone_interface, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| Rakesh627/PhoneFinder | ParseStarterProject/src/main/java/com/mc/phonefinder/usersettings/FindPhoneInterface.java | Java | apache-2.0 | 10,791 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.UUID;
import org.apache.geode.annotations.Immutable;
import org.apache.geode.cache.DiskStore;
import org.apache.geode.cache.DiskStoreFactory;
import org.apache.geode.internal.cache.persistence.DefaultDiskDirs;
/**
* Creates an attribute object for DiskStore.
* </p>
*
* @since GemFire prPersistSprint2
*/
public class DiskStoreAttributes implements Serializable, DiskStore {
private static final long serialVersionUID = 1L;
public boolean allowForceCompaction;
public boolean autoCompact;
public int compactionThreshold;
public int queueSize;
public int writeBufferSize;
public long maxOplogSizeInBytes;
public long timeInterval;
public int[] diskDirSizes;
private DiskDirSizesUnit diskDirSizesUnit;
public File[] diskDirs;
public String name;
private volatile float diskUsageWarningPct;
private volatile float diskUsageCriticalPct;
/**
* The default disk directory size unit.
*/
@Immutable
static final DiskDirSizesUnit DEFAULT_DISK_DIR_SIZES_UNIT = DiskDirSizesUnit.MEGABYTES;
public DiskStoreAttributes() {
// set all to defaults
autoCompact = DiskStoreFactory.DEFAULT_AUTO_COMPACT;
compactionThreshold = DiskStoreFactory.DEFAULT_COMPACTION_THRESHOLD;
allowForceCompaction = DiskStoreFactory.DEFAULT_ALLOW_FORCE_COMPACTION;
maxOplogSizeInBytes = DiskStoreFactory.DEFAULT_MAX_OPLOG_SIZE * (1024 * 1024);
timeInterval = DiskStoreFactory.DEFAULT_TIME_INTERVAL;
writeBufferSize = DiskStoreFactory.DEFAULT_WRITE_BUFFER_SIZE;
queueSize = DiskStoreFactory.DEFAULT_QUEUE_SIZE;
diskDirs = DefaultDiskDirs.getDefaultDiskDirs();
diskDirSizes = DiskStoreFactory.DEFAULT_DISK_DIR_SIZES;
diskDirSizesUnit = DEFAULT_DISK_DIR_SIZES_UNIT;
diskUsageWarningPct = DiskStoreFactory.DEFAULT_DISK_USAGE_WARNING_PERCENTAGE;
diskUsageCriticalPct = DiskStoreFactory.DEFAULT_DISK_USAGE_CRITICAL_PERCENTAGE;
}
@Override
public UUID getDiskStoreUUID() {
throw new UnsupportedOperationException("Not Implemented!");
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getAllowForceCompaction()
*/
@Override
public boolean getAllowForceCompaction() {
return allowForceCompaction;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getAutoCompact()
*/
@Override
public boolean getAutoCompact() {
return autoCompact;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getCompactionThreshold()
*/
@Override
public int getCompactionThreshold() {
return compactionThreshold;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getDiskDirSizes()
*/
@Override
public int[] getDiskDirSizes() {
int[] result = new int[diskDirSizes.length];
System.arraycopy(diskDirSizes, 0, result, 0, diskDirSizes.length);
return result;
}
public DiskDirSizesUnit getDiskDirSizesUnit() {
return diskDirSizesUnit;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getDiskDirs()
*/
@Override
public File[] getDiskDirs() {
File[] result = new File[diskDirs.length];
System.arraycopy(diskDirs, 0, result, 0, diskDirs.length);
return result;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getMaxOplogSize()
*/
@Override
public long getMaxOplogSize() {
return maxOplogSizeInBytes / (1024 * 1024);
}
/**
* Used by unit tests
*/
public long getMaxOplogSizeInBytes() {
return maxOplogSizeInBytes;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getName()
*/
@Override
public String getName() {
return name;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getQueueSize()
*/
@Override
public int getQueueSize() {
return queueSize;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getTimeInterval()
*/
@Override
public long getTimeInterval() {
return timeInterval;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getWriteBufferSize()
*/
@Override
public int getWriteBufferSize() {
return writeBufferSize;
}
@Override
public void flush() {
// nothing needed
}
@Override
public void forceRoll() {
// nothing needed
}
@Override
public boolean forceCompaction() {
return false;
}
@Override
public void destroy() {
// nothing needed
}
@Override
public float getDiskUsageWarningPercentage() {
return diskUsageWarningPct;
}
@Override
public float getDiskUsageCriticalPercentage() {
return diskUsageCriticalPct;
}
@Override
public void setDiskUsageWarningPercentage(float warningPercent) {
DiskStoreMonitor.checkWarning(warningPercent);
diskUsageWarningPct = warningPercent;
}
@Override
public void setDiskUsageCriticalPercentage(float criticalPercent) {
DiskStoreMonitor.checkCritical(criticalPercent);
diskUsageCriticalPct = criticalPercent;
}
public void setDiskDirSizesUnit(DiskDirSizesUnit unit) {
diskDirSizesUnit = unit;
}
private void readObject(final java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (diskDirSizesUnit == null) {
diskDirSizesUnit = DEFAULT_DISK_DIR_SIZES_UNIT;
}
}
public static void checkMinAndMaxOplogSize(long maxOplogSize) {
long MAX = Long.MAX_VALUE / (1024 * 1024);
if (maxOplogSize > MAX) {
throw new IllegalArgumentException(
String.format(
"%s has to be a number that does not exceed %s so the value given %s is not acceptable",
"max oplog size", maxOplogSize, MAX));
}
checkMinOplogSize(maxOplogSize);
}
public static void checkMinOplogSize(long maxOplogSize) {
if (maxOplogSize < 0) {
throw new IllegalArgumentException(
String.format(
"Maximum Oplog size specified has to be a non-negative number and the value given %s is not acceptable",
maxOplogSize));
}
}
public static void checkQueueSize(int queueSize) {
if (queueSize < 0) {
throw new IllegalArgumentException(
String.format(
"Queue size specified has to be a non-negative number and the value given %s is not acceptable",
queueSize));
}
}
public static void checkWriteBufferSize(int writeBufferSize) {
if (writeBufferSize < 0) {
throw new IllegalArgumentException(
String.format(
"Write buffer size specified has to be a non-negative number and the value given %s is not acceptable",
writeBufferSize));
}
}
/**
* Verify all directory sizes are positive
*/
public static void verifyNonNegativeDirSize(int[] sizes) {
for (int size : sizes) {
if (size < 0) {
throw new IllegalArgumentException(
String.format("Dir size cannot be negative : %s",
size));
}
}
}
public static void checkTimeInterval(long timeInterval) {
if (timeInterval < 0) {
throw new IllegalArgumentException(
String.format(
"Time Interval specified has to be a non-negative number and the value given %s is not acceptable",
timeInterval));
}
}
}
| jdeppe-pivotal/geode | geode-core/src/main/java/org/apache/geode/internal/cache/DiskStoreAttributes.java | Java | apache-2.0 | 8,257 |
/*
* SVG Salamander
* Copyright (c) 2004, Mark McKay
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Mark McKay can be contacted at mark@kitfox.com. Salamander and other
* projects can be found at http://www.kitfox.com
*
* Created on January 26, 2004, 8:40 PM
*/
package com.kitfox.svg.pathcmd;
//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath;
import java.awt.*;
import java.awt.geom.*;
/**
* This is a little used SVG function, as most editors will save curves as
* Beziers. To reduce the need to rely on the Batik library, this functionallity
* is being bypassed for the time being. In the future, it would be nice to
* extend the GeneralPath command to include the arcTo ability provided by Batik.
*
* @author Mark McKay
* @author <a href="mailto:mark@kitfox.com">Mark McKay</a>
*/
public class Arc extends PathCommand
{
public float rx = 0f;
public float ry = 0f;
public float xAxisRot = 0f;
public boolean largeArc = false;
public boolean sweep = false;
public float x = 0f;
public float y = 0f;
/** Creates a new instance of MoveTo */
public Arc() {
}
public Arc(boolean isRelative, float rx, float ry, float xAxisRot, boolean largeArc, boolean sweep, float x, float y) {
super(isRelative);
this.rx = rx;
this.ry = ry;
this.xAxisRot = xAxisRot;
this.largeArc = largeArc;
this.sweep = sweep;
this.x = x;
this.y = y;
}
// public void appendPath(ExtendedGeneralPath path, BuildHistory hist)
@Override
public void appendPath(GeneralPath path, BuildHistory hist)
{
float offx = isRelative ? hist.lastPoint.x : 0f;
float offy = isRelative ? hist.lastPoint.y : 0f;
arcTo(path, rx, ry, xAxisRot, largeArc, sweep,
x + offx, y + offy,
hist.lastPoint.x, hist.lastPoint.y);
// path.lineTo(x + offx, y + offy);
// hist.setPoint(x + offx, y + offy);
hist.setLastPoint(x + offx, y + offy);
hist.setLastKnot(x + offx, y + offy);
}
@Override
public int getNumKnotsAdded()
{
return 6;
}
/**
* Adds an elliptical arc, defined by two radii, an angle from the
* x-axis, a flag to choose the large arc or not, a flag to
* indicate if we increase or decrease the angles and the final
* point of the arc.
*
* @param rx the x radius of the ellipse
* @param ry the y radius of the ellipse
*
* @param angle the angle from the x-axis of the current
* coordinate system to the x-axis of the ellipse in degrees.
*
* @param largeArcFlag the large arc flag. If true the arc
* spanning less than or equal to 180 degrees is chosen, otherwise
* the arc spanning greater than 180 degrees is chosen
*
* @param sweepFlag the sweep flag. If true the line joining
* center to arc sweeps through decreasing angles otherwise it
* sweeps through increasing angles
*
* @param x the absolute x coordinate of the final point of the arc.
* @param y the absolute y coordinate of the final point of the arc.
* @param x0 - The absolute x coordinate of the initial point of the arc.
* @param y0 - The absolute y coordinate of the initial point of the arc.
*/
public void arcTo(GeneralPath path, float rx, float ry,
float angle,
boolean largeArcFlag,
boolean sweepFlag,
float x, float y, float x0, float y0)
{
// Ensure radii are valid
if (rx == 0 || ry == 0) {
path.lineTo((float) x, (float) y);
return;
}
if (x0 == x && y0 == y) {
// If the endpoints (x, y) and (x0, y0) are identical, then this
// is equivalent to omitting the elliptical arc segment entirely.
return;
}
Arc2D arc = computeArc(x0, y0, rx, ry, angle,
largeArcFlag, sweepFlag, x, y);
if (arc == null) return;
AffineTransform t = AffineTransform.getRotateInstance
(Math.toRadians(angle), arc.getCenterX(), arc.getCenterY());
Shape s = t.createTransformedShape(arc);
path.append(s, true);
}
/**
* This constructs an unrotated Arc2D from the SVG specification of an
* Elliptical arc. To get the final arc you need to apply a rotation
* transform such as:
*
* AffineTransform.getRotateInstance
* (angle, arc.getX()+arc.getWidth()/2, arc.getY()+arc.getHeight()/2);
*/
public static Arc2D computeArc(double x0, double y0,
double rx, double ry,
double angle,
boolean largeArcFlag,
boolean sweepFlag,
double x, double y) {
//
// Elliptical arc implementation based on the SVG specification notes
//
// Compute the half distance between the current and the final point
double dx2 = (x0 - x) / 2.0;
double dy2 = (y0 - y) / 2.0;
// Convert angle from degrees to radians
angle = Math.toRadians(angle % 360.0);
double cosAngle = Math.cos(angle);
double sinAngle = Math.sin(angle);
//
// Step 1 : Compute (x1, y1)
//
double x1 = (cosAngle * dx2 + sinAngle * dy2);
double y1 = (-sinAngle * dx2 + cosAngle * dy2);
// Ensure radii are large enough
rx = Math.abs(rx);
ry = Math.abs(ry);
double Prx = rx * rx;
double Pry = ry * ry;
double Px1 = x1 * x1;
double Py1 = y1 * y1;
// check that radii are large enough
double radiiCheck = Px1/Prx + Py1/Pry;
if (radiiCheck > 1) {
rx = Math.sqrt(radiiCheck) * rx;
ry = Math.sqrt(radiiCheck) * ry;
Prx = rx * rx;
Pry = ry * ry;
}
//
// Step 2 : Compute (cx1, cy1)
//
double sign = (largeArcFlag == sweepFlag) ? -1 : 1;
double sq = ((Prx*Pry)-(Prx*Py1)-(Pry*Px1)) / ((Prx*Py1)+(Pry*Px1));
sq = (sq < 0) ? 0 : sq;
double coef = (sign * Math.sqrt(sq));
double cx1 = coef * ((rx * y1) / ry);
double cy1 = coef * -((ry * x1) / rx);
//
// Step 3 : Compute (cx, cy) from (cx1, cy1)
//
double sx2 = (x0 + x) / 2.0;
double sy2 = (y0 + y) / 2.0;
double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1);
double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1);
//
// Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle)
//
double ux = (x1 - cx1) / rx;
double uy = (y1 - cy1) / ry;
double vx = (-x1 - cx1) / rx;
double vy = (-y1 - cy1) / ry;
double p, n;
// Compute the angle start
n = Math.sqrt((ux * ux) + (uy * uy));
p = ux; // (1 * ux) + (0 * uy)
sign = (uy < 0) ? -1d : 1d;
double angleStart = Math.toDegrees(sign * Math.acos(p / n));
// Compute the angle extent
n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy));
p = ux * vx + uy * vy;
sign = (ux * vy - uy * vx < 0) ? -1d : 1d;
double angleExtent = Math.toDegrees(sign * Math.acos(p / n));
if(!sweepFlag && angleExtent > 0) {
angleExtent -= 360f;
} else if (sweepFlag && angleExtent < 0) {
angleExtent += 360f;
}
angleExtent %= 360f;
angleStart %= 360f;
//
// We can now build the resulting Arc2D in double precision
//
Arc2D.Double arc = new Arc2D.Double();
arc.x = cx - rx;
arc.y = cy - ry;
arc.width = rx * 2.0;
arc.height = ry * 2.0;
arc.start = -angleStart;
arc.extent = -angleExtent;
return arc;
}
@Override
public String toString()
{
return "A " + rx + " " + ry
+ " " + xAxisRot + " " + largeArc
+ " " + sweep
+ " " + x + " " + y;
}
}
| Longri/cachebox3.0 | launcher/desktop_lwjgl/src/com/kitfox/svg/pathcmd/Arc.java | Java | apache-2.0 | 9,856 |
/*
* Copyright (c) 2008-2020, Hazelcast, 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 com.hazelcast.cache;
import com.hazelcast.cache.impl.CachePartitionEventData;
import com.hazelcast.cache.impl.CachePartitionSegment;
import com.hazelcast.cache.impl.CacheService;
import com.hazelcast.cache.impl.operation.CacheReplicationOperation;
import com.hazelcast.cache.impl.record.CacheRecord;
import com.hazelcast.cache.impl.record.CacheRecordFactory;
import com.hazelcast.cluster.Address;
import com.hazelcast.cluster.Member;
import com.hazelcast.cluster.impl.MemberImpl;
import com.hazelcast.config.InMemoryFormat;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.instance.impl.HazelcastInstanceImpl;
import com.hazelcast.instance.impl.HazelcastInstanceProxy;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.internal.serialization.SerializationService;
import com.hazelcast.internal.serialization.SerializationServiceBuilder;
import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder;
import com.hazelcast.internal.services.ServiceNamespace;
import com.hazelcast.internal.util.Clock;
import com.hazelcast.internal.util.CollectionUtil;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.version.MemberVersion;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.configuration.CompleteConfiguration;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider;
import java.lang.reflect.Field;
import java.net.UnknownHostException;
import java.util.Collection;
import static com.hazelcast.cache.CacheTestSupport.createServerCachingProvider;
import static org.junit.Assert.assertEquals;
/**
* Serialization test class for JCache
*/
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class CacheSerializationTest extends HazelcastTestSupport {
SerializationService service;
@Before
public void setup() {
SerializationServiceBuilder builder = new DefaultSerializationServiceBuilder();
service = builder.build();
}
@After
public void tearDown() {
}
@Test
public void testCacheRecord_withBinaryInMemoryData() {
String value = randomString();
CacheRecord cacheRecord = createRecord(InMemoryFormat.BINARY, value);
Data cacheRecordData = service.toData(cacheRecord);
CacheRecord deserialized = service.toObject(cacheRecordData);
assertEquals(value, service.toObject(deserialized.getValue()));
}
@Test
public void testCacheRecord_withObjectInMemoryData() {
String value = randomString();
CacheRecord cacheRecord = createRecord(InMemoryFormat.OBJECT, value);
Data cacheRecordData = service.toData(cacheRecord);
CacheRecord deserialized = service.toObject(cacheRecordData);
assertEquals(value, deserialized.getValue());
}
@Test
public void test_CacheReplicationOperation_serialization() throws Exception {
TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);
HazelcastInstance hazelcastInstance = factory.newHazelcastInstance();
try {
CachingProvider provider = createServerCachingProvider(hazelcastInstance);
CacheManager manager = provider.getCacheManager();
CompleteConfiguration configuration = new MutableConfiguration();
Cache cache1 = manager.createCache("cache1", configuration);
Cache cache2 = manager.createCache("cache2", configuration);
Cache cache3 = manager.createCache("cache3", configuration);
for (int i = 0; i < 1000; i++) {
cache1.put("key" + i, i);
cache2.put("key" + i, i);
cache3.put("key" + i, i);
}
HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) hazelcastInstance;
Field original = HazelcastInstanceProxy.class.getDeclaredField("original");
original.setAccessible(true);
HazelcastInstanceImpl impl = (HazelcastInstanceImpl) original.get(proxy);
NodeEngineImpl nodeEngine = impl.node.nodeEngine;
CacheService cacheService = nodeEngine.getService(CacheService.SERVICE_NAME);
int partitionCount = nodeEngine.getPartitionService().getPartitionCount();
for (int partitionId = 0; partitionId < partitionCount; partitionId++) {
CachePartitionSegment segment = cacheService.getSegment(partitionId);
int replicaIndex = 1;
Collection<ServiceNamespace> namespaces = segment.getAllNamespaces(replicaIndex);
if (CollectionUtil.isEmpty(namespaces)) {
continue;
}
CacheReplicationOperation operation = new CacheReplicationOperation();
operation.prepare(segment, namespaces, replicaIndex);
Data serialized = service.toData(operation);
try {
service.toObject(serialized);
} catch (Exception e) {
throw new Exception("Partition: " + partitionId, e);
}
}
} finally {
factory.shutdownAll();
}
}
@Test
public void testCachePartitionEventData() throws UnknownHostException {
Address address = new Address("127.0.0.1", 5701);
Member member = new MemberImpl(address, MemberVersion.UNKNOWN, true);
CachePartitionEventData cachePartitionEventData = new CachePartitionEventData("test", 1, member);
CachePartitionEventData deserialized = service.toObject(cachePartitionEventData);
assertEquals(cachePartitionEventData, deserialized);
}
private CacheRecord createRecord(InMemoryFormat format, String value) {
CacheRecordFactory factory = new CacheRecordFactory(format, service);
return factory.newRecordWithExpiry(value, Clock.currentTimeMillis(), -1);
}
}
| mdogan/hazelcast | hazelcast/src/test/java/com/hazelcast/cache/CacheSerializationTest.java | Java | apache-2.0 | 7,031 |
package com.sean.im.client.push.handler;
import com.alibaba.fastjson.JSON;
import com.sean.im.client.constant.Global;
import com.sean.im.client.core.ApplicationContext;
import com.sean.im.client.core.PushHandler;
import com.sean.im.client.form.MainForm;
import com.sean.im.client.tray.TrayManager;
import com.sean.im.client.util.MusicUtil;
import com.sean.im.commom.core.Protocol;
import com.sean.im.commom.entity.Message;
/**
* 移除群成员
* @author sean
*/
public class KickOutFlockHandler implements PushHandler
{
@Override
public void execute(Protocol notify)
{
Message msg = JSON.parseObject(notify.getParameter("msg"), Message.class);
// 界面上删除群
long flockId = Long.parseLong(msg.getContent());
MainForm.FORM.getFlockList().removeFlock(flockId);
// 压入消息队列
ApplicationContext.CTX.getMessageQueue().add(msg);
// 提示系统托盘闪烁
TrayManager.getInstance().startLight(0);
MusicUtil.play(Global.Root + "resource/sound/msg.wav");
}
}
| seanzwx/tmp | seatalk/im/im-client/src/main/java/com/sean/im/client/push/handler/KickOutFlockHandler.java | Java | apache-2.0 | 1,004 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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 com.intellij.psi.impl.cache.impl.idCache;
import com.intellij.lexer.Lexer;
import com.intellij.lexer.XHtmlHighlightingLexer;
import com.intellij.psi.impl.cache.impl.BaseFilterLexer;
import com.intellij.psi.impl.cache.impl.id.LexerBasedIdIndexer;
public class XHtmlIdIndexer extends LexerBasedIdIndexer {
protected Lexer createLexer(final BaseFilterLexer.OccurrenceConsumer consumer) {
return new XHtmlFilterLexer(new XHtmlHighlightingLexer(), consumer);
}
}
| jexp/idea2 | xml/impl/src/com/intellij/psi/impl/cache/impl/idCache/XHtmlIdIndexer.java | Java | apache-2.0 | 1,077 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.synapse.deployers;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.deployment.DeploymentException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.Startup;
import org.apache.synapse.config.xml.MultiXMLConfigurationBuilder;
import org.apache.synapse.config.xml.StartupFinder;
import java.io.File;
import java.util.Properties;
/**
* Handles the <code>Startup Task</code> deployment and undeployment
*
* @see org.apache.synapse.deployers.AbstractSynapseArtifactDeployer
*/
public class TaskDeployer extends AbstractSynapseArtifactDeployer {
private static Log log = LogFactory.getLog(TaskDeployer.class);
@Override
public String deploySynapseArtifact(OMElement artifactConfig, String fileName, Properties properties) {
if (log.isDebugEnabled()) {
log.debug("StartupTask Deployment from file : " + fileName + " : Started");
}
try {
Startup st = StartupFinder.getInstance().getStartup(artifactConfig, properties);
st.setFileName((new File(fileName)).getName());
if (log.isDebugEnabled()) {
log.debug("StartupTask named '" + st.getName()
+ "' has been built from the file " + fileName);
}
st.init(getSynapseEnvironment());
if (log.isDebugEnabled()) {
log.debug("Initialized the StartupTask : " + st.getName());
}
getSynapseConfiguration().addStartup(st);
if (log.isDebugEnabled()) {
log.debug("StartupTask Deployment from file : " + fileName + " : Completed");
}
log.info("StartupTask named '" + st.getName()
+ "' has been deployed from file : " + fileName);
return st.getName();
} catch (Exception e) {
handleSynapseArtifactDeploymentError(
"StartupTask Deployment from the file : " + fileName + " : Failed.", e);
}
return null;
}
@Override
public String updateSynapseArtifact(OMElement artifactConfig, String fileName,
String existingArtifactName, Properties properties) {
if (log.isDebugEnabled()) {
log.debug("StartupTask update from file : " + fileName + " has started");
}
try {
Startup st = StartupFinder.getInstance().getStartup(artifactConfig, properties);
st.setFileName((new File(fileName)).getName());
if (log.isDebugEnabled()) {
log.debug("StartupTask: " + st.getName() + " has been built from the file: " + fileName);
}
Startup existingSt = getSynapseConfiguration().getStartup(existingArtifactName);
existingSt.destroy();
st.init(getSynapseEnvironment());
if (existingArtifactName.equals(st.getName())) {
getSynapseConfiguration().updateStartup(st);
} else {
getSynapseConfiguration().addStartup(st);
getSynapseConfiguration().removeStartup(existingArtifactName);
log.info("StartupTask: " + existingArtifactName + " has been undeployed");
}
log.info("StartupTask: " + st.getName() + " has been updated from the file: " + fileName);
return st.getName();
} catch (DeploymentException e) {
handleSynapseArtifactDeploymentError("Error while updating the startup task from the " +
"file: " + fileName);
}
return null;
}
@Override
public void undeploySynapseArtifact(String artifactName) {
if (log.isDebugEnabled()) {
log.debug("StartupTask Undeployment of the task named : "
+ artifactName + " : Started");
}
try {
Startup st = getSynapseConfiguration().getStartup(artifactName);
if (st != null) {
getSynapseConfiguration().removeStartup(artifactName);
if (log.isDebugEnabled()) {
log.debug("Destroying the StartupTask named : " + artifactName);
}
st.destroy();
if (log.isDebugEnabled()) {
log.debug("StartupTask Undeployment of the sequence named : "
+ artifactName + " : Completed");
}
log.info("StartupTask named '" + st.getName() + "' has been undeployed");
} else if (log.isDebugEnabled()) {
log.debug("Startup task " + artifactName + " has already been undeployed");
}
} catch (Exception e) {
handleSynapseArtifactDeploymentError(
"StartupTask Undeployement of task named : " + artifactName + " : Failed", e);
}
}
@Override
public void restoreSynapseArtifact(String artifactName) {
if (log.isDebugEnabled()) {
log.debug("Restoring the StartupTask with name : " + artifactName + " : Started");
}
try {
Startup st = getSynapseConfiguration().getStartup(artifactName);
OMElement stElem = StartupFinder.getInstance().serializeStartup(null, st);
if (st.getFileName() != null) {
String fileName = getServerConfigurationInformation().getSynapseXMLLocation()
+ File.separator + MultiXMLConfigurationBuilder.TASKS_DIR
+ File.separator + st.getFileName();
writeToFile(stElem, fileName);
if (log.isDebugEnabled()) {
log.debug("Restoring the StartupTask with name : " + artifactName + " : Completed");
}
log.info("StartupTask named '" + artifactName + "' has been restored");
} else {
handleSynapseArtifactDeploymentError("Couldn't restore the StartupTask named '"
+ artifactName + "', filename cannot be found");
}
} catch (Exception e) {
handleSynapseArtifactDeploymentError(
"Restoring of the StartupTask named '" + artifactName + "' has failed", e);
}
}
}
| asanka88/apache-synapse | modules/core/src/main/java/org/apache/synapse/deployers/TaskDeployer.java | Java | apache-2.0 | 7,123 |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* 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 com.android.tools.idea.lang.rs;
import com.intellij.lang.ASTNode;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiParser;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
public class RenderscriptParser implements PsiParser {
@NotNull
@Override
public ASTNode parse(IElementType root, PsiBuilder builder) {
final PsiBuilder.Marker rootMarker = builder.mark();
while (!builder.eof()) {
builder.advanceLexer();
}
rootMarker.done(root);
return builder.getTreeBuilt();
}
}
| consulo/consulo-android | android/android/src/com/android/tools/idea/lang/rs/RenderscriptParser.java | Java | apache-2.0 | 1,189 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.wss4j.stax.impl.securityToken;
import org.apache.wss4j.common.bsp.BSPRule;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.UsernameTokenPrincipal;
import org.apache.wss4j.common.util.UsernameTokenUtil;
import org.apache.wss4j.stax.ext.WSInboundSecurityContext;
import org.apache.wss4j.stax.ext.WSSConstants;
import org.apache.wss4j.stax.securityToken.UsernameSecurityToken;
import org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.stax.config.JCEAlgorithmMapper;
import org.apache.xml.security.stax.ext.XMLSecurityConstants;
import org.apache.xml.security.stax.impl.securityToken.AbstractInboundSecurityToken;
import javax.crypto.spec.SecretKeySpec;
import javax.security.auth.Subject;
import java.security.Key;
import java.security.Principal;
public class UsernameSecurityTokenImpl extends AbstractInboundSecurityToken implements UsernameSecurityToken {
private static final long DEFAULT_ITERATION = 1000;
private WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType;
private String username;
private String password;
private String createdTime;
private byte[] nonce;
private byte[] salt;
private Long iteration;
private final WSInboundSecurityContext wsInboundSecurityContext;
private Subject subject;
private Principal principal;
public UsernameSecurityTokenImpl(WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType,
String username, String password, String createdTime, byte[] nonce,
byte[] salt, Long iteration,
WSInboundSecurityContext wsInboundSecurityContext, String id,
WSSecurityTokenConstants.KeyIdentifier keyIdentifier) {
super(wsInboundSecurityContext, id, keyIdentifier, true);
this.usernameTokenPasswordType = usernameTokenPasswordType;
this.username = username;
this.password = password;
this.createdTime = createdTime;
this.nonce = nonce;
this.salt = salt;
this.iteration = iteration;
this.wsInboundSecurityContext = wsInboundSecurityContext;
}
@Override
public boolean isAsymmetric() throws XMLSecurityException {
return false;
}
@Override
protected Key getKey(String algorithmURI, XMLSecurityConstants.AlgorithmUsage algorithmUsage,
String correlationID) throws XMLSecurityException {
Key key = getSecretKey().get(algorithmURI);
if (key != null) {
return key;
}
byte[] secretToken = generateDerivedKey(wsInboundSecurityContext);
String algoFamily = JCEAlgorithmMapper.getJCEKeyAlgorithmFromURI(algorithmURI);
key = new SecretKeySpec(secretToken, algoFamily);
setSecretKey(algorithmURI, key);
return key;
}
@Override
public WSSecurityTokenConstants.TokenType getTokenType() {
return WSSecurityTokenConstants.UsernameToken;
}
/**
* This method generates a derived key as defined in WSS Username
* Token Profile.
*
* @return Returns the derived key a byte array
* @throws WSSecurityException
*/
public byte[] generateDerivedKey() throws WSSecurityException {
return generateDerivedKey(wsInboundSecurityContext);
}
/**
* This method generates a derived key as defined in WSS Username
* Token Profile.
*
* @return Returns the derived key a byte array
* @throws org.apache.wss4j.common.ext.WSSecurityException
*
*/
protected byte[] generateDerivedKey(WSInboundSecurityContext wsInboundSecurityContext) throws WSSecurityException {
if (wsInboundSecurityContext != null) {
if (salt == null || salt.length == 0) {
wsInboundSecurityContext.handleBSPRule(BSPRule.R4217);
}
if (iteration == null || iteration < DEFAULT_ITERATION) {
wsInboundSecurityContext.handleBSPRule(BSPRule.R4218);
}
}
return UsernameTokenUtil.generateDerivedKey(password, salt, iteration.intValue());
}
@Override
public Principal getPrincipal() throws WSSecurityException {
if (this.principal == null) {
this.principal = new UsernameTokenPrincipal() {
//todo passwordType and passwordDigest return Enum-Type ?
@Override
public boolean isPasswordDigest() {
return usernameTokenPasswordType == WSSConstants.UsernameTokenPasswordType.PASSWORD_DIGEST;
}
@Override
public String getPasswordType() {
return usernameTokenPasswordType.getNamespace();
}
@Override
public String getName() {
return username;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getCreatedTime() {
return createdTime;
}
@Override
public byte[] getNonce() {
return nonce;
}
};
}
return this.principal;
}
public WSSConstants.UsernameTokenPasswordType getUsernameTokenPasswordType() {
return usernameTokenPasswordType;
}
public String getCreatedTime() {
return createdTime;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public byte[] getNonce() {
return nonce;
}
public byte[] getSalt() {
return salt;
}
public Long getIteration() {
return iteration;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
@Override
public Subject getSubject() throws WSSecurityException {
return subject;
}
}
| asoldano/wss4j | ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/securityToken/UsernameSecurityTokenImpl.java | Java | apache-2.0 | 7,035 |
/**********************************************************************
Copyright (c) 2005 Erik Bengtson and others.
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.
Contributors:
...
**********************************************************************/
package org.datanucleus.samples.metadata.datastoreidentity;
public class D3
{
private String name;
/**
* @return Returns the name.
*/
public String getName()
{
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name)
{
this.name = name;
}
}
| datanucleus/tests | jdo/general/src/java/org/datanucleus/samples/metadata/datastoreidentity/D3.java | Java | apache-2.0 | 1,143 |
package com.mic.log.spouts;
import java.util.Map;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
public class AppLogWriterSpout extends BaseRichSpout {
private SpoutOutputCollector _collector;
public void open(Map conf, TopologyContext context,
SpoutOutputCollector collector) {
this._collector = collector;
}
@Override
public void nextTuple() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
_collector.emit(new Values("command"));
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("command"));
}
}
| yifzhang/storm-miclog | src/jvm/com/mic/log/spouts/AppLogWriterSpout.java | Java | apache-2.0 | 885 |
package ca.uhn.fhir.cql.dstu3.builder;
/*-
* #%L
* HAPI FHIR JPA Server - Clinical Quality Language
* %%
* Copyright (C) 2014 - 2022 Smile CDR, 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.
* #L%
*/
import ca.uhn.fhir.cql.common.builder.BaseBuilder;
import org.hl7.fhir.dstu3.model.MeasureReport;
import org.hl7.fhir.dstu3.model.Period;
import org.hl7.fhir.dstu3.model.Reference;
import org.hl7.fhir.exceptions.FHIRException;
import org.opencds.cqf.cql.engine.runtime.Interval;
import java.util.Date;
public class MeasureReportBuilder extends BaseBuilder<MeasureReport> {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(MeasureReportBuilder.class);
public MeasureReportBuilder() {
super(new MeasureReport());
}
public MeasureReportBuilder buildStatus(String status) {
try {
this.complexProperty.setStatus(MeasureReport.MeasureReportStatus.fromCode(status));
} catch (FHIRException e) {
ourLog.warn("Exception caught while attempting to set Status to '" + status + "', assuming status COMPLETE!"
+ System.lineSeparator() + e.getMessage());
this.complexProperty.setStatus(MeasureReport.MeasureReportStatus.COMPLETE);
}
return this;
}
public MeasureReportBuilder buildType(MeasureReport.MeasureReportType type) {
this.complexProperty.setType(type);
return this;
}
public MeasureReportBuilder buildMeasureReference(String measureRef) {
this.complexProperty.setMeasure(new Reference(measureRef));
return this;
}
public MeasureReportBuilder buildPatientReference(String patientRef) {
this.complexProperty.setPatient(new Reference(patientRef));
return this;
}
public MeasureReportBuilder buildPeriod(Interval period) {
this.complexProperty.setPeriod(new Period().setStart((Date) period.getStart()).setEnd((Date) period.getEnd()));
return this;
}
}
| jamesagnew/hapi-fhir | hapi-fhir-jpaserver-cql/src/main/java/ca/uhn/fhir/cql/dstu3/builder/MeasureReportBuilder.java | Java | apache-2.0 | 2,503 |
/*
* Copyright (c) 2005 - 2014, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.event.output.adapter.wso2event;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.databridge.agent.AgentHolder;
import org.wso2.carbon.databridge.agent.DataPublisher;
import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException;
import org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException;
import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException;
import org.wso2.carbon.databridge.agent.exception.DataEndpointException;
import org.wso2.carbon.databridge.commons.Event;
import org.wso2.carbon.databridge.commons.exception.TransportException;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapter;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
import org.wso2.carbon.event.output.adapter.core.exception.ConnectionUnavailableException;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterRuntimeException;
import org.wso2.carbon.event.output.adapter.core.exception.TestConnectionNotSupportedException;
import org.wso2.carbon.event.output.adapter.wso2event.internal.util.WSO2EventAdapterConstants;
import java.util.Map;
import static org.wso2.carbon.event.output.adapter.wso2event.internal.util.WSO2EventAdapterConstants.*;
public final class WSO2EventAdapter implements OutputEventAdapter {
private static final Log log = LogFactory.getLog(WSO2EventAdapter.class);
private final OutputEventAdapterConfiguration eventAdapterConfiguration;
private final Map<String, String> globalProperties;
private DataPublisher dataPublisher = null;
private boolean isBlockingMode = false;
private long timeout = 0;
private String streamId;
public WSO2EventAdapter(OutputEventAdapterConfiguration eventAdapterConfiguration,
Map<String, String> globalProperties) {
this.eventAdapterConfiguration = eventAdapterConfiguration;
this.globalProperties = globalProperties;
}
/**
* Initialises the resource bundle
*/
@Override
public void init() {
streamId = eventAdapterConfiguration.getStaticProperties().get(
WSO2EventAdapterConstants.ADAPTER_STATIC_CONFIG_STREAM_NAME) + ":" +
eventAdapterConfiguration.getStaticProperties().get(WSO2EventAdapterConstants
.ADAPTER_STATIC_CONFIG_STREAM_VERSION);
String configPath = globalProperties.get(ADAPTOR_CONF_PATH);
if (configPath != null) {
AgentHolder.setConfigPath(configPath);
}
}
@Override
public void testConnect() throws TestConnectionNotSupportedException {
connect();
}
@Override
public synchronized void connect() {
String userName = eventAdapterConfiguration.getStaticProperties().get(ADAPTER_CONF_WSO2EVENT_PROP_USER_NAME);
String password = eventAdapterConfiguration.getStaticProperties().get(ADAPTER_CONF_WSO2EVENT_PROP_PASSWORD);
String authUrl = eventAdapterConfiguration.getStaticProperties()
.get(ADAPTER_CONF_WSO2EVENT_PROP_AUTHENTICATOR_URL);
String receiverUrl = eventAdapterConfiguration.getStaticProperties()
.get(ADAPTER_CONF_WSO2EVENT_PROP_RECEIVER_URL);
String protocol = eventAdapterConfiguration.getStaticProperties().get(ADAPTER_CONF_WSO2EVENT_PROP_PROTOCOL);
String publishingMode = eventAdapterConfiguration.getStaticProperties()
.get(ADAPTER_CONF_WSO2EVENT_PROP_PUBLISHING_MODE);
String timeoutString = eventAdapterConfiguration.getStaticProperties()
.get(ADAPTER_CONF_WSO2EVENT_PROP_PUBLISH_TIMEOUT_MS);
if (publishingMode.equalsIgnoreCase(ADAPTER_PUBLISHING_MODE_BLOCKING)) {
isBlockingMode = true;
} else {
try {
timeout = Long.parseLong(timeoutString);
} catch (RuntimeException e) {
throwRuntimeException(receiverUrl, authUrl, protocol, userName, e);
}
}
try {
if (authUrl != null && authUrl.length() > 0) {
dataPublisher = new DataPublisher(protocol, receiverUrl, authUrl, userName, password);
} else {
dataPublisher = new DataPublisher(protocol, receiverUrl, null, userName, password);
}
} catch (DataEndpointAgentConfigurationException e) {
throwRuntimeException(receiverUrl, authUrl, protocol, userName, e);
} catch (DataEndpointException e) {
throwConnectionException(receiverUrl, authUrl, protocol, userName, e);
} catch (DataEndpointConfigurationException e) {
throwRuntimeException(receiverUrl, authUrl, protocol, userName, e);
} catch (DataEndpointAuthenticationException e) {
throwConnectionException(receiverUrl, authUrl, protocol, userName, e);
} catch (TransportException e) {
throwConnectionException(receiverUrl, authUrl, protocol, userName, e);
}
}
@Override
public void publish(Object message, Map<String, String> dynamicProperties) {
Event event = (Event) (message);
//StreamDefinition streamDefinition = (StreamDefinition) ((Object[]) message)[1];
event.setStreamId(streamId);
if (isBlockingMode) {
dataPublisher.publish(event);
} else {
dataPublisher.tryPublish(event, timeout);
}
}
@Override
public void disconnect() {
if (dataPublisher != null) {
try {
dataPublisher.shutdown();
} catch (DataEndpointException e) {
String userName = eventAdapterConfiguration.getStaticProperties()
.get(ADAPTER_CONF_WSO2EVENT_PROP_USER_NAME);
String authUrl = eventAdapterConfiguration.getStaticProperties()
.get(ADAPTER_CONF_WSO2EVENT_PROP_AUTHENTICATOR_URL);
String receiverUrl = eventAdapterConfiguration.getStaticProperties()
.get(ADAPTER_CONF_WSO2EVENT_PROP_RECEIVER_URL);
String protocol = eventAdapterConfiguration.getStaticProperties()
.get(ADAPTER_CONF_WSO2EVENT_PROP_PROTOCOL);
logException("Error in shutting down the data publisher", receiverUrl, authUrl, protocol, userName, e);
}
}
}
@Override
public void destroy() {
}
private void throwRuntimeException(String receiverUrl, String authUrl, String protocol, String userName,
Exception e) {
throw new OutputEventAdapterRuntimeException(
"Error in data-bridge config for adaptor " + eventAdapterConfiguration.getName()
+ " with the receiverUrl:" + receiverUrl + " authUrl:" + authUrl + " protocol:" + protocol
+ " and userName:" + userName + "," + e.getMessage(), e);
}
private void logException(String message, String receiverUrl, String authUrl, String protocol, String userName,
Exception e) {
log.error(message + " for adaptor " + eventAdapterConfiguration.getName()
+ " with the receiverUrl:" + receiverUrl + " authUrl:" + authUrl + " protocol:" + protocol
+ " and userName:" + userName + "," + e.getMessage(), e);
}
private void throwConnectionException(String receiverUrl, String authUrl, String protocol, String userName,
Exception e) {
throw new ConnectionUnavailableException(
"Connection not available for adaptor " + eventAdapterConfiguration.getName()
+ " with the receiverUrl:" + receiverUrl + " authUrl:" + authUrl + " protocol:" + protocol
+ " and userName:" + userName + "," + e.getMessage(), e);
}
}
| kasungayan/carbon-analytics-common | components/event-publisher/event-output-adapters/org.wso2.carbon.event.output.adapter.wso2event/src/main/java/org/wso2/carbon/event/output/adapter/wso2event/WSO2EventAdapter.java | Java | apache-2.0 | 8,571 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.core.pattern;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.NullConfiguration;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.core.util.DummyNanoClock;
import org.apache.logging.log4j.core.util.SystemNanoClock;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.logging.log4j.util.Strings;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
*/
public class PatternParserTest {
static String OUTPUT_FILE = "output/PatternParser";
static String WITNESS_FILE = "witness/PatternParser";
LoggerContext ctx = LoggerContext.getContext();
Logger root = ctx.getRootLogger();
private static String msgPattern = "%m%n";
private final String mdcMsgPattern1 = "%m : %X%n";
private final String mdcMsgPattern2 = "%m : %X{key1}%n";
private final String mdcMsgPattern3 = "%m : %X{key2}%n";
private final String mdcMsgPattern4 = "%m : %X{key3}%n";
private final String mdcMsgPattern5 = "%m : %X{key1},%X{key2},%X{key3}%n";
private static String badPattern = "[%d{yyyyMMdd HH:mm:ss,SSS] %-5p [%c{10}] - %m%n";
private static String customPattern = "[%d{yyyyMMdd HH:mm:ss,SSS}] %-5p [%-25.25c{1}:%-4L] - %m%n";
private static String patternTruncateFromEnd = "%d; %-5p %5.-5c %m%n";
private static String patternTruncateFromBeginning = "%d; %-5p %5.5c %m%n";
private static String nestedPatternHighlight =
"%highlight{%d{dd MMM yyyy HH:mm:ss,SSS}{GMT+0} [%t] %-5level: %msg%n%throwable}";
private static final String KEY = "Converter";
private PatternParser parser;
@Before
public void setup() {
parser = new PatternParser(KEY);
}
private void validateConverter(final List<PatternFormatter> formatter, final int index, final String name) {
final PatternConverter pc = formatter.get(index).getConverter();
assertEquals("Incorrect converter " + pc.getName() + " at index " + index + " expected " + name,
pc.getName(), name);
}
/**
* Test the default pattern
*/
@Test
public void defaultPattern() {
final List<PatternFormatter> formatters = parser.parse(msgPattern);
assertNotNull(formatters);
assertTrue(formatters.size() == 2);
validateConverter(formatters, 0, "Message");
validateConverter(formatters, 1, "Line Sep");
}
/**
* Test the custom pattern
*/
@Test
public void testCustomPattern() {
final List<PatternFormatter> formatters = parser.parse(customPattern);
assertNotNull(formatters);
final Map<String, String> mdc = new HashMap<>();
mdc.put("loginId", "Fred");
final Throwable t = new Throwable();
final StackTraceElement[] elements = t.getStackTrace();
final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
.setLoggerName("org.apache.logging.log4j.PatternParserTest") //
.setMarker(MarkerManager.getMarker("TEST")) //
.setLoggerFqcn(Logger.class.getName()) //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world")) //
.setContextMap(mdc) //
.setThreadName("Thread1") //
.setSource(elements[0])
.setTimeMillis(System.currentTimeMillis()).build();
final StringBuilder buf = new StringBuilder();
for (final PatternFormatter formatter : formatters) {
formatter.format(event, buf);
}
final String str = buf.toString();
final String expected = "INFO [PatternParserTest :100 ] - Hello, world" + Strings.LINE_SEPARATOR;
assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected));
}
@Test
public void testPatternTruncateFromBeginning() {
final List<PatternFormatter> formatters = parser.parse(patternTruncateFromBeginning);
assertNotNull(formatters);
final LogEvent event = Log4jLogEvent.newBuilder() //
.setLoggerName("org.apache.logging.log4j.PatternParserTest") //
.setLoggerFqcn(Logger.class.getName()) //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world")) //
.setThreadName("Thread1") //
.setTimeMillis(System.currentTimeMillis()) //
.build();
final StringBuilder buf = new StringBuilder();
for (final PatternFormatter formatter : formatters) {
formatter.format(event, buf);
}
final String str = buf.toString();
final String expected = "INFO rTest Hello, world" + Strings.LINE_SEPARATOR;
assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected));
}
@Test
public void testPatternTruncateFromEnd() {
final List<PatternFormatter> formatters = parser.parse(patternTruncateFromEnd);
assertNotNull(formatters);
final LogEvent event = Log4jLogEvent.newBuilder() //
.setLoggerName("org.apache.logging.log4j.PatternParserTest") //
.setLoggerFqcn(Logger.class.getName()) //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world")) //
.setThreadName("Thread1") //
.setTimeMillis(System.currentTimeMillis()) //
.build();
final StringBuilder buf = new StringBuilder();
for (final PatternFormatter formatter : formatters) {
formatter.format(event, buf);
}
final String str = buf.toString();
final String expected = "INFO org.a Hello, world" + Strings.LINE_SEPARATOR;
assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected));
}
@Test
public void testBadPattern() {
final Calendar cal = Calendar.getInstance();
cal.set(2001, Calendar.FEBRUARY, 3, 4, 5, 6);
cal.set(Calendar.MILLISECOND, 789);
final long timestamp = cal.getTimeInMillis();
final List<PatternFormatter> formatters = parser.parse(badPattern);
assertNotNull(formatters);
final Throwable t = new Throwable();
final StackTraceElement[] elements = t.getStackTrace();
final LogEvent event = Log4jLogEvent.newBuilder() //
.setLoggerName("a.b.c") //
.setLoggerFqcn(Logger.class.getName()) //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world")) //
.setThreadName("Thread1") //
.setSource(elements[0]) //
.setTimeMillis(timestamp) //
.build();
final StringBuilder buf = new StringBuilder();
for (final PatternFormatter formatter : formatters) {
formatter.format(event, buf);
}
final String str = buf.toString();
// eats all characters until the closing '}' character
final String expected = "[2001-02-03 04:05:06,789] - Hello, world";
assertTrue("Expected to start with: " + expected + ". Actual: " + str, str.startsWith(expected));
}
@Test
public void testNestedPatternHighlight() {
testNestedPatternHighlight(Level.TRACE, "\u001B[30m");
testNestedPatternHighlight(Level.DEBUG, "\u001B[36m");
testNestedPatternHighlight(Level.INFO, "\u001B[32m");
testNestedPatternHighlight(Level.WARN, "\u001B[33m");
testNestedPatternHighlight(Level.ERROR, "\u001B[1;31m");
testNestedPatternHighlight(Level.FATAL, "\u001B[1;31m");
}
private void testNestedPatternHighlight(final Level level, final String expectedStart) {
final List<PatternFormatter> formatters = parser.parse(nestedPatternHighlight);
assertNotNull(formatters);
final Throwable t = new Throwable();
t.getStackTrace();
final LogEvent event = Log4jLogEvent.newBuilder() //
.setLoggerName("org.apache.logging.log4j.PatternParserTest") //
.setMarker(MarkerManager.getMarker("TEST")) //
.setLoggerFqcn(Logger.class.getName()) //
.setLevel(level) //
.setMessage(new SimpleMessage("Hello, world")) //
.setThreadName("Thread1") //
.setSource(/*stackTraceElement[0]*/ null) //
.setTimeMillis(System.currentTimeMillis()) //
.build();
final StringBuilder buf = new StringBuilder();
for (final PatternFormatter formatter : formatters) {
formatter.format(event, buf);
}
final String str = buf.toString();
final String expectedEnd = String.format("] %-5s: Hello, world%s\u001B[m", level, Strings.LINE_SEPARATOR);
assertTrue("Expected to start with: " + expectedStart + ". Actual: " + str, str.startsWith(expectedStart));
assertTrue("Expected to end with: \"" + expectedEnd + "\". Actual: \"" + str, str.endsWith(expectedEnd));
}
@Test
public void testNanoPatternShort() {
final List<PatternFormatter> formatters = parser.parse("%N");
assertNotNull(formatters);
assertEquals(1, formatters.size());
assertTrue(formatters.get(0).getConverter() instanceof NanoTimePatternConverter);
}
@Test
public void testNanoPatternLong() {
final List<PatternFormatter> formatters = parser.parse("%nano");
assertNotNull(formatters);
assertEquals(1, formatters.size());
assertTrue(formatters.get(0).getConverter() instanceof NanoTimePatternConverter);
}
@Test
public void testThreadNamePattern() {
testThreadNamePattern("%thread");
}
@Test
public void testThreadNameFullPattern() {
testThreadNamePattern("%threadName");
}
@Test
public void testThreadIdFullPattern() {
testThreadIdPattern("%threadId");
}
@Test
public void testThreadIdShortPattern1() {
testThreadIdPattern("%tid");
}
@Test
public void testThreadIdShortPattern2() {
testThreadIdPattern("%T");
}
@Test
public void testThreadPriorityShortPattern() {
testThreadPriorityPattern("%tp");
}
@Test
public void testThreadPriorityFullPattern() {
testThreadPriorityPattern("%threadPriority");
}
private void testThreadIdPattern(final String pattern) {
testFirstConverter(pattern, ThreadIdPatternConverter.class);
}
private void testThreadNamePattern(final String pattern) {
testFirstConverter(pattern, ThreadNamePatternConverter.class);
}
private void testThreadPriorityPattern(final String pattern) {
testFirstConverter(pattern, ThreadPriorityPatternConverter.class);
}
private void testFirstConverter(final String pattern, final Class<?> checkClass) {
final List<PatternFormatter> formatters = parser.parse(pattern);
assertNotNull(formatters);
final String msg = formatters.toString();
assertEquals(msg, 1, formatters.size());
assertTrue(msg, checkClass.isInstance(formatters.get(0).getConverter()));
}
@Test
public void testThreadNameShortPattern() {
testThreadNamePattern("%t");
}
@Test
public void testNanoPatternShortChangesConfigurationNanoClock() {
final Configuration config = new NullConfiguration();
assertTrue(config.getNanoClock() instanceof DummyNanoClock);
final PatternParser pp = new PatternParser(config, KEY, null);
assertTrue(config.getNanoClock() instanceof DummyNanoClock);
pp.parse("%m");
assertTrue(config.getNanoClock() instanceof DummyNanoClock);
pp.parse("%nano"); // this changes the config clock
assertTrue(config.getNanoClock() instanceof SystemNanoClock);
}
@Test
public void testNanoPatternLongChangesNanoClockFactoryMode() {
final Configuration config = new NullConfiguration();
assertTrue(config.getNanoClock() instanceof DummyNanoClock);
final PatternParser pp = new PatternParser(config, KEY, null);
assertTrue(config.getNanoClock() instanceof DummyNanoClock);
pp.parse("%m");
assertTrue(config.getNanoClock() instanceof DummyNanoClock);
pp.parse("%N");
assertTrue(config.getNanoClock() instanceof SystemNanoClock);
}
}
| codescale/logging-log4j2 | log4j-core/src/test/java/org/apache/logging/log4j/core/pattern/PatternParserTest.java | Java | apache-2.0 | 13,711 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.visor.verify;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.apache.ignite.internal.processors.cache.verify.PartitionKey;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.internal.visor.VisorDataTransferObject;
import org.jetbrains.annotations.NotNull;
/**
*
*/
public class VisorValidateIndexesJobResult extends VisorDataTransferObject {
/** */
private static final long serialVersionUID = 0L;
/** Results of indexes validation from node. */
private Map<PartitionKey, ValidateIndexesPartitionResult> partRes;
/** Results of reverse indexes validation from node. */
private Map<String, ValidateIndexesPartitionResult> idxRes;
/** Integrity check issues. */
private Collection<IndexIntegrityCheckIssue> integrityCheckFailures;
/**
* @param partRes Results of indexes validation from node.
* @param idxRes Results of reverse indexes validation from node.
* @param integrityCheckFailures Collection of indexes integrity check failures.
*/
public VisorValidateIndexesJobResult(
@NotNull Map<PartitionKey, ValidateIndexesPartitionResult> partRes,
@NotNull Map<String, ValidateIndexesPartitionResult> idxRes,
@NotNull Collection<IndexIntegrityCheckIssue> integrityCheckFailures
) {
this.partRes = partRes;
this.idxRes = idxRes;
this.integrityCheckFailures = integrityCheckFailures;
}
/**
* For externalization only.
*/
public VisorValidateIndexesJobResult() {
}
/** {@inheritDoc} */
@Override public byte getProtocolVersion() {
return V3;
}
/**
* @return Results of indexes validation from node.
*/
public Map<PartitionKey, ValidateIndexesPartitionResult> partitionResult() {
return partRes;
}
/**
* @return Results of reverse indexes validation from node.
*/
public Map<String, ValidateIndexesPartitionResult> indexResult() {
return idxRes == null ? Collections.emptyMap() : idxRes;
}
/**
* @return Collection of failed integrity checks.
*/
public Collection<IndexIntegrityCheckIssue> integrityCheckFailures() {
return integrityCheckFailures == null ? Collections.emptyList() : integrityCheckFailures;
}
/**
* @return {@code true} If any indexes issues found on node, otherwise returns {@code false}.
*/
public boolean hasIssues() {
return (integrityCheckFailures != null && !integrityCheckFailures.isEmpty()) ||
(partRes != null && partRes.entrySet().stream().anyMatch(e -> !e.getValue().issues().isEmpty())) ||
(idxRes != null && idxRes.entrySet().stream().anyMatch(e -> !e.getValue().issues().isEmpty()));
}
/** {@inheritDoc} */
@Override protected void writeExternalData(ObjectOutput out) throws IOException {
U.writeMap(out, partRes);
U.writeMap(out, idxRes);
U.writeCollection(out, integrityCheckFailures);
}
/** {@inheritDoc} */
@Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {
partRes = U.readMap(in);
if (protoVer >= V2)
idxRes = U.readMap(in);
if (protoVer >= V3)
integrityCheckFailures = U.readCollection(in);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(VisorValidateIndexesJobResult.class, this);
}
}
| ptupitsyn/ignite | modules/core/src/main/java/org/apache/ignite/internal/visor/verify/VisorValidateIndexesJobResult.java | Java | apache-2.0 | 4,517 |
/*
* (c) Copyright 2021 Micro Focus
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available 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 io.cloudslang.content.active_directory.entities;
import java.util.List;
public interface CreateUserInputInterface {
String getHost();
String getDistinguishedName();
String getUserCommonName();
String getUserPassword();
String getSAMAccountName();
String getUsername();
String getPassword();
String getProtocol();
Boolean getTrustAllRoots();
String getTrustKeystore();
String getTrustPassword();
Boolean getEscapeChars();
String getTimeout();
String getProxyHost();
int getProxyPort();
String getProxyUsername();
String getProxyPassword();
String getX509HostnameVerifier();
String getTlsVersion();
List<String> getAllowedCiphers();
}
| CloudSlang/cs-actions | cs-active-directory/src/main/java/io/cloudslang/content/active_directory/entities/CreateUserInputInterface.java | Java | apache-2.0 | 1,364 |
/**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br>
* University of Zurich, Switzerland.
* <p>
*/
package org.olat.presentation.group.area;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringEscapeUtils;
import org.olat.data.group.BusinessGroup;
import org.olat.data.group.area.BGArea;
import org.olat.data.group.area.BGAreaDao;
import org.olat.data.group.area.BGAreaDaoImpl;
import org.olat.data.group.context.BGContext;
import org.olat.data.group.context.BGContextDao;
import org.olat.data.group.context.BGContextDaoImpl;
import org.olat.lms.activitylogging.LoggingResourceable;
import org.olat.lms.activitylogging.ThreadLocalUserActivityLogger;
import org.olat.lms.group.BusinessGroupService;
import org.olat.lms.group.GroupLoggingAction;
import org.olat.presentation.framework.core.UserRequest;
import org.olat.presentation.framework.core.components.Component;
import org.olat.presentation.framework.core.components.choice.Choice;
import org.olat.presentation.framework.core.components.tabbedpane.TabbedPane;
import org.olat.presentation.framework.core.components.velocity.VelocityContainer;
import org.olat.presentation.framework.core.control.Controller;
import org.olat.presentation.framework.core.control.WindowControl;
import org.olat.presentation.framework.core.control.controller.BasicController;
import org.olat.presentation.framework.core.translator.PackageTranslator;
import org.olat.presentation.framework.core.translator.PackageUtil;
import org.olat.presentation.framework.core.translator.Translator;
import org.olat.system.event.Event;
import org.olat.system.spring.CoreSpringFactory;
/**
* Description:<BR>
* This controller can be used to edit the business grou area metadata and associate business groups to the business group area.
* <P>
* Initial Date: Aug 30, 2004
*
* @author gnaegi
*/
public class BGAreaEditController extends BasicController {
private static final String PACKAGE = PackageUtil.getPackageName(BGAreaEditController.class);
private static final String VELOCITY_ROOT = PackageUtil.getPackageVelocityRoot(PACKAGE);
// helpers
private final Translator trans;
// GUI components
private final TabbedPane tabbedPane;
private VelocityContainer editVC, detailsTabVC, groupsTabVC;
private BGAreaFormController areaController;
private GroupsToAreaDataModel groupsDataModel;
private Choice groupsChoice;
// area, context and group references
private BGArea area;
private final BGContext bgContext;
private List allGroups, inAreaGroups;
// managers
private final BGAreaDao areaManager;
private final BGContextDao contextManager;
/**
* Constructor for the business group area edit controller
*
* @param ureq
* The user request
* @param wControl
* The window control
* @param area
* The business group area
*/
public BGAreaEditController(final UserRequest ureq, final WindowControl wControl, final BGArea area) {
super(ureq, wControl);
this.trans = new PackageTranslator(PACKAGE, ureq.getLocale());
this.area = area;
this.areaManager = BGAreaDaoImpl.getInstance();
this.bgContext = area.getGroupContext();
this.contextManager = BGContextDaoImpl.getInstance();
// tabbed pane
tabbedPane = new TabbedPane("tabbedPane", ureq.getLocale());
tabbedPane.addListener(this);
// details tab
initAndAddDetailsTab(ureq, wControl);
// groups tab
initAndAddGroupsTab();
// initialize main view
initEditVC();
putInitialPanel(this.editVC);
}
/**
* initialize the main velocity wrapper container
*/
private void initEditVC() {
editVC = new VelocityContainer("edit", VELOCITY_ROOT + "/edit.html", trans, this);
editVC.put("tabbedpane", tabbedPane);
editVC.contextPut("title", trans.translate("area.edit.title", new String[] { StringEscapeUtils.escapeHtml(this.area.getName()).toString() }));
}
/**
* initialize the area details tab
*/
private void initAndAddDetailsTab(final UserRequest ureq, final WindowControl wControl) {
this.detailsTabVC = new VelocityContainer("detailstab", VELOCITY_ROOT + "/detailstab.html", this.trans, this);
// TODO:pb: refactor BGControllerFactory.create..AreaController to be
// usefull here
if (this.areaController != null) {
removeAsListenerAndDispose(this.areaController);
}
this.areaController = new BGAreaFormController(ureq, wControl, this.area, false);
listenTo(this.areaController);
this.detailsTabVC.put("areaForm", this.areaController.getInitialComponent());
this.tabbedPane.addTab(this.trans.translate("tab.details"), this.detailsTabVC);
}
/**
* initalize the group to area association tab
*/
private void initAndAddGroupsTab() {
groupsTabVC = new VelocityContainer("groupstab", VELOCITY_ROOT + "/groupstab.html", trans, this);
tabbedPane.addTab(trans.translate("tab.groups"), groupsTabVC);
this.allGroups = contextManager.getGroupsOfBGContext(this.bgContext);
this.inAreaGroups = areaManager.findBusinessGroupsOfArea(this.area);
this.groupsDataModel = new GroupsToAreaDataModel(this.allGroups, this.inAreaGroups);
groupsChoice = new Choice("groupsChoice", trans);
groupsChoice.setSubmitKey("submit");
groupsChoice.setCancelKey("cancel");
groupsChoice.setTableDataModel(groupsDataModel);
groupsChoice.addListener(this);
groupsTabVC.put(groupsChoice);
groupsTabVC.contextPut("noGroupsFound", (allGroups.size() > 0 ? Boolean.FALSE : Boolean.TRUE));
}
/**
*/
@Override
protected void event(final UserRequest ureq, final Component source, final Event event) {
if (source == this.groupsChoice) {
if (event == Choice.EVNT_VALIDATION_OK) {
doUpdateGroupAreaRelations();
// do logging
if (this.inAreaGroups.size() == 0) {
ThreadLocalUserActivityLogger.log(GroupLoggingAction.BGAREA_UPDATED_NOW_EMPTY, getClass());
} else {
for (final Iterator it = inAreaGroups.iterator(); it.hasNext();) {
final BusinessGroup aGroup = (BusinessGroup) it.next();
ThreadLocalUserActivityLogger.log(GroupLoggingAction.BGAREA_UPDATED_MEMBER_GROUP, getClass(), LoggingResourceable.wrap(aGroup));
}
}
}
}
}
@Override
protected void event(final UserRequest ureq, final Controller source, final Event event) {
if (source == this.areaController) {
if (event == Event.DONE_EVENT) {
final BGArea updatedArea = doAreaUpdate();
if (updatedArea == null) {
this.areaController.resetAreaName();
getWindowControl().setWarning(this.trans.translate("error.area.name.exists"));
} else {
this.area = updatedArea;
this.editVC.contextPut("title",
this.trans.translate("area.edit.title", new String[] { StringEscapeUtils.escapeHtml(this.area.getName()).toString() }));
}
} else if (event == Event.CANCELLED_EVENT) {
// area might have been changed, reload from db
this.area = this.areaManager.reloadArea(this.area);
// TODO:pb: refactor BGControllerFactory.create..AreaController to be
// usefull here
if (this.areaController != null) {
removeAsListenerAndDispose(this.areaController);
}
this.areaController = new BGAreaFormController(ureq, getWindowControl(), this.area, false);
listenTo(this.areaController);
this.detailsTabVC.put("areaForm", this.areaController.getInitialComponent());
}
}
}
/**
* Update a group area
*
* @return the updated area
*/
public BGArea doAreaUpdate() {
this.area.setName(this.areaController.getAreaName());
this.area.setDescription(this.areaController.getAreaDescription());
return this.areaManager.updateBGArea(this.area);
}
/**
* Update the groups associated to this area: remove and add groups
*/
private void doUpdateGroupAreaRelations() {
BusinessGroupService businessGroupService = (BusinessGroupService) CoreSpringFactory.getBean(BusinessGroupService.class);
// 1) add groups to area
final List addedGroups = groupsChoice.getAddedRows();
Iterator iterator = addedGroups.iterator();
while (iterator.hasNext()) {
final Integer position = (Integer) iterator.next();
BusinessGroup group = groupsDataModel.getGroup(position.intValue());
// refresh group to prevent stale object exception and context proxy
// issues
group = businessGroupService.loadBusinessGroup(group);
// refresh group also in table model
this.allGroups.set(position.intValue(), group);
// add group now to area and update in area group list
areaManager.addBGToBGArea(group, area);
this.inAreaGroups.add(group);
}
// 2) remove groups from area
final List removedGroups = groupsChoice.getRemovedRows();
iterator = removedGroups.iterator();
while (iterator.hasNext()) {
final Integer position = (Integer) iterator.next();
final BusinessGroup group = groupsDataModel.getGroup(position.intValue());
areaManager.removeBGFromArea(group, area);
this.inAreaGroups.remove(group);
}
}
/**
*/
@Override
protected void doDispose() {
// don't dispose anything
}
}
| huihoo/olat | olat7.8/src/main/java/org/olat/presentation/group/area/BGAreaEditController.java | Java | apache-2.0 | 10,780 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.river.test.spec.javaspace.conformance;
import java.util.logging.Level;
// net.jini
import net.jini.core.transaction.Transaction;
// org.apache.river
import org.apache.river.qa.harness.TestException;
import org.apache.river.qa.harness.QAConfig;
/**
* TransactionWriteTakeIfExistsTest asserts that if the entry is written and
* after that is taken by takeIfExists method within the non null
* transaction, the entry will never be visible outside the transaction and
* will not be added to the space when the transaction commits.
*
* @author Mikhail A. Markov
*/
public class TransactionWriteTakeIfExistsTest extends TransactionTest {
/**
* This method asserts that if the entry is written and
* after that is taken by takeIfExists method within the non null
* transaction, the entry will never be visible outside the transaction and
* will not be added to the space when the transaction commits.
*
* <P>Notes:<BR>For more information see the JavaSpaces specification
* section 3.1</P>
*/
public void run() throws Exception {
SimpleEntry sampleEntry1 = new SimpleEntry("TestEntry #1", 1);
SimpleEntry sampleEntry2 = new SimpleEntry("TestEntry #2", 2);
SimpleEntry result;
Transaction txn;
// first check that space is empty
if (!checkSpace(space)) {
throw new TestException(
"Space is not empty in the beginning.");
}
// create the non null transaction
txn = getTransaction();
/*
* write 1-st sample and 2-nd sample entries twice
* to the space within the transaction
*/
space.write(sampleEntry1, txn, leaseForeverTime);
space.write(sampleEntry1, txn, leaseForeverTime);
space.write(sampleEntry2, txn, leaseForeverTime);
space.write(sampleEntry2, txn, leaseForeverTime);
/*
* takeIfExists all written entries from the space
* within the transaction
*/
space.takeIfExists(sampleEntry1, txn, checkTime);
space.takeIfExists(sampleEntry1, txn, checkTime);
space.takeIfExists(sampleEntry2, txn, checkTime);
space.takeIfExists(sampleEntry2, txn, checkTime);
// commit the transaction
txnCommit(txn);
// check that there are no entries in the space
result = (SimpleEntry) space.read(null, null, checkTime);
if (result != null) {
throw new TestException(
"there is " + result + " still available in the"
+ " space after transaction's committing"
+ " but null is expected.");
}
logDebugText("There are no entries in the space after"
+ " transaction's committing, as expected.");
}
}
| pfirmstone/JGDMS | qa/src/org/apache/river/test/spec/javaspace/conformance/TransactionWriteTakeIfExistsTest.java | Java | apache-2.0 | 3,650 |
package org.hyperimage.connector.fedora3.ws;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the org.hyperimage.connector.fedora3.ws package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _AssetURN_QNAME = new QName("http://connector.ws.hyperimage.org/", "assetURN");
private final static QName _Token_QNAME = new QName("http://connector.ws.hyperimage.org/", "token");
private final static QName _GetAssetPreviewDataResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getAssetPreviewDataResponse");
private final static QName _ParentURN_QNAME = new QName("http://connector.ws.hyperimage.org/", "parentURN");
private final static QName _Username_QNAME = new QName("http://connector.ws.hyperimage.org/", "username");
private final static QName _GetAssetData_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getAssetData");
private final static QName _GetAssetPreviewData_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getAssetPreviewData");
private final static QName _GetHierarchyLevelResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getHierarchyLevelResponse");
private final static QName _Authenticate_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "authenticate");
private final static QName _HIWSLoggedException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSLoggedException");
private final static QName _GetMetadataRecord_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getMetadataRecord");
private final static QName _HIWSNotBinaryException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSNotBinaryException");
private final static QName _Session_QNAME = new QName("http://connector.ws.hyperimage.org/", "session");
private final static QName _HIWSDCMetadataException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSDCMetadataException");
private final static QName _HIWSAuthException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSAuthException");
private final static QName _HIWSAssetNotFoundException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSAssetNotFoundException");
private final static QName _GetWSVersion_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getWSVersion");
private final static QName _GetMetadataRecordResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getMetadataRecordResponse");
private final static QName _HIWSUTF8EncodingException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSUTF8EncodingException");
private final static QName _GetWSVersionResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getWSVersionResponse");
private final static QName _GetReposInfo_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getReposInfo");
private final static QName _HIWSXMLParserException_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "HIWSXMLParserException");
private final static QName _AuthenticateResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "authenticateResponse");
private final static QName _GetAssetDataResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getAssetDataResponse");
private final static QName _GetHierarchyLevel_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getHierarchyLevel");
private final static QName _GetReposInfoResponse_QNAME = new QName("http://fedora3.connector.hyperimage.org/", "getReposInfoResponse");
private final static QName _GetAssetPreviewDataResponseReturn_QNAME = new QName("", "return");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.hyperimage.connector.fedora3.ws
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link HIWSDCMetadataException }
*
*/
public HIWSDCMetadataException createHIWSDCMetadataException() {
return new HIWSDCMetadataException();
}
/**
* Create an instance of {@link GetAssetDataResponse }
*
*/
public GetAssetDataResponse createGetAssetDataResponse() {
return new GetAssetDataResponse();
}
/**
* Create an instance of {@link HIWSAuthException }
*
*/
public HIWSAuthException createHIWSAuthException() {
return new HIWSAuthException();
}
/**
* Create an instance of {@link HIWSAssetNotFoundException }
*
*/
public HIWSAssetNotFoundException createHIWSAssetNotFoundException() {
return new HIWSAssetNotFoundException();
}
/**
* Create an instance of {@link HIWSNotBinaryException }
*
*/
public HIWSNotBinaryException createHIWSNotBinaryException() {
return new HIWSNotBinaryException();
}
/**
* Create an instance of {@link GetHierarchyLevelResponse }
*
*/
public GetHierarchyLevelResponse createGetHierarchyLevelResponse() {
return new GetHierarchyLevelResponse();
}
/**
* Create an instance of {@link Authenticate }
*
*/
public Authenticate createAuthenticate() {
return new Authenticate();
}
/**
* Create an instance of {@link HiHierarchyLevel }
*
*/
public HiHierarchyLevel createHiHierarchyLevel() {
return new HiHierarchyLevel();
}
/**
* Create an instance of {@link HIWSLoggedException }
*
*/
public HIWSLoggedException createHIWSLoggedException() {
return new HIWSLoggedException();
}
/**
* Create an instance of {@link GetHierarchyLevel }
*
*/
public GetHierarchyLevel createGetHierarchyLevel() {
return new GetHierarchyLevel();
}
/**
* Create an instance of {@link AuthenticateResponse }
*
*/
public AuthenticateResponse createAuthenticateResponse() {
return new AuthenticateResponse();
}
/**
* Create an instance of {@link GetReposInfoResponse }
*
*/
public GetReposInfoResponse createGetReposInfoResponse() {
return new GetReposInfoResponse();
}
/**
* Create an instance of {@link GetAssetPreviewDataResponse }
*
*/
public GetAssetPreviewDataResponse createGetAssetPreviewDataResponse() {
return new GetAssetPreviewDataResponse();
}
/**
* Create an instance of {@link GetWSVersion }
*
*/
public GetWSVersion createGetWSVersion() {
return new GetWSVersion();
}
/**
* Create an instance of {@link GetMetadataRecordResponse }
*
*/
public GetMetadataRecordResponse createGetMetadataRecordResponse() {
return new GetMetadataRecordResponse();
}
/**
* Create an instance of {@link HiMetadataRecord }
*
*/
public HiMetadataRecord createHiMetadataRecord() {
return new HiMetadataRecord();
}
/**
* Create an instance of {@link HiTypedDatastream }
*
*/
public HiTypedDatastream createHiTypedDatastream() {
return new HiTypedDatastream();
}
/**
* Create an instance of {@link HIWSXMLParserException }
*
*/
public HIWSXMLParserException createHIWSXMLParserException() {
return new HIWSXMLParserException();
}
/**
* Create an instance of {@link GetMetadataRecord }
*
*/
public GetMetadataRecord createGetMetadataRecord() {
return new GetMetadataRecord();
}
/**
* Create an instance of {@link GetAssetPreviewData }
*
*/
public GetAssetPreviewData createGetAssetPreviewData() {
return new GetAssetPreviewData();
}
/**
* Create an instance of {@link HIWSUTF8EncodingException }
*
*/
public HIWSUTF8EncodingException createHIWSUTF8EncodingException() {
return new HIWSUTF8EncodingException();
}
/**
* Create an instance of {@link GetReposInfo }
*
*/
public GetReposInfo createGetReposInfo() {
return new GetReposInfo();
}
/**
* Create an instance of {@link GetWSVersionResponse }
*
*/
public GetWSVersionResponse createGetWSVersionResponse() {
return new GetWSVersionResponse();
}
/**
* Create an instance of {@link GetAssetData }
*
*/
public GetAssetData createGetAssetData() {
return new GetAssetData();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://connector.ws.hyperimage.org/", name = "assetURN")
public JAXBElement<String> createAssetURN(String value) {
return new JAXBElement<String>(_AssetURN_QNAME, String.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://connector.ws.hyperimage.org/", name = "token")
public JAXBElement<String> createToken(String value) {
return new JAXBElement<String>(_Token_QNAME, String.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetAssetPreviewDataResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getAssetPreviewDataResponse")
public JAXBElement<GetAssetPreviewDataResponse> createGetAssetPreviewDataResponse(GetAssetPreviewDataResponse value) {
return new JAXBElement<GetAssetPreviewDataResponse>(_GetAssetPreviewDataResponse_QNAME, GetAssetPreviewDataResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://connector.ws.hyperimage.org/", name = "parentURN")
public JAXBElement<String> createParentURN(String value) {
return new JAXBElement<String>(_ParentURN_QNAME, String.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://connector.ws.hyperimage.org/", name = "username")
public JAXBElement<String> createUsername(String value) {
return new JAXBElement<String>(_Username_QNAME, String.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetAssetData }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getAssetData")
public JAXBElement<GetAssetData> createGetAssetData(GetAssetData value) {
return new JAXBElement<GetAssetData>(_GetAssetData_QNAME, GetAssetData.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetAssetPreviewData }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getAssetPreviewData")
public JAXBElement<GetAssetPreviewData> createGetAssetPreviewData(GetAssetPreviewData value) {
return new JAXBElement<GetAssetPreviewData>(_GetAssetPreviewData_QNAME, GetAssetPreviewData.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetHierarchyLevelResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getHierarchyLevelResponse")
public JAXBElement<GetHierarchyLevelResponse> createGetHierarchyLevelResponse(GetHierarchyLevelResponse value) {
return new JAXBElement<GetHierarchyLevelResponse>(_GetHierarchyLevelResponse_QNAME, GetHierarchyLevelResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Authenticate }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "authenticate")
public JAXBElement<Authenticate> createAuthenticate(Authenticate value) {
return new JAXBElement<Authenticate>(_Authenticate_QNAME, Authenticate.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link HIWSLoggedException }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSLoggedException")
public JAXBElement<HIWSLoggedException> createHIWSLoggedException(HIWSLoggedException value) {
return new JAXBElement<HIWSLoggedException>(_HIWSLoggedException_QNAME, HIWSLoggedException.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetMetadataRecord }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getMetadataRecord")
public JAXBElement<GetMetadataRecord> createGetMetadataRecord(GetMetadataRecord value) {
return new JAXBElement<GetMetadataRecord>(_GetMetadataRecord_QNAME, GetMetadataRecord.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link HIWSNotBinaryException }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSNotBinaryException")
public JAXBElement<HIWSNotBinaryException> createHIWSNotBinaryException(HIWSNotBinaryException value) {
return new JAXBElement<HIWSNotBinaryException>(_HIWSNotBinaryException_QNAME, HIWSNotBinaryException.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://connector.ws.hyperimage.org/", name = "session")
public JAXBElement<String> createSession(String value) {
return new JAXBElement<String>(_Session_QNAME, String.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link HIWSDCMetadataException }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSDCMetadataException")
public JAXBElement<HIWSDCMetadataException> createHIWSDCMetadataException(HIWSDCMetadataException value) {
return new JAXBElement<HIWSDCMetadataException>(_HIWSDCMetadataException_QNAME, HIWSDCMetadataException.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link HIWSAuthException }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSAuthException")
public JAXBElement<HIWSAuthException> createHIWSAuthException(HIWSAuthException value) {
return new JAXBElement<HIWSAuthException>(_HIWSAuthException_QNAME, HIWSAuthException.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link HIWSAssetNotFoundException }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSAssetNotFoundException")
public JAXBElement<HIWSAssetNotFoundException> createHIWSAssetNotFoundException(HIWSAssetNotFoundException value) {
return new JAXBElement<HIWSAssetNotFoundException>(_HIWSAssetNotFoundException_QNAME, HIWSAssetNotFoundException.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetWSVersion }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getWSVersion")
public JAXBElement<GetWSVersion> createGetWSVersion(GetWSVersion value) {
return new JAXBElement<GetWSVersion>(_GetWSVersion_QNAME, GetWSVersion.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetMetadataRecordResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getMetadataRecordResponse")
public JAXBElement<GetMetadataRecordResponse> createGetMetadataRecordResponse(GetMetadataRecordResponse value) {
return new JAXBElement<GetMetadataRecordResponse>(_GetMetadataRecordResponse_QNAME, GetMetadataRecordResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link HIWSUTF8EncodingException }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSUTF8EncodingException")
public JAXBElement<HIWSUTF8EncodingException> createHIWSUTF8EncodingException(HIWSUTF8EncodingException value) {
return new JAXBElement<HIWSUTF8EncodingException>(_HIWSUTF8EncodingException_QNAME, HIWSUTF8EncodingException.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetWSVersionResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getWSVersionResponse")
public JAXBElement<GetWSVersionResponse> createGetWSVersionResponse(GetWSVersionResponse value) {
return new JAXBElement<GetWSVersionResponse>(_GetWSVersionResponse_QNAME, GetWSVersionResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetReposInfo }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getReposInfo")
public JAXBElement<GetReposInfo> createGetReposInfo(GetReposInfo value) {
return new JAXBElement<GetReposInfo>(_GetReposInfo_QNAME, GetReposInfo.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link HIWSXMLParserException }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "HIWSXMLParserException")
public JAXBElement<HIWSXMLParserException> createHIWSXMLParserException(HIWSXMLParserException value) {
return new JAXBElement<HIWSXMLParserException>(_HIWSXMLParserException_QNAME, HIWSXMLParserException.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link AuthenticateResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "authenticateResponse")
public JAXBElement<AuthenticateResponse> createAuthenticateResponse(AuthenticateResponse value) {
return new JAXBElement<AuthenticateResponse>(_AuthenticateResponse_QNAME, AuthenticateResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetAssetDataResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getAssetDataResponse")
public JAXBElement<GetAssetDataResponse> createGetAssetDataResponse(GetAssetDataResponse value) {
return new JAXBElement<GetAssetDataResponse>(_GetAssetDataResponse_QNAME, GetAssetDataResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetHierarchyLevel }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getHierarchyLevel")
public JAXBElement<GetHierarchyLevel> createGetHierarchyLevel(GetHierarchyLevel value) {
return new JAXBElement<GetHierarchyLevel>(_GetHierarchyLevel_QNAME, GetHierarchyLevel.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetReposInfoResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://fedora3.connector.hyperimage.org/", name = "getReposInfoResponse")
public JAXBElement<GetReposInfoResponse> createGetReposInfoResponse(GetReposInfoResponse value) {
return new JAXBElement<GetReposInfoResponse>(_GetReposInfoResponse_QNAME, GetReposInfoResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link byte[]}{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "return", scope = GetAssetPreviewDataResponse.class)
public JAXBElement<byte[]> createGetAssetPreviewDataResponseReturn(byte[] value) {
return new JAXBElement<byte[]>(_GetAssetPreviewDataResponseReturn_QNAME, byte[].class, GetAssetPreviewDataResponse.class, ((byte[]) value));
}
}
| bitgilde/HyperImage3 | hi3-editor/src/org/hyperimage/connector/fedora3/ws/ObjectFactory.java | Java | apache-2.0 | 21,077 |
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pig.backend.hadoop.hbase;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.ListIterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.apache.hadoop.hbase.mapreduce.TableInputFormat;
import org.apache.hadoop.hbase.mapreduce.TableRecordReader;
import org.apache.hadoop.hbase.mapreduce.TableSplit;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.mapreduce.InputSplit;
public class HBaseTableInputFormat extends TableInputFormat {
private static final Log LOG = LogFactory.getLog(HBaseTableInputFormat.class);
protected final byte[] gt_;
protected final byte[] gte_;
protected final byte[] lt_;
protected final byte[] lte_;
public HBaseTableInputFormat() {
this(-1, null, null, null, null);
}
protected HBaseTableInputFormat(long limit, byte[] gt, byte[] gte, byte[] lt, byte[] lte) {
super();
setTableRecordReader(new HBaseTableRecordReader(limit));
gt_ = gt;
gte_ = gte;
lt_ = lt;
lte_ = lte;
}
public static class HBaseTableIFBuilder {
protected byte[] gt_;
protected byte[] gte_;
protected byte[] lt_;
protected byte[] lte_;
protected long limit_;
protected Configuration conf_;
public HBaseTableIFBuilder withGt(byte[] gt) { gt_ = gt; return this; }
public HBaseTableIFBuilder withGte(byte[] gte) { gte_ = gte; return this; }
public HBaseTableIFBuilder withLt(byte[] lt) { lt_ = lt; return this; }
public HBaseTableIFBuilder withLte(byte[] lte) { lte_ = lte; return this; }
public HBaseTableIFBuilder withLimit(long limit) { limit_ = limit; return this; }
public HBaseTableIFBuilder withConf(Configuration conf) { conf_ = conf; return this; }
public HBaseTableInputFormat build() {
HBaseTableInputFormat inputFormat = new HBaseTableInputFormat(limit_, gt_, gte_, lt_, lte_);
if (conf_ != null) inputFormat.setConf(conf_);
return inputFormat;
}
}
@Override
public List<InputSplit> getSplits(org.apache.hadoop.mapreduce.JobContext context)
throws IOException {
List<InputSplit> splits = super.getSplits(context);
ListIterator<InputSplit> splitIter = splits.listIterator();
while (splitIter.hasNext()) {
TableSplit split = (TableSplit) splitIter.next();
byte[] startKey = split.getStartRow();
byte[] endKey = split.getEndRow();
// Skip if the region doesn't satisfy configured options.
if ((skipRegion(CompareOp.LESS, startKey, lt_)) ||
(skipRegion(CompareOp.GREATER, endKey, gt_)) ||
(skipRegion(CompareOp.GREATER, endKey, gte_)) ||
(skipRegion(CompareOp.LESS_OR_EQUAL, startKey, lte_)) ) {
splitIter.remove();
}
}
return splits;
}
private boolean skipRegion(CompareOp op, byte[] key, byte[] option ) throws IOException {
if (key.length == 0 || option == null)
return false;
BinaryComparator comp = new BinaryComparator(option);
RowFilter rowFilter = new RowFilter(op, comp);
return rowFilter.filterRowKey(key, 0, key.length);
}
protected class HBaseTableRecordReader extends TableRecordReader {
private long recordsSeen = 0;
private final long limit_;
private byte[] startRow_;
private byte[] endRow_;
private transient byte[] currRow_;
private int maxRowLength;
private BigInteger bigStart_;
private BigInteger bigEnd_;
private BigDecimal bigRange_;
private transient float progressSoFar_ = 0;
public HBaseTableRecordReader(long limit) {
limit_ = limit;
}
@Override
public void setScan(Scan scan) {
super.setScan(scan);
startRow_ = scan.getStartRow();
endRow_ = scan.getStopRow();
byte[] startPadded;
byte[] endPadded;
if (startRow_.length < endRow_.length) {
startPadded = Bytes.padTail(startRow_, endRow_.length - startRow_.length);
endPadded = endRow_;
} else if (endRow_.length < startRow_.length) {
startPadded = startRow_;
endPadded = Bytes.padTail(endRow_, startRow_.length - endRow_.length);
} else {
startPadded = startRow_;
endPadded = endRow_;
}
currRow_ = startRow_;
byte [] prependHeader = {1, 0};
bigStart_ = new BigInteger(Bytes.add(prependHeader, startPadded));
bigEnd_ = new BigInteger(Bytes.add(prependHeader, endPadded));
bigRange_ = new BigDecimal(bigEnd_.subtract(bigStart_));
maxRowLength = endRow_.length > startRow_.length ? endRow_.length : startRow_.length;
LOG.info("setScan with ranges: " + bigStart_ + " - " + bigEnd_ + " ( " + bigRange_ + ")");
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (limit_ > 0 && ++recordsSeen > limit_) {
return false;
}
boolean hasMore = super.nextKeyValue();
if (hasMore) {
currRow_ = getCurrentKey().get();
}
return hasMore;
}
@Override
public float getProgress() {
if (currRow_ == null || currRow_.length == 0 || endRow_.length == 0 || endRow_ == HConstants.LAST_ROW) {
return 0;
}
byte[] lastPadded = currRow_;
if(maxRowLength > currRow_.length) {
lastPadded = Bytes.padTail(currRow_, maxRowLength - currRow_.length);
}
byte [] prependHeader = {1, 0};
BigInteger bigLastRow = new BigInteger(Bytes.add(prependHeader, lastPadded));
if (bigLastRow.compareTo(bigEnd_) > 0) {
return progressSoFar_;
}
BigDecimal processed = new BigDecimal(bigLastRow.subtract(bigStart_));
try {
BigDecimal progress = processed.setScale(3).divide(bigRange_, BigDecimal.ROUND_HALF_DOWN);
progressSoFar_ = progress.floatValue();
return progressSoFar_;
} catch (java.lang.ArithmeticException e) {
return 0;
}
}
}
}
| apache/pig | src/org/apache/pig/backend/hadoop/hbase/HBaseTableInputFormat.java | Java | apache-2.0 | 7,754 |
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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 io.reactivex.internal.operators.maybe;
import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.DisposableHelper;
import io.reactivex.internal.fuseable.HasUpstreamMaybeSource;
import java.util.concurrent.atomic.AtomicReference;
/**
* Subscribes to the other source if the main source is empty.
*
* @param <T> the value type
*/
public final class MaybeSwitchIfEmptySingle<T> extends Single<T> implements HasUpstreamMaybeSource<T> {
final MaybeSource<T> source;
final SingleSource<? extends T> other;
public MaybeSwitchIfEmptySingle(MaybeSource<T> source, SingleSource<? extends T> other) {
this.source = source;
this.other = other;
}
@Override
public MaybeSource<T> source() {
return source;
}
@Override
protected void subscribeActual(SingleObserver<? super T> observer) {
source.subscribe(new SwitchIfEmptyMaybeObserver<T>(observer, other));
}
static final class SwitchIfEmptyMaybeObserver<T>
extends AtomicReference<Disposable>
implements MaybeObserver<T>, Disposable {
private static final long serialVersionUID = 4603919676453758899L;
final SingleObserver<? super T> downstream;
final SingleSource<? extends T> other;
SwitchIfEmptyMaybeObserver(SingleObserver<? super T> actual, SingleSource<? extends T> other) {
this.downstream = actual;
this.other = other;
}
@Override
public void dispose() {
DisposableHelper.dispose(this);
}
@Override
public boolean isDisposed() {
return DisposableHelper.isDisposed(get());
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.setOnce(this, d)) {
downstream.onSubscribe(this);
}
}
@Override
public void onSuccess(T value) {
downstream.onSuccess(value);
}
@Override
public void onError(Throwable e) {
downstream.onError(e);
}
@Override
public void onComplete() {
Disposable d = get();
if (d != DisposableHelper.DISPOSED) {
if (compareAndSet(d, null)) {
other.subscribe(new OtherSingleObserver<T>(downstream, this));
}
}
}
static final class OtherSingleObserver<T> implements SingleObserver<T> {
final SingleObserver<? super T> downstream;
final AtomicReference<Disposable> parent;
OtherSingleObserver(SingleObserver<? super T> actual, AtomicReference<Disposable> parent) {
this.downstream = actual;
this.parent = parent;
}
@Override
public void onSubscribe(Disposable d) {
DisposableHelper.setOnce(parent, d);
}
@Override
public void onSuccess(T value) {
downstream.onSuccess(value);
}
@Override
public void onError(Throwable e) {
downstream.onError(e);
}
}
}
} | NiteshKant/RxJava | src/main/java/io/reactivex/internal/operators/maybe/MaybeSwitchIfEmptySingle.java | Java | apache-2.0 | 3,840 |
/*
* Copyright 2022 ThoughtWorks, 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.
*/
package com.thoughtworks.go.plugin.configrepo.contract.material;
import com.google.gson.JsonObject;
import com.thoughtworks.go.plugin.configrepo.contract.AbstractCRTest;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class CRConfigMaterialTest extends AbstractCRTest<CRConfigMaterial> {
private final CRConfigMaterial named;
private final CRConfigMaterial namedDest;
private final CRConfigMaterial materialWithIgnores;
private final CRConfigMaterial invalidList;
public CRConfigMaterialTest() {
named = new CRConfigMaterial("primary", null,null);
namedDest = new CRConfigMaterial("primary", "folder",null);
List<String> patterns = new ArrayList<>();
patterns.add("externals");
patterns.add("tools");
materialWithIgnores = new CRConfigMaterial("primary", "folder",new CRFilter(patterns,false));
CRFilter badFilter = new CRFilter(patterns,false);
badFilter.setIncludesNoCheck(patterns);
invalidList = new CRConfigMaterial("primary", "folder",badFilter);
}
@Override
public void addGoodExamples(Map<String, CRConfigMaterial> examples) {
examples.put("namedExample", named);
examples.put("namedDest", namedDest);
examples.put("ignoreFilter", materialWithIgnores);
}
@Override
public void addBadExamples(Map<String, CRConfigMaterial> examples) {
examples.put("invalidList",invalidList);
}
@Test
public void shouldAppendTypeFieldWhenSerializingMaterials()
{
CRMaterial value = named;
JsonObject jsonObject = (JsonObject)gson.toJsonTree(value);
assertThat(jsonObject.get("type").getAsString(), is(CRConfigMaterial.TYPE_NAME));
}
@Test
public void shouldHandlePolymorphismWhenDeserializing()
{
CRMaterial value = named;
String json = gson.toJson(value);
CRConfigMaterial deserializedValue = (CRConfigMaterial)gson.fromJson(json,CRMaterial.class);
assertThat("Deserialized value should equal to value before serialization",
deserializedValue,is(value));
}
}
| gocd/gocd | plugin-infra/go-plugin-config-repo/src/test/java/com/thoughtworks/go/plugin/configrepo/contract/material/CRConfigMaterialTest.java | Java | apache-2.0 | 2,880 |
package org.hl7.fhir.dstu3.model.codesystems;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0
import org.hl7.fhir.dstu3.model.EnumFactory;
public class ObservationStatusEnumFactory implements EnumFactory<ObservationStatus> {
public ObservationStatus fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
return null;
if ("registered".equals(codeString))
return ObservationStatus.REGISTERED;
if ("preliminary".equals(codeString))
return ObservationStatus.PRELIMINARY;
if ("final".equals(codeString))
return ObservationStatus.FINAL;
if ("amended".equals(codeString))
return ObservationStatus.AMENDED;
if ("cancelled".equals(codeString))
return ObservationStatus.CANCELLED;
if ("entered-in-error".equals(codeString))
return ObservationStatus.ENTEREDINERROR;
if ("unknown".equals(codeString))
return ObservationStatus.UNKNOWN;
throw new IllegalArgumentException("Unknown ObservationStatus code '"+codeString+"'");
}
public String toCode(ObservationStatus code) {
if (code == ObservationStatus.REGISTERED)
return "registered";
if (code == ObservationStatus.PRELIMINARY)
return "preliminary";
if (code == ObservationStatus.FINAL)
return "final";
if (code == ObservationStatus.AMENDED)
return "amended";
if (code == ObservationStatus.CANCELLED)
return "cancelled";
if (code == ObservationStatus.ENTEREDINERROR)
return "entered-in-error";
if (code == ObservationStatus.UNKNOWN)
return "unknown";
return "?";
}
public String toSystem(ObservationStatus code) {
return code.getSystem();
}
}
| Gaduo/hapi-fhir | hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/codesystems/ObservationStatusEnumFactory.java | Java | apache-2.0 | 3,374 |
/*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* 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.optaplanner.examples.nqueens.app;
import java.io.File;
import org.junit.Test;
import org.optaplanner.benchmark.api.PlannerBenchmarkException;
import org.optaplanner.benchmark.api.PlannerBenchmarkFactory;
import org.optaplanner.benchmark.config.PlannerBenchmarkConfig;
import org.optaplanner.examples.common.app.PlannerBenchmarkTest;
public class BrokenNQueensBenchmarkTest extends PlannerBenchmarkTest {
@Override
protected String createBenchmarkConfigResource() {
return "org/optaplanner/examples/nqueens/benchmark/nqueensBenchmarkConfig.xml";
}
@Override
protected PlannerBenchmarkFactory buildPlannerBenchmarkFactory(File unsolvedDataFile) {
PlannerBenchmarkFactory benchmarkFactory = super.buildPlannerBenchmarkFactory(unsolvedDataFile);
PlannerBenchmarkConfig benchmarkConfig = benchmarkFactory.getPlannerBenchmarkConfig();
benchmarkConfig.setWarmUpSecondsSpentLimit(0L);
benchmarkConfig.getInheritedSolverBenchmarkConfig().getSolverConfig().getTerminationConfig()
.setStepCountLimit(-100); // Intentionally crash the solver
return benchmarkFactory;
}
// ************************************************************************
// Tests
// ************************************************************************
@Test(timeout = 100000, expected = PlannerBenchmarkException.class)
public void benchmarkBroken8queens() {
runBenchmarkTest(new File("data/nqueens/unsolved/8queens.xml"));
}
}
| gsheldon/optaplanner | optaplanner-examples/src/test/java/org/optaplanner/examples/nqueens/app/BrokenNQueensBenchmarkTest.java | Java | apache-2.0 | 2,156 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.monitor.util.celltypes;
import java.io.Serializable;
import java.util.Comparator;
public abstract class CellType<T> implements Comparator<T>, Serializable {
private static final long serialVersionUID = 1L;
private boolean sortable = true;
abstract public String alignment();
abstract public String format(Object obj);
public final void setSortable(boolean sortable) {
this.sortable = sortable;
}
public final boolean isSortable() {
return sortable;
}
}
| adamjshook/accumulo | server/monitor/src/main/java/org/apache/accumulo/monitor/util/celltypes/CellType.java | Java | apache-2.0 | 1,314 |
package io.cattle.platform.process.dao.impl;
import static io.cattle.platform.core.model.tables.AccountTable.*;
import io.cattle.platform.core.model.Account;
import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao;
import io.cattle.platform.process.dao.AccountDao;
public class AccountDaoImpl extends AbstractJooqDao implements AccountDao {
@Override
public Account findByUuid(String uuid) {
return create()
.selectFrom(ACCOUNT)
.where(ACCOUNT.UUID.eq(uuid))
.fetchOne();
}
}
| cloudnautique/cloud-cattle | code/iaas/logic/src/main/java/io/cattle/platform/process/dao/impl/AccountDaoImpl.java | Java | apache-2.0 | 551 |
package net.ros.client.render;
import com.google.common.collect.ImmutableList;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.block.model.ItemOverrideList;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import net.ros.client.render.model.ModelCacheManager;
import net.ros.client.render.model.obj.PipeOBJStates;
import net.ros.client.render.model.obj.ROSOBJState;
import net.ros.common.block.BlockPipeBase;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nonnull;
import javax.vecmath.Matrix4f;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ModelPipeInventory implements IBakedModel
{
private final Map<ROSOBJState, CompositeBakedModel> CACHE = new HashMap<>();
private final BlockPipeBase pipeBlock;
public ModelPipeInventory(BlockPipeBase pipeBlock)
{
this.pipeBlock = pipeBlock;
}
@Nonnull
@Override
public List<BakedQuad> getQuads(IBlockState state, EnumFacing face, long rand)
{
return Collections.emptyList();
}
private CompositeBakedModel getModel(ROSOBJState pipeState)
{
if (CACHE.containsKey(pipeState))
return CACHE.get(pipeState);
else
{
CompositeBakedModel model = new CompositeBakedModel(ModelCacheManager.getPipeQuads(pipeBlock, pipeState),
Minecraft.getMinecraft().getBlockRendererDispatcher()
.getModelForState(pipeBlock.getDefaultState()));
CACHE.put(pipeState, model);
return model;
}
}
@Nonnull
@Override
public ItemOverrideList getOverrides()
{
return itemHandler;
}
@Override
public boolean isAmbientOcclusion()
{
return false;
}
@Override
public boolean isGui3d()
{
return true;
}
@Override
public boolean isBuiltInRenderer()
{
return false;
}
@Nonnull
@Override
public TextureAtlasSprite getParticleTexture()
{
return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("minecraft:blocks/dirt");
}
@Nonnull
@Override
public ItemCameraTransforms getItemCameraTransforms()
{
return ItemCameraTransforms.DEFAULT;
}
private static class CompositeBakedModel implements IBakedModel
{
private IBakedModel pipeModel;
private final List<BakedQuad> genQuads;
CompositeBakedModel(List<BakedQuad> pipeQuads, IBakedModel pipeModel)
{
this.pipeModel = pipeModel;
ImmutableList.Builder<BakedQuad> genBuilder = ImmutableList.builder();
genBuilder.addAll(pipeQuads);
genQuads = genBuilder.build();
}
@Nonnull
@Override
public List<BakedQuad> getQuads(IBlockState state, EnumFacing face, long rand)
{
return face == null ? genQuads : Collections.emptyList();
}
@Override
public boolean isAmbientOcclusion()
{
return pipeModel.isAmbientOcclusion();
}
@Override
public boolean isGui3d()
{
return pipeModel.isGui3d();
}
@Override
public boolean isBuiltInRenderer()
{
return pipeModel.isBuiltInRenderer();
}
@Nonnull
@Override
public TextureAtlasSprite getParticleTexture()
{
return pipeModel.getParticleTexture();
}
@Nonnull
@Override
public ItemOverrideList getOverrides()
{
return ItemOverrideList.NONE;
}
@Override
public Pair<? extends IBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType
cameraTransformType)
{
return Pair.of(this, pipeModel.handlePerspective(cameraTransformType).getRight());
}
}
private final ItemOverrideList itemHandler = new ItemOverrideList(ImmutableList.of())
{
@Nonnull
@Override
public IBakedModel handleItemState(@Nonnull IBakedModel model, ItemStack stack, World world,
EntityLivingBase entity)
{
return ModelPipeInventory.this.getModel(PipeOBJStates.getVisibilityState(
pipeBlock.getPipeType().getSize(), EnumFacing.WEST, EnumFacing.EAST));
}
};
}
| mantal/Qbar | content/logistic/src/main/java/net/ros/client/render/ModelPipeInventory.java | Java | apache-2.0 | 4,971 |
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.low.level.api.sessions;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public class SessionsInvalidationTestGenerated extends AbstractSessionsInvalidationTest {
private void runTest(String testDataFilePath) throws Exception {
KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
}
public void testAllFilesPresentInSessionInvalidation() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation"), Pattern.compile("^([^\\.]+)$"), null, false);
}
@TestMetadata("binaryTree")
public void testBinaryTree() throws Exception {
runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/binaryTree/");
}
@TestMetadata("binaryTreeNoInvalidated")
public void testBinaryTreeNoInvalidated() throws Exception {
runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/binaryTreeNoInvalidated/");
}
@TestMetadata("binaryTreeWithAdditionalEdge")
public void testBinaryTreeWithAdditionalEdge() throws Exception {
runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/binaryTreeWithAdditionalEdge/");
}
@TestMetadata("binaryTreeWithInvalidInRoot")
public void testBinaryTreeWithInvalidInRoot() throws Exception {
runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/binaryTreeWithInvalidInRoot/");
}
@TestMetadata("linear")
public void testLinear() throws Exception {
runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/linear/");
}
@TestMetadata("rhombus")
public void testRhombus() throws Exception {
runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/rhombus/");
}
@TestMetadata("rhombusWithTwoInvalid")
public void testRhombusWithTwoInvalid() throws Exception {
runTest("idea/idea-frontend-fir/idea-fir-low-level-api/testdata/sessionInvalidation/rhombusWithTwoInvalid/");
}
}
| mdaniel/intellij-community | plugins/kotlin/fir-low-level-api/test/org/jetbrains/kotlin/idea/fir/low/level/api/sessions/SessionsInvalidationTestGenerated.java | Java | apache-2.0 | 2,951 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package io.github.jass2125.locadora.jpa;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
/**
*
* @author Anderson Souza
* @email jair_anderson_bs@hotmail.com
* @since 2015, Feb 9, 2016
*/
public class EntityManagerJPA {
private static EntityManager em;
private EntityManagerJPA() {
}
public static EntityManager getEntityManager(){
if(em == null) {
em = Persistence.createEntityManagerFactory("default").createEntityManager();
}
return em;
}
}
| ifpb-disciplinas-2015-2/locadora-jpa-web | src/main/java/io/github/jass2125/locadora/jpa/EntityManagerJPA.java | Java | apache-2.0 | 740 |
/*******************************************************************************
* Copyright 2012 Apigee Corporation
*
* 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.usergrid.persistence.query.tree;
import org.antlr.runtime.Token;
import org.usergrid.persistence.exceptions.PersistenceException;
/**
* @author tnine
*
*/
public class ContainsOperand extends Operand {
/**
* @param property
* @param literal
*/
public ContainsOperand(Token t) {
super(t);
}
/* (non-Javadoc)
* @see org.usergrid.persistence.query.tree.Operand#visit(org.usergrid.persistence.query.tree.QueryVisitor)
*/
@Override
public void visit(QueryVisitor visitor) throws PersistenceException {
visitor.visit(this);
}
public void setProperty(String name){
setChild(0, new Property(name));
}
public void setValue(String value){
setChild(1, new StringLiteral(value));
}
public Property getProperty(){
return (Property) this.children.get(0);
}
public StringLiteral getString(){
return (StringLiteral) this.children.get(1);
}
}
| futur/usergrid-stack | core/src/main/java/org/usergrid/persistence/query/tree/ContainsOperand.java | Java | apache-2.0 | 1,697 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.server.core.api.subtree;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.schema.SchemaManager;
import org.apache.directory.api.ldap.model.subtree.SubtreeSpecification;
import org.apache.directory.server.core.api.event.Evaluator;
import org.apache.directory.server.core.api.event.ExpressionEvaluator;
/**
* An evaluator used to determine if an entry is included in the collection
* represented by a subtree specification.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SubtreeEvaluator
{
/** A refinement filter evaluator */
private final Evaluator evaluator;
/**
* Creates a subtreeSpecification evaluatior which can be used to determine
* if an entry is included within the collection of a subtree.
*
* @param schemaManager The server schemaManager
*/
public SubtreeEvaluator( SchemaManager schemaManager )
{
evaluator = new ExpressionEvaluator( schemaManager );
}
/**
* Determines if an entry is selected by a subtree specification.
*
* @param subtree the subtree specification
* @param apDn the distinguished name of the administrative point containing the subentry
* @param entryDn the distinguished name of the candidate entry
* @param entry The entry to evaluate
* @return true if the entry is selected by the specification, false if it is not
* @throws LdapException if errors are encountered while evaluating selection
*/
public boolean evaluate( SubtreeSpecification subtree, Dn apDn, Dn entryDn, Entry entry )
throws LdapException
{
/* =====================================================================
* NOTE: Regarding the overall approach, we try to narrow down the
* possibilities by slowly pruning relative names off of the entryDn.
* For example we check first if the entry is a descendant of the AP.
* If so we use the relative name thereafter to calculate if it is
* a descendant of the base. This means shorter names to compare and
* less work to do while we continue to deduce inclusion by the subtree
* specification.
* =====================================================================
*/
// First construct the subtree base, which is the concatenation of the
// AP Dn and the subentry base
Dn subentryBaseDn = apDn;
subentryBaseDn = subentryBaseDn.add( subtree.getBase() );
if ( !entryDn.isDescendantOf( subentryBaseDn ) )
{
// The entry Dn is not part of the subtree specification, get out
return false;
}
/*
* Evaluate based on minimum and maximum chop values. Here we simply
* need to compare the distances respectively with the size of the
* baseRelativeRdn. For the max distance entries with a baseRelativeRdn
* size greater than the max distance are rejected. For the min distance
* entries with a baseRelativeRdn size less than the minimum distance
* are rejected.
*/
int entryRelativeDnSize = entryDn.size() - subentryBaseDn.size();
if ( ( subtree.getMaxBaseDistance() != SubtreeSpecification.UNBOUNDED_MAX )
&& ( entryRelativeDnSize > subtree.getMaxBaseDistance() ) )
{
return false;
}
if ( ( subtree.getMinBaseDistance() > 0 ) && ( entryRelativeDnSize < subtree.getMinBaseDistance() ) )
{
return false;
}
/*
* For specific exclusions we must iterate through the set and check
* if the baseRelativeRdn is a descendant of the exclusion. The
* isDescendant() function will return true if the compared names
* are equal so for chopAfter exclusions we must check for equality
* as well and reject if the relative names are equal.
*/
// Now, get the entry's relative part
if ( !subtree.getChopBeforeExclusions().isEmpty() || !subtree.getChopAfterExclusions().isEmpty() )
{
Dn entryRelativeDn = entryDn.getDescendantOf( apDn ).getDescendantOf( subtree.getBase() );
for ( Dn chopBeforeDn : subtree.getChopBeforeExclusions() )
{
if ( entryRelativeDn.isDescendantOf( chopBeforeDn ) )
{
return false;
}
}
for ( Dn chopAfterDn : subtree.getChopAfterExclusions() )
{
if ( entryRelativeDn.isDescendantOf( chopAfterDn ) && !chopAfterDn.equals( entryRelativeDn ) )
{
return false;
}
}
}
/*
* The last remaining step is to check and see if the refinement filter
* selects the entry candidate based on objectClass attribute values.
* To do this we invoke the refinement evaluator members evaluate() method.
*/
if ( subtree.getRefinement() != null )
{
return evaluator.evaluate( subtree.getRefinement(), entryDn, entry );
}
/*
* If nothing has rejected the candidate entry and there is no refinement
* filter then the entry is included in the collection represented by the
* subtree specification so we return true.
*/
return true;
}
}
| apache/directory-server | core-api/src/main/java/org/apache/directory/server/core/api/subtree/SubtreeEvaluator.java | Java | apache-2.0 | 6,471 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.core.appender;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SocketAppenderBuilderTest {
/**
* Tests https://issues.apache.org/jira/browse/LOG4J2-1620
*/
@Test
public void testDefaultImmediateFlush() {
assertTrue(SocketAppender.newBuilder().isImmediateFlush(),
"Regression of LOG4J2-1620: default value for immediateFlush should be true");
}
}
| apache/logging-log4j2 | log4j-core/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderBuilderTest.java | Java | apache-2.0 | 1,293 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.marshaller.jdk;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.util.io.GridByteArrayInputStream;
import org.apache.ignite.internal.util.io.GridByteArrayOutputStream;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.marshaller.AbstractNodeNameAwareMarshaller;
import org.jetbrains.annotations.Nullable;
/**
* Implementation of {@link org.apache.ignite.marshaller.Marshaller} based on JDK serialization mechanism.
* <p>
* <h1 class="header">Configuration</h1>
* <h2 class="header">Mandatory</h2>
* This marshaller has no mandatory configuration parameters.
* <h2 class="header">Java Example</h2>
* {@code JdkMarshaller} needs to be explicitly configured to override default {@link org.apache.ignite.marshaller.optimized.OptimizedMarshaller}.
* <pre name="code" class="java">
* JdkMarshaller marshaller = new JdkMarshaller();
*
* IgniteConfiguration cfg = new IgniteConfiguration();
*
* // Override default marshaller.
* cfg.setMarshaller(marshaller);
*
* // Starts grid.
* G.start(cfg);
* </pre>
* <h2 class="header">Spring Example</h2>
* JdkMarshaller can be configured from Spring XML configuration file:
* <pre name="code" class="xml">
* <bean id="grid.custom.cfg" class="org.apache.ignite.configuration.IgniteConfiguration" singleton="true">
* ...
* <property name="marshaller">
* <bean class="org.apache.ignite.marshaller.jdk.JdkMarshaller"/>
* </property>
* ...
* </bean>
* </pre>
* <p>
* <img src="http://ignite.apache.org/images/spring-small.png">
* <br>
* For information about Spring framework visit <a href="http://www.springframework.org/">www.springframework.org</a>
*/
public class JdkMarshaller extends AbstractNodeNameAwareMarshaller {
/** {@inheritDoc} */
@Override protected void marshal0(@Nullable Object obj, OutputStream out) throws IgniteCheckedException {
assert out != null;
ObjectOutputStream objOut = null;
try {
objOut = new JdkMarshallerObjectOutputStream(new JdkMarshallerOutputStreamWrapper(out));
// Make sure that we serialize only task, without class loader.
objOut.writeObject(obj);
objOut.flush();
}
catch (Exception e) {
throw new IgniteCheckedException("Failed to serialize object: " + obj, e);
}
finally{
U.closeQuiet(objOut);
}
}
/** {@inheritDoc} */
@Override protected byte[] marshal0(@Nullable Object obj) throws IgniteCheckedException {
GridByteArrayOutputStream out = null;
try {
out = new GridByteArrayOutputStream(DFLT_BUFFER_SIZE);
marshal(obj, out);
return out.toByteArray();
}
finally {
U.close(out, null);
}
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
@Override protected <T> T unmarshal0(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
assert in != null;
if (clsLdr == null)
clsLdr = getClass().getClassLoader();
ObjectInputStream objIn = null;
try {
objIn = new JdkMarshallerObjectInputStream(new JdkMarshallerInputStreamWrapper(in), clsLdr);
return (T)objIn.readObject();
}
catch (ClassNotFoundException e) {
throw new IgniteCheckedException("Failed to find class with given class loader for unmarshalling " +
"(make sure same versions of all classes are available on all nodes or enable peer-class-loading): " +
clsLdr, e);
}
catch (Exception e) {
throw new IgniteCheckedException("Failed to deserialize object with given class loader: " + clsLdr, e);
}
finally{
U.closeQuiet(objIn);
}
}
/** {@inheritDoc} */
@Override protected <T> T unmarshal0(byte[] arr, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
GridByteArrayInputStream in = null;
try {
in = new GridByteArrayInputStream(arr, 0, arr.length);
return unmarshal(in, clsLdr);
}
finally {
U.close(in, null);
}
}
/** {@inheritDoc} */
@Override public void onUndeploy(ClassLoader ldr) {
// No-op.
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(JdkMarshaller.class, this);
}
}
| leveyj/ignite | modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java | Java | apache-2.0 | 5,576 |
package io.cattle.platform.configitem.server.model.impl;
import java.io.IOException;
import io.cattle.platform.configitem.server.model.RefreshableConfigItem;
import io.cattle.platform.configitem.server.resource.ResourceRoot;
import io.cattle.platform.configitem.version.ConfigItemStatusManager;
public abstract class AbstractResourceRootConfigItem extends AbstractConfigItem implements RefreshableConfigItem {
ResourceRoot resourceRoot;
public AbstractResourceRootConfigItem(String name, ConfigItemStatusManager versionManager, ResourceRoot resourceRoot) {
super(name, versionManager);
this.resourceRoot = resourceRoot;
}
@Override
public String getSourceRevision() {
return resourceRoot.getSourceRevision();
}
@Override
public void refresh() throws IOException {
resourceRoot.scan();
}
public ResourceRoot getResourceRoot() {
return resourceRoot;
}
}
| alena1108/cattle | code/iaas/config-item/server/src/main/java/io/cattle/platform/configitem/server/model/impl/AbstractResourceRootConfigItem.java | Java | apache-2.0 | 945 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.util.json;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* JsonArray is a common non-thread safe data format for a collection of data.
* The contents of a JsonArray are only validated as JSON values on
* serialization.
*
* @see Jsoner
* @since 2.0.0
*/
public class JsonArray extends ArrayList<Object> implements Jsonable {
/**
* The serialization version this class is compatible with. This value
* doesn't need to be incremented if and only if the only changes to occur
* were updating comments, updating javadocs, adding new fields to the
* class, changing the fields from static to non-static, or changing the
* fields from transient to non transient. All other changes require this
* number be incremented.
*/
private static final long serialVersionUID = 1L;
/** Instantiates an empty JsonArray. */
public JsonArray() {
}
/**
* Instantiate a new JsonArray using ArrayList's constructor of the same
* type.
*
* @param collection represents the elements to produce the JsonArray with.
*/
public JsonArray(final Collection<?> collection) {
super(collection);
}
/**
* A convenience method that assumes every element of the JsonArray is
* castable to T before adding it to a collection of Ts.
*
* @param <T> represents the type that all of the elements of the JsonArray
* should be cast to and the type the collection will contain.
* @param destination represents where all of the elements of the JsonArray
* are added to after being cast to the generic type provided.
* @throws ClassCastException if the unchecked cast of an element to T
* fails.
*/
@SuppressWarnings("unchecked")
public <T> void asCollection(final Collection<T> destination) {
for (final Object o : this) {
destination.add((T)o);
}
}
/**
* A convenience method that assumes there is a BigDecimal, Number, or
* String at the given index. If a Number or String is there it is used to
* construct a new BigDecimal.
*
* @param index representing where the value is expected to be at.
* @return the value stored at the key or the default provided if the key
* doesn't exist.
* @throws ClassCastException if there was a value but didn't match the
* assumed return types.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
* @throws NumberFormatException if a String isn't a valid representation of
* a BigDecimal.
* @see BigDecimal
* @see Number#doubleValue()
*/
public BigDecimal getBigDecimal(final int index) {
Object returnable = this.get(index);
if (returnable instanceof BigDecimal) {
/* Success there was a BigDecimal. */
} else if (returnable instanceof Number) {
/* A number can be used to construct a BigDecimal. */
returnable = new BigDecimal(returnable.toString());
} else if (returnable instanceof String) {
/* A number can be used to construct a BigDecimal. */
returnable = new BigDecimal((String)returnable);
}
return (BigDecimal)returnable;
}
/**
* A convenience method that assumes there is a Boolean or String value at
* the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a boolean.
* @throws ClassCastException if there was a value but didn't match the
* assumed return type.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
*/
public Boolean getBoolean(final int index) {
Object returnable = this.get(index);
if (returnable instanceof String) {
returnable = Boolean.valueOf((String)returnable);
}
return (Boolean)returnable;
}
/**
* A convenience method that assumes there is a Number or String value at
* the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a byte.
* @throws ClassCastException if there was a value but didn't match the
* assumed return type.
* @throws NumberFormatException if a String isn't a valid representation of
* a BigDecimal or if the Number represents the double or float
* Infinity or NaN.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
* @see Number
*/
public Byte getByte(final int index) {
Object returnable = this.get(index);
if (returnable == null) {
return null;
}
if (returnable instanceof String) {
/* A String can be used to construct a BigDecimal. */
returnable = new BigDecimal((String)returnable);
}
return ((Number)returnable).byteValue();
}
/**
* A convenience method that assumes there is a Collection value at the
* given index.
*
* @param <T> the kind of collection to expect at the index. Note unless
* manually added, collection values will be a JsonArray.
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a Collection.
* @throws ClassCastException if there was a value but didn't match the
* assumed return type.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
* @see Collection
*/
@SuppressWarnings("unchecked")
public <T extends Collection<?>> T getCollection(final int index) {
/*
* The unchecked warning is suppressed because there is no way of
* guaranteeing at compile time the cast will work.
*/
return (T)this.get(index);
}
/**
* A convenience method that assumes there is a Number or String value at
* the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a double.
* @throws ClassCastException if there was a value but didn't match the
* assumed return type.
* @throws NumberFormatException if a String isn't a valid representation of
* a BigDecimal or if the Number represents the double or float
* Infinity or NaN.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
* @see Number
*/
public Double getDouble(final int index) {
Object returnable = this.get(index);
if (returnable == null) {
return null;
}
if (returnable instanceof String) {
/* A String can be used to construct a BigDecimal. */
returnable = new BigDecimal((String)returnable);
}
return ((Number)returnable).doubleValue();
}
/**
* A convenience method that assumes there is a String value at the given
* index representing a fully qualified name in dot notation of an enum.
*
* @param index representing where the value is expected to be at.
* @param <T> the Enum type the value at the index is expected to belong to.
* @return the enum based on the string found at the index, or null if the
* value at the index was null.
* @throws ClassNotFoundException if the element was a String but the
* declaring enum type couldn't be determined with it.
* @throws ClassCastException if the element at the index was not a String
* or if the fully qualified enum name is of the wrong type.
* @throws IllegalArgumentException if an enum type was dynamically
* determined but it doesn't define an enum with the dynamically
* determined name.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
* @see Enum#valueOf(Class, String)
*/
@SuppressWarnings("unchecked")
public <T extends Enum<T>> T getEnum(final int index) throws ClassNotFoundException {
/*
* Supressing the unchecked warning because the returnType is
* dynamically identified and could lead to a ClassCastException when
* returnType is cast to Class<T>, which is expected by the method's
* contract.
*/
T returnable;
final String element;
final String[] splitValues;
final int numberOfValues;
final StringBuilder returnTypeName;
final StringBuilder enumName;
final Class<T> returnType;
/* Make sure the element at the index is a String. */
element = this.getString(index);
if (element == null) {
return null;
}
/* Get the package, class, and enum names. */
splitValues = element.split("\\.");
numberOfValues = splitValues.length;
returnTypeName = new StringBuilder();
enumName = new StringBuilder();
for (int i = 0; i < numberOfValues; i++) {
if (i == (numberOfValues - 1)) {
/*
* If it is the last split value then it should be the name of
* the Enum since dots are not allowed in enum names.
*/
enumName.append(splitValues[i]);
} else if (i == (numberOfValues - 2)) {
/*
* If it is the penultimate split value then it should be the
* end of the package/enum type and not need a dot appended to
* it.
*/
returnTypeName.append(splitValues[i]);
} else {
/*
* Must be part of the package/enum type and will need a dot
* appended to it since they got removed in the split.
*/
returnTypeName.append(splitValues[i]);
returnTypeName.append(".");
}
}
/* Use the package/class and enum names to get the Enum<T>. */
returnType = (Class<T>)Class.forName(returnTypeName.toString());
returnable = Enum.valueOf(returnType, enumName.toString());
return returnable;
}
/**
* A convenience method that assumes there is a Number or String value at
* the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a float.
* @throws ClassCastException if there was a value but didn't match the
* assumed return type.
* @throws NumberFormatException if a String isn't a valid representation of
* a BigDecimal or if the Number represents the double or float
* Infinity or NaN.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
* @see Number
*/
public Float getFloat(final int index) {
Object returnable = this.get(index);
if (returnable == null) {
return null;
}
if (returnable instanceof String) {
/* A String can be used to construct a BigDecimal. */
returnable = new BigDecimal((String)returnable);
}
return ((Number)returnable).floatValue();
}
/**
* A convenience method that assumes there is a Number or String value at
* the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a int.
* @throws ClassCastException if there was a value but didn't match the
* assumed return type.
* @throws NumberFormatException if a String isn't a valid representation of
* a BigDecimal or if the Number represents the double or float
* Infinity or NaN.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
* @see Number
*/
public Integer getInteger(final int index) {
Object returnable = this.get(index);
if (returnable == null) {
return null;
}
if (returnable instanceof String) {
/* A String can be used to construct a BigDecimal. */
returnable = new BigDecimal((String)returnable);
}
return ((Number)returnable).intValue();
}
/**
* A convenience method that assumes there is a Number or String value at
* the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a long.
* @throws ClassCastException if there was a value but didn't match the
* assumed return type.
* @throws NumberFormatException if a String isn't a valid representation of
* a BigDecimal or if the Number represents the double or float
* Infinity or NaN.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
* @see Number
*/
public Long getLong(final int index) {
Object returnable = this.get(index);
if (returnable == null) {
return null;
}
if (returnable instanceof String) {
/* A String can be used to construct a BigDecimal. */
returnable = new BigDecimal((String)returnable);
}
return ((Number)returnable).longValue();
}
/**
* A convenience method that assumes there is a Map value at the given
* index.
*
* @param <T> the kind of map to expect at the index. Note unless manually
* added, Map values will be a JsonObject.
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a Map.
* @throws ClassCastException if there was a value but didn't match the
* assumed return type.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
* @see Map
*/
@SuppressWarnings("unchecked")
public <T extends Map<?, ?>> T getMap(final int index) {
/*
* The unchecked warning is suppressed because there is no way of
* guaranteeing at compile time the cast will work.
*/
return (T)this.get(index);
}
/**
* A convenience method that assumes there is a Number or String value at
* the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a short.
* @throws ClassCastException if there was a value but didn't match the
* assumed return type.
* @throws NumberFormatException if a String isn't a valid representation of
* a BigDecimal or if the Number represents the double or float
* Infinity or NaN.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
* @see Number
*/
public Short getShort(final int index) {
Object returnable = this.get(index);
if (returnable == null) {
return null;
}
if (returnable instanceof String) {
/* A String can be used to construct a BigDecimal. */
returnable = new BigDecimal((String)returnable);
}
return ((Number)returnable).shortValue();
}
/**
* A convenience method that assumes there is a Boolean, Number, or String
* value at the given index.
*
* @param index represents where the value is expected to be at.
* @return the value at the index provided cast to a String.
* @throws ClassCastException if there was a value but didn't match the
* assumed return type.
* @throws IndexOutOfBoundsException if the index is outside of the range of
* element indexes in the JsonArray.
*/
public String getString(final int index) {
Object returnable = this.get(index);
if (returnable instanceof Boolean) {
returnable = returnable.toString();
} else if (returnable instanceof Number) {
returnable = returnable.toString();
}
return (String)returnable;
}
/*
* (non-Javadoc)
* @see org.apache.camel.util.json.Jsonable#asJsonString()
*/
@Override
public String toJson() {
final StringWriter writable = new StringWriter();
try {
this.toJson(writable);
} catch (final IOException caught) {
/* See java.io.StringWriter. */
}
return writable.toString();
}
/*
* (non-Javadoc)
* @see org.apache.camel.util.json.Jsonable#toJsonString(java.io.Writer)
*/
@Override
public void toJson(final Writer writable) throws IOException {
boolean isFirstElement = true;
final Iterator<Object> elements = this.iterator();
writable.write('[');
while (elements.hasNext()) {
if (isFirstElement) {
isFirstElement = false;
} else {
writable.write(',');
}
writable.write(Jsoner.serialize(elements.next()));
}
writable.write(']');
}
}
| objectiser/camel | tooling/camel-util-json/src/main/java/org/apache/camel/util/json/JsonArray.java | Java | apache-2.0 | 19,042 |
/*
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* 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.jasig.portlet.notice.util;
import javax.portlet.PortletRequest;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Component("usernameFinder")
public final class UsernameFinder {
@Value("${UsernameFinder.unauthenticatedUsername}")
private String unauthenticatedUsername = "guest";
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* @deprecated Prefer interactions that are not based on the Portlet API
*/
@Deprecated
public String findUsername(PortletRequest req) {
return req.getRemoteUser() != null
? req.getRemoteUser()
: unauthenticatedUsername;
}
/**
* @since 4.0
*/
public String findUsername(HttpServletRequest request) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
logger.trace("Processing the following Authentication object: {}", authentication);
final String rslt = (String) authentication.getPrincipal();
logger.debug("Found username '{}' based on the contents of the SecurityContextHolder", rslt);
// Identification based on Spring Security is required to access Servlet-based APIs
if (rslt == null) {
throw new SecurityException("User not identified");
}
return rslt;
}
/**
* @deprecated Prefer interactions that are not based on the Portlet API
*/
@Deprecated
public boolean isAuthenticated(PortletRequest req) {
return !findUsername(req).equalsIgnoreCase(unauthenticatedUsername);
}
public boolean isAuthenticated(HttpServletRequest request) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
logger.trace("Processing the following Authentication object: {}", authentication);
return authentication != null && authentication.isAuthenticated();
}
}
| Jasig/NotificationPortlet | notification-portlet-webapp/src/main/java/org/jasig/portlet/notice/util/UsernameFinder.java | Java | apache-2.0 | 3,039 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.indexing.input;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterators;
import org.apache.druid.client.coordinator.CoordinatorClient;
import org.apache.druid.data.input.AbstractInputSource;
import org.apache.druid.data.input.InputFileAttribute;
import org.apache.druid.data.input.InputFormat;
import org.apache.druid.data.input.InputRowSchema;
import org.apache.druid.data.input.InputSourceReader;
import org.apache.druid.data.input.InputSplit;
import org.apache.druid.data.input.MaxSizeSplitHintSpec;
import org.apache.druid.data.input.SegmentsSplitHintSpec;
import org.apache.druid.data.input.SplitHintSpec;
import org.apache.druid.data.input.impl.InputEntityIteratingReader;
import org.apache.druid.data.input.impl.SplittableInputSource;
import org.apache.druid.indexing.common.ReingestionTimelineUtils;
import org.apache.druid.indexing.common.RetryPolicy;
import org.apache.druid.indexing.common.RetryPolicyFactory;
import org.apache.druid.indexing.common.SegmentLoaderFactory;
import org.apache.druid.indexing.firehose.WindowedSegmentId;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.guava.Comparators;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.query.filter.DimFilter;
import org.apache.druid.segment.IndexIO;
import org.apache.druid.segment.loading.SegmentLoader;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.TimelineObjectHolder;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.timeline.partition.PartitionChunk;
import org.apache.druid.timeline.partition.PartitionHolder;
import org.apache.druid.utils.Streams;
import org.joda.time.Duration;
import org.joda.time.Interval;
import javax.annotation.Nullable;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
public class DruidInputSource extends AbstractInputSource implements SplittableInputSource<List<WindowedSegmentId>>
{
private static final Logger LOG = new Logger(DruidInputSource.class);
/**
* A Comparator that orders {@link WindowedSegmentId} mainly by segmentId (which is important), and then by intervals
* (which is arbitrary, and only here for totality of ordering).
*/
private static final Comparator<WindowedSegmentId> WINDOWED_SEGMENT_ID_COMPARATOR =
Comparator.comparing(WindowedSegmentId::getSegmentId)
.thenComparing(windowedSegmentId -> windowedSegmentId.getIntervals().size())
.thenComparing(
(WindowedSegmentId a, WindowedSegmentId b) -> {
// Same segmentId, same intervals list size. Compare each interval.
int cmp = 0;
for (int i = 0; i < a.getIntervals().size(); i++) {
cmp = Comparators.intervalsByStartThenEnd()
.compare(a.getIntervals().get(i), b.getIntervals().get(i));
if (cmp != 0) {
return cmp;
}
}
return cmp;
}
);
private final String dataSource;
// Exactly one of interval and segmentIds should be non-null. Typically 'interval' is specified directly
// by the user creating this firehose and 'segmentIds' is used for sub-tasks if it is split for parallel
// batch ingestion.
@Nullable
private final Interval interval;
@Nullable
private final List<WindowedSegmentId> segmentIds;
private final DimFilter dimFilter;
private final List<String> dimensions;
private final List<String> metrics;
private final IndexIO indexIO;
private final CoordinatorClient coordinatorClient;
private final SegmentLoaderFactory segmentLoaderFactory;
private final RetryPolicyFactory retryPolicyFactory;
@JsonCreator
public DruidInputSource(
@JsonProperty("dataSource") final String dataSource,
@JsonProperty("interval") @Nullable Interval interval,
// Specifying "segments" is intended only for when this FirehoseFactory has split itself,
// not for direct end user use.
@JsonProperty("segments") @Nullable List<WindowedSegmentId> segmentIds,
@JsonProperty("filter") DimFilter dimFilter,
@Nullable @JsonProperty("dimensions") List<String> dimensions,
@Nullable @JsonProperty("metrics") List<String> metrics,
@JacksonInject IndexIO indexIO,
@JacksonInject CoordinatorClient coordinatorClient,
@JacksonInject SegmentLoaderFactory segmentLoaderFactory,
@JacksonInject RetryPolicyFactory retryPolicyFactory
)
{
Preconditions.checkNotNull(dataSource, "dataSource");
if ((interval == null && segmentIds == null) || (interval != null && segmentIds != null)) {
throw new IAE("Specify exactly one of 'interval' and 'segments'");
}
this.dataSource = dataSource;
this.interval = interval;
this.segmentIds = segmentIds;
this.dimFilter = dimFilter;
this.dimensions = dimensions;
this.metrics = metrics;
this.indexIO = Preconditions.checkNotNull(indexIO, "null IndexIO");
this.coordinatorClient = Preconditions.checkNotNull(coordinatorClient, "null CoordinatorClient");
this.segmentLoaderFactory = Preconditions.checkNotNull(segmentLoaderFactory, "null SegmentLoaderFactory");
this.retryPolicyFactory = Preconditions.checkNotNull(retryPolicyFactory, "null RetryPolicyFactory");
}
@JsonProperty
public String getDataSource()
{
return dataSource;
}
@Nullable
@JsonProperty
public Interval getInterval()
{
return interval;
}
@Nullable
@JsonProperty("segments")
@JsonInclude(Include.NON_NULL)
public List<WindowedSegmentId> getSegmentIds()
{
return segmentIds;
}
@JsonProperty("filter")
public DimFilter getDimFilter()
{
return dimFilter;
}
@JsonProperty
public List<String> getDimensions()
{
return dimensions;
}
@JsonProperty
public List<String> getMetrics()
{
return metrics;
}
@Override
protected InputSourceReader fixedFormatReader(InputRowSchema inputRowSchema, @Nullable File temporaryDirectory)
{
final SegmentLoader segmentLoader = segmentLoaderFactory.manufacturate(temporaryDirectory);
final List<TimelineObjectHolder<String, DataSegment>> timeline = createTimeline();
final Iterator<DruidSegmentInputEntity> entityIterator = FluentIterable
.from(timeline)
.transformAndConcat(holder -> {
//noinspection ConstantConditions
final PartitionHolder<DataSegment> partitionHolder = holder.getObject();
//noinspection ConstantConditions
return FluentIterable
.from(partitionHolder)
.transform(chunk -> new DruidSegmentInputEntity(segmentLoader, chunk.getObject(), holder.getInterval()));
}).iterator();
final List<String> effectiveDimensions = ReingestionTimelineUtils.getDimensionsToReingest(
dimensions,
inputRowSchema.getDimensionsSpec(),
timeline
);
List<String> effectiveMetrics;
if (metrics == null) {
effectiveMetrics = ReingestionTimelineUtils.getUniqueMetrics(timeline);
} else {
effectiveMetrics = metrics;
}
final DruidSegmentInputFormat inputFormat = new DruidSegmentInputFormat(
indexIO,
dimFilter,
effectiveDimensions,
effectiveMetrics
);
return new InputEntityIteratingReader(
inputRowSchema,
inputFormat,
entityIterator,
temporaryDirectory
);
}
private List<TimelineObjectHolder<String, DataSegment>> createTimeline()
{
if (interval == null) {
return getTimelineForSegmentIds(coordinatorClient, dataSource, segmentIds);
} else {
return getTimelineForInterval(coordinatorClient, retryPolicyFactory, dataSource, interval);
}
}
@Override
public Stream<InputSplit<List<WindowedSegmentId>>> createSplits(
InputFormat inputFormat,
@Nullable SplitHintSpec splitHintSpec
)
{
// segmentIds is supposed to be specified by the supervisor task during the parallel indexing.
// If it's not null, segments are already split by the supervisor task and further split won't happen.
if (segmentIds == null) {
return Streams.sequentialStreamFrom(
createSplits(
coordinatorClient,
retryPolicyFactory,
dataSource,
interval,
splitHintSpec == null ? SplittableInputSource.DEFAULT_SPLIT_HINT_SPEC : splitHintSpec
)
);
} else {
return Stream.of(new InputSplit<>(segmentIds));
}
}
@Override
public int estimateNumSplits(InputFormat inputFormat, @Nullable SplitHintSpec splitHintSpec)
{
// segmentIds is supposed to be specified by the supervisor task during the parallel indexing.
// If it's not null, segments are already split by the supervisor task and further split won't happen.
if (segmentIds == null) {
return Iterators.size(
createSplits(
coordinatorClient,
retryPolicyFactory,
dataSource,
interval,
splitHintSpec == null ? SplittableInputSource.DEFAULT_SPLIT_HINT_SPEC : splitHintSpec
)
);
} else {
return 1;
}
}
@Override
public SplittableInputSource<List<WindowedSegmentId>> withSplit(InputSplit<List<WindowedSegmentId>> split)
{
return new DruidInputSource(
dataSource,
null,
split.get(),
dimFilter,
dimensions,
metrics,
indexIO,
coordinatorClient,
segmentLoaderFactory,
retryPolicyFactory
);
}
@Override
public boolean needsFormat()
{
return false;
}
public static Iterator<InputSplit<List<WindowedSegmentId>>> createSplits(
CoordinatorClient coordinatorClient,
RetryPolicyFactory retryPolicyFactory,
String dataSource,
Interval interval,
SplitHintSpec splitHintSpec
)
{
final SplitHintSpec convertedSplitHintSpec;
if (splitHintSpec instanceof SegmentsSplitHintSpec) {
final SegmentsSplitHintSpec segmentsSplitHintSpec = (SegmentsSplitHintSpec) splitHintSpec;
convertedSplitHintSpec = new MaxSizeSplitHintSpec(
segmentsSplitHintSpec.getMaxInputSegmentBytesPerTask(),
segmentsSplitHintSpec.getMaxNumSegments()
);
} else {
convertedSplitHintSpec = splitHintSpec;
}
final List<TimelineObjectHolder<String, DataSegment>> timelineSegments = getTimelineForInterval(
coordinatorClient,
retryPolicyFactory,
dataSource,
interval
);
final Map<WindowedSegmentId, Long> segmentIdToSize = createWindowedSegmentIdFromTimeline(timelineSegments);
//noinspection ConstantConditions
return Iterators.transform(
convertedSplitHintSpec.split(
// segmentIdToSize is sorted by segment ID; useful for grouping up segments from the same time chunk into
// the same input split.
segmentIdToSize.keySet().iterator(),
segmentId -> new InputFileAttribute(
Preconditions.checkNotNull(segmentIdToSize.get(segmentId), "segment size for [%s]", segmentId)
)
),
InputSplit::new
);
}
/**
* Returns a map of {@link WindowedSegmentId} to size, sorted by {@link WindowedSegmentId#getSegmentId()}.
*/
private static SortedMap<WindowedSegmentId, Long> createWindowedSegmentIdFromTimeline(
List<TimelineObjectHolder<String, DataSegment>> timelineHolders
)
{
Map<DataSegment, WindowedSegmentId> windowedSegmentIds = new HashMap<>();
for (TimelineObjectHolder<String, DataSegment> holder : timelineHolders) {
for (PartitionChunk<DataSegment> chunk : holder.getObject()) {
windowedSegmentIds.computeIfAbsent(
chunk.getObject(),
segment -> new WindowedSegmentId(segment.getId().toString(), new ArrayList<>())
).addInterval(holder.getInterval());
}
}
// It is important to create this map after windowedSegmentIds is completely filled, because WindowedSegmentIds
// can be updated while being constructed. (Intervals are added.)
SortedMap<WindowedSegmentId, Long> segmentSizeMap = new TreeMap<>(WINDOWED_SEGMENT_ID_COMPARATOR);
windowedSegmentIds.forEach((segment, segmentId) -> segmentSizeMap.put(segmentId, segment.getSize()));
return segmentSizeMap;
}
public static List<TimelineObjectHolder<String, DataSegment>> getTimelineForInterval(
CoordinatorClient coordinatorClient,
RetryPolicyFactory retryPolicyFactory,
String dataSource,
Interval interval
)
{
Preconditions.checkNotNull(interval);
// This call used to use the TaskActionClient, so for compatibility we use the same retry configuration
// as TaskActionClient.
final RetryPolicy retryPolicy = retryPolicyFactory.makeRetryPolicy();
Collection<DataSegment> usedSegments;
while (true) {
try {
usedSegments = coordinatorClient.fetchUsedSegmentsInDataSourceForIntervals(
dataSource,
Collections.singletonList(interval)
);
break;
}
catch (Throwable e) {
LOG.warn(e, "Exception getting database segments");
final Duration delay = retryPolicy.getAndIncrementRetryDelay();
if (delay == null) {
throw e;
} else {
final long sleepTime = jitter(delay.getMillis());
LOG.info("Will try again in [%s].", new Duration(sleepTime).toString());
try {
Thread.sleep(sleepTime);
}
catch (InterruptedException e2) {
throw new RuntimeException(e2);
}
}
}
}
return VersionedIntervalTimeline.forSegments(usedSegments).lookup(interval);
}
public static List<TimelineObjectHolder<String, DataSegment>> getTimelineForSegmentIds(
CoordinatorClient coordinatorClient,
String dataSource,
List<WindowedSegmentId> segmentIds
)
{
final SortedMap<Interval, TimelineObjectHolder<String, DataSegment>> timeline = new TreeMap<>(
Comparators.intervalsByStartThenEnd()
);
for (WindowedSegmentId windowedSegmentId : Preconditions.checkNotNull(segmentIds, "segmentIds")) {
final DataSegment segment = coordinatorClient.fetchUsedSegment(
dataSource,
windowedSegmentId.getSegmentId()
);
for (Interval interval : windowedSegmentId.getIntervals()) {
final TimelineObjectHolder<String, DataSegment> existingHolder = timeline.get(interval);
if (existingHolder != null) {
if (!existingHolder.getVersion().equals(segment.getVersion())) {
throw new ISE("Timeline segments with the same interval should have the same version: " +
"existing version[%s] vs new segment[%s]", existingHolder.getVersion(), segment);
}
existingHolder.getObject().add(segment.getShardSpec().createChunk(segment));
} else {
timeline.put(
interval,
new TimelineObjectHolder<>(
interval,
segment.getInterval(),
segment.getVersion(),
new PartitionHolder<>(segment.getShardSpec().createChunk(segment))
)
);
}
}
}
// Validate that none of the given windows overlaps (except for when multiple segments share exactly the
// same interval).
Interval lastInterval = null;
for (Interval interval : timeline.keySet()) {
if (lastInterval != null && interval.overlaps(lastInterval)) {
throw new IAE(
"Distinct intervals in input segments may not overlap: [%s] vs [%s]",
lastInterval,
interval
);
}
lastInterval = interval;
}
return new ArrayList<>(timeline.values());
}
private static long jitter(long input)
{
final double jitter = ThreadLocalRandom.current().nextGaussian() * input / 4.0;
long retval = input + (long) jitter;
return retval < 0 ? 0 : retval;
}
}
| gianm/druid | indexing-service/src/main/java/org/apache/druid/indexing/input/DruidInputSource.java | Java | apache-2.0 | 17,743 |
import java.io.File;
import java.io.FilenameFilter;
class A {
{
new java.io.File("aaa").list(new FilenameFilter() {
public boolean accept(File dir, String name) {
<selection>return false; //To change body of implemented methods use File | Settings | File Templates.</selection>
}
});
}
} | joewalnes/idea-community | java/java-tests/testData/codeInsight/completion/style/AfterNew15-out.java | Java | apache-2.0 | 329 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.