repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
erdincay/pjsip-jni
src/org/pjsip/pjsua/pjsip_event_body_tx_msg.java
1444
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.36 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package org.pjsip.pjsua; public class pjsip_event_body_tx_msg { private long swigCPtr; protected boolean swigCMemOwn; protected pjsip_event_body_tx_msg(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(pjsip_event_body_tx_msg obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if(swigCPtr != 0 && swigCMemOwn) { swigCMemOwn = false; pjsuaJNI.delete_pjsip_event_body_tx_msg(swigCPtr); } swigCPtr = 0; } public void setTdata(SWIGTYPE_p_pjsip_tx_data value) { pjsuaJNI.pjsip_event_body_tx_msg_tdata_set(swigCPtr, this, SWIGTYPE_p_pjsip_tx_data.getCPtr(value)); } public SWIGTYPE_p_pjsip_tx_data getTdata() { long cPtr = pjsuaJNI.pjsip_event_body_tx_msg_tdata_get(swigCPtr, this); return (cPtr == 0) ? null : new SWIGTYPE_p_pjsip_tx_data(cPtr, false); } public pjsip_event_body_tx_msg() { this(pjsuaJNI.new_pjsip_event_body_tx_msg(), true); } }
gpl-2.0
smarr/graal
graal/com.oracle.graal.compiler.hsail.test/src/com/oracle/graal/compiler/hsail/test/lambda/DoubleTwoInputMathBase.java
1930
/* * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.compiler.hsail.test.lambda; public abstract class DoubleTwoInputMathBase extends DoubleMathBase { double[] inArray1 = new double[size * size]; double[] inArray2 = new double[size * size]; @Result double[] bigOutArray = new double[size * size]; @Override String getInputString(int idx) { return "(" + inArray1[idx] + ", " + inArray2[idx] + ")"; } /** * Initializes the input and output arrays. */ @Override void setupArrays() { super.setupArrays(); // make combinations of the input array for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { int idx = i * size + j; inArray1[idx] = inArray[i]; inArray2[idx] = inArray[j]; bigOutArray[idx] = 0; } } } }
gpl-2.0
Jianchu/LogiqlSolver
src/dataflow/DataflowAnnotatedTypeFactory.java
12867
package dataflow; import org.checkerframework.common.basetype.BaseAnnotatedTypeFactory; import org.checkerframework.common.basetype.BaseTypeChecker; import org.checkerframework.framework.type.AnnotatedTypeMirror; import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType; import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedPrimitiveType; import org.checkerframework.framework.type.QualifierHierarchy; import org.checkerframework.framework.type.treeannotator.ListTreeAnnotator; import org.checkerframework.framework.type.treeannotator.TreeAnnotator; import org.checkerframework.framework.util.GraphQualifierHierarchy; import org.checkerframework.framework.util.MultiGraphQualifierHierarchy.MultiGraphFactory; import org.checkerframework.javacutil.AnnotationUtils; import org.checkerframework.javacutil.ElementUtils; import org.checkerframework.javacutil.TreeUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeMirror; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewArrayTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree.Kind; import dataflow.qual.DataFlow; import dataflow.qual.DataFlowTop; import dataflow.util.DataflowUtils; public class DataflowAnnotatedTypeFactory extends BaseAnnotatedTypeFactory { protected final AnnotationMirror DATAFLOW, DATAFLOWBOTTOM, DATAFLOWTOP; private ExecutableElement dataflowValue = TreeUtils.getMethod( "dataflow.qual.DataFlow", "typeNames", 0, processingEnv); private final Map<String, TypeMirror> typeNamesMap = new HashMap<String, TypeMirror>(); //cannot use DataFlow.class.toString(), the string would be "interface dataflow.quals.DataFlow" //private ExecutableElement dataflowValue = TreeUtils.getMethod(DataFlow.class.toString(), "typeNames", 0, processingEnv); public DataflowAnnotatedTypeFactory(BaseTypeChecker checker) { super(checker); DATAFLOW = AnnotationUtils.fromClass(elements, DataFlow.class); DATAFLOWBOTTOM = DataflowUtils.createDataflowAnnotation(DataflowUtils.convert(""), processingEnv); DATAFLOWTOP = AnnotationUtils.fromClass(elements, DataFlowTop.class); postInit(); } @Override public TreeAnnotator createTreeAnnotator() { return new ListTreeAnnotator( super.createTreeAnnotator(), new DataflowTreeAnnotator() ); } @Override public QualifierHierarchy createQualifierHierarchy(MultiGraphFactory factory) { return new DataFlowQualifierHierarchy(factory, DATAFLOWBOTTOM); } @Override public AnnotatedDeclaredType getBoxedType(AnnotatedPrimitiveType type) { TypeElement typeElt = types.boxedClass(type.getUnderlyingType()); AnnotationMirror am = DataflowUtils.createDataflowAnnotation(typeElt.asType().toString(), this.processingEnv); AnnotatedDeclaredType dt = fromElement(typeElt); dt.addAnnotation(am); return dt; } @Override public AnnotatedPrimitiveType getUnboxedType(AnnotatedDeclaredType type) throws IllegalArgumentException { PrimitiveType primitiveType = types.unboxedType(type.getUnderlyingType()); AnnotationMirror am = DataflowUtils.createDataflowAnnotation(primitiveType.toString(), this.processingEnv); AnnotatedPrimitiveType pt = (AnnotatedPrimitiveType) AnnotatedTypeMirror.createType( primitiveType, this, false); pt.addAnnotation(am); return pt; } private final class DataFlowQualifierHierarchy extends GraphQualifierHierarchy { public DataFlowQualifierHierarchy(MultiGraphFactory f, AnnotationMirror bottom) { super(f, bottom); } private boolean isSubtypeWithRoots(AnnotationMirror rhs, AnnotationMirror lhs) { Set<String> rTypeNamesSet = new HashSet<String>(Arrays.asList(DataflowUtils.getTypeNames(rhs))); Set<String> lTypeNamesSet = new HashSet<String>(Arrays.asList(DataflowUtils.getTypeNames(lhs))); Set<String> rRootsSet = new HashSet<String>(Arrays.asList(DataflowUtils.getTypeNameRoots(rhs))); Set<String> lRootsSet = new HashSet<String>(Arrays.asList(DataflowUtils.getTypeNameRoots(lhs))); Set<String> combinedTypeNames = new HashSet<String>(); combinedTypeNames.addAll(rTypeNamesSet); combinedTypeNames.addAll(lTypeNamesSet); Set<String> combinedRoots = new HashSet<String>(); combinedRoots.addAll(rRootsSet); combinedRoots.addAll(lRootsSet); AnnotationMirror combinedAnno = DataflowUtils.createDataflowAnnotationWithRoots( combinedTypeNames, combinedRoots, processingEnv); AnnotationMirror refinedCombinedAnno = refineDataflow(combinedAnno); AnnotationMirror refinedLhs = refineDataflow(lhs); if (AnnotationUtils.areSame(refinedCombinedAnno, refinedLhs)) { return true; } else { return false; } } private boolean isSubtypeWithoutRoots(AnnotationMirror rhs, AnnotationMirror lhs) { Set<String> rTypeNamesSet = new HashSet<String>(Arrays.asList(DataflowUtils.getTypeNames(rhs))); Set<String> lTypeNamesSet = new HashSet<String>(Arrays.asList(DataflowUtils.getTypeNames(lhs))); if (lTypeNamesSet.containsAll(rTypeNamesSet)) { return true; } else { return false; } } @Override public boolean isSubtype(AnnotationMirror rhs, AnnotationMirror lhs) { if (AnnotationUtils.areSameIgnoringValues(rhs, DATAFLOW) && AnnotationUtils.areSameIgnoringValues(lhs, DATAFLOW)) { return isSubtypeWithRoots(rhs, lhs); // return isSubtypeWithoutRoots(rhs, lhs); } else { //if (rhs != null && lhs != null) if (AnnotationUtils.areSameIgnoringValues(rhs, DATAFLOW)) { rhs = DATAFLOW; } else if (AnnotationUtils.areSameIgnoringValues(lhs, DATAFLOW)) { lhs = DATAFLOW; } return super.isSubtype(rhs, lhs); } } } public class DataflowTreeAnnotator extends TreeAnnotator { public DataflowTreeAnnotator() { super(DataflowAnnotatedTypeFactory.this); } @Override public Void visitNewArray(final NewArrayTree node, final AnnotatedTypeMirror type) { AnnotationMirror dataFlowType = DataflowUtils.genereateDataflowAnnoFromNewClass(type, processingEnv); TypeMirror tm = type.getUnderlyingType(); typeNamesMap.put(tm.toString(), tm); type.replaceAnnotation(dataFlowType); return super.visitNewArray(node, type); } @Override public Void visitNewClass(NewClassTree node, AnnotatedTypeMirror type) { AnnotationMirror dataFlowType = DataflowUtils.genereateDataflowAnnoFromNewClass(type, processingEnv); TypeMirror tm = type.getUnderlyingType(); typeNamesMap.put(tm.toString(), tm); type.replaceAnnotation(dataFlowType); return super.visitNewClass(node, type); } @Override public Void visitLiteral(LiteralTree node, AnnotatedTypeMirror type) { if (!node.getKind().equals(Kind.NULL_LITERAL)) { AnnotatedTypeMirror annoType = type; AnnotationMirror dataFlowType = DataflowUtils.generateDataflowAnnoFromLiteral(annoType, processingEnv); type.replaceAnnotation(dataFlowType); } return super.visitLiteral(node, type); } @Override public Void visitMethodInvocation(MethodInvocationTree node, AnnotatedTypeMirror type) { ExecutableElement methodElement = TreeUtils.elementFromUse(node); boolean isBytecode = ElementUtils.isElementFromByteCode(methodElement); if (isBytecode) { AnnotationMirror dataFlowType = DataflowUtils.genereateDataflowAnnoFromByteCode(type, processingEnv); TypeMirror tm = type.getUnderlyingType(); typeNamesMap.put(tm.toString(), tm); type.replaceAnnotation(dataFlowType); } return super.visitMethodInvocation(node, type); } } public AnnotationMirror refineDataflow(AnnotationMirror type) { String[] typeNameRoots = DataflowUtils.getTypeNameRoots(type); Set<String> refinedRoots = new HashSet<String>(); if (typeNameRoots.length == 0) { } else if (typeNameRoots.length == 1) { refinedRoots.add(typeNameRoots[0]); } else { List<String> rootsList = new ArrayList<String>(Arrays.asList(typeNameRoots)); while (rootsList.size() != 0) { TypeMirror decType = getTypeMirror(rootsList.get(0)); if (!isComparable(decType, rootsList)) { refinedRoots.add(rootsList.get(0)); rootsList.remove(0); } } } String[] typeNames = DataflowUtils.getTypeNames(type); Arrays.sort(typeNames); Set<String> refinedtypeNames = new HashSet<String>(); if (refinedRoots.size() == 0) { refinedtypeNames = new HashSet<String>(Arrays.asList(typeNames)); return DataflowUtils.createDataflowAnnotation(refinedtypeNames, processingEnv); } else { for (String typeName : typeNames) { if (typeName == "") { continue; } TypeMirror decType = getTypeMirror(typeName); if (shouldPresent(decType, refinedRoots)) { refinedtypeNames.add(typeName); } } } return DataflowUtils.createDataflowAnnotationWithRoots(refinedtypeNames, refinedRoots, processingEnv); } private boolean isComparable(TypeMirror decType, List<String> rootsList) { for (int i = 1; i < rootsList.size(); i++) { if (rootsList.get(i) == "") { continue; } TypeMirror comparedDecType = getTypeMirror(rootsList.get(i)); if (this.types.isSubtype(comparedDecType, decType)) { rootsList.remove(i); return true; } else if (this.types.isSubtype(decType, comparedDecType)) { rootsList.remove(0); return true; } } return false; } private boolean shouldPresent(TypeMirror decType, Set<String> refinedRoots) { for (String refinedRoot : refinedRoots) { if (refinedRoot == "") { continue; } TypeMirror comparedDecType = getTypeMirror(refinedRoot); if (this.types.isSubtype(decType, comparedDecType)) { return false; } else if (this.types.isSubtype(comparedDecType, decType)) { return true; } } return true; } private TypeMirror getTypeMirror(String typeName) { if (this.typeNamesMap.keySet().contains(typeName)) { return this.typeNamesMap.get(typeName); } else { return elements.getTypeElement(convertToReferenceType(typeName)).asType(); } } private String convertToReferenceType(String typeName) { switch (typeName) { case "int": return Integer.class.getName(); case "short": return Short.class.getName(); case "byte": return Byte.class.getName(); case "long": return Long.class.getName(); case "char": return Character.class.getName(); case "float": return Float.class.getName(); case "double": return Double.class.getName(); case "boolean": return Boolean.class.getName(); default: return typeName; } } public Map<String, TypeMirror> getTypeNameMap() { return this.typeNamesMap; } }
gpl-2.0
fix4j/fix4j-assert
fix4j-assert-core/src/main/java/org/fix4j/test/fixmodel/Group.java
375
package org.fix4j.test.fixmodel; import org.fix4j.test.fixspec.GroupType; import org.fix4j.test.fixspec.Tag; import java.util.List; /** * User: ben * Date: 26/09/2014 * Time: 5:33 AM */ public interface Group extends FieldSource, PrettyPrintable { GroupType getType(); Field getNoOfField(); List<FieldsAndGroups> getRepeats(); Tag<Integer> getTag(); }
gpl-2.0
SkidJava/BaseClient
new_1.8.8/net/minecraft/item/ItemDye.java
6203
package net.minecraft.item; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockPlanks; import net.minecraft.block.IGrowable; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntitySheep; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; public class ItemDye extends Item { public static final int[] dyeColors = new int[] {1973019, 11743532, 3887386, 5320730, 2437522, 8073150, 2651799, 11250603, 4408131, 14188952, 4312372, 14602026, 6719955, 12801229, 15435844, 15790320}; public ItemDye() { this.setHasSubtypes(true); this.setMaxDamage(0); this.setCreativeTab(CreativeTabs.tabMaterials); } /** * Returns the unlocalized name of this item. This version accepts an ItemStack so different stacks can have * different names based on their damage or NBT. */ public String getUnlocalizedName(ItemStack stack) { int i = stack.getMetadata(); return super.getUnlocalizedName() + "." + EnumDyeColor.byDyeDamage(i).getUnlocalizedName(); } /** * Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ) { if (!playerIn.canPlayerEdit(pos.offset(side), side, stack)) { return false; } else { EnumDyeColor enumdyecolor = EnumDyeColor.byDyeDamage(stack.getMetadata()); if (enumdyecolor == EnumDyeColor.WHITE) { if (applyBonemeal(stack, worldIn, pos)) { if (!worldIn.isRemote) { worldIn.playAuxSFX(2005, pos, 0); } return true; } } else if (enumdyecolor == EnumDyeColor.BROWN) { IBlockState iblockstate = worldIn.getBlockState(pos); Block block = iblockstate.getBlock(); if (block == Blocks.log && iblockstate.getValue(BlockPlanks.VARIANT) == BlockPlanks.EnumType.JUNGLE) { if (side == EnumFacing.DOWN) { return false; } if (side == EnumFacing.UP) { return false; } pos = pos.offset(side); if (worldIn.isAirBlock(pos)) { IBlockState iblockstate1 = Blocks.cocoa.onBlockPlaced(worldIn, pos, side, hitX, hitY, hitZ, 0, playerIn); worldIn.setBlockState(pos, iblockstate1, 2); if (!playerIn.capabilities.isCreativeMode) { --stack.stackSize; } } return true; } } return false; } } public static boolean applyBonemeal(ItemStack stack, World worldIn, BlockPos target) { IBlockState iblockstate = worldIn.getBlockState(target); if (iblockstate.getBlock() instanceof IGrowable) { IGrowable igrowable = (IGrowable)iblockstate.getBlock(); if (igrowable.canGrow(worldIn, target, iblockstate, worldIn.isRemote)) { if (!worldIn.isRemote) { if (igrowable.canUseBonemeal(worldIn, worldIn.rand, target, iblockstate)) { igrowable.grow(worldIn, worldIn.rand, target, iblockstate); } --stack.stackSize; } return true; } } return false; } public static void spawnBonemealParticles(World worldIn, BlockPos pos, int amount) { if (amount == 0) { amount = 15; } Block block = worldIn.getBlockState(pos).getBlock(); if (block.getMaterial() != Material.air) { block.setBlockBoundsBasedOnState(worldIn, pos); for (int i = 0; i < amount; ++i) { double d0 = itemRand.nextGaussian() * 0.02D; double d1 = itemRand.nextGaussian() * 0.02D; double d2 = itemRand.nextGaussian() * 0.02D; worldIn.spawnParticle(EnumParticleTypes.VILLAGER_HAPPY, (double)((float)pos.getX() + itemRand.nextFloat()), (double)pos.getY() + (double)itemRand.nextFloat() * block.getBlockBoundsMaxY(), (double)((float)pos.getZ() + itemRand.nextFloat()), d0, d1, d2, new int[0]); } } } /** * Returns true if the item can be used on the given entity, e.g. shears on sheep. */ public boolean itemInteractionForEntity(ItemStack stack, EntityPlayer playerIn, EntityLivingBase target) { if (target instanceof EntitySheep) { EntitySheep entitysheep = (EntitySheep)target; EnumDyeColor enumdyecolor = EnumDyeColor.byDyeDamage(stack.getMetadata()); if (!entitysheep.getSheared() && entitysheep.getFleeceColor() != enumdyecolor) { entitysheep.setFleeceColor(enumdyecolor); --stack.stackSize; } return true; } else { return false; } } /** * returns a list of items with the same ID, but different meta (eg: dye returns 16 items) */ public void getSubItems(Item itemIn, CreativeTabs tab, List<ItemStack> subItems) { for (int i = 0; i < 16; ++i) { subItems.add(new ItemStack(itemIn, 1, i)); } } }
gpl-2.0
TEAMMATES/teammates
src/test/java/teammates/logic/api/MockUserProvision.java
1379
package teammates.logic.api; import teammates.common.datatransfer.UserInfo; import teammates.common.datatransfer.UserInfoCookie; /** * Allows mocking of the {@link UserProvision} API used in production. * * <p>Instead of getting user information from the authentication service, * the API will return pre-determined information instead. */ public class MockUserProvision extends UserProvision { private UserInfo mockUser = new UserInfo("user.id"); private boolean isLoggedIn; private UserInfo loginUser(String userId, boolean isAdmin) { isLoggedIn = true; mockUser.id = userId; mockUser.isAdmin = isAdmin; return getCurrentUser(null); } /** * Adds a logged-in user without admin rights. * * @return The user info after login process */ public UserInfo loginUser(String userId) { return loginUser(userId, false); } /** * Adds a logged-in user as an admin. * * @return The user info after login process */ public UserInfo loginAsAdmin(String userId) { return loginUser(userId, true); } /** * Removes the logged-in user information. */ public void logoutUser() { isLoggedIn = false; } @Override UserInfo getCurrentLoggedInUser(UserInfoCookie uic) { return isLoggedIn ? mockUser : null; } }
gpl-2.0
chdoig/ache
src/main/java/focusedCrawler/util/storage/AbstractStorageItemFactory.java
1554
/* ############################################################################ ## ## Copyright (C) 2006-2009 University of Utah. All rights reserved. ## ## This file is part of DeepPeep. ## ## This file may be used under the terms of the GNU General Public ## License version 2.0 as published by the Free Software Foundation ## and appearing in the file LICENSE.GPL included in the packaging of ## this file. Please review the following to ensure GNU General Public ## Licensing requirements will be met: ## http://www.opensource.org/licenses/gpl-license.php ## ## If you are unsure which license is appropriate for your use (for ## instance, you are interested in developing a commercial derivative ## of DeepPeep), please contact us at deeppeep@sci.utah.edu. ## ## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ## ############################################################################ */ package focusedCrawler.util.storage; import focusedCrawler.util.ParameterFile; public abstract class AbstractStorageItemFactory implements StorageItemFactory { private ParameterFile config; public AbstractStorageItemFactory() { super(); } public AbstractStorageItemFactory(ParameterFile config) { setConfig(config); } public ParameterFile getConfig() { return config; } //getConfig public void setConfig(ParameterFile newConfig) { this.config = newConfig; } //setConfig } //class
gpl-2.0
heartsome/translationstudio8
ts/net.heartsome.cat.ts.ui.xliffeditor.nattable/src/net/heartsome/cat/ts/ui/xliffeditor/nattable/propertyTester/SignOffPropertyTester.java
3045
package net.heartsome.cat.ts.ui.xliffeditor.nattable.propertyTester; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.heartsome.cat.ts.core.file.RowIdUtil; import net.heartsome.cat.ts.core.file.XLFHandler; import net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable; import org.eclipse.core.expressions.PropertyTester; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; /** * 签发的 test * @author peason * @version * @since JDK1.6 */ public class SignOffPropertyTester extends PropertyTester { public static final String PROPERTY_NAMESPACE = "signedOff"; public static final String PROPERTY_ENABLED = "enabled"; public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { // IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); // if (window != null) { // IWorkbenchPage page = window.getActivePage(); // if (page != null) { // IEditorPart editor = page.getActiveEditor(); // if (editor != null && editor instanceof XLIFFEditorImplWithNatTable) { // XLIFFEditorImplWithNatTable xliffEditor = (XLIFFEditorImplWithNatTable) editor; // if (xliffEditor != null && xliffEditor.getTable() != null) { // long l = System.currentTimeMillis(); // XLFHandler handler = xliffEditor.getXLFHandler(); // List<String> selectedRowIds = xliffEditor.getSelectedRowIds(); // if (selectedRowIds != null && selectedRowIds.size() > 0) { // boolean isLock = true; // boolean isDraft = true; // for (String rowId : selectedRowIds) { // if (!handler.isDraft(rowId) && isDraft) { // isDraft = false; // if (!isLock) { // break; // } // } // if (!handler.isLocked(rowId) && isLock) { // isLock = false; // if (!isDraft) { // break; // } // } // } // if (isLock || isDraft) { // return false; // } // final Map<String, List<String>> tmpGroup = RowIdUtil.groupRowIdByFileName(selectedRowIds); // boolean hasNullTgt = true; // group: // for (Entry<String, List<String>> entry : tmpGroup.entrySet()) { // List<String> lstRowIdList = entry.getValue(); // for (String rowId : lstRowIdList) { // String tgtText = handler.getTgtContent(rowId); // if (tgtText != null && !tgtText.equals("") && hasNullTgt) { // hasNullTgt = false; // break group; // } // } // } // if (hasNullTgt) { // System.out.println(getClass() + ": "+ (System.currentTimeMillis() - l)); // return false; // } // System.out.println(getClass() + ": "+ (System.currentTimeMillis() - l)); // return true; // } // System.out.println(getClass() + ": "+ (System.currentTimeMillis() - l)); // } // } // } // } // return false; return true; } }
gpl-2.0
orph/wikipedia-miner
src/org/wikipedia/miner/util/MySqlDatabase.java
9157
/* * MySqlDatabase.java * Copyright (C) 2007 David Milne, d.n.milne@gmail.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.wikipedia.miner.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.sql.SQLException; /** * This convenience class provides access to a MySql database via the MySqlConnector-J toolkit. * * @author David Milne */ public class MySqlDatabase { private Connection connection ; private String server ; private String databaseName ; private String userName ; private String password ; private String encoding ; private int statementsIssued ; /** * Initializes a newly created MySqlDatabase and attempts to make a connection to the * database defined by the arguments given. * * @param server the connection string for the server (e.g 130.232.231.053:8080 or bob:8080) * @param databaseName the name of the database (e.g <em>enwiki</em>) * @param userName the user for the sql database (null if anonymous) * @param password the users password (null if anonymous) * @param encoding the character encoding (e.g. utf8) in which data is stored (null if using database default) * @throws Exception if there is a problem connecting to the database defined by given arguments. */ public MySqlDatabase(String server, String databaseName, String userName, String password, String encoding) throws Exception{ this.server = server ; this.databaseName = databaseName ; this.userName = userName ; this.password = password ; this.encoding = encoding ; this.statementsIssued = 0 ; connect() ; } /** * @return true if the connection to the database is active, otherwise false. */ public boolean checkConnection() { try { //try a simple query Statement stmt = createStatement() ; ResultSet rs = stmt.executeQuery("SHOW TABLES") ; rs.close() ; stmt.close() ; return true ; } catch (SQLException e) { return false ; } } /** * attempts to make a connection to the mysql database. * @throws SQLException if a connection cannot be made. * @throws InstantiationException if the mysql driver class cannot be instantiated * @throws IllegalAccessException if the mysql driver class cannot be instantiated * @throws ClassNotFoundException if the mysql driver class cannot be found */ public void connect() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException{ // load the sql drivers Class.forName("org.gjt.mm.mysql.Driver").newInstance(); // establish a connection String url = "jdbc:mysql://" + server + "/" + databaseName ; boolean argsStarted = false ; if (userName != null && !userName.equals("")) { url = url + "?user=" + userName ; argsStarted = true ; } if (password != null && !password.equals("")) { if (argsStarted) url = url + "&password=" + password ; else url = url + "?password=" + password ; argsStarted = true ; } if (encoding != null && !encoding.equals("")) { if (argsStarted) url = url + "&characterEncoding=" + encoding ; else url = url + "?characterEncoding=" + encoding ; } connection = DriverManager.getConnection(url) ; } /** * Specifies whether each update statement is to be automatically executed immediately, or left until commit() is called. * It is often more efficent set this to false and wait for several update statements to be issued before calling commit(). * This is false by default. * * @param autocommit true if each update statement is to be automatically executed immediately, otherwise false. * @throws SQLException if there is a problem with the database connection */ public void setAutoCommit(boolean autocommit) throws SQLException { this.connection.setAutoCommit(autocommit) ; } /** * Commits any pending update statements. This is only neccessary if autocommit has been set to false. * * @throws SQLException if there is a problem with the database connection */ public void commit() throws SQLException { this.connection.commit() ; } /** * Creates a Statement object for sending SQL statements to the database. * * @return the statement object * @throws SQLException if there is a problem with the database connection */ public Statement createStatement() throws SQLException { statementsIssued ++ ; try { return connection.createStatement() ; } catch (SQLException e) { try { this.connect() ; return connection.createStatement() ; } catch (Exception e2) { throw new SQLException() ; } } } /** * Returns the number of statements (queries) that have been issued to the database since this * connection was initialized. * * @return as above */ public int getStatementsIssuedSinceStartup() { return statementsIssued ; } /** * returns true if this database contains a table with the given table name, otherwise false. * * @param tableName the name of the table to check * @return true if this database contains a table with the given table name, otherwise false. * @throws SQLException if there is a problem with the database */ public boolean tableExists(String tableName) throws SQLException { boolean exists = true ; Statement stmt = createStatement() ; try { stmt.executeQuery("SELECT 1 FROM `" + tableName + "` LIMIT 0") ; } catch (SQLException e) { exists = false ; } stmt.close() ; return exists ; } /** * returns true if this database contains an index for the given table and index name, otherwise false. * * @param tableName the name of the table to check * @param indexName the name of the index to check * @return true if this database contains an index for the given table and index name, otherwise false. * @throws SQLException if there is a problem with the database */ public boolean indexExists(String tableName, String indexName) throws SQLException { boolean exists = true ; Statement stmt = createStatement() ; ResultSet rs = stmt.executeQuery("SELECT * FROM information_schema.statistics " + "WHERE TABLE_SCHEMA='" + databaseName + "' " + "AND TABLE_NAME='" + tableName + "' " + "AND INDEX_NAME='" + indexName + "' ;") ; if (rs.first()) exists = true ; else exists = false ; rs.close() ; stmt.close() ; return exists ; } /** * Returns an estimated row count for a given table. This may not be accurate (particularly if the table is * in a state of flux) but will always be quickly and efficiently calculated. * * @param tableName the name of the table to check * @return the number of rows in the given table * @throws SQLException if there is a problem with the database */ public int getRowCountEstimate(String tableName) throws SQLException { int count = 0 ; Statement stmt = createStatement() ; ResultSet rs = stmt.executeQuery("SHOW TABLE STATUS " + "WHERE name='" + tableName + "';") ; if (rs.first()) count = rs.getInt("Rows") ; rs.close() ; stmt.close() ; return count ; } /** * Returns an exact row count for a given table. This will always be accurate but may take some time * to calculate for larger tables. * * @param tableName the name of the table to check * @return the number of rows in the given table * @throws SQLException if there is a problem with the database */ public int getRowCountExact(String tableName) throws SQLException { int count = 0 ; Statement stmt = createStatement() ; ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName) ; if (rs.first()) count = rs.getInt(1) ; rs.close() ; stmt.close() ; return count ; } /** * Modifies a string so that it can be safely inserted into a database; escapes all special characters such * as quotes and slashes * * @param s the string to modify * @return the modified string */ public String addEscapes( String s ) { StringBuffer sb = new StringBuffer(); int index; int length = s.length(); char ch; for( index = 0; index < length; ++index ) if(( ch = s.charAt( index )) == '\"' ) sb.append( "\\\"" ); else if( ch == '\'' ) sb.append( "\\'" ); else if( ch == '\\' ) sb.append( "\\\\" ); else sb.append( ch ); return( sb.toString()); } }
gpl-2.0
dumptruckman/MC-Server-GUI--multi-
lib/quartz-2.0.1/quartz/src/main/java/org/quartz/impl/matchers/EverythingMatcher.java
1769
/* * All content copyright Terracotta, Inc., unless otherwise indicated. 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.quartz.impl.matchers; import org.quartz.JobKey; import org.quartz.Matcher; import org.quartz.TriggerKey; import org.quartz.utils.Key; /** * Matches on the complete key being equal (both name and group). * * @author jhouse */ public class EverythingMatcher<T extends Key> implements Matcher<T> { protected EverythingMatcher() { } /** * Create an EverythingMatcher that matches all jobs. */ public static EverythingMatcher<JobKey> allJobs() { return new EverythingMatcher<JobKey>(); } /** * Create an EverythingMatcher that matches all triggers. */ public static EverythingMatcher<TriggerKey> allTriggers() { return new EverythingMatcher<TriggerKey>(); } public boolean isMatch(T key) { return true; } @Override public boolean equals(Object obj) { if(obj == null) return false; return obj.getClass().equals(getClass()); } @Override public int hashCode() { return getClass().getName().hashCode(); } }
gpl-2.0
Debian/openjfx
modules/controls/src/main/java/javafx/scene/control/ResizeFeaturesBase.java
2556
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javafx.scene.control; import javafx.beans.NamedArg; /** * An immutable wrapper class for use by the column resize policies offered by * controls such as {@link TableView} and {@link TreeTableView}. * @since JavaFX 8.0 */ public class ResizeFeaturesBase<S> { private final TableColumnBase<S,?> column; private final Double delta; /** * Creates an instance of this class, with the provided TableColumnBase and * delta values being set and stored in this immutable instance. * * @param column The column upon which the resize is occurring, or null * if this ResizeFeatures instance is being created as a result of a * resize operation. * @param delta The amount of horizontal space added or removed in the * resize operation. */ public ResizeFeaturesBase(@NamedArg("column") TableColumnBase<S,?> column, @NamedArg("delta") Double delta) { this.column = column; this.delta = delta; } /** * Returns the column upon which the resize is occurring, or null * if this ResizeFeatures instance was created as a result of a * resize operation. */ public TableColumnBase<S,?> getColumn() { return column; } /** * Returns the amount of horizontal space added or removed in the * resize operation. */ public Double getDelta() { return delta; } }
gpl-2.0
midaboghetich/netnumero
src/com/numhero/client/widget/combobox/ServiceUnitEnumComboBox.java
268
package com.numhero.client.widget.combobox; import com.numhero.shared.enums.ServiceUnitEnum; public class ServiceUnitEnumComboBox extends EnumComboBox<ServiceUnitEnum> { public ServiceUnitEnumComboBox() { super(ServiceUnitEnum.class); } }
gpl-2.0
JoeyLeeuwinga/Firemox
src/main/java/net/sf/firemox/xml/event/Endofphase.java
1940
/* * Created on 27 févr. 2005 * * Firemox is a turn based strategy simulator * Copyright (C) 2003-2007 Fabrice Daugan * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.sf.firemox.xml.event; import java.io.IOException; import java.io.OutputStream; import net.sf.firemox.event.Event; import net.sf.firemox.xml.XmlEvent; import net.sf.firemox.xml.XmlParser; import net.sf.firemox.xml.XmlToMDB; /** * @author <a href="mailto:fabdouglas@users.sourceforge.net">Fabrice Daugan </a> * @since 0.82 */ public class Endofphase implements XmlToMDB { /** * <ul> * Structure of stream : Data[size] * <li>idEvent [1]</li> * <li>idZone [1]</li> * <li>test [...]</li> * <li>idPhase [2]</li> * </ul> * * @param node * the XML event structure * @param out * output stream where the card structure will be saved * @return the amount of written action, so return always ZERO. * @see net.sf.firemox.event.phase.EndOfPhase * @throws IOException */ public final int buildMdb(XmlParser.Node node, OutputStream out) throws IOException { // write the idEvent Event.EOP.write(out); XmlEvent.buildMdbPhase(node, out); return 0; } }
gpl-2.0
breitling/KoulUnitTestingModules
src/test/java/org/breitling/dragon/framework/test/TestHazelcastUtils.java
1266
package org.breitling.dragon.framework.test; import com.hazelcast.core.HazelcastInstance; import org.junit.Test; import org.breitling.dragon.framework.types.SimpleTest; import org.breitling.dragon.framework.util.HazelcastUtils; import org.junit.After; import static org.junit.Assert.assertNotNull; import org.junit.Before; public class TestHazelcastUtils extends SimpleTest { private HazelcastInstance instance; // TEST CASES @Test public void testCreateTestInstance_DefaultNames_Instance() { instance = HazelcastUtils.createTestInstance(); assertNotNull(instance); } @Test public void testCreateTestInstance_Names_Instance() { instance = HazelcastUtils.createTestInstance("MyCluster", "MyCaching"); assertNotNull(instance); } @Test public void testCreateTestInstance_All_Instance() { instance = HazelcastUtils.createTestInstance("localhost", 5702, "My-Cluster", "My-Caching"); assertNotNull(instance); } @After public void testCaseTearDown() { instance.shutdown(); instance = null; super.testCaseTearDown(); } }
gpl-2.0
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/jndi/src/main/java/org/apache/harmony/jndi/provider/ldap/parser/TokenMgrError.java
5551
/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 4.1 */ /* JavaCCOptions: */ /* * 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. */ /* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 4.1 */ /* JavaCCOptions: */ package org.apache.harmony.jndi.provider.ldap.parser; /** Token Manager Error. */ public class TokenMgrError extends Error { /** * The version identifier for this Serializable class. * Increment only if the <i>serialized</i> form of the * class changes. */ private static final long serialVersionUID = 1L; /* * Ordinals for various reasons why an Error of this type can be thrown. */ /** * Lexical error occurred. */ static final int LEXICAL_ERROR = 0; /** * An attempt was made to create a second instance of a static token manager. */ static final int STATIC_LEXER_ERROR = 1; /** * Tried to change to an invalid lexical state. */ static final int INVALID_LEXICAL_STATE = 2; /** * Detected (and bailed out of) an infinite loop in the token manager. */ static final int LOOP_DETECTED = 3; /** * Indicates the reason why the exception is thrown. It will have * one of the above 4 values. */ int errorCode; /** * Replaces unprintable characters by their escaped (or unicode escaped) * equivalents in the given string */ protected static final String addEscapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } /** * Returns a detailed message for the Error when it is thrown by the * token manager to indicate a lexical error. * Parameters : * EOFSeen : indicates if EOF caused the lexical error * curLexState : lexical state in which this error occurred * errorLine : line number when the error occurred * errorColumn : column number when the error occurred * errorAfter : prefix that was seen before this error occurred * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /** * You can also modify the body of this method to customize your error messages. * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not * of end-users concern, so you can return something like : * * "Internal Error : Please file a bug report .... " * * from this method for such cases in the release version of your parser. */ public String getMessage() { return super.getMessage(); } /* * Constructors of various flavors follow. */ /** No arg constructor. */ public TokenMgrError() { } /** Constructor with message and reason. */ public TokenMgrError(String message, int reason) { super(message); errorCode = reason; } /** Full Constructor. */ public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); } } /* JavaCC - OriginalChecksum=6b4a38ce96dcb6e22ad144cf7cbd370c (do not edit this line) */
gpl-2.0
saurabhkpatel/academic_projects
CSE687_Object_oriented_design_C++/Pr4s15/RemoteCodeManagement/server2root/Java/Getattrs.java
2664
/* * @(#)Getattrs.java 1.4 00/04/28 * * Copyright 1997, 1998, 1999 Sun Microsystems, Inc. All Rights * Reserved. * * Sun grants you ("Licensee") a non-exclusive, royalty free, * license to use, modify and redistribute this software in source and * binary code form, provided that i) this copyright notice and license * appear on all copies of the software; and ii) Licensee does not * utilize the software in a manner which is disparaging to Sun. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE * HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE * FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, * MODIFYING OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN * NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT * OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * This software is not designed or intended for use in on-line * control of aircraft, air traffic, aircraft navigation or aircraft * communications; or in the design, construction, operation or * maintenance of any nuclear facility. Licensee represents and warrants * that it will not use or redistribute the Software for such purposes. */ import javax.naming.*; import javax.naming.directory.*; import java.util.Hashtable; /** * Demonstrates how to retrieve selected attributes of a named object. * * usage: java Getattrs */ class Getattrs { public static void main(String[] args) { // Set up the environment for creating the initial context Hashtable env = new Hashtable(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try { // Create initial context DirContext ctx = new InitialDirContext(env); // Specify the ids of the attributes to return String[] attrIDs = {"sn", "telephonenumber", "golfhandicap", "mail"}; // Get the attributes requested Attributes answer = ctx.getAttributes("cn=Ted Geisel, ou=People", attrIDs); // Print the answer GetattrsAll.printAttrs(answer); // Close the context when we're done ctx.close(); } catch (Exception e) { e.printStackTrace(); } } }
gpl-2.0
bharathk005/prism-4.2.1-src-teaser-patch
src/prism/SCCComputerLockstep.java
14510
//============================================================================== // // Copyright (c) 2002- // Authors: // * Carlos S. Bederian (Universidad Nacional de Cordoba) // * Dave Parker <david.parker@comlab.ox.ac.uk> (University of Oxford, formerly University of Birmingham) // //------------------------------------------------------------------------------ // // This file is part of PRISM. // // PRISM is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // PRISM 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 PRISM; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //============================================================================== package prism; import java.util.Stack; import java.util.Vector; import jdd.JDD; import jdd.JDDNode; import jdd.JDDVars; /** * SCC (strongly connected component) decomposition using lockstep search with trimming * (from Bloem/Gabow/Somenzi 2000) */ public class SCCComputerLockstep extends SCCComputer { private class DecompTask { JDDNode _nodes; JDDNode _edges; DecompTask(JDDNode nodes, JDDNode edges) { _nodes = nodes; _edges = edges; } JDDNode getNodes() { return _nodes; } JDDNode getEdges() { return _edges; } } private JDDNode allSCCs; private Stack<DecompTask> tasks; /** * Build (B)SCC computer for a given model. */ public SCCComputerLockstep(PrismComponent parent, JDDNode reach, JDDNode trans01, JDDVars allDDRowVars, JDDVars allDDColVars) throws PrismException { super(parent, reach, trans01, allDDRowVars, allDDColVars); } // Methods for SCCComputer @Override public void computeSCCs() { sccs = new Vector<JDDNode>(); allSCCs = JDD.Constant(0); tasks = new Stack<DecompTask>(); JDD.Ref(reach); JDD.Ref(trans01); tasks.push(new DecompTask(reach, trans01)); while (!tasks.isEmpty()) { lockstep(tasks.pop()); } JDD.Ref(reach); notInSCCs = JDD.And(reach, JDD.Not(allSCCs)); } @Override public void computeSCCs(JDDNode filter) { //computeSCCs(); sccs = new Vector<JDDNode>(); allSCCs = JDD.Constant(0); tasks = new Stack<DecompTask>(); JDD.Ref(reach); JDD.Ref(trans01); tasks.push(new DecompTask(reach, trans01)); while (!tasks.isEmpty()) { lockstep(tasks.pop(), filter); } JDD.Ref(reach); notInSCCs = JDD.And(reach, JDD.Not(allSCCs)); } // Computation // Return the image of nodes in edges // Refs: result // Derefs: edges, nodes private JDDNode image(JDDNode nodes, JDDNode edges) { JDDNode tmp; // Get transitions that start at nodes tmp = JDD.Apply(JDD.TIMES, edges, nodes); // Get img(nodes) tmp = JDD.ThereExists(tmp, allDDRowVars); tmp = JDD.PermuteVariables(tmp, allDDColVars, allDDRowVars); return tmp; } // Return the preimage of nodes in edges // Refs: result // Derefs: edges, nodes private JDDNode preimage(JDDNode nodes, JDDNode edges) { JDDNode tmp; // Get transitions that end at nodes tmp = JDD.PermuteVariables(nodes, allDDRowVars, allDDColVars); tmp = JDD.Apply(JDD.TIMES, edges, tmp); // Get pre(nodes) tmp = JDD.ThereExists(tmp, allDDColVars); return tmp; } // Report a SCC found by lockstep private void report(JDDNode nodes) { if (nodes.equals(JDD.ZERO)) { JDD.Deref(nodes); return; } // Sanity check, partitioning of the state space should prevent this assert !sccs.contains(nodes); /* if (prism.getVerbose()) { log.println("Found SCC:"); JDD.PrintVector(nodes, rows); } */ sccs.addElement(nodes); JDD.Ref(nodes); allSCCs = JDD.Or(allSCCs, nodes); } // Trim nodes that have no path to a node in a nontrivial SCC // or have no path from a node in a nontrivial SCC // Refs: result // Derefs: nodes, edges private JDDNode trim(JDDNode nodes, JDDNode edges) { JDDNode old; JDDNode current; JDDNode img; JDDNode pre; //int i = 1; JDD.Ref(nodes); current = nodes; do { old = current; JDD.Ref(current); JDD.Ref(edges); img = image(current, edges); JDD.Ref(current); JDD.Ref(edges); pre = preimage(current, edges); current = JDD.And(current, JDD.And(img, pre)); /*if (prism.getVerbose()) { log.println("Trimming pass " + i + ":"); JDD.PrintVector(current, rows); i++; }*/ } while (!current.equals(old)); JDD.Deref(nodes); JDD.Deref(edges); return current; } // Lockstep SCC decomposition with trimming from [BGS00] // Refs: reported result // Derefs: nodes and edges in the DecompTask private void lockstep(DecompTask task) { JDDNode nodes = task.getNodes(); JDDNode edges = task.getEdges(); JDDNode tmp; if (nodes.equals(JDD.ZERO)) { JDD.Deref(nodes); JDD.Deref(edges); return; } /* if (prism.getVerbose()) { log.println("Lockstep pass on nodes: "); JDD.PrintVector(nodes, rows); } */ // trim nodes JDD.Ref(edges); nodes = trim(nodes, edges); JDD.Ref(nodes); edges = JDD.Apply(JDD.TIMES, edges, nodes); JDD.Ref(nodes); edges = JDD.Apply(JDD.TIMES, edges, JDD.PermuteVariables(nodes, allDDRowVars, allDDColVars)); // pick a starting node JDD.Ref(nodes); JDDNode v = JDD.RestrictToFirst(nodes, allDDRowVars); // mainLog.println("Lockstep - picked node:"); // JDD.PrintVector(v, allDDRowVars); JDDNode f = v; // forward set of v JDDNode ffront = v; // last update to f JDD.Ref(f); JDD.Ref(ffront); JDDNode b = v; // backward set of v JDDNode bfront = v; // last update to b JDD.Ref(b); JDD.Ref(bfront); JDD.Deref(v); // Compute forward and backward sets in lockstep until either one converges while (!ffront.equals(JDD.ZERO) && !bfront.equals(JDD.ZERO)) { JDD.Ref(edges); // Get the image of the last update tmp = image(ffront, edges); // find new states in this update JDD.Ref(f); ffront = JDD.And(tmp, JDD.Not(f)); // add states to the forward set JDD.Ref(ffront); f = JDD.Or(f, ffront); JDD.Ref(edges); // Get the preimage of the last update tmp = preimage(bfront, edges); // find new states in this update JDD.Ref(b); bfront = JDD.And(tmp, JDD.Not(b)); // add states to the backward set JDD.Ref(bfront); b = JDD.Or(b, bfront); } JDDNode convergedSet; // set that converged first JDDNode sccUpdate; // update in the last approximation of the scc // if ffront is empty, the forward set converged first if (ffront.equals(JDD.ZERO)) { convergedSet = f; JDD.Ref(convergedSet); // keep looking for states in the backward set until // its intersection with the forward set stops growing JDD.Ref(bfront); JDD.Ref(f); sccUpdate = JDD.And(bfront, f); while (!sccUpdate.equals(JDD.ZERO)) { JDD.Deref(sccUpdate); JDD.Ref(edges); JDD.Ref(b); bfront = JDD.And(preimage(bfront, edges), JDD.Not(b)); JDD.Ref(bfront); b = JDD.Or(bfront, b); JDD.Ref(f); JDD.Ref(bfront); sccUpdate = JDD.And(bfront, f); } } // bfront is empty, the backward set converged first else { convergedSet = b; JDD.Ref(convergedSet); // keep looking for states in the backward set until // its intersection with the forward set stops growing JDD.Ref(ffront); JDD.Ref(b); sccUpdate = JDD.And(ffront, b); while (!sccUpdate.equals(JDD.ZERO)) { JDD.Deref(sccUpdate); JDD.Ref(edges); JDD.Ref(f); ffront = JDD.And(image(ffront, edges), JDD.Not(f)); JDD.Ref(ffront); f = JDD.Or(ffront, f); JDD.Ref(b); JDD.Ref(ffront); sccUpdate = JDD.And(ffront, b); } } JDD.Deref(sccUpdate); JDD.Deref(ffront); JDD.Deref(bfront); // Found our SCC JDDNode scc = JDD.Apply(JDD.TIMES, f, b); // check if SCC is nontrivial and report JDD.Ref(scc); tmp = JDD.PermuteVariables(scc, allDDRowVars, allDDColVars); JDD.Ref(edges); tmp = JDD.And(tmp, edges); JDD.Ref(scc); tmp = JDD.And(tmp, scc); if (!tmp.equals(JDD.ZERO)) { JDD.Ref(scc); report(scc); } JDD.Deref(tmp); // FIXME: restricting newEdges isn't necessary, needs benchmarking // (speed vs memory?) // newNodes1 = convergedSet \ scc //JDD.Ref(scc); JDD.Ref(convergedSet); JDDNode newNodes1 = JDD.And(convergedSet, JDD.Not(scc)); // newEdges1 = edges \intersect (newNodes x newNodes^t) JDD.Ref(edges); JDD.Ref(newNodes1); JDDNode newEdges1 = JDD.Apply(JDD.TIMES, edges, newNodes1); JDD.Ref(newNodes1); tmp = JDD.PermuteVariables(newNodes1, allDDRowVars, allDDColVars); newEdges1 = JDD.Apply(JDD.TIMES, newEdges1, tmp); // newNodes2 = nodes \ convergedSet //JDD.Ref(nodes); //JDD.Ref(convergedSet); JDDNode newNodes2 = JDD.And(nodes, JDD.Not(convergedSet)); // newEdges2 = edges \intersect (newNodes x newNodes^t) //JDD.Ref(edges); JDD.Ref(newNodes2); JDDNode newEdges2 = JDD.Apply(JDD.TIMES, edges, newNodes2); JDD.Ref(newNodes2); tmp = JDD.PermuteVariables(newNodes2, allDDRowVars, allDDColVars); newEdges2 = JDD.Apply(JDD.TIMES, newEdges2, tmp); // Queue new sets for search tasks.push(new DecompTask(newNodes2, newEdges2)); tasks.push(new DecompTask(newNodes1, newEdges1)); //JDD.Deref(scc); //JDD.Deref(convergedSet); //JDD.Deref(nodes); //JDD.Deref(edges); } private void lockstep(DecompTask task, JDDNode filter) { JDDNode nodes = task.getNodes(); JDDNode edges = task.getEdges(); JDDNode tmp; if (nodes.equals(JDD.ZERO)) { JDD.Deref(nodes); JDD.Deref(edges); return; } /* if (prism.getVerbose()) { log.println("Lockstep pass on nodes: "); JDD.PrintVector(nodes, rows); } */ // trim nodes JDD.Ref(edges); nodes = trim(nodes, edges); JDD.Ref(nodes); edges = JDD.Apply(JDD.TIMES, edges, nodes); JDD.Ref(nodes); edges = JDD.Apply(JDD.TIMES, edges, JDD.PermuteVariables(nodes, allDDRowVars, allDDColVars)); // pick a starting node JDD.Ref(nodes); JDDNode v = JDD.RestrictToFirst(nodes, allDDRowVars); // mainLog.println("Lockstep - picked node:"); // JDD.PrintVector(v, allDDRowVars); JDDNode f = v; // forward set of v JDDNode ffront = v; // last update to f JDD.Ref(f); JDD.Ref(ffront); JDDNode b = v; // backward set of v JDDNode bfront = v; // last update to b JDD.Ref(b); JDD.Ref(bfront); JDD.Deref(v); // Compute forward and backward sets in lockstep until either one converges while (!ffront.equals(JDD.ZERO) && !bfront.equals(JDD.ZERO)) { JDD.Ref(edges); // Get the image of the last update tmp = image(ffront, edges); // find new states in this update JDD.Ref(f); ffront = JDD.And(tmp, JDD.Not(f)); // add states to the forward set JDD.Ref(ffront); f = JDD.Or(f, ffront); JDD.Ref(edges); // Get the preimage of the last update tmp = preimage(bfront, edges); // find new states in this update JDD.Ref(b); bfront = JDD.And(tmp, JDD.Not(b)); // add states to the backward set JDD.Ref(bfront); b = JDD.Or(b, bfront); } JDDNode convergedSet; // set that converged first JDDNode sccUpdate; // update in the last approximation of the scc // if ffront is empty, the forward set converged first if (ffront.equals(JDD.ZERO)) { convergedSet = f; JDD.Ref(convergedSet); // keep looking for states in the backward set until // its intersection with the forward set stops growing JDD.Ref(bfront); JDD.Ref(f); sccUpdate = JDD.And(bfront, f); while (!sccUpdate.equals(JDD.ZERO)) { JDD.Deref(sccUpdate); JDD.Ref(edges); JDD.Ref(b); bfront = JDD.And(preimage(bfront, edges), JDD.Not(b)); JDD.Ref(bfront); b = JDD.Or(bfront, b); JDD.Ref(f); JDD.Ref(bfront); sccUpdate = JDD.And(bfront, f); } } // bfront is empty, the backward set converged first else { convergedSet = b; JDD.Ref(convergedSet); // keep looking for states in the backward set until // its intersection with the forward set stops growing JDD.Ref(ffront); JDD.Ref(b); sccUpdate = JDD.And(ffront, b); while (!sccUpdate.equals(JDD.ZERO)) { JDD.Deref(sccUpdate); JDD.Ref(edges); JDD.Ref(f); ffront = JDD.And(image(ffront, edges), JDD.Not(f)); JDD.Ref(ffront); f = JDD.Or(ffront, f); JDD.Ref(b); JDD.Ref(ffront); sccUpdate = JDD.And(ffront, b); } } JDD.Deref(sccUpdate); JDD.Deref(ffront); JDD.Deref(bfront); // Found our SCC JDDNode scc = JDD.Apply(JDD.TIMES, f, b); // check if SCC is nontrivial and report JDD.Ref(scc); tmp = JDD.PermuteVariables(scc, allDDRowVars, allDDColVars); JDD.Ref(edges); tmp = JDD.And(tmp, edges); JDD.Ref(scc); tmp = JDD.And(tmp, scc); if (!tmp.equals(JDD.ZERO)) { JDD.Ref(scc); report(scc); } JDD.Deref(tmp); // FIXME: restricting newEdges isn't necessary, needs benchmarking // (speed vs memory?) // newNodes1 = convergedSet \ scc //JDD.Ref(scc); JDD.Ref(convergedSet); JDDNode newNodes1 = JDD.And(convergedSet, JDD.Not(scc)); if (JDD.AreInterecting(newNodes1, filter)) { // newEdges1 = edges \intersect (newNodes x newNodes^t) JDD.Ref(edges); JDD.Ref(newNodes1); JDDNode newEdges1 = JDD.Apply(JDD.TIMES, edges, newNodes1); JDD.Ref(newNodes1); tmp = JDD.PermuteVariables(newNodes1, allDDRowVars, allDDColVars); newEdges1 = JDD.Apply(JDD.TIMES, newEdges1, tmp); tasks.push(new DecompTask(newNodes1, newEdges1)); } else JDD.Deref(newNodes1); // newNodes2 = nodes \ convergedSet //JDD.Ref(nodes); //JDD.Ref(convergedSet); JDDNode newNodes2 = JDD.And(nodes, JDD.Not(convergedSet)); if (JDD.AreInterecting(newNodes2, filter)) { // newEdges2 = edges \intersect (newNodes x newNodes^t) JDD.Ref(edges); JDD.Ref(newNodes2); JDDNode newEdges2 = JDD.Apply(JDD.TIMES, edges, newNodes2); JDD.Ref(newNodes2); tmp = JDD.PermuteVariables(newNodes2, allDDRowVars, allDDColVars); newEdges2 = JDD.Apply(JDD.TIMES, newEdges2, tmp); // Queue new sets for search tasks.push(new DecompTask(newNodes2, newEdges2)); } else JDD.Deref(newNodes2); //JDD.Deref(scc); //JDD.Deref(convergedSet); //JDD.Deref(nodes); JDD.Deref(edges); } }
gpl-2.0
blazegraph/database
bigdata-rdf-test/src/test/java/com/bigdata/rdf/sparql/ast/optimizers/TestASTSetValueExpressionOptimizer.java
7554
/** Copyright (C) SYSTAP, LLC DBA Blazegraph 2006-2016. All rights reserved. Contact: SYSTAP, LLC DBA Blazegraph 2501 Calvert ST NW #106 Washington, DC 20008 licenses@blazegraph.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Created on Aug 29, 2011 */ package com.bigdata.rdf.sparql.ast.optimizers; import java.util.UUID; import org.openrdf.query.algebra.StatementPattern.Scope; import com.bigdata.bop.BOpContext; import com.bigdata.bop.Constant; import com.bigdata.bop.ContextBindingSet; import com.bigdata.bop.IBindingSet; import com.bigdata.bop.IQueryContext; import com.bigdata.bop.PipelineOp; import com.bigdata.bop.bindingSet.ListBindingSet; import com.bigdata.bop.engine.BOpStats; import com.bigdata.bop.engine.BlockingBufferWithStats; import com.bigdata.bop.engine.IRunningQuery; import com.bigdata.bop.engine.MockRunningQuery; import com.bigdata.bop.solutions.MockQuery; import com.bigdata.bop.solutions.MockQueryContext; import com.bigdata.rdf.internal.IV; import com.bigdata.rdf.internal.XSD; import com.bigdata.rdf.sparql.ast.ASTContainer; import com.bigdata.rdf.sparql.ast.AbstractASTEvaluationTestCase; import com.bigdata.rdf.sparql.ast.AssignmentNode; import com.bigdata.rdf.sparql.ast.ConstantNode; import com.bigdata.rdf.sparql.ast.FunctionNode; import com.bigdata.rdf.sparql.ast.IQueryNode; import com.bigdata.rdf.sparql.ast.JoinGroupNode; import com.bigdata.rdf.sparql.ast.ProjectionNode; import com.bigdata.rdf.sparql.ast.QueryNodeWithBindingSet; import com.bigdata.rdf.sparql.ast.QueryRoot; import com.bigdata.rdf.sparql.ast.QueryType; import com.bigdata.rdf.sparql.ast.StatementPatternNode; import com.bigdata.rdf.sparql.ast.VarNode; import com.bigdata.rdf.sparql.ast.eval.AST2BOpContext; import com.bigdata.relation.accesspath.IAsynchronousIterator; import com.bigdata.relation.accesspath.IBlockingBuffer; import com.bigdata.relation.accesspath.ThickAsynchronousIterator; /** * Test suite for {@link ASTSetValueExpressionsOptimizer}. * * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a> * @version $Id$ */ public class TestASTSetValueExpressionOptimizer extends AbstractASTEvaluationTestCase { /** * */ public TestASTSetValueExpressionOptimizer() { } /** * @param name */ public TestASTSetValueExpressionOptimizer(String name) { super(name); } /** * Given * * <pre> * SELECT ?s (?o as 12+1) where {?s ?p ?o} * </pre> * * Verify that the AST is rewritten as: * * <pre> * SELECT ?s (?o as 13) where {?s ?p ?o} * </pre> * * TODO unit test with FILTER(sameTerm(var,constExpr)) in {@link ASTBindingAssigner} */ public void test_reduceFunctionToConstant() { /* * Note: DO NOT share structures in this test!!!! */ @SuppressWarnings("rawtypes") final IV c1 = makeIV(store.getValueFactory().createLiteral(1)); @SuppressWarnings("rawtypes") final IV c12 = makeIV(store.getValueFactory().createLiteral(12)); @SuppressWarnings("rawtypes") final IV c13 = store.getLexiconRelation().getInlineIV( store.getValueFactory().createLiteral("13", XSD.INTEGER)); store.commit(); @SuppressWarnings("rawtypes") final BOpContext context; { final BOpStats stats = new BOpStats(); final PipelineOp mockQuery = new MockQuery(); final IAsynchronousIterator<IBindingSet[]> source = new ThickAsynchronousIterator<IBindingSet[]>( new IBindingSet[][] {}); final IBlockingBuffer<IBindingSet[]> sink = new BlockingBufferWithStats<IBindingSet[]>( mockQuery, stats); final UUID queryId = UUID.randomUUID(); final IQueryContext queryContext = new MockQueryContext(queryId); final IRunningQuery runningQuery = new MockRunningQuery(null/* fed */ , store.getIndexManager()/* indexManager */,queryContext ); context = BOpContext.newMock(runningQuery, null/* fed */, store.getIndexManager()/* localIndexManager */, -1/* partitionId */, stats, mockQuery, false/* lastInvocation */, source, sink, null/* sink2 */); } final IBindingSet[] bsets = new IBindingSet[] { // new ContextBindingSet(context, new ListBindingSet(// // new IVariable[] { Var.var("p") },// // new IConstant[] { new Constant<IV>(mockIV) } )) // }; // The source AST. final QueryRoot given = new QueryRoot(QueryType.SELECT); { final ProjectionNode projection = new ProjectionNode(); given.setProjection(projection); projection.addProjectionVar(new VarNode("s")); final FunctionNode fn = FunctionNode.add(new ConstantNode(c12), new ConstantNode(c1)); projection.addProjectionExpression(new AssignmentNode(new VarNode( "o"), fn)); final JoinGroupNode whereClause = new JoinGroupNode(); given.setWhereClause(whereClause); whereClause.addChild(new StatementPatternNode(new VarNode("s"), new VarNode("p"), new VarNode("o"), null/* c */, Scope.DEFAULT_CONTEXTS)); } // The expected AST after the rewrite. final QueryRoot expected = new QueryRoot(QueryType.SELECT); { final ProjectionNode projection = new ProjectionNode(); expected.setProjection(projection); projection.addProjectionVar(new VarNode("s")); final FunctionNode fn = FunctionNode.add(new ConstantNode(c12), new ConstantNode(c1)); fn.setValueExpression(new Constant<IV<?, ?>>(c13)); projection.addProjectionExpression(new AssignmentNode(new VarNode( "o"), fn)); final JoinGroupNode whereClause = new JoinGroupNode(); expected.setWhereClause(whereClause); whereClause.addChild(new StatementPatternNode(new VarNode("s"), new VarNode("p"), new VarNode("o"), null/* c */, Scope.DEFAULT_CONTEXTS)); } final IASTOptimizer rewriter = new ASTSetValueExpressionsOptimizer(); final IQueryNode actual = rewriter.optimize(new AST2BOpContext( new ASTContainer(given), store), new QueryNodeWithBindingSet(given, bsets)) .getQueryNode(); assertSameAST(expected, actual); } }
gpl-2.0
malaporte/kaziranga
src/jdk/nashorn/internal/objects/NativeRegExp.java
33380
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.nashorn.internal.objects; import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; import java.lang.invoke.MethodHandle; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import jdk.nashorn.internal.objects.annotations.Attribute; import jdk.nashorn.internal.objects.annotations.Constructor; import jdk.nashorn.internal.objects.annotations.Function; import jdk.nashorn.internal.objects.annotations.Getter; import jdk.nashorn.internal.objects.annotations.Property; import jdk.nashorn.internal.objects.annotations.ScriptClass; import jdk.nashorn.internal.objects.annotations.SpecializedFunction; import jdk.nashorn.internal.objects.annotations.Where; import jdk.nashorn.internal.runtime.BitVector; import jdk.nashorn.internal.runtime.JSType; import jdk.nashorn.internal.runtime.ParserException; import jdk.nashorn.internal.runtime.PropertyMap; import jdk.nashorn.internal.runtime.ScriptFunction; import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.runtime.ScriptRuntime; import jdk.nashorn.internal.runtime.linker.Bootstrap; import jdk.nashorn.internal.runtime.regexp.RegExp; import jdk.nashorn.internal.runtime.regexp.RegExpFactory; import jdk.nashorn.internal.runtime.regexp.RegExpMatcher; import jdk.nashorn.internal.runtime.regexp.RegExpResult; /** * ECMA 15.10 RegExp Objects. */ @ScriptClass("RegExp") public final class NativeRegExp extends ScriptObject { /** ECMA 15.10.7.5 lastIndex property */ @Property(attributes = Attribute.NOT_ENUMERABLE | Attribute.NOT_CONFIGURABLE) public Object lastIndex; /** Compiled regexp */ private RegExp regexp; // Reference to global object needed to support static RegExp properties private final Global globalObject; // initialized by nasgen private static PropertyMap $nasgenmap$; private NativeRegExp(final Global global) { super(global.getRegExpPrototype(), $nasgenmap$); this.globalObject = global; } NativeRegExp(final String input, final String flagString, final Global global, final ScriptObject proto) { super(proto, $nasgenmap$); try { this.regexp = RegExpFactory.create(input, flagString); } catch (final ParserException e) { // translate it as SyntaxError object and throw it e.throwAsEcmaException(); throw new AssertionError(); //guard against null warnings below } this.globalObject = global; this.setLastIndex(0); } NativeRegExp(final String input, final String flagString, final Global global) { this(input, flagString, global, global.getRegExpPrototype()); } NativeRegExp(final String input, final String flagString) { this(input, flagString, Global.instance()); } NativeRegExp(final String string, final Global global) { this(string, "", global); } NativeRegExp(final String string) { this(string, Global.instance()); } NativeRegExp(final NativeRegExp regExp) { this(Global.instance()); this.lastIndex = regExp.getLastIndexObject(); this.regexp = regExp.getRegExp(); } @Override public String getClassName() { return "RegExp"; } /** * ECMA 15.10.4 * * Constructor * * @param isNew is the new operator used for instantiating this regexp * @param self self reference * @param args arguments (optional: pattern and flags) * @return new NativeRegExp */ @Constructor(arity = 2) public static NativeRegExp constructor(final boolean isNew, final Object self, final Object... args) { if (args.length > 1) { return newRegExp(args[0], args[1]); } else if (args.length > 0) { return newRegExp(args[0], UNDEFINED); } return newRegExp(UNDEFINED, UNDEFINED); } /** * ECMA 15.10.4 * * Constructor - specialized version, no args, empty regexp * * @param isNew is the new operator used for instantiating this regexp * @param self self reference * @return new NativeRegExp */ @SpecializedFunction(isConstructor=true) public static NativeRegExp constructor(final boolean isNew, final Object self) { return new NativeRegExp("", ""); } /** * ECMA 15.10.4 * * Constructor - specialized version, pattern, no flags * * @param isNew is the new operator used for instantiating this regexp * @param self self reference * @param pattern pattern * @return new NativeRegExp */ @SpecializedFunction(isConstructor=true) public static NativeRegExp constructor(final boolean isNew, final Object self, final Object pattern) { return newRegExp(pattern, UNDEFINED); } /** * ECMA 15.10.4 * * Constructor - specialized version, pattern and flags * * @param isNew is the new operator used for instantiating this regexp * @param self self reference * @param pattern pattern * @param flags flags * @return new NativeRegExp */ @SpecializedFunction(isConstructor=true) public static NativeRegExp constructor(final boolean isNew, final Object self, final Object pattern, final Object flags) { return newRegExp(pattern, flags); } /** * External constructor used in generated code, which explains the public access * * @param regexp regexp * @param flags flags * @return new NativeRegExp */ public static NativeRegExp newRegExp(final Object regexp, final Object flags) { String patternString = ""; String flagString = ""; if (regexp != UNDEFINED) { if (regexp instanceof NativeRegExp) { if (flags != UNDEFINED) { throw typeError("regex.cant.supply.flags"); } return (NativeRegExp)regexp; // 15.10.3.1 - undefined flags and regexp as } patternString = JSType.toString(regexp); } if (flags != UNDEFINED) { flagString = JSType.toString(flags); } return new NativeRegExp(patternString, flagString); } /** * Build a regexp that matches {@code string} as-is. All meta-characters will be escaped. * * @param string pattern string * @return flat regexp */ static NativeRegExp flatRegExp(final String string) { // escape special characters StringBuilder sb = null; final int length = string.length(); for (int i = 0; i < length; i++) { final char c = string.charAt(i); switch (c) { case '^': case '$': case '\\': case '.': case '*': case '+': case '?': case '(': case ')': case '[': case '{': case '|': if (sb == null) { sb = new StringBuilder(length * 2); sb.append(string, 0, i); } sb.append('\\'); sb.append(c); break; default: if (sb != null) { sb.append(c); } break; } } return new NativeRegExp(sb == null ? string : sb.toString(), ""); } private String getFlagString() { final StringBuilder sb = new StringBuilder(3); if (regexp.isGlobal()) { sb.append('g'); } if (regexp.isIgnoreCase()) { sb.append('i'); } if (regexp.isMultiline()) { sb.append('m'); } return sb.toString(); } @Override public String safeToString() { return "[RegExp " + toString() + "]"; } @Override public String toString() { return "/" + regexp.getSource() + "/" + getFlagString(); } /** * Nashorn extension: RegExp.prototype.compile - everybody implements this! * * @param self self reference * @param pattern pattern * @param flags flags * @return new NativeRegExp */ @Function(attributes = Attribute.NOT_ENUMERABLE) public static ScriptObject compile(final Object self, final Object pattern, final Object flags) { final NativeRegExp regExp = checkRegExp(self); final NativeRegExp compiled = newRegExp(pattern, flags); // copy over regexp to 'self' regExp.setRegExp(compiled.getRegExp()); // Some implementations return undefined. Some return 'self'. Since return // value is most likely be ignored, we can play safe and return 'self'. return regExp; } /** * ECMA 15.10.6.2 RegExp.prototype.exec(string) * * @param self self reference * @param string string to match against regexp * @return array containing the matches or {@code null} if no match */ @Function(attributes = Attribute.NOT_ENUMERABLE) public static ScriptObject exec(final Object self, final Object string) { return checkRegExp(self).exec(JSType.toString(string)); } /** * ECMA 15.10.6.3 RegExp.prototype.test(string) * * @param self self reference * @param string string to test for matches against regexp * @return true if matches found, false otherwise */ @Function(attributes = Attribute.NOT_ENUMERABLE) public static boolean test(final Object self, final Object string) { return checkRegExp(self).test(JSType.toString(string)); } /** * ECMA 15.10.6.4 RegExp.prototype.toString() * * @param self self reference * @return string version of regexp */ @Function(attributes = Attribute.NOT_ENUMERABLE) public static String toString(final Object self) { return checkRegExp(self).toString(); } /** * ECMA 15.10.7.1 source * * @param self self reference * @return the input string for the regexp */ @Getter(attributes = Attribute.NON_ENUMERABLE_CONSTANT) public static Object source(final Object self) { return checkRegExp(self).getRegExp().getSource(); } /** * ECMA 15.10.7.2 global * * @param self self reference * @return true if this regexp is flagged global, false otherwise */ @Getter(attributes = Attribute.NON_ENUMERABLE_CONSTANT) public static Object global(final Object self) { return checkRegExp(self).getRegExp().isGlobal(); } /** * ECMA 15.10.7.3 ignoreCase * * @param self self reference * @return true if this regexp if flagged to ignore case, false otherwise */ @Getter(attributes = Attribute.NON_ENUMERABLE_CONSTANT) public static Object ignoreCase(final Object self) { return checkRegExp(self).getRegExp().isIgnoreCase(); } /** * ECMA 15.10.7.4 multiline * * @param self self reference * @return true if this regexp is flagged to be multiline, false otherwise */ @Getter(attributes = Attribute.NON_ENUMERABLE_CONSTANT) public static Object multiline(final Object self) { return checkRegExp(self).getRegExp().isMultiline(); } /** * Getter for non-standard RegExp.input property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "input") public static Object getLastInput(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getInput(); } /** * Getter for non-standard RegExp.multiline property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "multiline") public static Object getLastMultiline(final Object self) { return false; // doesn't ever seem to become true and isn't documented anyhwere } /** * Getter for non-standard RegExp.lastMatch property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "lastMatch") public static Object getLastMatch(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getGroup(0); } /** * Getter for non-standard RegExp.lastParen property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "lastParen") public static Object getLastParen(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getLastParen(); } /** * Getter for non-standard RegExp.leftContext property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "leftContext") public static Object getLeftContext(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getInput().substring(0, match.getIndex()); } /** * Getter for non-standard RegExp.rightContext property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "rightContext") public static Object getRightContext(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getInput().substring(match.getIndex() + match.length()); } /** * Getter for non-standard RegExp.$1 property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "$1") public static Object getGroup1(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getGroup(1); } /** * Getter for non-standard RegExp.$2 property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "$2") public static Object getGroup2(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getGroup(2); } /** * Getter for non-standard RegExp.$3 property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "$3") public static Object getGroup3(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getGroup(3); } /** * Getter for non-standard RegExp.$4 property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "$4") public static Object getGroup4(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getGroup(4); } /** * Getter for non-standard RegExp.$5 property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "$5") public static Object getGroup5(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getGroup(5); } /** * Getter for non-standard RegExp.$6 property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "$6") public static Object getGroup6(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getGroup(6); } /** * Getter for non-standard RegExp.$7 property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "$7") public static Object getGroup7(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getGroup(7); } /** * Getter for non-standard RegExp.$8 property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "$8") public static Object getGroup8(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getGroup(8); } /** * Getter for non-standard RegExp.$9 property. * @param self self object * @return last regexp input */ @Getter(where = Where.CONSTRUCTOR, attributes = Attribute.CONSTANT, name = "$9") public static Object getGroup9(final Object self) { final RegExpResult match = Global.instance().getLastRegExpResult(); return match == null ? "" : match.getGroup(9); } private RegExpResult execInner(final String string) { final boolean isGlobal = regexp.isGlobal(); int start = getLastIndex(); if (!isGlobal) { start = 0; } if (start < 0 || start > string.length()) { if (isGlobal) { setLastIndex(0); } return null; } final RegExpMatcher matcher = regexp.match(string); if (matcher == null || !matcher.search(start)) { if (isGlobal) { setLastIndex(0); } return null; } if (isGlobal) { setLastIndex(matcher.end()); } final RegExpResult match = new RegExpResult(string, matcher.start(), groups(matcher)); globalObject.setLastRegExpResult(match); return match; } // String.prototype.split method ignores the global flag and should not update lastIndex property. private RegExpResult execSplit(final String string, final int start) { if (start < 0 || start > string.length()) { return null; } final RegExpMatcher matcher = regexp.match(string); if (matcher == null || !matcher.search(start)) { return null; } final RegExpResult match = new RegExpResult(string, matcher.start(), groups(matcher)); globalObject.setLastRegExpResult(match); return match; } /** * Convert java.util.regex.Matcher groups to JavaScript groups. * That is, replace null and groups that didn't match with undefined. */ private Object[] groups(final RegExpMatcher matcher) { final int groupCount = matcher.groupCount(); final Object[] groups = new Object[groupCount + 1]; final BitVector groupsInNegativeLookahead = regexp.getGroupsInNegativeLookahead(); for (int i = 0, lastGroupStart = matcher.start(); i <= groupCount; i++) { final int groupStart = matcher.start(i); if (lastGroupStart > groupStart || groupsInNegativeLookahead != null && groupsInNegativeLookahead.isSet(i)) { // (1) ECMA 15.10.2.5 NOTE 3: need to clear Atom's captures each time Atom is repeated. // (2) ECMA 15.10.2.8 NOTE 3: Backreferences to captures in (?!Disjunction) from elsewhere // in the pattern always return undefined because the negative lookahead must fail. groups[i] = UNDEFINED; continue; } final String group = matcher.group(i); groups[i] = group == null ? UNDEFINED : group; lastGroupStart = groupStart; } return groups; } /** * Executes a search for a match within a string based on a regular * expression. It returns an array of information or null if no match is * found. * * @param string String to match. * @return NativeArray of matches, string or null. */ public NativeRegExpExecResult exec(final String string) { final RegExpResult match = execInner(string); if (match == null) { return null; } return new NativeRegExpExecResult(match, globalObject); } /** * Executes a search for a match within a string based on a regular * expression. * * @param string String to match. * @return True if a match is found. */ public boolean test(final String string) { return execInner(string) != null; } /** * Searches and replaces the regular expression portion (match) with the * replaced text instead. For the "replacement text" parameter, you can use * the keywords $1 to $2 to replace the original text with values from * sub-patterns defined within the main pattern. * * @param string String to match. * @param replacement Replacement string. * @return String with substitutions. */ String replace(final String string, final String replacement, final ScriptFunction function) throws Throwable { final RegExpMatcher matcher = regexp.match(string); if (matcher == null) { return string; } if (!regexp.isGlobal()) { if (!matcher.search(0)) { return string; } final StringBuilder sb = new StringBuilder(); sb.append(string, 0, matcher.start()); if (function != null) { final Object self = function.isStrict() ? UNDEFINED : Global.instance(); sb.append(callReplaceValue(getReplaceValueInvoker(), function, self, matcher, string)); } else { appendReplacement(matcher, string, replacement, sb); } sb.append(string, matcher.end(), string.length()); return sb.toString(); } setLastIndex(0); if (!matcher.search(0)) { return string; } int thisIndex = 0; int previousLastIndex = 0; final StringBuilder sb = new StringBuilder(); final MethodHandle invoker = function == null ? null : getReplaceValueInvoker(); final Object self = function == null || function.isStrict() ? UNDEFINED : Global.instance(); do { sb.append(string, thisIndex, matcher.start()); if (function != null) { sb.append(callReplaceValue(invoker, function, self, matcher, string)); } else { appendReplacement(matcher, string, replacement, sb); } thisIndex = matcher.end(); if (thisIndex == string.length() && matcher.start() == matcher.end()) { // Avoid getting empty match at end of string twice break; } // ECMA 15.5.4.10 String.prototype.match(regexp) if (thisIndex == previousLastIndex) { setLastIndex(thisIndex + 1); previousLastIndex = thisIndex + 1; } else { previousLastIndex = thisIndex; } } while (previousLastIndex <= string.length() && matcher.search(previousLastIndex)); sb.append(string, thisIndex, string.length()); return sb.toString(); } private void appendReplacement(final RegExpMatcher matcher, final String text, final String replacement, final StringBuilder sb) { /* * Process substitution patterns: * * $$ -> $ * $& -> the matched substring * $` -> the portion of string that preceeds matched substring * $' -> the portion of string that follows the matched substring * $n -> the nth capture, where n is [1-9] and $n is NOT followed by a decimal digit * $nn -> the nnth capture, where nn is a two digit decimal number [01-99]. */ int cursor = 0; Object[] groups = null; while (cursor < replacement.length()) { char nextChar = replacement.charAt(cursor); if (nextChar == '$') { // Skip past $ cursor++; if (cursor == replacement.length()) { // nothing after "$" sb.append('$'); break; } nextChar = replacement.charAt(cursor); final int firstDigit = nextChar - '0'; if (firstDigit >= 0 && firstDigit <= 9 && firstDigit <= matcher.groupCount()) { // $0 is not supported, but $01 is. implementation-defined: if n>m, ignore second digit. int refNum = firstDigit; cursor++; if (cursor < replacement.length() && firstDigit < matcher.groupCount()) { final int secondDigit = replacement.charAt(cursor) - '0'; if (secondDigit >= 0 && secondDigit <= 9) { final int newRefNum = firstDigit * 10 + secondDigit; if (newRefNum <= matcher.groupCount() && newRefNum > 0) { // $nn ($01-$99) refNum = newRefNum; cursor++; } } } if (refNum > 0) { if (groups == null) { groups = groups(matcher); } // Append group if matched. if (groups[refNum] != UNDEFINED) { sb.append((String) groups[refNum]); } } else { // $0. ignore. assert refNum == 0; sb.append("$0"); } } else if (nextChar == '$') { sb.append('$'); cursor++; } else if (nextChar == '&') { sb.append(matcher.group()); cursor++; } else if (nextChar == '`') { sb.append(text, 0, matcher.start()); cursor++; } else if (nextChar == '\'') { sb.append(text, matcher.end(), text.length()); cursor++; } else { // unknown substitution or $n with n>m. skip. sb.append('$'); } } else { sb.append(nextChar); cursor++; } } } private static final Object REPLACE_VALUE = new Object(); private static final MethodHandle getReplaceValueInvoker() { return Global.instance().getDynamicInvoker(REPLACE_VALUE, new Callable<MethodHandle>() { @Override public MethodHandle call() { return Bootstrap.createDynamicInvoker("dyn:call", String.class, ScriptFunction.class, Object.class, Object[].class); } }); } private String callReplaceValue(final MethodHandle invoker, final ScriptFunction function, final Object self, final RegExpMatcher matcher, final String string) throws Throwable { final Object[] groups = groups(matcher); final Object[] args = Arrays.copyOf(groups, groups.length + 2); args[groups.length] = matcher.start(); args[groups.length + 1] = string; return (String)invoker.invokeExact(function, self, args); } /** * Breaks up a string into an array of substrings based on a regular * expression or fixed string. * * @param string String to match. * @param limit Split limit. * @return Array of substrings. */ NativeArray split(final String string, final long limit) { if (limit == 0L) { return new NativeArray(); } final List<Object> matches = new ArrayList<>(); RegExpResult match; final int inputLength = string.length(); int splitLastLength = -1; int splitLastIndex = 0; int splitLastLastIndex = 0; while ((match = execSplit(string, splitLastIndex)) != null) { splitLastIndex = match.getIndex() + match.length(); if (splitLastIndex > splitLastLastIndex) { matches.add(string.substring(splitLastLastIndex, match.getIndex())); final Object[] groups = match.getGroups(); if (groups.length > 1 && match.getIndex() < inputLength) { for (int index = 1; index < groups.length && matches.size() < limit; index++) { matches.add(groups[index]); } } splitLastLength = match.length(); if (matches.size() >= limit) { break; } } // bump the index to avoid infinite loop if (splitLastIndex == splitLastLastIndex) { splitLastIndex++; } else { splitLastLastIndex = splitLastIndex; } } if (matches.size() < limit) { // check special case if we need to append an empty string at the // end of the match // if the lastIndex was the entire string if (splitLastLastIndex == string.length()) { if (splitLastLength > 0 || execSplit("", 0) == null) { matches.add(""); } } else { matches.add(string.substring(splitLastLastIndex, inputLength)); } } return new NativeArray(matches.toArray()); } /** * Tests for a match in a string. It returns the index of the match, or -1 * if not found. * * @param string String to match. * @return Index of match. */ int search(final String string) { final RegExpResult match = execInner(string); if (match == null) { return -1; } return match.getIndex(); } /** * Fast lastIndex getter * @return last index property as int */ public int getLastIndex() { return JSType.toInteger(lastIndex); } /** * Fast lastIndex getter * @return last index property as boxed integer */ public Object getLastIndexObject() { return lastIndex; } /** * Fast lastIndex setter * @param lastIndex lastIndex */ public void setLastIndex(final int lastIndex) { this.lastIndex = JSType.toObject(lastIndex); } private static NativeRegExp checkRegExp(final Object self) { if (self instanceof NativeRegExp) { return (NativeRegExp)self; } else if (self != null && self == Global.instance().getRegExpPrototype()) { return Global.instance().getDefaultRegExp(); } else { throw typeError("not.a.regexp", ScriptRuntime.safeToString(self)); } } boolean getGlobal() { return regexp.isGlobal(); } private RegExp getRegExp() { return regexp; } private void setRegExp(final RegExp regexp) { this.regexp = regexp; } }
gpl-2.0
mixaceh/openyu-cms.j
openyu-cms-core/src/main/java/org/openyu/cms/friendType/vo/impl/ActionOptionImpl.java
1497
package org.openyu.cms.friendType.vo.impl; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.openyu.cms.friendType.vo.ActionType; import org.openyu.cms.friendType.vo.ActionOption; import org.openyu.commons.bean.supporter.NamesBeanSupporter; /** * 操作選項 */ //-------------------------------------------------- //jaxb //-------------------------------------------------- @XmlRootElement(name = "actionOption") @XmlAccessorType(XmlAccessType.FIELD) public class ActionOptionImpl extends NamesBeanSupporter implements ActionOption { private static final long serialVersionUID = 4644282406281853593L; /** * 操作類別,key */ private ActionType id; public ActionOptionImpl(ActionType id) { this.id = id; } public ActionOptionImpl() { this(null); } public ActionType getId() { return id; } public void setId(ActionType id) { this.id = id; } public int hashCode() { return new HashCodeBuilder().append(id).toHashCode(); } public String toString() { ToStringBuilder builder = new ToStringBuilder(this); builder.append("id", id); builder.appendSuper(super.toString()); return builder.toString(); } public Object clone() { ActionOptionImpl copy = null; copy = (ActionOptionImpl) super.clone(); return copy; } }
gpl-2.0
blazegraph/database
bigdata-core/bigdata-sails/src/java/com/bigdata/rdf/sail/webapp/DeleteServlet.java
36408
/** Copyright (C) SYSTAP, LLC DBA Blazegraph 2006-2016. All rights reserved. Contact: SYSTAP, LLC DBA Blazegraph 2501 Calvert ST NW #106 Washington, DC 20008 licenses@blazegraph.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.bigdata.rdf.sail.webapp; import java.io.IOException; import java.io.InputStream; import java.io.PipedOutputStream; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.FutureTask; import java.util.concurrent.atomic.AtomicLong; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.MalformedQueryException; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParser; import org.openrdf.rio.RDFParserFactory; import org.openrdf.rio.RDFParserRegistry; import org.openrdf.rio.helpers.RDFHandlerBase; import org.openrdf.sail.SailException; import com.bigdata.journal.ITx; import com.bigdata.rdf.sail.BigdataSail.BigdataSailConnection; import com.bigdata.rdf.sail.sparql.Bigdata2ASTSPARQLParser; import com.bigdata.rdf.sail.BigdataSailRepositoryConnection; import com.bigdata.rdf.sail.webapp.BigdataRDFContext.AbstractQueryTask; import com.bigdata.rdf.sail.webapp.client.EncodeDecodeValue; import com.bigdata.rdf.sail.webapp.client.MiniMime; import com.bigdata.rdf.sparql.ast.ASTContainer; /** * Handler for DELETE by query (DELETE verb) and DELETE by data (POST). * * @author martyncutcher */ public class DeleteServlet extends BigdataRDFServlet { /** * */ private static final long serialVersionUID = 1L; static private final transient Logger log = Logger .getLogger(DeleteServlet.class); /** * Note: includedInferred is false because inferences can not be deleted * (they are retracted by truth maintenance when they can no longer be * proven). */ private static final boolean includeInferred = false; public DeleteServlet() { } @Override protected void doDelete(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { if (!isWritable(getServletContext(), req, resp)) { // Service must be writable. return; } final String queryStr = req.getParameter("query"); // final boolean suppressTruthMaintenance = getBooleanValue(req, QueryServlet.ATTR_TRUTH_MAINTENANCE, false); if (queryStr != null) { doDeleteWithQuery(req, resp); } else { doDeleteWithAccessPath(req, resp); // } else { // // resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } /** * Delete all statements materialized by a DESCRIBE or CONSTRUCT query. */ private void doDeleteWithQuery(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final String baseURI = req.getRequestURL().toString(); final String namespace = getNamespace(req); final String queryStr = req.getParameter("query"); final boolean suppressTruthMaintenance = getBooleanValue(req, QueryServlet.ATTR_TRUTH_MAINTENANCE, false); final Map<String, Value> bindings = parseBindings(req, resp); if (bindings == null) { // invalid bindings definition generated error response 400 while parsing return; } if (queryStr == null) throw new UnsupportedOperationException(); if (log.isInfoEnabled()) log.info("delete with query: " + queryStr); try { if (getIndexManager().isGroupCommit()) { /* * When group commit is enabled we must fully materialize the * solutions from the query and then delete them. This is because * intermediate checkpoints of the indices would otherwise not be * visible if we were reading on the last commit time rather than * the unisolated index view. */ submitApiTask( new DeleteWithQueryMaterializedTask(req, resp, namespace, ITx.UNISOLATED, // queryStr,// baseURI,// suppressTruthMaintenance, bindings// )).get(); } else { /* * When group commit is NOT enabled we can use an approach that * streams solutions from the last commit point into the DELETE * operation. This is more scalable since it is a streaming * operation. */ submitApiTask( new DeleteWithQuerySteamingTask(req, resp, namespace, ITx.UNISOLATED, // queryStr,// baseURI,// suppressTruthMaintenance, bindings// )).get(); } } catch (Throwable t) { launderThrowable(t, resp, "UPDATE-WITH-QUERY" + ": queryStr=" + queryStr + ", baseURI=" + baseURI); } } /** * An approach based on streaming the query results from the last commit * time. This approach is NOT compatible with group commit since it will not * observe any mutations that have been applied since the last commit point * when it reads on the last commit time. * <p> * Note: To avoid materializing the statements, this runs the query against * the last commit time and uses a pipe to connect the query directly to the * process deleting the statements. This is done while it is holding the * unisolated connection which prevents concurrent modifications. Therefore * the entire SELECT + DELETE operation is ACID. However, when group commit * is enabled the last commit time might not be the last modification to the * indices which would break the serializability guarantee of the applied * mutations. * * @author bryan */ private static class DeleteWithQuerySteamingTask extends AbstractRestApiTask<Void> { private final String queryStr; private final String baseURI; private final boolean suppressTruthMaintenance; private final Map<String, Value> bindings; /** * * @param namespace * The namespace of the target KB instance. * @param timestamp * The timestamp used to obtain a mutable connection. * @param baseURI * The base URI for the operation. * @param bindings */ public DeleteWithQuerySteamingTask(final HttpServletRequest req, final HttpServletResponse resp, final String namespace, final long timestamp, final String queryStr,// final String baseURI, final boolean suppressTruthMaintenance, final Map<String, Value> bindings ) { super(req, resp, namespace, timestamp); this.queryStr = queryStr; this.baseURI = baseURI; this.suppressTruthMaintenance = suppressTruthMaintenance; this.bindings = bindings; } @Override public boolean isReadOnly() { return false; } @Override public Void call() throws Exception { final long begin = System.currentTimeMillis(); final AtomicLong nmodified = new AtomicLong(0L); /* * Parse the query before obtaining the connection object. * * @see BLZG-2039 SPARQL QUERY and SPARQL UPDATE should be parsed * before obtaining the connection */ // Setup the baseURI for this request. final String baseURI = BigdataRDFContext.getBaseURI(req, resp); // Parse the query. final ASTContainer astContainer = new Bigdata2ASTSPARQLParser().parseQuery2(queryStr, baseURI); BigdataSailRepositoryConnection repoConn = null; BigdataSailConnection conn = null; boolean success = false; try { repoConn = getConnection(); conn = repoConn.getSailConnection(); boolean truthMaintenance = conn.getTruthMaintenance(); if (truthMaintenance && suppressTruthMaintenance) { conn.setTruthMaintenance(false); } { if (log.isInfoEnabled()) log.info("delete with query: " + queryStr); final BigdataRDFContext context = BigdataServlet .getBigdataRDFContext(req.getServletContext()); /* * Note: pipe is drained by this thread to consume the query * results, which are the statements to be deleted. */ final PipedOutputStream os = new PipedOutputStream(); // The read-only connection for the query. BigdataSailRepositoryConnection roconn = null; try { final long readOnlyTimestamp = ITx.READ_COMMITTED; roconn = getQueryConnection(namespace, readOnlyTimestamp); // Use this format for the query results. final RDFFormat format = RDFFormat.NTRIPLES; final AbstractQueryTask queryTask = context .getQueryTask(roconn, namespace, readOnlyTimestamp, queryStr, baseURI, astContainer, includeInferred, bindings, format.getDefaultMIMEType(), req, resp, os); switch (queryTask.queryType) { case DESCRIBE: case CONSTRUCT: break; default: throw new MalformedQueryException( "Must be DESCRIBE or CONSTRUCT query"); } final RDFParserFactory factory = RDFParserRegistry .getInstance().get(format); final RDFParser rdfParser = factory.getParser(); rdfParser.setValueFactory(conn.getTripleStore() .getValueFactory()); rdfParser.setVerifyData(false); rdfParser.setStopAtFirstError(true); rdfParser .setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE); rdfParser.setRDFHandler(new RemoveStatementHandler(conn, // nmodified /*, defaultDeleteContext*/)); // Wrap as Future. final FutureTask<Void> ft = new FutureTask<Void>( queryTask); // Submit query for evaluation. context.queryService.execute(ft); // Reads on the statements produced by the query. final InputStream is = newPipedInputStream(os); // Run parser : visited statements will be deleted. rdfParser.parse(is, baseURI); // Await the Future (of the Query) ft.get(); if (truthMaintenance && suppressTruthMaintenance) { conn.setTruthMaintenance(true); } } finally { if (roconn != null) { // close the read-only connection for the query. roconn.rollback(); } } } conn.commit(); success = true; final long elapsed = System.currentTimeMillis() - begin; reportModifiedCount(nmodified.get(), elapsed); return null; } finally { if (conn != null) { if (!success) conn.rollback(); conn.close(); } if (repoConn != null) { repoConn.close(); } } } } // class DeleteWithQueryStreamingTask /** * An approach based on fully materializing the * * TODO We should use the HTree here for a more scalable buffer if * the analytic mode is enabled (or transparently overflow to the * HTree). * * TODO This operator materializes the RDF Values for the CONSTRUCTED * statements, buffers then, and then removes those statements. The * materialization step is not necessary if we handle this all at the * IV layer. * * @author bryan */ private static class DeleteWithQueryMaterializedTask extends AbstractRestApiTask<Void> { private final String queryStr; private final String baseURI; private final boolean suppressTruthMaintenance; private final Map<String, Value> bindings; /** * * @param namespace * The namespace of the target KB instance. * @param timestamp * The timestamp used to obtain a mutable connection. * @param baseURI * The base URI for the operation. */ public DeleteWithQueryMaterializedTask(final HttpServletRequest req, final HttpServletResponse resp, final String namespace, final long timestamp, final String queryStr,// final String baseURI, // final boolean suppressTruthMaintenance, // final Map<String, Value> bindings) { super(req, resp, namespace, timestamp); this.queryStr = queryStr; this.baseURI = baseURI; this.suppressTruthMaintenance = suppressTruthMaintenance; this.bindings = bindings; } @Override public boolean isReadOnly() { return false; } @Override public Void call() throws Exception { final long begin = System.currentTimeMillis(); final AtomicLong nmodified = new AtomicLong(0L); /* * Parse the query before obtaining the connection object. * * @see BLZG-2039 SPARQL QUERY and SPARQL UPDATE should be parsed * before obtaining the connection */ // Setup the baseURI for this request. final String baseURI = BigdataRDFContext.getBaseURI(req, resp); // Parse the query. final ASTContainer astContainer = new Bigdata2ASTSPARQLParser().parseQuery2(queryStr, baseURI); BigdataSailRepositoryConnection repoConn = null; BigdataSailConnection conn = null; boolean success = false; try { repoConn = getConnection(); conn = repoConn.getSailConnection(); boolean truthMaintenance = conn.getTruthMaintenance(); if (truthMaintenance && suppressTruthMaintenance) { conn.setTruthMaintenance(false); } { if (log.isInfoEnabled()) log.info("delete with query: " + queryStr); final BigdataRDFContext context = BigdataServlet .getBigdataRDFContext(req.getServletContext()); /* * Note: pipe is drained by this thread to consume the query * results, which are the statements to be deleted. */ final PipedOutputStream os = new PipedOutputStream(); // Use this format for the query results. final RDFFormat format = RDFFormat.NTRIPLES; final AbstractQueryTask queryTask = context.getQueryTask(repoConn, namespace, ITx.UNISOLATED, queryStr, baseURI, astContainer, includeInferred, bindings, format.getDefaultMIMEType(), req, resp, os); switch (queryTask.queryType) { case DESCRIBE: case CONSTRUCT: break; default: throw new MalformedQueryException( "Must be DESCRIBE or CONSTRUCT query"); } final RDFParserFactory factory = RDFParserRegistry.getInstance() .get(format); final RDFParser rdfParser = factory.getParser(); rdfParser.setValueFactory(conn.getTripleStore() .getValueFactory()); rdfParser.setVerifyData(false); rdfParser.setStopAtFirstError(true); rdfParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE); final BufferStatementHandler buffer = new BufferStatementHandler(conn, // nmodified /*, defaultDeleteContext*/); rdfParser.setRDFHandler(buffer); // Wrap as Future. final FutureTask<Void> ft = new FutureTask<Void>(queryTask); // Submit query for evaluation. context.queryService.execute(ft); // Reads on the statements produced by the query. final InputStream is = newPipedInputStream(os); // Run parser : visited statements will be buffered. rdfParser.parse(is, baseURI); // Await the Future (of the Query) ft.get(); // Delete the buffered statements. buffer.removeAll(); if (truthMaintenance && suppressTruthMaintenance) { conn.setTruthMaintenance(true); } } conn.commit(); success = true; final long elapsed = System.currentTimeMillis() - begin; reportModifiedCount(nmodified.get(), elapsed); return null; } finally { if (conn != null) { if (!success) conn.rollback(); conn.close(); } if (repoConn != null) { repoConn.close(); } } } } // class DeleteWithQueryMaterializedTask @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { if (!isWritable(getServletContext(), req, resp)) { // Service must be writable. return; } final String contentType = req.getContentType(); final String queryStr = req.getParameter("query"); // final boolean suppressTruthMaintenance = getBooleanValue(req, QueryServlet.ATTR_TRUTH_MAINTENANCE, false); final Map<String, Value> bindings = parseBindings(req, resp); if (bindings == null) { // invalid bindings definition generated error response 400 while parsing return; } if (queryStr != null) { doDeleteWithQuery(req, resp); } else if (contentType != null) { doDeleteWithBody(req, resp); } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } /** * DELETE request with a request body containing the statements to be * removed. */ private void doDeleteWithBody(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final String baseURI = req.getRequestURL().toString(); final String contentType = req.getContentType(); final boolean suppressTruthMaintenance = getBooleanValue(req, QueryServlet.ATTR_TRUTH_MAINTENANCE, false); if (contentType == null) throw new UnsupportedOperationException(); if (log.isInfoEnabled()) log.info("Request body: " + contentType); /** * There is a request body, so let's try and parse it. * * <a href="https://sourceforge.net/apps/trac/bigdata/ticket/620"> * UpdateServlet fails to parse MIMEType when doing conneg. </a> */ final RDFFormat format = RDFFormat.forMIMEType(new MiniMime( contentType).getMimeType()); if (format == null) { buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN, "Content-Type not recognized as RDF: " + contentType); return; } final RDFParserFactory rdfParserFactory = RDFParserRegistry .getInstance().get(format); if (rdfParserFactory == null) { buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN, "Parser factory not found: Content-Type=" + contentType + ", format=" + format); return; } /* * Allow the caller to specify the default contexts. */ final Resource[] defaultContext; { final String[] s = req.getParameterValues("context-uri"); if (s != null && s.length > 0) { try { defaultContext = toURIs(s); } catch (IllegalArgumentException ex) { buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN, ex.getLocalizedMessage()); return; } } else { defaultContext = new Resource[0]; } } try { submitApiTask( new DeleteWithBodyTask(req, resp, getNamespace(req), ITx.UNISOLATED, baseURI, suppressTruthMaintenance, defaultContext, rdfParserFactory)).get(); } catch (Throwable t) { BigdataRDFServlet.launderThrowable(t, resp, "DELETE-WITH-BODY: baseURI=" + baseURI + ", context-uri=" + Arrays.toString(defaultContext)); } } private static class DeleteWithBodyTask extends AbstractRestApiTask<Void> { private final String baseURI; private final boolean suppressTruthMaintenance; private final Resource[] defaultContext; private final RDFParserFactory rdfParserFactory; /** * * @param namespace * The namespace of the target KB instance. * @param timestamp * The timestamp used to obtain a mutable connection. * @param baseURI * The base URI for the operation. * @param defaultContext * The context(s) for triples without an explicit named graph * when the KB instance is operating in a quads mode. * @param rdfParserFactory * The factory for the {@link RDFParser}. This should have * been chosen based on the caller's knowledge of the * appropriate content type. */ public DeleteWithBodyTask(final HttpServletRequest req, final HttpServletResponse resp, final String namespace, final long timestamp, final String baseURI, // final boolean suppressTruthMaintenance, // final Resource[] defaultContext, final RDFParserFactory rdfParserFactory) { super(req, resp, namespace, timestamp); this.baseURI = baseURI; this.suppressTruthMaintenance = suppressTruthMaintenance; this.defaultContext = defaultContext; this.rdfParserFactory = rdfParserFactory; } @Override public boolean isReadOnly() { return false; } @Override public Void call() throws Exception { final long begin = System.currentTimeMillis(); BigdataSailRepositoryConnection repoConn = null; BigdataSailConnection conn = null; boolean success = false; try { repoConn = getConnection(); conn = repoConn.getSailConnection(); boolean truthMaintenance = conn.getTruthMaintenance(); if (truthMaintenance && suppressTruthMaintenance) { conn.setTruthMaintenance(false); } final RDFParser rdfParser = rdfParserFactory.getParser(); final AtomicLong nmodified = new AtomicLong(0L); rdfParser.setValueFactory(conn.getTripleStore() .getValueFactory()); rdfParser.setVerifyData(true); rdfParser.setStopAtFirstError(true); rdfParser .setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE); rdfParser.setRDFHandler(new RemoveStatementHandler(conn, // nmodified, defaultContext)); /* * Run the parser, which will cause statements to be deleted. */ rdfParser.parse(req.getInputStream(), baseURI); if (truthMaintenance && suppressTruthMaintenance) { conn.setTruthMaintenance(true); } // Commit the mutation. conn.commit(); success = true; final long elapsed = System.currentTimeMillis() - begin; reportModifiedCount(nmodified.get(), elapsed); return null; } finally { if (conn != null) { if (!success) conn.rollback(); conn.close(); } if (repoConn != null) { repoConn.close(); } } } } /** * Helper class buffers statements as they are visited by the parser. */ static class BufferStatementHandler extends RDFHandlerBase { private final BigdataSailConnection conn; private final AtomicLong nmodified; private final Resource[] defaultContext; private final Set<Statement> stmts = new LinkedHashSet<Statement>(); public BufferStatementHandler(final BigdataSailConnection conn, final AtomicLong nmodified, final Resource... defaultContext) { this.conn = conn; this.nmodified = nmodified; final boolean quads = conn.getTripleStore().isQuads(); if (quads && defaultContext != null) { // The context may only be specified for quads. this.defaultContext = defaultContext; // new Resource[] { // defaultContext }; } else { this.defaultContext = new Resource[0]; } } @Override public void handleStatement(final Statement stmt) throws RDFHandlerException { stmts.add(stmt); } void removeAll() throws SailException { for (Statement stmt : stmts) { doRemoveStatement(stmt); } } private void doRemoveStatement(final Statement stmt) throws SailException { final Resource[] c = (Resource[]) (stmt.getContext() == null ? defaultContext : new Resource[] { stmt.getContext() }); conn.removeStatements(// stmt.getSubject(), // stmt.getPredicate(), // stmt.getObject(), // c); if (c.length >= 2) { // removed from more than one context nmodified.addAndGet(c.length); } else { nmodified.incrementAndGet(); } } } /** * Helper class removes statements from the sail as they are visited by a parser. */ static class RemoveStatementHandler extends RDFHandlerBase { private final BigdataSailConnection conn; private final AtomicLong nmodified; private final Resource[] defaultContext; public RemoveStatementHandler(final BigdataSailConnection conn, final AtomicLong nmodified, final Resource... defaultContext) { this.conn = conn; this.nmodified = nmodified; final boolean quads = conn.getTripleStore().isQuads(); if (quads && defaultContext != null) { // The context may only be specified for quads. this.defaultContext = defaultContext; //new Resource[] { defaultContext }; } else { this.defaultContext = new Resource[0]; } } @Override public void handleStatement(final Statement stmt) throws RDFHandlerException { final Resource[] c = (Resource[]) (stmt.getContext() == null ? defaultContext : new Resource[] { stmt.getContext() }); try { conn.removeStatements(// stmt.getSubject(), // stmt.getPredicate(), // stmt.getObject(), // c ); } catch (SailException e) { throw new RDFHandlerException(e); } if (c.length >= 2) { // removed from more than one context nmodified.addAndGet(c.length); } else { nmodified.incrementAndGet(); } } } /** * Delete all statements described by an access path. */ private void doDeleteWithAccessPath(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final String namespace = getNamespace(req); final boolean suppressTruthMaintenance = getBooleanValue(req, QueryServlet.ATTR_TRUTH_MAINTENANCE, false); final Resource s; final URI p; final Value o; final Resource[] c; try { s = EncodeDecodeValue.decodeResource(req.getParameter("s")); p = EncodeDecodeValue.decodeURI(req.getParameter("p")); o = EncodeDecodeValue.decodeValue(req.getParameter("o")); c = decodeContexts(req, "c"); // c = EncodeDecodeValue.decodeContexts(req.getParameterValues("c")); } catch (IllegalArgumentException ex) { buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN, ex.getLocalizedMessage()); return; } if (log.isInfoEnabled()) log.info("DELETE-WITH-ACCESS-PATH: (s=" + s + ", p=" + p + ", o=" + o + ", c=" + Arrays.toString(c) + ")"); try { submitApiTask( new DeleteWithAccessPathTask(req, resp, namespace, ITx.UNISOLATED, suppressTruthMaintenance, s, p, o, c)).get(); } catch (Throwable t) { BigdataRDFServlet.launderThrowable(t, resp, "DELETE-WITH-ACCESS-PATH: (s=" + s + ",p=" + p + ",o=" + o + ",c=" + Arrays.toString(c) + ")"); } } // static private transient final Resource[] nullArray = new Resource[]{}; private static class DeleteWithAccessPathTask extends AbstractRestApiTask<Void> { private Resource s; private URI p; private final Value o; private final Resource[] c; private final boolean suppressTruthMaintenance; /** * * @param namespace * The namespace of the target KB instance. * @param timestamp * The timestamp used to obtain a mutable connection. * @param baseURI * The base URI for the operation. * @param defaultContext * The context(s) for triples without an explicit named graph * when the KB instance is operating in a quads mode. * @param rdfParserFactory * The factory for the {@link RDFParser}. This should have * been chosen based on the caller's knowledge of the * appropriate content type. */ public DeleteWithAccessPathTask(final HttpServletRequest req, final HttpServletResponse resp, // final String namespace, final long timestamp,// final boolean suppressTruthMaintenance, // final Resource s, final URI p, final Value o, final Resource[] c) { super(req, resp, namespace, timestamp); this.suppressTruthMaintenance = suppressTruthMaintenance; this.s = s; this.p = p; this.o = o; this.c = c; } @Override public boolean isReadOnly() { return true; } @Override public Void call() throws Exception { final long begin = System.currentTimeMillis(); BigdataSailRepositoryConnection repoConn = null; BigdataSailConnection conn = null; boolean success = false; try { repoConn = getConnection(); conn = repoConn.getSailConnection(); boolean truthMaintenance = conn.getTruthMaintenance(); if (truthMaintenance && suppressTruthMaintenance) { conn.setTruthMaintenance(false); } // Remove all statements matching that access path. // final long nmodified = conn.getSailConnection() // .getBigdataSail().getDatabase() // .removeStatements(s, p, o, c); // Remove all statements matching that access path. long nmodified = 0; if (c != null && c.length > 0) { for (Resource r : c) { nmodified += conn.getTripleStore().removeStatements(s, p, o, r); } } else { nmodified += conn.getTripleStore().removeStatements(s, p, o, null); } if (truthMaintenance && suppressTruthMaintenance) { conn.setTruthMaintenance(true); } // Commit the mutation. conn.commit(); success = true; final long elapsed = System.currentTimeMillis() - begin; reportModifiedCount(nmodified, elapsed); return null; } finally { if (conn != null) { if (!success) conn.rollback(); conn.close(); } if (repoConn != null) { repoConn.close(); } } } } }
gpl-2.0
openjdk/jdk7u
jdk/src/share/classes/sun/management/snmp/jvmmib/JvmMemMgrPoolRelEntryMeta.java
7753
/* * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.management.snmp.jvmmib; // // Generated by mibgen version 5.0 (06/02/03) when compiling JVM-MANAGEMENT-MIB in standard metadata mode. // // java imports // import java.io.Serializable; // jmx imports // import javax.management.MBeanServer; import com.sun.jmx.snmp.SnmpCounter; import com.sun.jmx.snmp.SnmpCounter64; import com.sun.jmx.snmp.SnmpGauge; import com.sun.jmx.snmp.SnmpInt; import com.sun.jmx.snmp.SnmpUnsignedInt; import com.sun.jmx.snmp.SnmpIpAddress; import com.sun.jmx.snmp.SnmpTimeticks; import com.sun.jmx.snmp.SnmpOpaque; import com.sun.jmx.snmp.SnmpString; import com.sun.jmx.snmp.SnmpStringFixed; import com.sun.jmx.snmp.SnmpOid; import com.sun.jmx.snmp.SnmpNull; import com.sun.jmx.snmp.SnmpValue; import com.sun.jmx.snmp.SnmpVarBind; import com.sun.jmx.snmp.SnmpStatusException; // jdmk imports // import com.sun.jmx.snmp.agent.SnmpMibNode; import com.sun.jmx.snmp.agent.SnmpMib; import com.sun.jmx.snmp.agent.SnmpMibEntry; import com.sun.jmx.snmp.agent.SnmpStandardObjectServer; import com.sun.jmx.snmp.agent.SnmpStandardMetaServer; import com.sun.jmx.snmp.agent.SnmpMibSubRequest; import com.sun.jmx.snmp.agent.SnmpMibTable; import com.sun.jmx.snmp.EnumRowStatus; import com.sun.jmx.snmp.SnmpDefinitions; /** * The class is used for representing SNMP metadata for the "JvmMemMgrPoolRelEntry" group. * The group is defined with the following oid: 1.3.6.1.4.1.42.2.145.3.163.1.1.2.120.1. */ public class JvmMemMgrPoolRelEntryMeta extends SnmpMibEntry implements Serializable, SnmpStandardMetaServer { static final long serialVersionUID = 7414270971113459798L; /** * Constructor for the metadata associated to "JvmMemMgrPoolRelEntry". */ public JvmMemMgrPoolRelEntryMeta(SnmpMib myMib, SnmpStandardObjectServer objserv) { objectserver = objserv; varList = new int[2]; varList[0] = 3; varList[1] = 2; SnmpMibNode.sort(varList); } /** * Get the value of a scalar variable */ public SnmpValue get(long var, Object data) throws SnmpStatusException { switch((int)var) { case 3: return new SnmpString(node.getJvmMemMgrRelPoolName()); case 2: return new SnmpString(node.getJvmMemMgrRelManagerName()); default: break; } throw new SnmpStatusException(SnmpStatusException.noSuchObject); } /** * Set the value of a scalar variable */ public SnmpValue set(SnmpValue x, long var, Object data) throws SnmpStatusException { switch((int)var) { case 3: throw new SnmpStatusException(SnmpStatusException.snmpRspNotWritable); case 2: throw new SnmpStatusException(SnmpStatusException.snmpRspNotWritable); default: break; } throw new SnmpStatusException(SnmpStatusException.snmpRspNotWritable); } /** * Check the value of a scalar variable */ public void check(SnmpValue x, long var, Object data) throws SnmpStatusException { switch((int) var) { case 3: throw new SnmpStatusException(SnmpStatusException.snmpRspNotWritable); case 2: throw new SnmpStatusException(SnmpStatusException.snmpRspNotWritable); default: throw new SnmpStatusException(SnmpStatusException.snmpRspNotWritable); } } /** * Allow to bind the metadata description to a specific object. */ protected void setInstance(JvmMemMgrPoolRelEntryMBean var) { node = var; } // ------------------------------------------------------------ // // Implements the "get" method defined in "SnmpMibEntry". // See the "SnmpMibEntry" Javadoc API for more details. // // ------------------------------------------------------------ public void get(SnmpMibSubRequest req, int depth) throws SnmpStatusException { objectserver.get(this,req,depth); } // ------------------------------------------------------------ // // Implements the "set" method defined in "SnmpMibEntry". // See the "SnmpMibEntry" Javadoc API for more details. // // ------------------------------------------------------------ public void set(SnmpMibSubRequest req, int depth) throws SnmpStatusException { objectserver.set(this,req,depth); } // ------------------------------------------------------------ // // Implements the "check" method defined in "SnmpMibEntry". // See the "SnmpMibEntry" Javadoc API for more details. // // ------------------------------------------------------------ public void check(SnmpMibSubRequest req, int depth) throws SnmpStatusException { objectserver.check(this,req,depth); } /** * Returns true if "arc" identifies a scalar object. */ public boolean isVariable(long arc) { switch((int)arc) { case 3: case 2: return true; default: break; } return false; } /** * Returns true if "arc" identifies a readable scalar object. */ public boolean isReadable(long arc) { switch((int)arc) { case 3: case 2: return true; default: break; } return false; } // ------------------------------------------------------------ // // Implements the "skipVariable" method defined in "SnmpMibEntry". // See the "SnmpMibEntry" Javadoc API for more details. // // ------------------------------------------------------------ public boolean skipVariable(long var, Object data, int pduVersion) { return super.skipVariable(var,data,pduVersion); } /** * Return the name of the attribute corresponding to the SNMP variable identified by "id". */ public String getAttributeName(long id) throws SnmpStatusException { switch((int)id) { case 3: return "JvmMemMgrRelPoolName"; case 2: return "JvmMemMgrRelManagerName"; default: break; } throw new SnmpStatusException(SnmpStatusException.noSuchObject); } protected JvmMemMgrPoolRelEntryMBean node; protected SnmpStandardObjectServer objectserver = null; }
gpl-2.0
arodchen/MaxSim
maxine/com.oracle.max.vm.ext.vma/test/test/IntStaticArrayRead.java
1364
/* * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package test; public class IntStaticArrayRead { private static int[] intArray; public static void main(String[] args) { intArray = new int[10]; for (int i = 0; i < intArray.length; i++) { @SuppressWarnings("unused") int j = intArray[i]; } } }
gpl-2.0
FireSight/GoonWars
src/server/campaign/util/ELORanking.java
1357
/* * MekWars - Copyright (C) 2004 * * Derived from MegaMekNET (http://www.sourceforge.net/projects/megameknet) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ package server.campaign.util; public class ELORanking { public static double calcWinProp(double PlayerRating, double OponentRating) { return 1 / (Math.pow(10,((OponentRating - PlayerRating) / 400)) + 1); } public static double getNewRatingWinner(double WinnerRating,double LoserRating,int KValue) { return WinnerRating + (KValue*(1-calcWinProp(WinnerRating,LoserRating))); } public static double getNewRatingLoser(double WinnerRating,double LoserRating,int KValue) { //K-Value of the loser is one less than the winner, so scale slowly rises /* if (KValue > 1) KValue--;*/ return LoserRating + (KValue*(0-calcWinProp(LoserRating,WinnerRating))); } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/langtools/test/tools/javac/ConstBoolAppend.java
1560
/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /* * @test * @bug 4102672 * @summary When a constant boolean expression was appended to a * constant string, the value was accidentally being converted * into an integer. * @author turnidge * * @compile ConstBoolAppend.java * @run main ConstBoolAppend */ public class ConstBoolAppend { public static void main(String[] args) throws Exception { if (!("" + true).equals("true")) { throw new Exception("append of bools is wrong: 4102672"); } } }
gpl-2.0
smarr/Truffle
compiler/src/org.graalvm.compiler.jtt/src/org/graalvm/compiler/jtt/optimize/Fold_InstanceOf01.java
2122
/* * Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.jtt.optimize; import org.junit.Test; import org.graalvm.compiler.jtt.JTTTest; /* * Tests constant folding of integer operations. */ public class Fold_InstanceOf01 extends JTTTest { static final Object object = new DummyTestClass(); public static boolean test(int arg) { if (arg == 0) { return object instanceof DummyTestClass; } if (arg == 1) { Object obj = new DummyTestClass(); return obj instanceof DummyTestClass; } if (arg == 2) { return null instanceof DummyTestClass; } return false; } @Test public void run0() throws Throwable { runTest("test", 0); } @Test public void run1() throws Throwable { runTest("test", 1); } @Test public void run2() throws Throwable { runTest("test", 2); } }
gpl-2.0
md-5/jdk10
test/hotspot/jtreg/gc/epsilon/TestLogTrace.java
1451
/* * Copyright (c) 2017, 2018, Red Hat, Inc. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package gc.epsilon; /** * @test TestLogTrace * @key gc * @requires vm.gc.Epsilon & !vm.graal.enabled * @summary Test that tracing does not crash Epsilon * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC -Xlog:gc*=trace gc.epsilon.TestLogTrace */ public class TestLogTrace { public static void main(String[] args) throws Exception { System.out.println("Hello World"); } }
gpl-2.0
evalincius/Hermit_1.3.8_android
src/org/semanticweb/HermiT/datatypes/binarydata/BinaryDataLengthInterval.java
4920
/* Copyright 2008, 2009, 2010 by the Oxford University Computing Laboratory This file is part of HermiT. HermiT 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. HermiT 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 HermiT. If not, see <http://www.gnu.org/licenses/>. */ package org.semanticweb.HermiT.datatypes.binarydata; import java.util.Collection; public class BinaryDataLengthInterval { protected final BinaryDataType m_binaryDataType; protected final int m_minLength; protected final int m_maxLength; public BinaryDataLengthInterval(BinaryDataType binaryDataType,int minLength,int maxLength) { assert !isIntervalEmpty(binaryDataType,minLength,maxLength); m_binaryDataType=binaryDataType; m_minLength=minLength; m_maxLength=maxLength; } /** * Computes the intersection of this interval with the supplied one. If the two intervals do not intersect, the result is null. */ public BinaryDataLengthInterval intersectWith(BinaryDataLengthInterval that) { if (m_binaryDataType!=that.m_binaryDataType) return null; int newMinLength=Math.max(m_minLength,that.m_minLength); int newMaxLength=Math.min(m_maxLength,that.m_maxLength); if (isIntervalEmpty(m_binaryDataType,newMinLength,newMaxLength)) return null; else if (isEqual(m_binaryDataType,newMinLength,newMaxLength)) return this; else if (that.isEqual(m_binaryDataType,newMinLength,newMaxLength)) return that; else return new BinaryDataLengthInterval(m_binaryDataType,newMinLength,newMaxLength); } protected boolean isEqual(BinaryDataType binaryDataType,int minLength,int maxLength) { return m_binaryDataType==binaryDataType && m_minLength==minLength && m_maxLength==maxLength; } public int subtractSizeFrom(int argument) { if (argument<=0 || m_maxLength==Integer.MAX_VALUE) return 0; // If m_minLength or m_maxLength is more than 7, then the number of // values exceeds the range of long. if (m_minLength>=7 || m_maxLength>=7) return 0; // We now compute the actual number of values. long size=getNumberOfValuesOfLength(m_maxLength)-getNumberOfValuesOfLength(m_minLength-1); return (int)Math.max(argument-size,0L); } protected long getNumberOfValuesOfLength(int length) { if (length<0) return 0L; else { long valuesOfLength=1L; long total=1L; for (int i=1;i<=length;i++) { valuesOfLength*=256L; total+=valuesOfLength; } return total; } } public boolean contains(BinaryData value) { return m_binaryDataType==value.getBinaryDataType() && m_minLength<=value.getNumberOfBytes() && value.getNumberOfBytes()<=m_maxLength; } public void enumerateValues(Collection<Object> values) { if (m_maxLength==Integer.MAX_VALUE) throw new IllegalStateException("Internal error: the data range is infinite!"); if (m_minLength==0) values.add(new BinaryData(m_binaryDataType,new byte[0])); byte[] temp=new byte[m_maxLength]; processPosition(temp,values,0); } protected void processPosition(byte[] temp,Collection<Object> values,int position) { if (position<m_maxLength) { for (int b=0;b<=255;b++) { temp[position]=(byte)b; if (m_minLength<=position+1) { byte[] copy=new byte[position+1]; System.arraycopy(temp,0,copy,0,copy.length); values.add(new BinaryData(m_binaryDataType,copy)); } processPosition(temp,values,position+1); } } } public String toString() { StringBuffer buffer=new StringBuffer(); buffer.append(m_binaryDataType.toString()); buffer.append('['); buffer.append(m_minLength); buffer.append(".."); if (m_maxLength==Integer.MAX_VALUE) buffer.append("+INF"); else buffer.append(m_maxLength); buffer.append(']'); return buffer.toString(); } protected static boolean isIntervalEmpty(BinaryDataType binaryDataType,int minLength,int maxLength) { return minLength>maxLength; } }
gpl-2.0
OOP-BPGC-201415/Project
Submissions-2/Mess_Mgmt/Group-7/ClerkTest.java
1515
import junit.framework.TestCase; import org.easymock.EasyMock; import org.easymock.MockControl; public class ClerkTest extends TestCase{ private Clerk mockClerk; private MockControl mockClerk_control; protected void setUp(){ mockClerk_control = MockControl.createControl(Clerk.class); mockClerk = (Clerk) mockClerk_control.getMock(); } public void testClerkMock() { mockClerk.markAttendance(); mockClerk_control.setReturnValue(true); mockClerk.recSalary(); mockClerk_control.setReturnValue(true); mockClerk.takeMoney(); mockClerk_control.setReturnValue(true); mockClerk.scanCard(); mockClerk_control.setReturnValue(true); mockClerk.getName(); mockClerk_control.setReturnValue("Sumathi"); mockClerk.setName(EasyMock.isA(String.class)); mockClerk_control.setReturnValue(true); mockClerk.getMob(); mockClerk_control.setReturnValue("9444444444"); mockClerk.setMob(EasyMock.isA(String.class)); mockClerk_control.setReturnValue(true); mockClerk.Responsibility(); mockClerk_control.setReturnValue("Clerk"); mockClerk_control.replay(); assertTrue(mockClerk.markAttendance()); assertTrue(mockClerk.recSalary()); assertTrue(mockClerk.takeMoney()); assertTrue(mockClerk.scanCard()); assertTrue(mockClerk.setName("Sumathi")); assertTrue(mockClerk.setMob("9879875465")); assertEquals("Clerk",mockClerk.Responsibility()); assertEquals("Sumathi",mockClerk.getName()); assertEquals("9444444444",mockClerk.getMob()); } }
gpl-2.0
rschatz/graal-core
graal/com.oracle.graal.truffle/src/com/oracle/graal/truffle/DefaultLoopNodeFactory.java
1473
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.truffle; import com.oracle.graal.serviceprovider.ServiceProvider; import com.oracle.truffle.api.nodes.LoopNode; import com.oracle.truffle.api.nodes.RepeatingNode; @ServiceProvider(LoopNodeFactory.class) public class DefaultLoopNodeFactory implements LoopNodeFactory { public LoopNode create(RepeatingNode repeatingNode) { return OptimizedOSRLoopNode.create(repeatingNode); } }
gpl-2.0
ximenesuk/bioformats
components/scifio/src/loci/formats/cache/CrosshairStrategy.java
4037
/* * #%L * OME SCIFIO package for reading and converting scientific file formats. * %% * Copyright (C) 2005 - 2012 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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 HOLDERS 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package loci.formats.cache; /** * A crosshair strategy caches planes extending from the the current * dimensional position along each individual axis, but not combinations of * axes. For example, if the current position is Z5-C2-T18, the strategy will * preload the next and previous focal planes (Z6-C2-T18 and Z4-C2-T18), * the next and previous channels (Z5-C3-T18 and Z5-C1-T18), * and the next and previous time points (Z5-C2-T19 and Z5-C2-T17), * but nothing diverging on multiple axes (e.g., Z6-C3-T19 or Z4-C1-T17). * <p> * Planes closest to the current position are loaded first, with axes * prioritized according to the cache strategy's priority settings. * <p> * To illustrate the crosshair strategy, here is a diagram showing a case * in 2D with 35 dimensional positions (5Z x 7T). For both Z and T, order is * centered, range is 2, and priority is normal. * The numbers indicate the order planes will be cached, with "0" * corresponding to the current dimensional position (Z2-3T). * <pre> * T 0 1 2 3 4 5 6 * Z /--------------------- * 0 | 6 * 1 | 2 * 2 | 8 4 0 3 7 * 3 | 1 * 4 | 5 * </pre> * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/cache/CrosshairStrategy.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/cache/CrosshairStrategy.java;hb=HEAD">Gitweb</a></dd></dl> */ public class CrosshairStrategy extends CacheStrategy { // -- Constructor -- /** Constructs a crosshair strategy. */ public CrosshairStrategy(int[] lengths) { super(lengths); } // -- CacheStrategy API methods -- /* @see CacheStrategy#getPossiblePositions() */ protected int[][] getPossiblePositions() { // only positions diverging along a single axis can ever be cached int len = 1; for (int i=0; i<lengths.length; i++) len += lengths[i] - 1; int[][] p = new int[len][lengths.length]; for (int i=0, c=0; i<lengths.length; i++) { for (int j=1; j<lengths[i]; j++) p[++c][i] = j; } return p; } }
gpl-2.0
dls-controls/pvmanager
pvmanager-sys/src/main/java/org/epics/pvmanager/sys/SystemDataSource.java
2422
/** * Copyright (C) 2010-14 pvmanager developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.epics.pvmanager.sys; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.logging.Logger; import org.epics.pvmanager.ChannelHandler; import org.epics.pvmanager.DataSource; import org.epics.pvmanager.vtype.DataTypeSupport; import static org.epics.pvmanager.util.Executors.*; /** * Data source to produce simulated signals that can be using during development * and testing. * * @author carcassi */ public final class SystemDataSource extends DataSource { static { // Install type support for the types it generates. DataTypeSupport.install(); } public SystemDataSource() { super(false); } private static final Logger log = Logger.getLogger(SystemDataSource.class.getName()); /** * ExecutorService on which all data is polled. */ private static ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(namedPool("pvmanager-sys poller ")); static ScheduledExecutorService getScheduledExecutorService() { return exec; } @Override @SuppressWarnings("unchecked") protected ChannelHandler createChannel(String channelName) { if ("free_mb".equals(channelName)) { return new FreeMemoryChannelHandler(channelName); } if ("max_mb".equals(channelName)) { return new MaxMemoryChannelHandler(channelName); } if ("used_mb".equals(channelName)) { return new UsedMemoryChannelHandler(channelName); } if ("time".equals(channelName)) { return new TimeChannelHandler(channelName); } if ("user".equals(channelName)) { return new UserChannelHandler(channelName); } if ("host_name".equals(channelName)) { return new HostnameChannelHandler(channelName); } if ("qualified_host_name".equals(channelName)) { return new QualifiedHostnameChannelHandler(channelName); } if (channelName.startsWith(SystemPropertyChannelHandler.PREFIX)) { return new SystemPropertyChannelHandler(channelName); } throw new IllegalArgumentException("Channel " + channelName + " does not exist"); } }
gpl-2.0
linqingyicen/projectforge-webapp
src/main/java/org/projectforge/xml/stream/converter/VersionConverter.java
1210
///////////////////////////////////////////////////////////////////////////// // // Project ProjectForge Community Edition // www.projectforge.org // // Copyright (C) 2001-2014 Kai Reinhard (k.reinhard@micromata.de) // // ProjectForge is dual-licensed. // // This community edition is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 3 of the License. // // This community edition is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General // Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, see http://www.gnu.org/licenses/. // ///////////////////////////////////////////////////////////////////////////// package org.projectforge.xml.stream.converter; import org.projectforge.Version; public class VersionConverter extends AbstractValueConverter<Version> { @Override public Version fromString(final String str) { return new Version(str); } }
gpl-3.0
qualitified/qualitified-crm
qualitified-crm-core/src/main/java/ca/pfv/spmf/algorithms/frequentpatterns/fpgrowth/MFINode.java
2645
package ca.pfv.spmf.algorithms.frequentpatterns.fpgrowth; /* This file is copyright (c) 2008-2015 Philippe Fournier-Viger * * This file is part of the SPMF DATA MINING SOFTWARE * (http://www.philippe-fournier-viger.com/spmf). * * SPMF 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. * * SPMF 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 * SPMF. If not, see <http://www.gnu.org/licenses/>. */ import java.util.ArrayList; import java.util.List; import ca.pfv.spmf.patterns.itemset_array_integers_with_count.Itemset; /** * This is an implementation of a MFI-Node as used by the FPMax algorithm. * * @see MFITree * @see Itemset * @see AlgoFPMax * @author Philippe Fournier-Viger, 2015 */ public class MFINode { int itemID = -1; // item id // int counter = 1; // frequency counter (a.k.a. support) int level; // at which level in the MFI tree this node appears // the parent node of that node or null if it is the root MFINode parent = null; // the child nodes of that node List<MFINode> childs = new ArrayList<MFINode>(); MFINode nodeLink = null; // link to next node with the same item id (for the header table). /** * constructor */ MFINode(){ } /** * Return the immediate child of this node having a given ID. * If there is no such child, return null; */ MFINode getChildWithID(int id) { // for each child node for(MFINode child : childs){ // if the id is the one that we are looking for if(child.itemID == id){ // return that node return child; } } // if not found, return null return null; } /** * Method for getting a string representation of this tree * (to be used for debugging purposes). * @param an indentation * @return a string */ public String toString(String indent) { StringBuilder output = new StringBuilder(); output.append(""+ itemID); // output.append(" (count="+ counter); output.append(" level="+ level); output.append(")\n"); String newIndent = indent + " "; for (MFINode child : childs) { output.append(newIndent+ child.toString(newIndent)); } return output.toString(); } }
gpl-3.0
murraycu/gwt-glom
src/main/java/org/glom/web/client/event/QuickFindChangeEvent.java
1617
/* * Copyright (C) 2011 Openismus GmbH * * This file is part of GWT-Glom. * * GWT-Glom 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. * * GWT-Glom 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 GWT-Glom. If not, see <http://www.gnu.org/licenses/>. */ package org.glom.web.client.event; import com.google.gwt.event.shared.GwtEvent; /** * */ public class QuickFindChangeEvent extends GwtEvent<QuickFindChangeEventHandler> { public static Type<QuickFindChangeEventHandler> TYPE = new Type<>(); private final String newQuickFindText; public QuickFindChangeEvent(final String newQuickFindText) { this.newQuickFindText = newQuickFindText; } public String getNewQuickFindText() { return newQuickFindText; } @Override public Type<QuickFindChangeEventHandler> getAssociatedType() { return TYPE; } @Override protected void dispatch(final QuickFindChangeEventHandler handler) { handler.onQuickFindChange(this); } @Override public String toDebugString() { String name = this.getClass().getName(); name = name.substring(name.lastIndexOf(".") + 1); return "event: " + name + ": " + newQuickFindText; } }
gpl-3.0
HuygensING/timbuctoo
timbuctoo-instancev4/src/main/java/nl/knaw/huygens/timbuctoo/v5/dropwizard/tasks/StopBdbDataStore.java
1527
package nl.knaw.huygens.timbuctoo.v5.dropwizard.tasks; import io.dropwizard.servlets.tasks.Task; import nl.knaw.huygens.timbuctoo.util.Tuple; import nl.knaw.huygens.timbuctoo.v5.berkeleydb.BdbEnvironmentCreator; import nl.knaw.huygens.timbuctoo.v5.dataset.dto.DataSetMetaData; import java.io.PrintWriter; import java.util.List; import java.util.Map; public class StopBdbDataStore extends Task { private static final String DATA_SET_ID_PARAM = "dataSetId"; private static final String DATA_STORE_PARAM = "dataStore"; private final BdbEnvironmentCreator environmentCreator; public StopBdbDataStore(BdbEnvironmentCreator environmentCreator) { super("stopDataStore"); this.environmentCreator = environmentCreator; } @Override public void execute(Map<String, List<String>> immutableMultimap, PrintWriter printWriter) throws Exception { if (immutableMultimap.containsKey(DATA_SET_ID_PARAM) && immutableMultimap.containsKey(DATA_STORE_PARAM)) { final String dataSetId = immutableMultimap.get(DATA_SET_ID_PARAM).iterator().next(); final String dataStore = immutableMultimap.get(DATA_STORE_PARAM).iterator().next(); final Tuple<String, String> ownerDataSet = DataSetMetaData.splitCombinedId(dataSetId); environmentCreator.closeDatabase(ownerDataSet.getLeft(), ownerDataSet.getRight(), dataStore); } else { printWriter.println( String.format("Make sure your request contains the params '%s' and '%s'", DATA_SET_ID_PARAM, DATA_STORE_PARAM) ); } } }
gpl-3.0
FunCat/JDI
Java/JDI/jdi-uitest-cucumber/src/main/java/com/epam/jdi/cucumber/stepdefs/ru/LinkStepsRU.java
827
package com.epam.jdi.cucumber.stepdefs.ru; import com.epam.jdi.uitests.core.interfaces.common.ILink; import cucumber.api.java.en.Then; import static com.epam.jdi.cucumber.Utils.getElementByName; public class LinkStepsRU { @Then("^ссылка \"([^\"]*)\" из \"([^\"]*)\" содержит \"([^\"]*)\"$") public void linkFromContains(String linkName, String containerName, String contains) { ILink link = getElementByName(containerName, linkName); link.waitReferenceContains(contains); } @Then("^ссылка \"([^\"]*)\" из \"([^\"]*)\" соответствует \"([^\"]*)\"$") public void linkFromMuchReference(String linkName, String containerName, String regex) { ILink link = getElementByName(containerName, linkName); link.waitMatchReference(regex); } }
gpl-3.0
mrGeen/Artemis
uk/ac/sanger/artemis/components/filetree/JTreeTable.java
28863
/* * * * This file is part of Artemis * * Copyright(C) 2006 Genome Research Limited * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or(at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ package uk.ac.sanger.artemis.components.filetree; import javax.swing.*; import javax.swing.tree.*; import javax.swing.table.*; import javax.swing.filechooser.FileSystemView; import java.io.File; import java.io.IOException; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.*; import java.awt.dnd.*; import java.awt.image.BufferedImage; import java.util.Vector; import uk.ac.sanger.artemis.j2ssh.FileTransferProgressMonitor; import uk.ac.sanger.artemis.j2ssh.FTProgress; import uk.ac.sanger.artemis.Options; import uk.ac.sanger.artemis.Entry; import uk.ac.sanger.artemis.EntryGroup; import uk.ac.sanger.artemis.SimpleEntryGroup; import uk.ac.sanger.artemis.util.OutOfRangeException; import uk.ac.sanger.artemis.util.FileDocument; import uk.ac.sanger.artemis.io.EntryInformation; import uk.ac.sanger.artemis.io.SimpleEntryInformation; import uk.ac.sanger.artemis.components.EntryEdit; import uk.ac.sanger.artemis.components.EntryFileDialog; import uk.ac.sanger.artemis.components.SwingWorker; import uk.ac.sanger.artemis.components.MessageDialog; import uk.ac.sanger.artemis.sequence.NoSequenceException; /** * * This example shows how to create a simple JTreeTable component, * by using a JTree as a renderer (and editor) for the cells in a * particular column in the JTable. * * modified from the example at: * http://java.sun.com/products/jfc/tsc/articles/treetable1/ * */ public class JTreeTable extends JTable implements DragGestureListener, DragSourceListener, DropTargetListener, ActionListener, Autoscroll { /** */ private static final long serialVersionUID = 1L; /** popup menu */ private JPopupMenu popup; /** busy cursor */ private Cursor cbusy = new Cursor(Cursor.WAIT_CURSOR); /** done cursor */ private Cursor cdone = new Cursor(Cursor.DEFAULT_CURSOR); /** file separator */ private String fs = new String(System.getProperty("file.separator")); /** AutoScroll margin */ private static final int AUTOSCROLL_MARGIN = 45; /** used by AutoScroll method */ private Insets autoscrollInsets = new Insets( 0, 0, 0, 0 ); protected TreeTableCellRenderer tree; public JTreeTable(TreeModel treeTableModel) { super(); DragSource dragSource = DragSource.getDefaultDragSource(); dragSource.createDefaultDragGestureRecognizer( this, // component where drag originates DnDConstants.ACTION_COPY_OR_MOVE, // actions this); // drag gesture recognizer setDropTarget(new DropTarget(this,this)); // Create the tree. It will be used as a renderer and editor. tree = new TreeTableCellRenderer(treeTableModel); // Install a tableModel representing the visible rows in the tree. super.setModel(new TreeTableModelAdapter(treeTableModel, tree)); // Force the JTable and JTree to share their row selection models. tree.setSelectionModel(new DefaultTreeSelectionModel() { /***/ private static final long serialVersionUID = 1L; // Extend the implementation of the constructor, as if: /* public this() */ { setSelectionModel(listSelectionModel); } }); // Make the tree and table row heights the same. tree.setRowHeight(getRowHeight()); // Install the tree editor renderer and editor. setDefaultRenderer(TreeTableModel.class, tree); setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor()); setShowGrid(false); setIntercellSpacing(new Dimension(3, 0)); //Listen for when a file is selected MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent me) { if(me.getClickCount() == 2 && isFileSelection() && !me.isPopupTrigger()) { setCursor(cbusy); FileNode node = getSelectedNode(); String selected = node.getFile().getAbsolutePath(); showFilePane(selected); setCursor(cdone); } } }; this.addMouseListener(mouseListener); // Popup menu addMouseListener(new PopupListener()); popup = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Refresh"); menuItem.addActionListener(this); popup.add(menuItem); JMenuItem gotoItem = new JMenuItem("GoTo Directory..."); gotoItem.addActionListener(this); popup.add(gotoItem); popup.add(new JSeparator()); //open menu JMenu openMenu = new JMenu("Open With"); popup.add(openMenu); menuItem = new JMenuItem("Jemboss Alignment Editor"); menuItem.addActionListener(this); openMenu.add(menuItem); menuItem = new JMenuItem("Artemis"); menuItem.addActionListener(this); openMenu.add(menuItem); menuItem = new JMenuItem("Rename..."); menuItem.addActionListener(this); popup.add(menuItem); menuItem = new JMenuItem("New Folder..."); menuItem.addActionListener(this); popup.add(menuItem); menuItem = new JMenuItem("Delete..."); menuItem.addActionListener(this); popup.add(menuItem); popup.add(new JSeparator()); menuItem = new JMenuItem("De-select All"); menuItem.addActionListener(this); popup.add(menuItem); // Set the first visible column to 10 pixels wide TableColumn col = getColumnModel().getColumn(1); col.setPreferredWidth(10); } public TreeTableCellRenderer getTree() { return tree; } /** * * Get FileNode of selected node * @return node that is currently selected * */ public FileNode getSelectedNode() { TreePath path = tree.getLeadSelectionPath(); if(path == null) return null; FileNode node = (FileNode)path.getLastPathComponent(); return node; } /* Workaround for BasicTableUI anomaly. Make sure the UI never tries to * paint the editor. The UI currently uses different techniques to * paint the renderers and editors and overriding setBounds() below * is not the right thing to do for an editor. Returning -1 for the * editing row in this case, ensures the editor is never painted. */ public int getEditingRow() { return (getColumnClass(editingColumn) == TreeTableModel.class) ? -1 : editingRow; } private void refresh(FileNode node) { node.removeAllChildren(); node.reset(); node.getChildren( ((FileSystemModel)tree.getModel()).getFilter() ); ((DefaultTreeModel)tree.getModel()).nodeStructureChanged(node); tree.revalidate(); tree.repaint(); revalidate(); } protected void refreshAll() { FileSystemModel model = (FileSystemModel)tree.getModel(); Object root = model.getRoot(); Vector vnodes = new Vector(); addChildren(vnodes, (FileNode)root, model); for(int i = 0; i<vnodes.size(); i++) refresh((FileNode)vnodes.get(i)); tree.revalidate(); repaint(); revalidate(); } private void addChildren(Vector v, FileNode node, FileSystemModel model) { int nchild = model.getChildCount(node); for(int i = 0; i<nchild; i++) { FileNode fn = (FileNode)model.getChild(node, i); if(fn.isDirectory()) v.add(fn); } } /** * * Get FileNodes of selected nodes * @return node that is currently selected * */ private FileNode[] getSelectedNodes() { TreePath path[] = tree.getSelectionPaths(); if(path == null) return null; int numberSelected = path.length; FileNode nodes[] = new FileNode[numberSelected]; for(int i=0;i<numberSelected;i++) nodes[i] = (FileNode)path[i].getLastPathComponent(); return nodes; } /** * * Get selected files * @return node that is currently selected * */ private File[] getSelectedFiles() { FileNode[] fn = getSelectedNodes(); int numberSelected = fn.length; File files[] = new File[numberSelected]; for(int i=0;i<numberSelected;i++) files[i] = fn[i].getFile(); return files; } /** * * Popup menu actions * @param e action event * */ public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem)(e.getSource()); FileNode node = getSelectedNode(); if(source.getText().equals("Refresh")) { if(node == null) return; else if(node.isLeaf()) node = (FileNode)node.getParent(); node.removeAllChildren(); node.reset(); node.getChildren( ((FileSystemModel)tree.getModel()).getFilter() ); ((DefaultTreeModel)tree.getModel()).nodeStructureChanged(node); tree.repaint(); revalidate(); repaint(); return; } if(source.getText().startsWith("GoTo Directory")) { String dir = JOptionPane.showInputDialog(this, "GoTo Directory", System.getProperty("home.dir")); File fileDir = new File(dir); if(!fileDir.exists()) { JOptionPane.showMessageDialog(this, dir + " not found."); return; } else if(fileDir.isFile()) { JOptionPane.showMessageDialog(this, dir + " is a file."); return; } FileNode rootNode = (FileNode) ((DefaultTreeModel)tree.getModel()).getRoot(); FileNode newNode = new FileNode(fileDir); rootNode.add(newNode); ((DefaultTreeModel)tree.getModel()).nodeStructureChanged(rootNode); revalidate(); return; } if(node == null) { JOptionPane.showMessageDialog(null,"No file selected.", "Warning", JOptionPane.WARNING_MESSAGE); return; } final File f = node.getFile(); if(source.getText().equals("Jemboss Alignment Editor")) { org.emboss.jemboss.editor.AlignJFrame ajFrame = new org.emboss.jemboss.editor.AlignJFrame(f); ajFrame.setVisible(true); } else if(source.getText().equals("Artemis")) { setCursor(cbusy); String selected = node.getFile().getAbsolutePath(); showFilePane(selected); setCursor(cdone); } else if(source.getText().equals("New Folder...")) { if(node.isLeaf()) node = (FileNode)node.getParent(); String path = node.getFile().getAbsolutePath(); String inputValue = JOptionPane.showInputDialog(null, "Folder Name","Create New Folder in "+path, JOptionPane.QUESTION_MESSAGE); if(inputValue != null && !inputValue.equals("") ) { String fullname = path+fs+inputValue; File dir = new File(fullname); if(dir.exists()) JOptionPane.showMessageDialog(null, fullname+" alread exists!", "Error", JOptionPane.ERROR_MESSAGE); else { if(dir.mkdir()) refresh(node); else JOptionPane.showMessageDialog(null, "Cannot make the folder\n"+fullname, "Error", JOptionPane.ERROR_MESSAGE); } } } else if(source.getText().equals("Delete...")) { File fn[] = getSelectedFiles(); String[] names = new String[fn.length]; for(int i=0; i<fn.length;i++) names[i] = fn[i].getAbsolutePath(); JList list = new JList(names); JScrollPane jsp = new JScrollPane(list); int n = JOptionPane.showConfirmDialog(null, jsp, "Delete "+fn.length+" Files", JOptionPane.YES_NO_OPTION); FileNode nodes[] = getSelectedNodes(); if(n == JOptionPane.YES_OPTION) for(int i=0; i<nodes.length;i++) deleteFile(nodes[i]); } else if(source.getText().equals("Rename...")) { String inputValue = (String)JOptionPane.showInputDialog(null, "New File Name","Rename "+f.getName(), JOptionPane.QUESTION_MESSAGE,null,null,f.getName()); if(inputValue != null && !inputValue.equals("") ) { String path = f.getParent(); String fullname = path+fs+inputValue; File newFile = new File(fullname); try { renameFile(f,node,newFile.getCanonicalPath()); } catch(IOException ioe){} } } else if(source.getText().equals("De-select All")) clearSelection(); } /** * * Method to rename a file and update the filenode's. * @param oldFile file to rename * @param oldNode filenode to be removed * @param newFullName name of the new file * */ private void renameFile(final File oldFile, final FileNode oldNode, String newFullName) { final File fnew = new File(newFullName); if(fnew.exists()) JOptionPane.showMessageDialog(null, newFullName+" alread exists!", "Warning", JOptionPane.ERROR_MESSAGE); else { if(oldFile.renameTo(fnew)) { Runnable renameFileInTree = new Runnable() { public void run () { refresh((FileNode)oldNode.getParent()); }; }; SwingUtilities.invokeLater(renameFileInTree); } else JOptionPane.showMessageDialog(null, "Cannot rename \n"+oldFile.getAbsolutePath()+ "\nto\n"+fnew.getAbsolutePath(), "Rename Error", JOptionPane.ERROR_MESSAGE); } return; } /** * * Delete a file from the tree * @param node node to delete * */ public void deleteFile(final FileNode node) { File f = node.getFile(); if(f.delete()) { Runnable deleteFileFromTree = new Runnable() { public void run () { refresh((FileNode)node.getParent()); }; }; SwingUtilities.invokeLater(deleteFileFromTree); } else JOptionPane.showMessageDialog(null,"Cannot delete\n"+ f.getAbsolutePath(),"Warning", JOptionPane.ERROR_MESSAGE); } /** * * Opens a JFrame with the file contents displayed. * @param filename file name to display * */ public void showFilePane(final String filename) { SwingWorker entryWorker = new SwingWorker() { EntryEdit entry_edit; public Object construct() { try { EntryInformation new_entry_information = new SimpleEntryInformation(Options.getArtemisEntryInformation()); final Entry entry = new Entry(EntryFileDialog.getEntryFromFile( null, new FileDocument(new File(filename)), new_entry_information, true)); if(entry == null) return null; final EntryGroup entry_group = new SimpleEntryGroup(entry.getBases()); entry_group.add(entry); entry_edit = new EntryEdit(entry_group); return null; } catch(NoSequenceException e) { new MessageDialog(null, "read failed: entry contains no sequence"); } catch(OutOfRangeException e) { new MessageDialog(null, "read failed: one of the features in " + " the entry has an out of range " + "location: " + e.getMessage()); } catch(NullPointerException npe) { npe.printStackTrace(); } return null; } public void finished() { if(entry_edit != null) entry_edit.setVisible(true); } }; entryWorker.start(); } /** * * Return true if selected node is a file * @return true is a file is selected, false if * a directory is selected * */ public boolean isFileSelection() { TreePath path = tree.getLeadSelectionPath(); if(path == null) return false; FileNode node = (FileNode)path.getLastPathComponent(); return node.isLeaf(); } // // The renderer used to display the tree nodes, a JTree. // public class TreeTableCellRenderer extends JTree implements TableCellRenderer { /** */ private static final long serialVersionUID = 1L; protected int visibleRow; public TreeTableCellRenderer(TreeModel model) { super(model); } public void setBounds(int x, int y, int w, int h) { super.setBounds(x, 0, w, JTreeTable.this.getHeight()); } public void paint(Graphics g) { g.translate(0, -visibleRow * getRowHeight()); super.paint(g); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if(isSelected) setBackground(table.getSelectionBackground()); else setBackground(table.getBackground()); visibleRow = row; return this; } } // // The editor used to interact with tree nodes, a JTree. // public class TreeTableCellEditor extends AbstractCellEditor implements TableCellEditor { public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int r, int c) { return tree; } } /** * * Popup menu listener * */ class PopupListener extends MouseAdapter { public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if(e.isPopupTrigger()) popup.show(e.getComponent(), e.getX(), e.getY()); } } private boolean writeByteFile(byte[] contents, File fn) { if(fn.exists()) { int n = JOptionPane.showConfirmDialog(null, "Overwrite \n"+fn.getName()+"?", "Overwrite File", JOptionPane.YES_NO_OPTION); if(n == JOptionPane.NO_OPTION) return false; } else if(!fn.getParentFile().canWrite()) JOptionPane.showMessageDialog(null,"Cannot write to "+fn.getName(), "Write Permission Denied", JOptionPane.WARNING_MESSAGE); try { FileOutputStream out = new FileOutputStream(fn); out.write(contents); out.close(); } catch(FileNotFoundException fnfe) {return false;} catch(IOException ioe) {return false;} return true; } private void localDrop(DropTargetDropEvent e, Vector vnode, FileNode dropNode) { try { for(int i=0; i<vnode.size(); i++) { FileNode fn = (FileNode)vnode.get(i); // fn = getNode(fn.getFile().getAbsolutePath()); if (dropNode.isLeaf()) { e.rejectDrop(); return; } String dropDir = dropNode.getFile().getAbsolutePath(); String newFullName = dropDir+fs+fn.toString(); renameFile(fn.getFile(),fn,newFullName); } } catch(Exception ufe){} } private void remoteDrop(final DropTargetDropEvent e, final Vector vnode, final FileNode dropNode) { SwingWorker getFileWorker = new SwingWorker() { FileTransferProgressMonitor monitor; public Object construct() { try { monitor = new FileTransferProgressMonitor(JTreeTable.this); for(int i=0; i<vnode.size(); i++) { final RemoteFileNode fn = (RemoteFileNode)vnode.get(i); final File dropDest; String dropDir = null; if (dropNode.isLeaf()) { FileNode pn = (FileNode)dropNode.getParent(); dropDir = pn.getFile().getAbsolutePath(); dropDest = new File(dropDir,fn.getFile()); } else { dropDir = dropNode.getFile().getAbsolutePath(); dropDest = new File(dropDir,fn.getFile()); } try { FTProgress progress = monitor.add(fn.getFile()); final byte[] contents = fn.getFileContents(progress); //final String ndropDir = dropDir; Runnable updateTheTree = new Runnable() { public void run () { if(writeByteFile(contents, dropDest)) { if(dropNode.isLeaf()) refresh((FileNode)dropNode.getParent()); else refresh(dropNode); } }; }; SwingUtilities.invokeLater(updateTheTree); } catch (Exception exp) { System.out.println("FileTree: caught exception"); exp.printStackTrace(); } } e.getDropTargetContext().dropComplete(true); } catch (Exception exp) { e.rejectDrop(); } return null; } public void finished() { if(monitor != null) monitor.close(); } }; getFileWorker.start(); } //////////////////// // DRAG AND DROP //////////////////// // drag source public void dragGestureRecognized(DragGestureEvent e) { // ignore if mouse popup trigger InputEvent ie = e.getTriggerEvent(); if(ie instanceof MouseEvent) if(((MouseEvent)ie).isPopupTrigger()) return; // drag only files if(isFileSelection()) { final int nlist = tree.getSelectionCount(); if(nlist > 1) { TransferableFileNodeList list = new TransferableFileNodeList(nlist); FileNode nodes[] = getSelectedNodes(); for(int i=0; i<nodes.length; i++) list.add(nodes[i]); BufferedImage buff = getImage(nodes[0].getFile()); e.startDrag(DragSource.DefaultCopyDrop, // cursor buff, new Point(0,0), (Transferable)list, // transferable data this); // drag source listener } else { BufferedImage buff = getImage(getSelectedNode().getFile()); e.startDrag(DragSource.DefaultCopyDrop, // cursor buff, new Point(0,0), (Transferable)getSelectedNode(), // transferable data this); // drag source listener } } } /** * * FileSystemView provides a platform-independent way to get the * appropriate icon * */ private BufferedImage getImage(File temp) { // get the right icon FileSystemView fsv = FileSystemView.getFileSystemView( ); Icon icn = fsv.getSystemIcon(temp); Toolkit tk = Toolkit.getDefaultToolkit( ); Dimension dim = tk.getBestCursorSize( icn.getIconWidth( ),icn.getIconHeight( )); BufferedImage buff = new BufferedImage(dim.width,dim.height, BufferedImage.TYPE_INT_ARGB); icn.paintIcon(this,buff.getGraphics( ),0,0); return buff; } public void dragDropEnd(DragSourceDropEvent e) {} public void dragEnter(DragSourceDragEvent e) {} public void dragExit(DragSourceEvent e) {} public void dragOver(DragSourceDragEvent e) {} public void dropActionChanged(DragSourceDragEvent e) {} // drop sink public void dragEnter(DropTargetDragEvent e) { if(e.isDataFlavorSupported(FileNode.FILENODE) || e.isDataFlavorSupported(RemoteFileNode.REMOTEFILENODE) || e.isDataFlavorSupported(TransferableFileNodeList.TRANSFERABLEFILENODELIST)) e.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); } public void drop(final DropTargetDropEvent e) { final Transferable t = e.getTransferable(); final FileNode dropNode = getSelectedNode(); if(dropNode == null) { e.rejectDrop(); return; } if(t.isDataFlavorSupported(TransferableFileNodeList.TRANSFERABLEFILENODELIST)) { try { TransferableFileNodeList filelist = (TransferableFileNodeList) t.getTransferData(TransferableFileNodeList.TRANSFERABLEFILENODELIST); if(filelist.get(0) instanceof RemoteFileNode) remoteDrop(e, filelist, dropNode); else localDrop(e, filelist, dropNode); } catch(UnsupportedFlavorException exp){} catch(IOException ioe){} } else if(t.isDataFlavorSupported(FileNode.FILENODE)) { try { Vector v = new Vector(); FileNode fn = (FileNode)t.getTransferData(FileNode.FILENODE); v.add(fn); localDrop(e, v, dropNode); } catch(Exception ufe){} } else if(t.isDataFlavorSupported(RemoteFileNode.REMOTEFILENODE)) { try { Vector v = new Vector(); final RemoteFileNode fn = (RemoteFileNode)t.getTransferData(RemoteFileNode.REMOTEFILENODE); v.add(fn); remoteDrop(e, v, dropNode); } catch(Exception ufe){} } else { e.rejectDrop(); return; } } /** * * When a suitable DataFlavor is offered over a remote file * node the node is highlighted/selected and the drag * accepted. Otherwise the drag is rejected. * */ public void dragOver(DropTargetDragEvent e) { if(e.isDataFlavorSupported(FileNode.FILENODE)) { Point ploc = e.getLocation(); TreePath ePath = tree.getPathForLocation(ploc.x,ploc.y); if (ePath == null) { e.rejectDrag(); return; } FileNode node = (FileNode)ePath.getLastPathComponent(); if(!node.isDirectory()) e.rejectDrag(); else { tree.setSelectionPath(ePath); e.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); } } else if(e.isDataFlavorSupported(RemoteFileNode.REMOTEFILENODE) || e.isDataFlavorSupported(TransferableFileNodeList.TRANSFERABLEFILENODELIST)) { Point ploc = e.getLocation(); TreePath ePath = tree.getPathForLocation(ploc.x,ploc.y); if (ePath == null) e.rejectDrag(); else { tree.setSelectionPath(ePath); e.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); } } else e.rejectDrag(); return; } public void dropActionChanged(DropTargetDragEvent e) {} public void dragExit(DropTargetEvent e){} //////////////////// // AUTO SCROLLING // //////////////////// /** * * Handles the auto scrolling of the JTree. * @param location The location of the mouse. * */ public void autoscroll( Point location ) { int top = 0, left = 0, bottom = 0, right = 0; Dimension size = getSize(); Rectangle rect = getVisibleRect(); int bottomEdge = rect.y + rect.height; int rightEdge = rect.x + rect.width; if( location.y - rect.y < AUTOSCROLL_MARGIN && rect.y > 0 ) top = AUTOSCROLL_MARGIN; if( location.x - rect.x < AUTOSCROLL_MARGIN && rect.x > 0 ) left = AUTOSCROLL_MARGIN; if( bottomEdge - location.y < AUTOSCROLL_MARGIN && bottomEdge < size.height ) bottom = AUTOSCROLL_MARGIN; if( rightEdge - location.x < AUTOSCROLL_MARGIN && rightEdge < size.width ) right = AUTOSCROLL_MARGIN; rect.x += right - left; rect.y += bottom - top; scrollRectToVisible( rect ); } /** * * Gets the insets used for the autoscroll. * @return The insets. * */ public Insets getAutoscrollInsets() { Dimension size = getSize(); Rectangle rect = getVisibleRect(); autoscrollInsets.top = rect.y + AUTOSCROLL_MARGIN; autoscrollInsets.left = rect.x + AUTOSCROLL_MARGIN; autoscrollInsets.bottom = size.height - (rect.y+rect.height) + AUTOSCROLL_MARGIN; autoscrollInsets.right = size.width - (rect.x+rect.width) + AUTOSCROLL_MARGIN; return autoscrollInsets; } }
gpl-3.0
aspigex/HareDBWebRESTful
HareDB_HBaseClient_FacadeAPI/src/main/java/com/haredb/harespark/bean/input/CreateTableBean.java
1051
package com.haredb.harespark.bean.input; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class CreateTableBean implements IInputBean { private String tablename; private List<String> columnNames; private List<String> dataTypes; public CreateTableBean() { } public CreateTableBean(String tablename, List<String> columnNames, List<String> dataTypes) { super(); this.tablename = tablename; this.columnNames = columnNames; this.dataTypes = dataTypes; } public String getTablename() { return tablename; } public void setTablename(String tablename) { this.tablename = tablename; } public List<String> getColumnNames() { return columnNames; } public void setColumnNames(List<String> columnNames) { this.columnNames = columnNames; } public List<String> getDataTypes() { return dataTypes; } public void setDataTypes(List<String> dataType) { this.dataTypes = dataType; } @Override public <T> Class<?> getBeanClass() { return this.getClass(); } }
gpl-3.0
kazoompa/opal
opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/rest/client/authorization/TabPanelAuthorizer.java
1547
/* * Copyright (c) 2021 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.obiba.opal.web.gwt.rest.client.authorization; import com.github.gwtbootstrap.client.ui.TabPanel; import com.github.gwtbootstrap.client.ui.base.ListItem; import com.github.gwtbootstrap.client.ui.base.UnorderedList; /** * Authorize a tab panel. */ public class TabPanelAuthorizer implements HasAuthorization { private final TabPanel tabs; private final int index; private int selectedIndex; public TabPanelAuthorizer(TabPanel tabs, int index) { this.tabs = tabs; this.index = index; } @Override public void beforeAuthorization() { // if the tab to hide is the selected one, tab selection changes selectedIndex = tabs.getSelectedTab(); getNavTab(index).setVisible(false); } @Override public void authorized() { getNavTab(index).setVisible(true); // restore the previous tab selection if(selectedIndex == index) { tabs.selectTab(index); } } @Override public void unauthorized() { getNavTab(index).setVisible(false); if(selectedIndex == index) { tabs.selectTab(index + 1); } } private ListItem getNavTab(int i) { UnorderedList ul = (UnorderedList) tabs.getWidget(0); return (ListItem) ul.getWidget(i); } }
gpl-3.0
MStefko/STEADIER-SAILOR
src/main/java/ch/epfl/leb/sass/models/fluorophores/commands/internal/FluorophoreReceiver.java
14422
/* * Copyright (C) 2017 Laboratory of Experimental Biophysics * Ecole Polytechnique Federale de Lausanne * * 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 ch.epfl.leb.sass.models.fluorophores.commands.internal; import ch.epfl.leb.sass.utils.RNG; import ch.epfl.leb.sass.models.psfs.PSFBuilder; import ch.epfl.leb.sass.models.components.Camera; import ch.epfl.leb.sass.models.fluorophores.Fluorophore; import ch.epfl.leb.sass.models.fluorophores.internal.DefaultFluorophore; import ch.epfl.leb.sass.models.illuminations.Illumination; import ch.epfl.leb.sass.models.photophysics.FluorophoreDynamics; import java.io.File; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; /** * Populates a field of view with fluorophores. * * The FluorophoreGenerator contains a number of methods for creating actual * fluorophore instances and in different arrangements, such as placing them on * a grid, randomly distributing them in the FOV, and placing them according to * input from a text file. * * @author Marcel Stefko * @author Kyle M. Douglass */ public class FluorophoreReceiver { /** * Randomly populate the field of view with fluorophores. * * @param numFluors The number of fluorophores to add to the field of view. * @param camera The camera for determining the size of the field of view. * @param illumination The illumination profile on the sample. * @param psfBuilder Builder for calculating microscope PSFs. * @param fluorDynamics The fluorophore dynamics properties. * @return The list of fluorophores. */ public static ArrayList<Fluorophore> generateFluorophoresRandom2D( int numFluors, Camera camera, Illumination illumination, PSFBuilder psfBuilder, FluorophoreDynamics fluorDynamics) { Random rnd = RNG.getUniformGenerator(); ArrayList<Fluorophore> result = new ArrayList(); double x; double y; double z = 0; Fluorophore fluorophore; for (int i=0; i < numFluors; i++) { x = camera.getNX() * rnd.nextDouble(); y = camera.getNY() * rnd.nextDouble(); fluorophore = new DefaultFluorophore( psfBuilder, illumination, fluorDynamics.getSignal(), fluorDynamics.getStateSystem(), fluorDynamics.getStartingState(), x, y, z); result.add(fluorophore); illumination.addListener(fluorophore.getIlluminationListener()); } return result; } /** * Randomly populate the field of view with fluorophores in three dimensions. * * @param numFluors The number of fluorophores to add to the field of view. * @param zLow The lower bound on the range in z in units of pixels * @param zHigh The upper bound on the range in z in units of pixels * @param camera The camera for determining the size of the field of view. * @param illumination The illumination profile on the sample. * @param psfBuilder Builder for calculating microscope PSFs. * @param fluorDynamics The fluorophore dynamics properties. * @return The list of fluorophores. */ public static ArrayList<Fluorophore> generateFluorophoresRandom3D( int numFluors, double zLow, double zHigh, Camera camera, Illumination illumination, PSFBuilder psfBuilder, FluorophoreDynamics fluorDynamics) { Random rnd = RNG.getUniformGenerator(); ArrayList<Fluorophore> result = new ArrayList(); double x; double y; double z; Fluorophore fluorophore; for (int i=0; i < numFluors; i++) { x = camera.getNX() * rnd.nextDouble(); y = camera.getNY() * rnd.nextDouble(); z = (zHigh - zLow) * rnd.nextDouble() + zLow; fluorophore = new DefaultFluorophore( psfBuilder, illumination, fluorDynamics.getSignal(), fluorDynamics.getStateSystem(), fluorDynamics.getStartingState(), x, y, z); result.add(fluorophore); illumination.addListener(fluorophore.getIlluminationListener()); } return result; } /** * Generate a rectangular grid of fluorophores. * * @param spacing The distance along the grid between nearest neighbors. * @param camera The camera for determining the size of the field of view. * @param illumination The illumination profile on the sample. * @param psfBuilder Builder for calculating microscope PSFs. * @param fluorDynamics The fluorophore dynamics properties. * @return The list of fluorophores. */ public static ArrayList<Fluorophore> generateFluorophoresGrid2D( int spacing, Camera camera, Illumination illumination, PSFBuilder psfBuilder, FluorophoreDynamics fluorDynamics) { int limitX = camera.getNX(); int limitY = camera.getNY(); double z = 0.0; ArrayList<Fluorophore> result = new ArrayList(); Fluorophore fluorophore; for (int i=spacing; i < limitX; i+=spacing) { for (int j=spacing; j < limitY; j+= spacing) { fluorophore = new DefaultFluorophore( psfBuilder, illumination, fluorDynamics.getSignal(), fluorDynamics.getStateSystem(), fluorDynamics.getStartingState(), i, j, z); result.add(fluorophore); illumination.addListener(fluorophore.getIlluminationListener()); } } return result; } /** * Create fluorophores on a 2D grid and step-wise in the axial direction. * * @param spacing The distance along the grid between nearest neighbors. * @param zLow The lower bound on the range in z in units of pixels. * @param zHigh The upper bound on the range in z in units of pixels. * @param camera The camera for determining the size of the field of view. * @param illumination The illumination profile on the sample. * @param psfBuilder Builder for calculating microscope PSFs. * @param fluorDynamics The fluorophore dynamics properties. * @return The list of fluorophores. */ public static ArrayList<Fluorophore> generateFluorophoresGrid3D( int spacing, double zLow, double zHigh, Camera camera, Illumination illumination, PSFBuilder psfBuilder, FluorophoreDynamics fluorDynamics) { int limitX = camera.getNX(); int limitY = camera.getNY(); double numFluors = ((double) limitX - spacing) * ((double) limitY - spacing) / spacing / spacing; double zSpacing = (zHigh - zLow) / (numFluors - 1); double z = zLow; ArrayList<Fluorophore> result = new ArrayList(); Fluorophore fluorophore; for (int i = spacing; i < limitX; i += spacing) { for (int j = spacing; j < limitY; j += spacing) { fluorophore = new DefaultFluorophore( psfBuilder, illumination, fluorDynamics.getSignal(), fluorDynamics.getStateSystem(), fluorDynamics.getStartingState(), i, j, z); result.add(fluorophore); illumination.addListener(fluorophore.getIlluminationListener()); z += zSpacing; } } return result; } /** * Parse a CSV file and generate fluorophores from it. * * @param file The CSV file. If this is null, then a dialog is opened. * @param camera The camera for determining the size of the field of view. * @param illumination The illumination profile on the sample. * @param psfBuilder Builder for calculating microscope PSFs. * @param fluorDynamics The fluorophore dynamics properties. * @param rescale if true, positions are rescaled to fit into frame, * otherwise positions outside of frame are cropped * @return list of fluorophores. * @throws FileNotFoundException * @throws IOException */ public static ArrayList<Fluorophore> generateFluorophoresFromCSV( File file, Camera camera, Illumination illumination, PSFBuilder psfBuilder, FluorophoreDynamics fluorDynamics, boolean rescale) throws FileNotFoundException, IOException { if (file==null) { file = getFileFromDialog(); } System.out.println("Building fluorophore PSF's..."); // load all fluorophores ArrayList<Fluorophore> result = new ArrayList(); double x; double y; double z; int counter = 0; Fluorophore fluorophore; BufferedReader br; String line; String splitBy = ","; br = new BufferedReader(new FileReader(file)); // read all lines while ((line = br.readLine()) != null) { // skip comments if (line.startsWith("#")) { continue; } // read 2 doubles from beginning of line String[] entries = line.split(splitBy); x = Double.parseDouble(entries[0]); y = Double.parseDouble(entries[1]); try { z = Double.parseDouble(entries[2]); } catch (ArrayIndexOutOfBoundsException ex){ // There is no z-column, so set the z-position to 0.0. z = 0.0; } // Ignore entries with negative x- and y-positions. if (x>=0.0 && y>=0.0) { // we subtract 0.5 to make the positions agree with how ThunderSTORM computes positions // i.e. origin is in the very top left of image, not in the center of top left pixel as it is in our simulation fluorophore = new DefaultFluorophore( psfBuilder, illumination, fluorDynamics.getSignal(), fluorDynamics.getStateSystem(), fluorDynamics.getStartingState(), x - 0.5, y - 0.5, z); result.add(fluorophore); illumination.addListener(fluorophore.getIlluminationListener()); counter++; if (counter % 5000 == 0) { System.out.println("Processed fluorophore number: " + counter); } } } System.out.println("Done building PSF's."); // rescale positions to fit into frame if (rescale) { System.out.println("Building rescaled PSF's...."); ArrayList<Fluorophore> result_rescaled = new ArrayList<Fluorophore>(); double max_x_coord = 0.0; for (Fluorophore f: result) { // Remove the fluorophores that were added in the first step. illumination.deleteListener(f.getIlluminationListener()); if (f.getX() > max_x_coord) max_x_coord = f.getX(); } double factor = camera.getNX()/max_x_coord; for (Fluorophore f: result) { fluorophore = new DefaultFluorophore( psfBuilder, illumination, fluorDynamics.getSignal(), fluorDynamics.getStateSystem(), fluorDynamics.getStartingState(), f.getX() * factor, f.getY() * factor, f.getZ() * factor); result_rescaled.add(fluorophore); illumination.addListener(fluorophore.getIlluminationListener()); } System.out.println("Done building rescaled PSF's."); return result_rescaled; // or crop fluorophores outside of frame } else { ArrayList<Fluorophore> result_cropped = new ArrayList<Fluorophore>(); for (Fluorophore f: result) { // Remove the fluorophores that were added in the first step. illumination.deleteListener(f.getIlluminationListener()); if (f.getX() < camera.getNX() && f.getY() < camera.getNY()) { result_cropped.add(f); illumination.addListener(f.getIlluminationListener()); } } return result_cropped; } } private static File getFileFromDialog() { JFileChooser fc = new JFileChooser(); int returnVal; fc.setDialogType(JFileChooser.OPEN_DIALOG); //set a default filename fc.setSelectedFile(new File("emitters.csv")); //Set an extension filter fc.setFileFilter(new FileNameExtensionFilter("CSV file","csv")); returnVal = fc.showOpenDialog(null); if (returnVal != JFileChooser.APPROVE_OPTION) { throw new RuntimeException("You need to select an emitter file!"); } return fc.getSelectedFile(); } }
gpl-3.0
eetlite/eet.osslite.cz
common/src/main/java/cz/eetlite/dao/registration/domain/CashDeskToKeystore.java
672
package cz.eetlite.dao.registration.domain; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import lombok.Data; //@Entity @Table(name = "cashdesk_to_keystore") @Data public class CashDeskToKeystore { @Id private Long id; @Embedded private Identification identification; @Embedded private Validity validity; @ManyToOne @JoinColumn(name = "id_cashdesk", nullable = false) private CashDesk cashdesk; @ManyToOne @JoinColumn(name = "id_keystore", nullable = false) private CertificateKeystore keystore; }
gpl-3.0
oreonengine/oreon-engine
oreonengine/oe-vk-api/src/main/java/org/oreon/core/vk/wrapper/buffer/StagingBuffer.java
868
package org.oreon.core.vk.wrapper.buffer; import static org.lwjgl.vulkan.VK10.VK_BUFFER_USAGE_TRANSFER_SRC_BIT; import static org.lwjgl.vulkan.VK10.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; import static org.lwjgl.vulkan.VK10.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; import java.nio.ByteBuffer; import org.lwjgl.vulkan.VkDevice; import org.lwjgl.vulkan.VkPhysicalDeviceMemoryProperties; import org.oreon.core.vk.memory.VkBuffer; public class StagingBuffer extends VkBuffer{ public StagingBuffer(VkDevice device, VkPhysicalDeviceMemoryProperties memoryProperties, ByteBuffer dataBuffer) { super(device, dataBuffer.limit(), VK_BUFFER_USAGE_TRANSFER_SRC_BIT); allocate(memoryProperties, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); bindBufferMemory(); mapMemory(dataBuffer); } }
gpl-3.0
0359xiaodong/twidere
src/edu/ucdavis/earlybird/CSVFileFilter.java
461
package edu.ucdavis.earlybird; import java.io.File; import java.io.FileFilter; public final class CSVFileFilter implements FileFilter { @Override public boolean accept(final File file) { return file.isFile() && "csv".equalsIgnoreCase(getExtension(file)); } static String getExtension(final File file) { final String name = file.getName(); final int pos = name.lastIndexOf('.'); if (pos == -1) return null; return name.substring(pos + 1); } }
gpl-3.0
OpenWIS/openwis
openwis-dataservice/openwis-dataservice-common/openwis-dataservice-common-domain/src/test/java/eu/akka/openwis/dataservice/common/domain/ClassLoaderProxy.java
1206
package eu.akka.openwis.dataservice.common.domain; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Class ClassLoaderProxy. <P> * This proxy class loader is used by test to load the valid persitence.xml. <P> */ public class ClassLoaderProxy extends ClassLoader { /** The logger. */ private static Logger logger = LoggerFactory.getLogger(ClassLoaderProxy.class); /** * Instantiates a new class loader proxy. * * @param parent the parent */ public ClassLoaderProxy(final ClassLoader parent) { super(); } /** * {@inheritDoc} * @see java.lang.ClassLoader#getResources(java.lang.String) */ @Override public Enumeration<URL> getResources(final String name) throws IOException { Enumeration<URL> result; logger.info("lookup for: {}", name); if (!"META-INF/persistence.xml".equals(name)) { result = super.getResources(name); } else { logger.info("Redirecting persistence.xml to test-persistence.xml"); result = super.getResources("META-INF/test-persistence.xml"); } return result; } }
gpl-3.0
flimsy/asteria-2.0
src/server/world/entity/player/skill/impl/Slayer.java
612
package server.world.entity.player.skill.impl; import server.world.entity.player.Player; import server.world.entity.player.skill.SkillEvent; import server.world.entity.player.skill.SkillManager.SkillConstant; public class Slayer extends SkillEvent { @Override public int eventFireIndex() { // TODO Auto-generated method stub return 0; } @Override public void fireResetEvent(Player player) { // TODO Auto-generated method stub } @Override public SkillConstant skillConstant() { // TODO Auto-generated method stub return null; } }
gpl-3.0
morogoku/MTweaks-KernelAdiutorMOD
app/src/main/java/com/moro/mtweaks/fragments/kernel/BusDispFragment.java
9446
/* * Copyright (C) 2015-2016 Willi Ye <williye97@gmail.com> * * This file is part of Kernel Adiutor. * * Kernel Adiutor 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. * * Kernel Adiutor 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 Kernel Adiutor. If not, see <http://www.gnu.org/licenses/>. * */ package com.moro.mtweaks.fragments.kernel; import com.moro.mtweaks.R; import com.moro.mtweaks.fragments.ApplyOnBootFragment; import com.moro.mtweaks.fragments.recyclerview.RecyclerViewFragment; import com.moro.mtweaks.utils.AppSettings; import com.moro.mtweaks.utils.Utils; import com.moro.mtweaks.utils.kernel.bus.VoltageDisp; import com.moro.mtweaks.views.recyclerview.CardView; import com.moro.mtweaks.views.recyclerview.DescriptionView; import com.moro.mtweaks.views.recyclerview.RecyclerViewItem; import com.moro.mtweaks.views.recyclerview.SeekBarView; import com.moro.mtweaks.views.recyclerview.SwitchView; import com.moro.mtweaks.views.recyclerview.TitleView; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Created by morogoku on 06.11.18. */ public class BusDispFragment extends RecyclerViewFragment { private List<SeekBarView> mVoltages = new ArrayList<>(); private SeekBarView mSeekbarProf = new SeekBarView(); private static float mVoltMinValue = -100000f; private static float mVoltMaxValue = 25000f; private static int mVoltStep = 6250; public static int mDefZeroPosition = (Math.round(mVoltMaxValue - mVoltMinValue) / mVoltStep) - (Math.round(mVoltMaxValue) / mVoltStep); @Override protected void init() { super.init(); addViewPagerFragment(ApplyOnBootFragment.newInstance(this)); } @Override protected void addItems(List<RecyclerViewItem> items) { mVoltages.clear(); final List<String> freqs = VoltageDisp.getFreqs(); final List<String> voltages = VoltageDisp.getVoltages(); final List<String> voltagesStock = VoltageDisp.getStockVoltages(); if (freqs != null && voltages != null && voltagesStock != null && freqs.size() == voltages.size()) { CardView freqCard = new CardView(getActivity()); freqCard.setTitle(getString(R.string.busDisp_volt_title)); DescriptionView disp = new DescriptionView(); disp.setSummary(getString(R.string.busDisp_volt_summary)); freqCard.addItem(disp); List<String> progress = new ArrayList<>(); for (float i = mVoltMinValue; i < (mVoltMaxValue + mVoltStep); i += mVoltStep) { String global = String.valueOf(i / VoltageDisp.getOffset()); progress.add(global); } seekbarProfInit(mSeekbarProf, freqs, voltages, voltagesStock, progress); freqCard.addItem(mSeekbarProf); Boolean enableGlobal = AppSettings.getBoolean("busDisp_global_volts", true, getActivity()); SwitchView voltControl = new SwitchView(); voltControl.setTitle(getString(R.string.cpu_manual_volt)); voltControl.setSummaryOn(getString(R.string.cpu_manual_volt_summaryOn)); voltControl.setSummaryOff(getString(R.string.cpu_manual_volt_summaryOff)); voltControl.setChecked(enableGlobal); voltControl.addOnSwitchListener((switchView, isChecked) -> { if (isChecked) { AppSettings.saveBoolean("busDisp_global_volts", true, getActivity()); AppSettings.saveBoolean("busDisp_individual_volts", false, getActivity()); reload(); } else { AppSettings.saveBoolean("busDisp_global_volts", false, getActivity()); AppSettings.saveBoolean("busDisp_individual_volts", true, getActivity()); AppSettings.saveInt("busDisp_seekbarPref_value", mDefZeroPosition, getActivity()); reload(); } }); freqCard.addItem(voltControl); if (freqCard.size() > 0) { items.add(freqCard); } TitleView tunables = new TitleView(); tunables.setText(getString(R.string.voltages)); items.add(tunables); for (int i = 0; i < freqs.size(); i++) { SeekBarView seekbar = new SeekBarView(); seekbarInit(seekbar, freqs.get(i), voltages.get(i), voltagesStock.get(i)); mVoltages.add(seekbar); } } items.addAll(mVoltages); } private void seekbarProfInit(SeekBarView seekbar, final List<String> freqs, final List<String> voltages, final List<String> voltagesStock, List<String> progress) { Boolean enableSeekbar = AppSettings.getBoolean("busDisp_global_volts", true, getActivity()); int global = AppSettings.getInt("busDisp_seekbarPref_value", mDefZeroPosition, getActivity()); int value = 0; for (int i = 0; i < progress.size(); i++) { if (i == global){ value = i; break; } } seekbar.setTitle(getString(R.string.cpu_volt_profile)); seekbar.setSummary(getString(R.string.cpu_volt_profile_summary)); seekbar.setUnit(getString(R.string.mv)); seekbar.setItems(progress); seekbar.setProgress(value); seekbar.setEnabled(enableSeekbar); if(!enableSeekbar) seekbar.setAlpha(0.4f); else seekbar.setAlpha(1f); seekbar.setOnSeekBarListener(new SeekBarView.OnSeekBarListener() { @Override public void onStop(SeekBarView seekBarView, int position, String value) { for (int i = 0; i < voltages.size(); i++) { String volt = String.valueOf(Utils.strToFloat(voltagesStock.get(i)) + Utils.strToFloat(value)); String freq = freqs.get(i); VoltageDisp.setVoltage(freq, volt, getActivity()); AppSettings.saveInt("busDisp_seekbarPref_value", position, getActivity()); } getHandler().postDelayed(BusDispFragment.this::reload, 200); } @Override public void onMove(SeekBarView seekBarView, int position, String value) { } }); } private void seekbarInit(SeekBarView seekbar, final String freq, String voltage, String voltageStock) { int mOffset = VoltageDisp.getOffset(); float mMin = (Utils.strToFloat(voltageStock) - (- mVoltMinValue / 1000)) * mOffset; float mMax = ((Utils.strToFloat(voltageStock) + (mVoltMaxValue / 1000)) * mOffset) + mVoltStep; List<String> progress = new ArrayList<>(); for(float i = mMin ; i < mMax; i += mVoltStep){ String string = String.valueOf(i / mOffset); progress.add(string); } int value = 0; for (int i = 0; i < progress.size(); i++) { if (Objects.equals(progress.get(i), voltage)){ value = i; break; } } Boolean enableSeekbar = AppSettings.getBoolean("busDisp_individual_volts", false, getActivity()); seekbar.setTitle(freq + " " + getString(R.string.mhz)); seekbar.setSummary(getString(R.string.def) + ": " + voltageStock + " " + getString(R.string.mv)); seekbar.setUnit(getString(R.string.mv)); seekbar.setItems(progress); seekbar.setProgress(value); seekbar.setEnabled(enableSeekbar); if(!enableSeekbar) seekbar.setAlpha(0.4f); else seekbar.setAlpha(1f); seekbar.setOnSeekBarListener(new SeekBarView.OnSeekBarListener() { @Override public void onStop(SeekBarView seekBarView, int position, String value) { VoltageDisp.setVoltage(freq, value, getActivity()); getHandler().postDelayed(() -> reload(), 200); } @Override public void onMove(SeekBarView seekBarView, int position, String value) { } }); } private void reload() { List<String> freqs = VoltageDisp.getFreqs(); List<String> voltages = VoltageDisp.getVoltages(); List<String> voltagesStock = VoltageDisp.getStockVoltages(); if (freqs != null && voltages != null && voltagesStock != null) { for (int i = 0; i < mVoltages.size(); i++) { seekbarInit(mVoltages.get(i), freqs.get(i), voltages.get(i), voltagesStock.get(i)); } List<String> progress = new ArrayList<>(); for (float i = mVoltMinValue; i < (mVoltMaxValue + mVoltStep); i += mVoltStep) { String global = String.valueOf(i / VoltageDisp.getOffset()); progress.add(global); } seekbarProfInit(mSeekbarProf, freqs, voltages, voltagesStock, progress); } } }
gpl-3.0
TAI-EPAM/JDI
Java/Tests/jdi-uitest-webtests/src/test/java/com/epam/jdi/uitests/testing/unittests/dataproviders/TableDP.java
21707
package com.epam.jdi.uitests.testing.unittests.dataproviders; import com.epam.jdi.uitests.core.interfaces.complex.tables.interfaces.ITable; import org.openqa.selenium.By; import org.testng.annotations.DataProvider; import static com.epam.jdi.uitests.testing.unittests.enums.Preconditions.SIMPLE_PAGE; import static com.epam.jdi.uitests.testing.unittests.enums.Preconditions.SUPPORT_PAGE; import static com.epam.jdi.uitests.testing.unittests.pageobjects.EpamJDISite.simpleTablePage; import static java.util.Arrays.asList; /** * Created by Natalia_Grebenshchikova on 10/8/2015. */ public class TableDP { @DataProvider(name = "differentTables") public static Object[][] differentTables() { return new Object[][]{ {SUPPORT_PAGE, new TableProvider("Table with all headers", ITable::hasAllHeaders), "2/6", "Now, Plans", "Drivers, Test Runner, Asserter, Logger, Reporter, BDD/DSL", "||X||Now|Plans||\n" + "||Drivers||Selenium, Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||Test Runner||TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Asserter||TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Logger||Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||Reporter||Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||BDD/DSL||Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SUPPORT_PAGE, new TableProvider("Table with no headers", ITable::hasNoHeaders), "3/6", "1, 2, 3", "1, 2, 3, 4, 5, 6", "||X||1|2|3||\n" + "||1||Drivers|Selenium, Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||2||Test Runner|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||3||Asserter|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||4||Logger|Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||5||Reporter|Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||6||BDD/DSL|Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SUPPORT_PAGE, new TableProvider("Table with only column headers", ITable::hasOnlyColumnHeaders), "3/6", "Type, Now, Plans", "1, 2, 3, 4, 5, 6", "||X||Type|Now|Plans||\n" + "||1||Drivers|Selenium, Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||2||Test Runner|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||3||Asserter|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||4||Logger|Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||5||Reporter|Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||6||BDD/DSL|Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SUPPORT_PAGE, new TableProvider("Table with only row headers", ITable::hasOnlyRowHeaders), "2/6", "1, 2", "Drivers, Test Runner, Asserter, Logger, Reporter, BDD/DSL", "||X||1|2||\n" + "||Drivers||Selenium, Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||Test Runner||TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Asserter||TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Logger||Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||Reporter||Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||BDD/DSL||Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SUPPORT_PAGE, new TableProvider("Table with specified columns (Type, Now)", table -> table.hasColumnHeaders(asList("Type", "Now"))), "2/6", "Type, Now", "1, 2, 3, 4, 5, 6", "||X||Type|Now||\n" + "||1||Drivers|Selenium, Custom||\n" + "||2||Test Runner|TestNG, JUnit, Custom||\n" + "||3||Asserter|TestNG, JUnit, Custom||\n" + "||4||Logger|Log4J, TestNG log, Custom||\n" + "||5||Reporter|Jenkins, Allure, Custom||\n" + "||6||BDD/DSL|Custom||", "null"}, {SUPPORT_PAGE, new TableProvider("Table with specified rows (First Row, Second Row, Third Row)", table -> table.hasRowHeaders(asList("First Row", "Second Row", "Third Row"))), "2/3", "Now, Plans", "First Row, Second Row, Third Row", "||X||Now|Plans||\n" + "||First Row||Selenium, Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||Second Row||TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Third Row||TestNG, JUnit, Custom|MSTest, NUnit, Epam||", "null"}, {SUPPORT_PAGE, new TableProvider("Table with limited columns (2)", table -> table.setColumnsCount(2)), "2/6", "Type, Now", "1, 2, 3, 4, 5, 6", "||X||Type|Now||\n" + "||1||Drivers|Selenium, Custom||\n" + "||2||Test Runner|TestNG, JUnit, Custom||\n" + "||3||Asserter|TestNG, JUnit, Custom||\n" + "||4||Logger|Log4J, TestNG log, Custom||\n" + "||5||Reporter|Jenkins, Allure, Custom||\n" + "||6||BDD/DSL|Custom||", "null"}, {SUPPORT_PAGE, new TableProvider("Table with limited rows (4)", table -> table.setRowsCount(4)), "3/4", "Type, Now, Plans", "1, 2, 3, 4", "||X||Type|Now|Plans||\n" + "||1||Drivers|Selenium, Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||2||Test Runner|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||3||Asserter|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||4||Logger|Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||", "null"}, {SIMPLE_PAGE, new TableProvider("Custom table with custom headers", simpleTablePage.getTable(By.xpath(".//tr[position() > 1]/td[1]"), By.xpath(".//tr[1]/td[position() > 1]"), By.xpath(".//tr[position() > 1][%s]/td[position() > 1]"), By.xpath(".//tr[position() > 1]/td[position() > 1][%s]")), ITable::hasAllHeaders), "2/5", "Selenium Custom, JavaScript, Appium, WinAPI, Sikuli", "Test Runner, Asserter, Logger, Reporter, BDD/DSL", "||X||Selenium Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||Test Runner||TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||Asserter||TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Logger||Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||Reporter||Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||BDD/DSL||Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, // TODO /* {SIMPLE_PAGE, new TableProvider("Custom table with custom rows", simpleTablePage.getTable(By.xpath(".//tr/td[1]"), null, By.xpath(".//tr[position() > 1][%s]/td[position() > 1]"), By.xpath(".//tr/td[%s]"), 2, 2), Table::hasOnlyRowHeaders), "2/6", "", "Drivers, Test Runner, Asserter, Logger, Reporter, BDD/DSL", "||X||1|2||\n" + "||Drivers||Selenium Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||Test Runner||TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||Asserter||TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Logger||Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||Reporter||Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||BDD/DSL||Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SIMPLE_PAGE, new TableProvider("Custom table with custom columns", simpleTablePage.getTable(null, By.xpath(".//tr[1]/td[position() > 1]"), By.xpath(".//tr[position() > 1][%s]/td[position() > 1]"), By.xpath(".//tr[position() > 1]/td[position() > 1][%s]")), Table::hasAllHeaders), "2/5", "Selenium Custom, JavaScript, Appium, WinAPI, Sikuli", "Drivers, Test Runner, Asserter, Logger, Reporter, BDD/DSL", "||X||Drivers|Selenium Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||1||Test Runner|TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||2||Asserter|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||3||Logger|Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||4||Reporter|Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||5||BDD/DSL|Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SIMPLE_PAGE, new TableProvider("Custom table with no headers", simpleTablePage.getTable(null, null, By.xpath(".//tr[%s]/td"), By.xpath(".//tr/td[%s]")), table -> table), "3/6", "", "1, 2, 3, 4, 5, 6", "||1|Drivers|Selenium Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||2|Test Runner|TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||3|Asserter|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||4|Logger|Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||5|Reporter|Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||6|BDD/DSL|Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SIMPLE_PAGE, new TableProvider("Custom table with both headers", simpleTablePage.getTable(true, true, By.xpath(".//tr[position() > 1]/td[1]"), By.xpath(".//tr[1]/td")), Table::hasAllHeaders), "2/5", "Selenium Custom, JavaScript, Appium, WinAPI, Sikuli", "Test Runner, Asserter, Logger, Reporter, BDD/DSL", "||X||Selenium Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||Test Runner||TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||Asserter||TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Logger||Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||Reporter||Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||BDD/DSL||Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SIMPLE_PAGE, new TableProvider("Custom table with rows headers", simpleTablePage.getTable(true, false, By.xpath(".//tr/td[1]"), null), Table::hasAllHeaders), "2/6", "1, 2", "Drivers, Test Runner, Asserter, Logger, Reporter, BDD/DSL", "||X||1|2||\n" + "||Drivers||Selenium Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||Test Runner||TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||Asserter||TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Logger||Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||Reporter||Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||BDD/DSL||Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SIMPLE_PAGE, new TableProvider("Custom table with column headers", simpleTablePage.getTable(false, true, null, By.xpath(".//tr[1]/td")), table -> table), "3/5", "Drivers, Selenium Custom, JavaScript, Appium, WinAPI, Sikuli", "1, 2, 3, 4, 5, 6", "||X||Drivers|Selenium Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||1||Test Runner|TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||2||Asserter|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||3||Logger|Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||4||Reporter|Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||5||BDD/DSL|Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SIMPLE_PAGE, new TableProvider("Table without rows and columns", simpleTablePage.getTable(false, false, null, null), table -> table), "3/6", "1, 2, 3", "1, 2, 3, 4, 5, 6", "||X||1|2|3||\n" + "||1||Drivers|Selenium Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||2||Test Runner|TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||3||Asserter|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||4||Logger|Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||5||Reporter|Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||6||BDD/DSL|Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SIMPLE_PAGE, new TableProvider("Table with custom rows and columns start index and both headers", simpleTablePage.getTable(By.xpath(".//tr[position() > 1]/td[1]"), By.xpath(".//tr[1]/td[position() > 1]"), 2, 2), Table::hasAllHeaders), "2/5", "Selenium Custom, JavaScript, Appium, WinAPI, Sikuli", "Test Runner, Asserter, Logger, Reporter, BDD/DSL", "||Drivers||Selenium Custom||JavaScript, Appium, WinAPI, Sikuli||\n" + "||Test Runner||TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||Asserter||TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Logger||Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||Reporter||Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||BDD/DSL||Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SIMPLE_PAGE, new TableProvider("Table with custom rows and columns start index and rows header", simpleTablePage.getTable(By.xpath(".//tr/td[1]"), null, 1, 2), Table::hasAllHeaders), "2/6", "", "Drivers, Test Runner, Asserter, Logger, Reporter, BDD/DSL", "||Drivers||Selenium Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||Test Runner||TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||Asserter||TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Logger||Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||Reporter||Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||BDD/DSL||Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SIMPLE_PAGE, new TableProvider("Table with custom rows and columns start index and columns header", simpleTablePage.getTable(null, By.xpath(".//tr[1]/td"), 2, 1), table -> table), "3/5", "Selenium Custom, JavaScript, Appium, WinAPI, Sikuli", "1, 2, 3, 4, 5, 6", "||Drivers||Selenium Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||Test Runner|TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||Asserter|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Logger|Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||Reporter|Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||BDD/DSL|Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {SIMPLE_PAGE, new TableProvider("Table with custom rows and columns start index but without any headers", simpleTablePage.getTable(null, null, 1, 1), table -> table), "3/6", "", "1, 2, 3, 4, 5, 6", "||Drivers|Selenium Custom|JavaScript, Appium, WinAPI, Sikuli||\n" + "||Test Runner|TestNG, JUnit Custom|MSTest, NUnit, Epam||\n" + "||Asserter|TestNG, JUnit, Custom|MSTest, NUnit, Epam||\n" + "||Logger|Log4J, TestNG log, Custom|Epam, XML/Json logging, Hyper logging||\n" + "||Reporter|Jenkins, Allure, Custom|EPAM Report portal, Serenity, TimCity, Hudson||\n" + "||BDD/DSL|Custom|Cucumber, Jbehave, Thucydides, SpecFlow||", "null"}, {DYNAMIC_TABLE_PAGE, new TableProvider("Table with footer", dynamicTablePage.dynamicTable, Table::hasAllHeaders), "2/8", "Column 1, Column 2", "Microsoft Technologies, Mobile, UXD, Version Control Systems, JavaScript Components and Frameworks, Software Construction, Life Sciences, Content management", "||X||Column 1|Column 2||\n" + "||Microsoft Technologies||Select,See More,.NET Technologies|Select,See More,Internet Technologies||\n" + "||Mobile||Select,See More,HTML5/CSS3|Select,See More,JQuery Mobile||\n" + "||UXD||Select,See More,(X)CSS Development|Select,See More,Grunt (The JavaScript Task Runner)||\n" + "||Version Control Systems||Select,See More,CVS|Select,See More,TortoiseSVN||\n" + "||JavaScript Components and Frameworks||Select,See More,Backbone marionette js|Select,See More,Bootstrap||\n" + "||Software Construction||Select,See More,Internet Technologies|Select,See More,JavaScript Components and Frameworks||\n" + "||Life Sciences||Select,See More,Biology|Select,See More,Chemistry||\n" + "||Content management||Select,See More,Drupal|Select,See More,Adobe Day CRX||\n"+ "||1 column|2 column|3 column||", "1 column, 2 column, 3 column"}*/ }; } }
gpl-3.0
stevanpa/nuthatch
src/nuthatch/examples/xmpllang/full/XmplWalker.java
1119
package nuthatch.examples.xmpllang.full; import nuthatch.examples.xmpllang.Type; import nuthatch.examples.xmpllang.XmplNode; import nuthatch.library.ActionFactory; import nuthatch.library.FactoryFactory; import nuthatch.library.Walk; import nuthatch.tree.TreeCursor; import nuthatch.tree.errors.BranchNotFoundError; import nuthatch.walker.impl.AbstractWalker; public class XmplWalker extends AbstractWalker<XmplNode, Type, XmplWalker> { public XmplWalker(TreeCursor<XmplNode, Type> cursor, Walk<XmplWalker> step) { super(cursor, step); } public XmplWalker(XmplNode expr, Walk<XmplWalker> step) { super(new XmplCursor(expr), step); } @Override public TreeCursor<XmplNode, Type> go(int i) throws BranchNotFoundError { return super.go(i); } public void replace(XmplNode e) { super.replace(new XmplCursor(e)); } @Override protected XmplWalker subWalk(TreeCursor<XmplNode, Type> cursor, Walk<XmplWalker> step) { return new XmplWalker(cursor, step); } public static ActionFactory<XmplNode, Type, XmplCursor, XmplWalker> getActionFactory() { return FactoryFactory.getActionFactory(); } }
gpl-3.0
andrebask/secomobile
src/it/polimi/secomobile/ui/TableAdapter.java
991
package it.polimi.secomobile.ui; import java.util.ArrayList; import org.json.JSONObject; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; public class TableAdapter extends BaseAdapter { private Context context; private ArrayList<JSONObject> tupleList; private ArrayList<String> idList; public TableAdapter(Context context, ArrayList<JSONObject> tupleList, ArrayList<String> idList) { this.context = context; this.tupleList = tupleList; this.idList = idList; } public int getCount() { return tupleList.size(); } public Object getItem(int position) { return tupleList.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { JSONObject tuple = tupleList.get(position); return new ExpandableView(this.context, tuple, idList); } }
gpl-3.0
jtux270/translate
ovirt/backend/manager/modules/restapi/jaxrs/src/test/java/org/ovirt/engine/api/restapi/resource/AbstractBackendCdRomsResourceTest.java
4383
package org.ovirt.engine.api.restapi.resource; import java.util.List; import java.util.ArrayList; import org.junit.Ignore; import org.junit.Test; import org.ovirt.engine.api.model.CdRom; import org.ovirt.engine.api.model.CdRoms; import org.ovirt.engine.api.model.File; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.queries.VdcQueryParametersBase; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.compat.Guid; @Ignore public class AbstractBackendCdRomsResourceTest<T extends AbstractBackendReadOnlyDevicesResource<CdRom, CdRoms, VM>> extends AbstractBackendCollectionResourceTest<CdRom, VM, T> { protected final static Guid PARENT_ID = GUIDS[1]; protected final static String ISO_PATH = "Fedora-13-x86_64-Live.iso"; protected final static String CURRENT_ISO_PATH = "Fedora-20-x86_64-Live.iso"; protected VdcQueryType queryType; protected VdcQueryParametersBase queryParams; protected String queryIdName; public AbstractBackendCdRomsResourceTest(T collection, VdcQueryType queryType, VdcQueryParametersBase queryParams, String queryIdName) { super(collection, null, ""); this.queryType = queryType; this.queryParams = queryParams; this.queryIdName = queryIdName; } @Test @Ignore public void testQuery() throws Exception { // skip test inherited from base class as searching // over CdRoms is unsupported by the backend } protected void setUpQueryExpectations(String query) throws Exception { setUpEntityQueryExpectations(1); control.replay(); } protected void setUpQueryExpectations(String query, Object failure) throws Exception { setUpEntityQueryExpectations(1, failure); control.replay(); } protected void setUpEntityQueryExpectations(int times) throws Exception { setUpEntityQueryExpectations(times, null); } protected void setUpEntityQueryExpectations(int times, Object failure) throws Exception { while (times-- > 0) { setUpEntityQueryExpectations(queryType, queryParams.getClass(), new String[] { queryIdName }, new Object[] { PARENT_ID }, getEntityList(), failure); } } protected List<VM> getEntityList() { List<VM> entities = new ArrayList<VM>(); for (int i = 0; i < NAMES.length; i++) { entities.add(getEntity(i)); } return entities; } protected VM getEntity(int index) { return setUpEntityExpectations(); } static VM setUpEntityExpectations() { return setUpEntityExpectations(null); } static VM setUpEntityExpectations(VMStatus status) { VM vm = new VM(); vm.setId(PARENT_ID); vm.setIsoPath(ISO_PATH); vm.setCurrentCd(CURRENT_ISO_PATH); vm.setStatus(status); return vm; } protected List<CdRom> getCollection() { return collection.list().getCdRoms(); } static CdRom getModel(int index) { CdRom model = new CdRom(); model.setFile(new File()); model.getFile().setId(ISO_PATH); return model; } static CdRom getModelWithCurrentCd() { CdRom model = new CdRom(); model.setFile(new File()); model.getFile().setId(CURRENT_ISO_PATH); return model; } protected void verifyModel(CdRom model, int index) { verifyModelWithIso(model, ISO_PATH); verifyLinks(model); } static void verifyModelSpecific(CdRom model, int index) { verifyModelWithIso(model, ISO_PATH); } static void verifyModelWithIso(CdRom model, String isoPath) { assertEquals(Guid.Empty.toString(), model.getId()); assertTrue(model.isSetVm()); assertEquals(PARENT_ID.toString(), model.getVm().getId()); assertTrue(model.isSetFile()); assertEquals(isoPath, model.getFile().getId()); } }
gpl-3.0
SuperMap-iDesktop/SuperMap-iDesktop-Cross
Controls/src/main/java/com/supermap/desktop/ui/controls/progress/package-info.java
89
/** * */ /** * @author wuxb * */ package com.supermap.desktop.ui.controls.progress;
gpl-3.0
Yannici/bedwars-reloaded
v1_11_r1/src/main/java/io/github/bedwarsrel/com/v1_11_r1/VillagerItemShop.java
4189
package io.github.bedwarsrel.com.v1_11_r1; import io.github.bedwarsrel.BedwarsRel; import io.github.bedwarsrel.game.Game; import io.github.bedwarsrel.utils.Utils; import io.github.bedwarsrel.villager.MerchantCategory; import io.github.bedwarsrel.villager.VillagerTrade; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import net.minecraft.server.v1_11_R1.EntityHuman; import net.minecraft.server.v1_11_R1.EntityVillager; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_11_R1.CraftWorld; import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_11_R1.entity.CraftVillager; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.MerchantRecipe; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.scheduler.BukkitRunnable; public class VillagerItemShop { private MerchantCategory category = null; private Game game = null; private Player player = null; public VillagerItemShop(Game g, Player p, MerchantCategory category) { this.game = g; this.player = p; this.category = category; } private EntityVillager createVillager() { try { EntityVillager ev = new EntityVillager(((CraftWorld) this.game.getRegion().getWorld()).getHandle()); return ev; } catch (Exception e) { BedwarsRel.getInstance().getBugsnag().notify(e); e.printStackTrace(); } return null; } private EntityHuman getEntityHuman() { try { return ((CraftPlayer) this.player).getHandle(); } catch (Exception e) { BedwarsRel.getInstance().getBugsnag().notify(e); e.printStackTrace(); } return null; } public void openTrading() { // As task because of inventory issues new BukkitRunnable() { @SuppressWarnings("deprecation") @Override public void run() { try { EntityVillager entityVillager = VillagerItemShop.this.createVillager(); CraftVillager craftVillager = (CraftVillager) entityVillager.getBukkitEntity(); EntityHuman entityHuman = VillagerItemShop.this.getEntityHuman(); // set location List<MerchantRecipe> recipeList = new ArrayList<MerchantRecipe>(); for (VillagerTrade trade : VillagerItemShop.this.category .getFilteredOffers()) { ItemStack reward = trade.getRewardItem(); Method colorable = Utils.getColorableMethod(reward.getType()); if (Utils.isColorable(reward)) { reward .setDurability(game.getPlayerTeam(player).getColor().getDyeColor().getWoolData()); } else if (colorable != null) { ItemMeta meta = reward.getItemMeta(); colorable.setAccessible(true); colorable.invoke(meta, new Object[]{VillagerItemShop.this.game .getPlayerTeam(VillagerItemShop.this.player).getColor().getColor()}); reward.setItemMeta(meta); } if (!(trade.getHandle() .getInstance() instanceof net.minecraft.server.v1_11_R1.MerchantRecipe)) { continue; } MerchantRecipe recipe = new MerchantRecipe(trade.getRewardItem(), 1024); recipe.addIngredient(trade.getItem1()); if (trade.getItem2() != null) { recipe.addIngredient(trade.getItem2()); } else { recipe.addIngredient(new ItemStack(Material.AIR)); } recipe.setUses(0); recipe.setExperienceReward(false); recipeList.add(recipe); } craftVillager.setRecipes(recipeList); craftVillager.setRiches(0); entityVillager.setTradingPlayer(entityHuman); ((CraftPlayer) player).getHandle().openTrade(entityVillager); } catch (Exception ex) { BedwarsRel.getInstance().getBugsnag().notify(ex); ex.printStackTrace(); } } }.runTask(BedwarsRel.getInstance()); } }
gpl-3.0
BjerknesClimateDataCentre/QuinCe
WebApp/src/uk/ac/exeter/QuinCe/web/Instrument/newInstrument/InstrumentFileExistsException.java
733
package uk.ac.exeter.QuinCe.web.Instrument.newInstrument; import uk.ac.exeter.QuinCe.data.Instrument.FileDefinition; /** * Exception for attempting to add an {@link FileDefinition} where a file with * the same description has already been added. * * @author Steve Jones * */ public class InstrumentFileExistsException extends Exception { /** * Serial Version UID */ private static final long serialVersionUID = 3317044919826150286L; /** * Basic constructor * * @param file * The duplicate instrument file */ public InstrumentFileExistsException(FileDefinition file) { super("An instrument file with the description '" + file.getFileDescription() + "' already exists"); } }
gpl-3.0
applifireAlgo/bloodbank
bloodbank/src/main/java/com/app/server/repository/TalukaRepository.java
1559
package com.app.server.repository; import com.athena.server.repository.SearchInterface; import com.athena.annotation.Complexity; import com.athena.annotation.SourceCodeAuthorClass; import com.athena.framework.server.exception.repository.SpartanPersistenceException; import java.util.List; import com.athena.framework.server.exception.biz.SpartanConstraintViolationException; @SourceCodeAuthorClass(createdBy = "john.doe", updatedBy = "", versionNumber = "1", comments = "Repository for Taluka Master table Entity", complexity = Complexity.LOW) public interface TalukaRepository<T> extends SearchInterface { public List<T> findAll() throws SpartanPersistenceException; public T save(T entity) throws SpartanPersistenceException; public List<T> save(List<T> entity) throws SpartanPersistenceException; public void delete(String id) throws SpartanPersistenceException; public void update(T entity) throws SpartanConstraintViolationException, SpartanPersistenceException; public void update(List<T> entity) throws SpartanPersistenceException; public List<T> findByCountryId(String countryId) throws Exception, SpartanPersistenceException; public List<T> findByStateId(String stateId) throws Exception, SpartanPersistenceException; public List<T> findByRegionId(String regionId) throws Exception, SpartanPersistenceException; public List<T> findByDistrictId(String districtId) throws Exception, SpartanPersistenceException; public T findById(String talukaId) throws Exception, SpartanPersistenceException; }
gpl-3.0
varad/hextris
src/net/hextris/MainFrame.java
8020
package net.hextris; import java.awt.Color; import javax.swing.*; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.WindowEvent; import java.awt.event.KeyEvent; import java.util.ResourceBundle; /** * Main Hextris window. * @author fränk * @author Radek Varbuchta */ public class MainFrame extends JFrame { private static final long serialVersionUID = -2432811889021456787L; private static ResourceBundle rb = java.util.ResourceBundle.getBundle("net/hextris/language"); private Hextris hextris = null; private Context ctx = Context.getContext(); public MainFrame(Hextris h) { super(rb.getString("appName")); this.hextris = h; initialize(); } /** * Create widgets and stuff. */ public void initialize() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } this.setContentPane(this.hextris); this.setResizable(false); this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); // menubar JMenuBar menuBar = new JMenuBar(); JMenu gameMenu = new JMenu(rb.getString("Game")); gameMenu.setMnemonic('g'); JMenu helpMenu = new JMenu(rb.getString("Help")); JMenuItem newGameMI = new JMenuItem(rb.getString("New_Game")); JMenuItem newDemoMI = new JMenuItem(rb.getString("Demo")); //---JMenuItem highScoresMI = new JMenuItem(rb.getString("Highscores")); JMenuItem prefsMI = new JMenuItem(rb.getString("Preferences")); JMenuItem exitMI = new JMenuItem(rb.getString("Quit")); JMenuItem gameInfo = new JMenuItem(rb.getString("About")); JMenuItem gameHelp = new JMenuItem(rb.getString("Help")); gameMenu.add(newGameMI); gameMenu.add(newDemoMI); //---gameMenu.add(highScoresMI); gameMenu.add(prefsMI); gameMenu.add(exitMI); helpMenu.add(gameInfo); helpMenu.add(gameHelp); menuBar.add(gameMenu); menuBar.add(helpMenu); newGameMI.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.Event.ALT_MASK, false)); newGameMI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hextris.newGame(false, true); } }); newDemoMI.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.Event.ALT_MASK, false)); newDemoMI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hextris.newGame(true, true); } }); /*---highScoresMI.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, java.awt.Event.ALT_MASK, false)); highScoresMI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hextris.showHighScores(); } });*/ prefsMI.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.Event.ALT_MASK, false)); prefsMI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showGameProperties(); } }); exitMI.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.Event.ALT_MASK, false)); exitMI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { exit(); } }); gameInfo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showGameInfo(); } }); gameHelp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showGameHelp(); } }); this.hextris.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { hextris.gameKeyPressed(e); } }); this.setJMenuBar(menuBar); this.hextris.setFocusable(true); this.hextris.setRequestFocusEnabled(true); //this.hextris.highScores.read(); this.hextris.setBackground(Color.BLACK); this.setIconImage(Toolkit.getDefaultToolkit().createImage(this.getClass().getResource("/net/hextris/images/hextris_icon.gif"))); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); } @Override public void dispose() { super.dispose(); hextris.setMoverThread(null); } /** * Bring up the properties dialog. */ private void showGameProperties() { PrefsDlg dlg = new PrefsDlg(JOptionPane.getFrameForComponent(this)); dlg.setLocationRelativeTo(this); dlg.setVisible(true); this.pack(); } /** * Show a little info dialog. */ private void showGameInfo() { JTextArea jta = new JTextArea("Tetris with Hexagons\n\n" + "written by Frank Felfe\n\n" + "based on an idea by David Markley\n" + "and code from Java-Tetris by Christian Schneider\n\n" + "released under the terms of the GNU General Public License"); jta.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLoweredBevelBorder(), BorderFactory.createEmptyBorder(3, 3, 3, 3))); JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(this), jta, "Hextris " + Hextris.getVersion(), JOptionPane.INFORMATION_MESSAGE); } /** * show a little help window * */ private void showGameHelp() { JTextArea jta = new JTextArea( "Please visit the hextris homepage at\n" + "http://hextris.inner-space.de/\n\n" + "Keys:\n" + "move left - " + KeyEvent.getKeyText(ctx.getKeyValue(Context.Key.MOVE_LEFT)) + " or Left\n" + "move right - " + KeyEvent.getKeyText(ctx.getKeyValue(Context.Key.MOVE_RIGHT)) + " or Right\n" + "rotate clockwise - " + KeyEvent.getKeyText(ctx.getKeyValue(Context.Key.ROTATE_RIGHT)) + " or Up\n" + "rotate counterclockwise - " + KeyEvent.getKeyText(ctx.getKeyValue(Context.Key.ROTATE_LEFT)) + "\n" + "move down - " + KeyEvent.getKeyText(ctx.getKeyValue(Context.Key.MOVE_DOWN)) + " or Down\n" + "fall down - " + KeyEvent.getKeyText(ctx.getKeyValue(Context.Key.FALL_DOWN)) + " or Space\n\n" //"Score:\n" + //"move down - level x severity\n" + //"fall down - level x severity x 2 x lines\n" + //"stone - 10 x level x severity\n" + //"line removed - 100 x level x severity x lines" ); jta.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLoweredBevelBorder(), BorderFactory.createEmptyBorder(3, 3, 3, 3))); JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(this), jta, "Hextris Help", JOptionPane.INFORMATION_MESSAGE); } private void exit() { System.exit(0); } protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { exit(); } } public void setHextris(Hextris h) { this.hextris = h; } }
gpl-3.0
Kimmax/leaguelib
src/main/java/com/achimala/leaguelib/models/runes/RuneType.java
193
package com.achimala.leaguelib.models.runes; /** * An enumeration of Rune types (i.e. Marks, Quintessences, etc.) */ public enum RuneType { MARK, SEAL, GLYPH, QUINTESSENCE; }
gpl-3.0
jlopezjuy/ClothesHipster
anelclothesapp/src/main/java/ar/com/anelsoftware/clothes/config/Constants.java
372
package ar.com.anelsoftware.clothes.config; /** * Application constants. */ public final class Constants { //Regex for acceptable logins public static final String LOGIN_REGEX = "^[_'.@A-Za-z0-9-]*$"; public static final String SYSTEM_ACCOUNT = "system"; public static final String ANONYMOUS_USER = "anonymoususer"; private Constants() { } }
gpl-3.0
mhall119/Phoenicia
app/src/androidTest/java/com/linguaculturalists/phoenicia/mock/MockMethod.java
267
package com.linguaculturalists.phoenicia.mock; /** * Created by mhall on 4/17/16. */ public class MockMethod { public boolean called = false; public int call_count = 0; public void call() { this.called = true; this.call_count++; } }
gpl-3.0
OpenSilk/SyncthingAndroid
app/src/main/java/syncthing/android/ui/common/ExpandCollapseHelper.java
7269
/* * */ package syncthing.android.ui.common; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateDecelerateInterpolator; /** * Helper to animate collapse and expand animation */ public class ExpandCollapseHelper { /** * This method expandes the view that was clicked. * * @param expandingLayout layout to expand * @param cardView cardView * @param recyclerView recyclerView */ public static void animateCollapsing(final View expandingLayout, final ExpandableView cardView, final RecyclerView recyclerView, boolean wobble) { final int origHeight = expandingLayout.getHeight(); ValueAnimator animator = createHeightAnimator(expandingLayout, origHeight, 0); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animator) { expandingLayout.setVisibility(View.GONE); //reset height else recycled views never show ViewGroup.LayoutParams layoutParams = expandingLayout.getLayoutParams(); layoutParams.height = origHeight; expandingLayout.setLayoutParams(layoutParams); cardView.getExpandable().setExpanded(false); //notifyAdapter(recyclerView, recyclerView.getLayoutManager().getPosition((View)cardView)); // Card card = cardView.getCard(); // if (card.getOnCollapseAnimatorEndListener()!=null) // card.getOnCollapseAnimatorEndListener().onCollapseEnd(card); } }); if (wobble) { AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(animator, createWobbleAnimator(cardView.getView())); animatorSet.start(); } else { animator.start(); } } /** * This method collapse the view that was clicked. * * @param expandingLayout layout to collapse * @param cardView cardView * @param recyclerView recyclerView */ public static void animateExpanding(final View expandingLayout, final ExpandableView cardView, final RecyclerView recyclerView, boolean wobble) { /* Update the layout so the extra content becomes visible.*/ expandingLayout.setVisibility(View.VISIBLE); View parent = (View) expandingLayout.getParent(); final int widthSpec = View.MeasureSpec.makeMeasureSpec( parent.getMeasuredWidth() - parent.getPaddingLeft() - parent.getPaddingRight(), View.MeasureSpec.AT_MOST); final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); expandingLayout.measure(widthSpec, heightSpec); ValueAnimator animator = createHeightAnimator(expandingLayout, 0, expandingLayout.getMeasuredHeight()); if (recyclerView != null) { animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { final int listViewHeight = recyclerView.getHeight(); final int listViewBottomPadding = recyclerView.getPaddingBottom(); final View v = findDirectChild(expandingLayout, recyclerView); @Override public void onAnimationUpdate(final ValueAnimator valueAnimator) { if (recyclerView.getLayoutManager().canScrollVertically()) { final int bottom = v.getBottom(); if (bottom > listViewHeight) { final int top = v.getTop(); if (top > 0) { //recyclerView.scrollBy(0,Math.min(bottom - listViewHeight + listViewBottomPadding, top)); recyclerView.smoothScrollBy(0,Math.min(bottom - listViewHeight + listViewBottomPadding + 4, top)); } } } } }); } animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); cardView.getExpandable().setExpanded(true); //notifyAdapter(recyclerView,recyclerView.getLayoutManager().getPosition((View)cardView)); // Card card = cardView.getCard(); // if (card.getOnExpandAnimatorEndListener()!=null) // card.getOnExpandAnimatorEndListener().onExpandEnd(card); } }); if (wobble) { AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(animator, createWobbleAnimator((View)cardView)); animatorSet.start(); } else { animator.start(); } } private static View findDirectChild(final View view, final RecyclerView recyclerView) { View result = view; View parent = (View) result.getParent(); while (parent != recyclerView) { result = parent; parent = (View) result.getParent(); } return result; } public static ValueAnimator createHeightAnimator(final View view, final int start, final int end) { ValueAnimator animator = ValueAnimator.ofInt(start, end); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(final ValueAnimator valueAnimator) { int value = (Integer) valueAnimator.getAnimatedValue(); ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); layoutParams.height = value; view.setLayoutParams(layoutParams); } }); return animator; } public static Animator createWobbleAnimator(final View view) { ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "rotationX", 0f, 30f); objectAnimator.setDuration(100); objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(view, "rotationX", 30f, 0f); objectAnimator.setDuration(100); objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); AnimatorSet set = new AnimatorSet(); set.playSequentially(objectAnimator, objectAnimator2); return set; } /** * This method notifies the adapter after setting expand value inside cards * * @param recyclerView */ public static void notifyAdapter(RecyclerView recyclerView, int position){ if (recyclerView instanceof CardRecyclerView) { CardRecyclerView cardRecyclerView = (CardRecyclerView) recyclerView; if (cardRecyclerView.getAdapter()!=null){ cardRecyclerView.getAdapter().notifyItemChanged(position); } } } }
gpl-3.0
ac2cz/FoxTelem
lib/mysql-connector-java-8.0.13/src/main/core-api/java/com/mysql/cj/result/Field.java
13358
/* * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 2.0, as published by the * Free Software Foundation. * * This program is also distributed with certain software (including but not * limited to OpenSSL) that is licensed under separate terms, as designated in a * particular file or component or in included license documentation. The * authors of MySQL hereby grant you an additional permission to link the * program and your derivative works with the separately licensed software that * they have included with MySQL. * * Without limiting anything contained in the foregoing, this file, which is * part of MySQL Connector/J, is also subject to the Universal FOSS Exception, * version 1.0, a copy of which can be found at * http://oss.oracle.com/licenses/universal-foss-exception. * * 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, version 2.0, * for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.cj.result; import com.mysql.cj.CharsetMapping; import com.mysql.cj.MysqlType; import com.mysql.cj.ServerVersion; import com.mysql.cj.util.LazyString; /** * Field is a class used to describe fields in a ResultSet */ public class Field { private int collationIndex = 0; private String encoding = "US-ASCII"; private int colDecimals; private short colFlag; private LazyString databaseName = null; private LazyString tableName = null; private LazyString originalTableName = null; private LazyString columnName = null; private LazyString originalColumnName = null; private String fullName = null; private long length; // Internal length of the field; private int mysqlTypeId = -1; // the MySQL type ID in legacy protocol private MysqlType mysqlType = MysqlType.UNKNOWN; public Field(LazyString databaseName, LazyString tableName, LazyString originalTableName, LazyString columnName, LazyString originalColumnName, long length, int mysqlTypeId, short colFlag, int colDecimals, int collationIndex, String encoding, MysqlType mysqlType) { this.databaseName = databaseName; this.tableName = tableName; this.originalTableName = originalTableName; this.columnName = columnName; this.originalColumnName = originalColumnName; this.length = length; this.colFlag = colFlag; this.colDecimals = colDecimals; this.mysqlTypeId = mysqlTypeId; this.collationIndex = collationIndex; // ucs2, utf16, and utf32 cannot be used as a client character set, but if it was received from server under some circumstances we can parse them as utf16 this.encoding = "UnicodeBig".equals(encoding) ? "UTF-16" : encoding; // MySQL encodes JSON data with utf8mb4. if (mysqlType == MysqlType.JSON) { this.encoding = "UTF-8"; } this.mysqlType = mysqlType; adjustFlagsByMysqlType(); } private void adjustFlagsByMysqlType() { switch (this.mysqlType) { case BIT: if (this.length > 1) { this.colFlag |= MysqlType.FIELD_FLAG_BINARY; this.colFlag |= MysqlType.FIELD_FLAG_BLOB; } break; case BINARY: case VARBINARY: this.colFlag |= MysqlType.FIELD_FLAG_BINARY; this.colFlag |= MysqlType.FIELD_FLAG_BLOB; break; case DECIMAL_UNSIGNED: case TINYINT_UNSIGNED: case SMALLINT_UNSIGNED: case INT_UNSIGNED: case FLOAT_UNSIGNED: case DOUBLE_UNSIGNED: case BIGINT_UNSIGNED: case MEDIUMINT_UNSIGNED: this.colFlag |= MysqlType.FIELD_FLAG_UNSIGNED; break; default: break; } } /** * Used by prepared statements to re-use result set data conversion methods * when generating bound parameter retrieval instance for statement interceptors. * * @param tableName * not used * @param columnName * not used * @param collationIndex * the MySQL collation/character set index * @param encoding * encoding of data in this field * @param mysqlType * {@link MysqlType} * @param length * length in characters or bytes (for BINARY data). */ public Field(String tableName, String columnName, int collationIndex, String encoding, MysqlType mysqlType, int length) { this.databaseName = new LazyString(null); this.tableName = new LazyString(tableName); this.originalTableName = new LazyString(null); this.columnName = new LazyString(columnName); this.originalColumnName = new LazyString(null); this.length = length; this.mysqlType = mysqlType; this.colFlag = 0; this.colDecimals = 0; adjustFlagsByMysqlType(); switch (mysqlType) { case CHAR: case VARCHAR: case TINYTEXT: case TEXT: case MEDIUMTEXT: case LONGTEXT: case JSON: // TODO: this becomes moot when DBMD results aren't built from ByteArrayRow // it possibly overrides correct encoding already existing in the Field instance this.collationIndex = collationIndex; // ucs2, utf16, and utf32 cannot be used as a client character set, but if it was received from server under some circumstances we can parse them as utf16 this.encoding = "UnicodeBig".equals(encoding) ? "UTF-16" : encoding; break; default: // ignoring charsets for non-string types } } /** * Returns the Java encoding for this field. * * @return the Java encoding */ public String getEncoding() { return this.encoding; } // TODO Remove this after DBMD isn't using ByteArrayRow results. public void setEncoding(String javaEncodingName, ServerVersion version) { this.encoding = javaEncodingName; this.collationIndex = CharsetMapping.getCollationIndexForJavaEncoding(javaEncodingName, version); } public String getColumnLabel() { return getName(); } public String getDatabaseName() { return this.databaseName.toString(); } public int getDecimals() { return this.colDecimals; } public String getFullName() { if (this.fullName == null) { StringBuilder fullNameBuf = new StringBuilder(this.tableName.length() + 1 + this.columnName.length()); fullNameBuf.append(this.tableName.toString()); fullNameBuf.append('.'); fullNameBuf.append(this.columnName.toString()); this.fullName = fullNameBuf.toString(); } return this.fullName; } public long getLength() { return this.length; } public int getMysqlTypeId() { return this.mysqlTypeId; } public void setMysqlTypeId(int id) { this.mysqlTypeId = id; } public String getName() { return this.columnName.toString(); } public String getOriginalName() { return this.originalColumnName.toString(); } public String getOriginalTableName() { return this.originalTableName.toString(); } public int getJavaType() { return this.mysqlType.getJdbcType(); } public String getTableName() { return this.tableName.toString(); } public boolean isAutoIncrement() { return ((this.colFlag & MysqlType.FIELD_FLAG_AUTO_INCREMENT) > 0); } public boolean isBinary() { return ((this.colFlag & MysqlType.FIELD_FLAG_BINARY) > 0); } public void setBinary() { this.colFlag |= MysqlType.FIELD_FLAG_BINARY; } public boolean isBlob() { return ((this.colFlag & MysqlType.FIELD_FLAG_BLOB) > 0); } public void setBlob() { this.colFlag |= MysqlType.FIELD_FLAG_BLOB; } public boolean isMultipleKey() { return ((this.colFlag & MysqlType.FIELD_FLAG_MULTIPLE_KEY) > 0); } public boolean isNotNull() { return ((this.colFlag & MysqlType.FIELD_FLAG_NOT_NULL) > 0); } public boolean isPrimaryKey() { return ((this.colFlag & MysqlType.FIELD_FLAG_PRIMARY_KEY) > 0); } public boolean isFromFunction() { return this.originalTableName.length() == 0; } /** * Is this field _definitely_ not writable? * * @return true if this field can not be written to in an INSERT/UPDATE * statement. */ public boolean isReadOnly() { return this.originalColumnName.length() == 0 && this.originalTableName.length() == 0; } public boolean isUniqueKey() { return ((this.colFlag & MysqlType.FIELD_FLAG_UNIQUE_KEY) > 0); } public boolean isUnsigned() { return ((this.colFlag & MysqlType.FIELD_FLAG_UNSIGNED) > 0); } public boolean isZeroFill() { return ((this.colFlag & MysqlType.FIELD_FLAG_ZEROFILL) > 0); } @Override public String toString() { try { StringBuilder asString = new StringBuilder(); asString.append(super.toString()); asString.append("["); asString.append("catalog="); asString.append(this.getDatabaseName()); asString.append(",tableName="); asString.append(this.getTableName()); asString.append(",originalTableName="); asString.append(this.getOriginalTableName()); asString.append(",columnName="); asString.append(this.getName()); asString.append(",originalColumnName="); asString.append(this.getOriginalName()); asString.append(",mysqlType="); asString.append(getMysqlTypeId()); asString.append("("); MysqlType ft = getMysqlType(); if (ft.equals(MysqlType.UNKNOWN)) { asString.append(" Unknown MySQL Type # "); asString.append(getMysqlTypeId()); } else { asString.append("FIELD_TYPE_"); asString.append(ft.getName()); } asString.append(")"); asString.append(",sqlType="); asString.append(ft.getJdbcType()); asString.append(",flags="); if (isAutoIncrement()) { asString.append(" AUTO_INCREMENT"); } if (isPrimaryKey()) { asString.append(" PRIMARY_KEY"); } if (isUniqueKey()) { asString.append(" UNIQUE_KEY"); } if (isBinary()) { asString.append(" BINARY"); } if (isBlob()) { asString.append(" BLOB"); } if (isMultipleKey()) { asString.append(" MULTI_KEY"); } if (isUnsigned()) { asString.append(" UNSIGNED"); } if (isZeroFill()) { asString.append(" ZEROFILL"); } asString.append(", charsetIndex="); asString.append(this.collationIndex); asString.append(", charsetName="); asString.append(this.encoding); asString.append("]"); return asString.toString(); } catch (Throwable t) { return super.toString() + "[<unable to generate contents>]"; } } public boolean isSingleBit() { return (this.length <= 1); } public boolean getValueNeedsQuoting() { switch (this.mysqlType) { case BIGINT: case BIGINT_UNSIGNED: case BIT: case DECIMAL: case DECIMAL_UNSIGNED: case DOUBLE: case DOUBLE_UNSIGNED: case INT: case INT_UNSIGNED: case MEDIUMINT: case MEDIUMINT_UNSIGNED: case FLOAT: case FLOAT_UNSIGNED: case SMALLINT: case SMALLINT_UNSIGNED: case TINYINT: case TINYINT_UNSIGNED: return false; default: return true; } } public int getCollationIndex() { return this.collationIndex; } public MysqlType getMysqlType() { return this.mysqlType; } public void setMysqlType(MysqlType mysqlType) { this.mysqlType = mysqlType; } public short getFlags() { return this.colFlag; } public void setFlags(short colFlag) { this.colFlag = colFlag; } }
gpl-3.0
aviau/syncany-gbp
syncany-lib/src/test/java/org/syncany/tests/scenarios/framework/ChangeTypeFileToSymlinkWithTargetFolder.java
1281
/* * Syncany, www.syncany.org * Copyright (C) 2011-2014 Philipp C. Heckel <philipp.heckel@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.syncany.tests.scenarios.framework; import java.io.File; import org.syncany.util.EnvironmentUtil; import org.syncany.util.FileUtil; public class ChangeTypeFileToSymlinkWithTargetFolder extends AbstractClientAction { @Override public void execute() throws Exception { if (!EnvironmentUtil.symlinksSupported()) { return; // no symbolic links on Windows } File file = pickFile(1782); log(this, file.getAbsolutePath()); file.delete(); FileUtil.createSymlink("/etc/init.d", file); } }
gpl-3.0
ojbMMXV/BeamForge
src/main/java/org/beamforge/extensions/thingiverse/gui/mapping/ThingFileClickListener.java
2693
/** * This file is part of VisiCut. * Copyright (C) 2011 - 2013 Thomas Oster <thomas.oster@rwth-aachen.de> * RWTH Aachen University - 52062 Aachen, Germany * <p> * VisiCut 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. * <p> * VisiCut 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. * <p> * You should have received a copy of the GNU Lesser General Public License * along with VisiCut. If not, see <http://www.gnu.org/licenses/>. **/ package org.beamforge.extensions.thingiverse.gui.mapping; import org.beamforge.extensions.thingiverse.ThingiverseManager; import org.beamforge.extensions.thingiverse.model.ThingFile; import org.beamforge.ui.MainView; import javax.swing.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; /** * This class listens for double clicks on a thing file (right panel) to load it into thingiverse * * @author Sven */ public class ThingFileClickListener extends MouseAdapter { // save main view for loading files JLabel lblOpeningFile; public ThingFileClickListener(JLabel lblOpeningFile) { this.lblOpeningFile = lblOpeningFile; } @Override public void mouseClicked(MouseEvent evt) { JList list = (JList) evt.getSource(); // clieckt list if (evt.getClickCount() == 2) { // double click int index = list.locationToIndex(evt.getPoint()); if (index < 0) { // nothing visible return; } final ThingFile aFile = (ThingFile) list.getModel().getElementAt(index); if (aFile == null) { // nothing visible return; } // enable user feedback SwingUtilities.invokeLater(() -> lblOpeningFile.setVisible(true)); // load file into thingiverse new Thread(() -> { // request file from thingivserse ThingiverseManager thingiverse = ThingiverseManager.getInstance(); File svgfile = thingiverse.downloadThingFile(aFile); // display file MainView.getInstance().loadFile(svgfile, false); // disable user feedback SwingUtilities.invokeLater(() -> lblOpeningFile.setVisible(false)); }).start(); } } }
gpl-3.0
gstreamer-java/gir2java
generated-src/generated/gobject20/gobject/GTypeModuleClass.java
825
package generated.gobject20.gobject; import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Field; import org.bridj.ann.Library; @Library("gobject-2.0") public class GTypeModuleClass extends StructObject { static { BridJ.register(); } public GTypeModuleClass() { super(); } public GTypeModuleClass(Pointer pointer) { super(pointer); } @Field(0) public GObjectClass gtypemoduleclass_field_parent_class() { return this.io.getNativeObjectField(this, 0); } @Field(0) public GTypeModuleClass gtypemoduleclass_field_parent_class(GObjectClass gtypemoduleclass_field_parent_class) { this.io.setNativeObjectField(this, 0, gtypemoduleclass_field_parent_class); return this; } }
gpl-3.0
LinEvil/Nukkit
src/main/java/cn/nukkit/scheduler/ServerScheduler.java
7466
package cn.nukkit.scheduler; import cn.nukkit.Server; import cn.nukkit.plugin.Plugin; import cn.nukkit.utils.PluginException; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; /** * @author Nukkit Project Team */ public class ServerScheduler { public static int WORKERS = 4; private final AsyncPool asyncPool; private final Queue<TaskHandler> pending; private final Queue<TaskHandler> queue; private final Map<Integer, TaskHandler> taskMap; private final AtomicInteger currentTaskId; private volatile int currentTick; public ServerScheduler() { this.pending = new ConcurrentLinkedQueue<>(); this.currentTaskId = new AtomicInteger(); this.queue = new PriorityQueue<>(11, (left, right) -> left.getNextRunTick() - right.getNextRunTick()); this.taskMap = new ConcurrentHashMap<>(); this.asyncPool = new AsyncPool(Server.getInstance(), WORKERS); } public TaskHandler scheduleTask(Task task) { return addTask(task, 0, 0, false); } public TaskHandler scheduleTask(Runnable task) { return addTask(null, task, 0, 0, false); } public TaskHandler scheduleTask(Runnable task, boolean asynchronous) { return addTask(null, task, 0, 0, asynchronous); } public TaskHandler scheduleAsyncTask(AsyncTask task) { return addTask(null, task, 0, 0, true); } @Deprecated public void scheduleAsyncTaskToWorker(AsyncTask task, int worker) { scheduleAsyncTask(task); } public int getAsyncTaskPoolSize() { return asyncPool.getSize(); } public void increaseAsyncTaskPoolSize(int newSize) { throw new UnsupportedOperationException("Cannot increase a working pool size."); } public TaskHandler scheduleDelayedTask(Task task, int delay) { return this.addTask(task, delay, 0, false); } public TaskHandler scheduleDelayedTask(Task task, int delay, boolean asynchronous) { return this.addTask(task, delay, 0, asynchronous); } public TaskHandler scheduleDelayedTask(Runnable task, int delay) { return addTask(null, task, delay, 0, false); } public TaskHandler scheduleDelayedTask(Runnable task, int delay, boolean asynchronous) { return addTask(null, task, delay, 0, asynchronous); } public TaskHandler scheduleRepeatingTask(Runnable task, int period) { return addTask(null, task, 0, period, false); } public TaskHandler scheduleRepeatingTask(Runnable task, int period, boolean asynchronous) { return addTask(null, task, 0, period, asynchronous); } public TaskHandler scheduleRepeatingTask(Task task, int period) { return addTask(task, 0, period, false); } public TaskHandler scheduleRepeatingTask(Task task, int period, boolean asynchronous) { return addTask(task, 0, period, asynchronous); } public TaskHandler scheduleDelayedRepeatingTask(Task task, int delay, int period) { return addTask(task, delay, period, false); } public TaskHandler scheduleDelayedRepeatingTask(Task task, int delay, int period, boolean asynchronous) { return addTask(task, delay, period, asynchronous); } public TaskHandler scheduleDelayedRepeatingTask(Runnable task, int delay, int period) { return addTask(null, task, delay, period, false); } public TaskHandler scheduleDelayedRepeatingTask(Runnable task, int delay, int period, boolean asynchronous) { return addTask(null, task, delay, period, asynchronous); } public void cancelTask(int taskId) { if (taskMap.containsKey(taskId)) { taskMap.remove(taskId).cancel(); } } public void cancelTask(Plugin plugin) { if (plugin == null) { throw new NullPointerException("Plugin cannot be null!"); } for (Map.Entry<Integer, TaskHandler> entry : taskMap.entrySet()) { TaskHandler taskHandler = entry.getValue(); if (plugin.equals(taskHandler.getPlugin())) { taskHandler.cancel(); /* It will remove from task map automatic in next main heartbeat. */ } } } public void cancelAllTasks() { for (Map.Entry<Integer, TaskHandler> entry : this.taskMap.entrySet()) { entry.getValue().cancel(); } this.taskMap.clear(); this.queue.clear(); this.currentTaskId.set(0); } public boolean isQueued(int taskId) { return this.taskMap.containsKey(taskId); } private TaskHandler addTask(Task task, int delay, int period, boolean asynchronous) { return addTask(task instanceof PluginTask ? ((PluginTask) task).getOwner() : null, () -> task.onRun(currentTick + delay), delay, period, asynchronous); } private TaskHandler addTask(Plugin plugin, Runnable task, int delay, int period, boolean asynchronous) { if (plugin != null && plugin.isDisabled()) { throw new PluginException("Plugin '" + plugin.getName() + "' attempted to register a task while disabled."); } if (delay < 0 || period < 0) { throw new PluginException("Attempted to register a task with negative delay or period."); } TaskHandler taskHandler = new TaskHandler(plugin, "Unknown", task, nextTaskId(), asynchronous); taskHandler.setDelay(delay); taskHandler.setPeriod(period); taskHandler.setNextRunTick(taskHandler.isDelayed() ? currentTick + taskHandler.getDelay() : currentTick); pending.offer(taskHandler); taskMap.put(taskHandler.getTaskId(), taskHandler); return taskHandler; } public void mainThreadHeartbeat(int currentTick) { this.currentTick = currentTick; // Accepts pending. while (!pending.isEmpty()) { queue.offer(pending.poll()); } // Main heart beat. while (isReady(currentTick)) { TaskHandler taskHandler = queue.poll(); if (taskHandler.isCancelled()) { taskMap.remove(taskHandler.getTaskId()); continue; } else if (taskHandler.isAsynchronous()) { asyncPool.submitTask(taskHandler.getTask()); } else { try { taskHandler.run(currentTick); } catch (Exception e) { Server.getInstance().getLogger().critical("Could not execute taskHandler " + taskHandler.getTaskName() + ": " + e.getMessage()); Server.getInstance().getLogger().logException(e); } } if (taskHandler.isRepeating()) { taskHandler.setNextRunTick(currentTick + taskHandler.getPeriod()); pending.offer(taskHandler); } else { taskMap.remove(taskHandler.getTaskId()).cancel(); } } AsyncTask.collectTask(); } public int getQueueSize() { return queue.size() + pending.size(); } private boolean isReady(int currentTick) { return this.queue.peek() != null && this.queue.peek().getNextRunTick() <= currentTick; } private int nextTaskId() { return currentTaskId.incrementAndGet(); } }
gpl-3.0
texalbuja/taller-facturacion-electronica
taller-facturacion-electronica/src/main/java/ec/facturacion/electronica/ws/autorizacion/RespuestaComprobante.java
5602
package ec.facturacion.electronica.ws.autorizacion; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for respuestaComprobante complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="respuestaComprobante"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="claveAccesoConsultada" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="numeroComprobantes" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="autorizaciones" minOccurs="0"&gt; * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="autorizacion" type="{http://ec.gob.sri.ws.autorizacion}autorizacion" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * &lt;/element&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "respuestaComprobante", propOrder = { "claveAccesoConsultada", "numeroComprobantes", "autorizaciones" }) public class RespuestaComprobante { protected String claveAccesoConsultada; protected String numeroComprobantes; protected RespuestaComprobante.Autorizaciones autorizaciones; /** * Gets the value of the claveAccesoConsultada property. * * @return * possible object is * {@link String } * */ public String getClaveAccesoConsultada() { return claveAccesoConsultada; } /** * Sets the value of the claveAccesoConsultada property. * * @param value * allowed object is * {@link String } * */ public void setClaveAccesoConsultada(String value) { this.claveAccesoConsultada = value; } /** * Gets the value of the numeroComprobantes property. * * @return * possible object is * {@link String } * */ public String getNumeroComprobantes() { return numeroComprobantes; } /** * Sets the value of the numeroComprobantes property. * * @param value * allowed object is * {@link String } * */ public void setNumeroComprobantes(String value) { this.numeroComprobantes = value; } /** * Gets the value of the autorizaciones property. * * @return * possible object is * {@link RespuestaComprobante.Autorizaciones } * */ public RespuestaComprobante.Autorizaciones getAutorizaciones() { return autorizaciones; } /** * Sets the value of the autorizaciones property. * * @param value * allowed object is * {@link RespuestaComprobante.Autorizaciones } * */ public void setAutorizaciones(RespuestaComprobante.Autorizaciones value) { this.autorizaciones = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="autorizacion" type="{http://ec.gob.sri.ws.autorizacion}autorizacion" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "autorizacion" }) public static class Autorizaciones { protected List<Autorizacion> autorizacion; /** * Gets the value of the autorizacion property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the autorizacion property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAutorizacion().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Autorizacion } * * */ public List<Autorizacion> getAutorizacion() { if (autorizacion == null) { autorizacion = new ArrayList<Autorizacion>(); } return this.autorizacion; } } }
gpl-3.0
marklipson/hypnotuner
src/com/marklipson/musicgen/TestServlet.java
455
package com.marklipson.musicgen; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TestServlet extends HttpServlet { @Override protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException { resp.getWriter().write( "hello" ); } }
gpl-3.0
RaysaOliveira/cloudsim-plus
cloudsim-plus/src/test/java/org/cloudbus/cloudsim/vms/VmSimpleTest.java
13901
/* * Title: CloudSim Toolkit Description: CloudSim (Cloud Simulation) Toolkit for Modeling and * Simulation of Clouds Licence: GPL - http://www.gnu.org/copyleft/gpl.html * * Copyright (c) 2009-2012, The University of Melbourne, Australia */ package org.cloudbus.cloudsim.vms; import org.cloudbus.cloudsim.brokers.DatacenterBroker; import org.cloudbus.cloudsim.hosts.HostSimple; import org.cloudbus.cloudsim.hosts.HostSimpleTest; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import java.util.ArrayList; import java.util.List; import org.cloudbus.cloudsim.core.CloudSim; import org.cloudbus.cloudsim.mocks.CloudSimMocker; import org.cloudbus.cloudsim.mocks.Mocks; import org.cloudsimplus.listeners.VmDatacenterEventInfo; import org.cloudsimplus.listeners.EventListener; import org.cloudsimplus.listeners.VmHostEventInfo; import org.cloudbus.cloudsim.schedulers.cloudlet.CloudletScheduler; import org.cloudbus.cloudsim.schedulers.cloudlet.CloudletSchedulerTimeShared; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import static org.easymock.EasyMock.createMock; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Anton Beloglazov * @since CloudSim Toolkit 2.0 */ public class VmSimpleTest { private static final int BROKER_ID = 0; private static final int ID = 1; private static final double MIPS = 1000; private static final int PES_NUMBER = 2; private static final int RAM = 1024; private static final long BW = 10000; private static final long SIZE = 1000; private static final String VMM = "Xen"; private CloudletSchedulerTimeShared vmScheduler; private VmSimple vm; @Before public void setUp() throws Exception { vmScheduler = new CloudletSchedulerTimeShared(); final CloudSim cloudsim = CloudSimMocker.createMock(mocker -> mocker.clock(0)); final DatacenterBroker broker = Mocks.createMockBroker(cloudsim); vm = VmSimpleTest.createVm(vmScheduler); vm.setBroker(broker); } /** * Creates a VM with the 1 PE and half mips capacity defined in * {@link #MIPS}. * * @param vmId the id of the VM * @return */ public static Vm createVmWithOnePeAndHalfMips(final int vmId) { return createVm(vmId, MIPS / 2, 1, RAM, BW, SIZE, CloudletScheduler.NULL); } /** * Creates a VM with 1 PE and the total mips capacity defined in * {@link #MIPS}. * * @param vmId the id of the VM * @return */ public static Vm createVmWithOnePeAndTotalMips(final int vmId) { return createVm(vmId, MIPS, 1, RAM, BW, SIZE, CloudletScheduler.NULL); } /** * Creates a VM with the given numberOfPes and default configuration for * HOST_MIPS, HOST_RAM, HOST_BW and Storage. * * @param vmId * @param numberOfPes * @return */ public static VmSimple createVm(final int vmId, final int numberOfPes) { return createVm(vmId, MIPS, numberOfPes); } /** * Creates a VM with the default configuration defined in the Test Class' * constants. * * @param cloudletScheduler * @return */ public static VmSimple createVm(CloudletScheduler cloudletScheduler) { return createVm(ID, MIPS, PES_NUMBER, RAM, BW, SIZE, cloudletScheduler); } /** * Creates a VM with the given mips and numberOfPes and default * configuration for HOST_RAM, HOST_BW and Storage. * * @param vmId * @param mips * @param numberOfPes * @return */ public static VmSimple createVm(final int vmId, final double mips, final int numberOfPes) { return createVm(vmId, mips, numberOfPes, RAM, BW, SIZE, CloudletScheduler.NULL); } /** * Creates a VM with 1 PE. * * @param vmId id of the VM * @param capacity a capacity that will be set to all resources, such as CPU, HOST_RAM, HOST_BW, etc. * @return */ public static VmSimple createVm(final int vmId, long capacity) { return createVm(vmId, capacity, 1, capacity, capacity, capacity, CloudletScheduler.NULL); } public static VmSimple createVm(final int vmId, final double mips, final int numberOfPes, final long ram, final long bw, final long storage) { final CloudSim cloudsim = CloudSimMocker.createMock(mocker -> mocker.clock(0).anyTimes()); final DatacenterBroker broker = Mocks.createMockBroker(cloudsim); final VmSimple vm = new VmSimple(vmId, mips, numberOfPes); vm.setRam(ram).setBw(bw) .setSize(storage) .setCloudletScheduler(CloudletScheduler.NULL) .setBroker(broker); return vm; } public static VmSimple createVm(final int vmId, final double mips, final int numberOfPes, final long ram, final long bw, final long storage, final CloudletScheduler scheduler) { final CloudSim cloudsim = CloudSimMocker.createMock(mocker -> mocker.clock(0).anyTimes()); final DatacenterBroker broker = Mocks.createMockBroker(cloudsim); final VmSimple vm = new VmSimple(vmId, mips, numberOfPes); vm.setRam(ram).setBw(bw) .setSize(storage) .setCloudletScheduler(scheduler) .setBroker(broker); return vm; } /** * Creates a VM with the given numberOfPes for a given user and default * configuration for HOST_MIPS, HOST_RAM, HOST_BW and Storage. * * @param vmId * @param broker * @param numberOfPes * @return */ public static VmSimple createVmWithSpecificNumberOfPEsForSpecificUser( final int vmId, final DatacenterBroker broker, final int numberOfPes) { final VmSimple vm = createVm(vmId, MIPS, numberOfPes, RAM, BW, SIZE, CloudletScheduler.NULL); vm.setBroker(broker); return vm; } @Test public void testGetMips() { assertEquals(MIPS, vm.getMips(), 0); } @Test public void testToString() { assertEquals("Vm " + vm.getId(), vm.toString()); } @Test public void testSetMips() { vm.setMips(MIPS / 2); assertEquals(MIPS / 2, vm.getMips(), 0); } @Test public void testSetRam() { vm.setRam(RAM / 2); assertEquals(RAM / 2, vm.getRam().getCapacity(), 0); } @Test public void testAddStateHistoryEntry_addEntryToEmptyList(){ final double time=0, allocatedMips=1000, requestedMips=100; final boolean inMigration = false; VmStateHistoryEntry entry = new VmStateHistoryEntry(time, allocatedMips, requestedMips, inMigration); vm.addStateHistoryEntry(entry); assertFalse(vm.getStateHistory().isEmpty()); } @Test public void testAddStateHistoryEntry_checkAddedEntryValues(){ final VmStateHistoryEntry entry = new VmStateHistoryEntry(0, 1000, 100, false); vm.addStateHistoryEntry(entry); assertEquals(entry, vm.getStateHistory().get(vm.getStateHistory().size()-1)); } @Test public void testAddStateHistoryEntry_tryToAddEntryWithSameTime(){ final VmStateHistoryEntry entry = new VmStateHistoryEntry(0, 1000, 100, false); vm.addStateHistoryEntry(entry); vm.addStateHistoryEntry(entry); assertEquals(1, vm.getStateHistory().size()); } @Test public void testAddStateHistoryEntry_changeAddedEntry(){ VmStateHistoryEntry entry = new VmStateHistoryEntry(0, 1000, 100, false); vm.addStateHistoryEntry(entry); entry.setInMigration(true); vm.addStateHistoryEntry(entry); assertEquals(entry, vm.getStateHistory().get(vm.getStateHistory().size()-1)); } @Test public void testSetBw() { vm.setBw(BW / 2); assertEquals(BW / 2, vm.getBw().getCapacity(), 0); } @Test public void testRemoveOnHostAllocationListener() { EventListener<VmHostEventInfo> listener = (info) -> {}; vm.addOnHostAllocationListener(listener); assertTrue(vm.removeOnHostAllocationListener(listener)); } @Test public void testRemoveOnHostAllocationListener_Null() { assertFalse(vm.removeOnHostAllocationListener(null)); } @Test public void testRemoveOnHostDeallocationListener_Null() { assertFalse(vm.removeOnHostDeallocationListener(null)); } @Test public void testRemoveOnHostDeallocationListener() { final EventListener<VmHostEventInfo> listener = (info) -> {}; vm.addOnHostDeallocationListener(listener); assertTrue(vm.removeOnHostDeallocationListener(listener)); } @Test public void testRemoveOnVmCreationFailureListener_Null() { assertFalse(vm.removeOnCreationFailureListener(null)); } @Test public void testRemoveOnVmCreationFailureListener() { final EventListener<VmDatacenterEventInfo> listener = (info) -> {}; vm.addOnCreationFailureListener(listener); assertTrue(vm.removeOnCreationFailureListener(listener)); } @Test public void testRemoveOnUpdateVmProcessingListener_Null() { assertFalse(vm.removeOnUpdateProcessingListener(null)); } @Test public void testRemoveOnUpdateVmProcessingListener() { final EventListener<VmHostEventInfo> listener = (info) -> {}; vm.addOnUpdateProcessingListener(listener); assertTrue(vm.removeOnUpdateProcessingListener(listener)); } @Test public void testGetNumberOfPes() { assertEquals(PES_NUMBER, vm.getNumberOfPes()); } @Test public void testGetRam() { assertEquals(RAM, vm.getRam().getCapacity()); } @Test public void testGetBw() { assertEquals(BW, vm.getBw().getCapacity()); } @Test public void testGetSize() { assertEquals(SIZE, vm.getStorage().getCapacity()); } @Test public void testGetVmm() { assertEquals(VMM, vm.getVmm()); } @Test public void testGetHost() { final HostSimple host = HostSimpleTest.createHostSimple(0, 1); vm.setHost(host); assertEquals(host, vm.getHost()); } @Test public void testIsInMigration() { vm.setInMigration(true); assertTrue(vm.isInMigration()); } @Test public void testGetTotalUtilization() { assertEquals(0, vm.getCpuPercentUsage(0), 0); } @Test public void testGetTotalUtilizationMips() { assertEquals(0, vm.getTotalCpuMipsUsage(0), 0); } @Test public void testGetUid() { assertEquals(BROKER_ID + "-" + ID, vm.getUid()); } @Test public void testUpdateVmProcessing() { final List<Double> mipsShare1 = new ArrayList<>(1); final List<Double> mipsShare2 = new ArrayList<>(1); mipsShare1.add(1.0); mipsShare2.add(1.0); assertEquals(vmScheduler.updateProcessing(0, mipsShare1), vm.updateProcessing(0, mipsShare2), 0); } @Test public void testIsCreated() { vm.setCreated(true); assertTrue(vm.isCreated()); } @Test public void testGetCurrentRequestedBw_WhenVmWasCreatedInsideHost() { final double currentBwUsagePercent = 0.5; final CloudletScheduler cloudletScheduler = createMock(CloudletScheduler.class); cloudletScheduler.setVm(EasyMock.anyObject()); EasyMock.expectLastCall().once(); expect(cloudletScheduler.getCurrentRequestedBwPercentUtilization()) .andReturn(currentBwUsagePercent); replay(cloudletScheduler); final Vm vm0 = VmSimpleTest.createVm(cloudletScheduler); vm0.setCreated(true); final long expectedCurrentBwUtilization = (long)(currentBwUsagePercent*BW); assertEquals(expectedCurrentBwUtilization, vm0.getCurrentRequestedBw()); verify(cloudletScheduler); } @Test public void testGetCurrentRequestedBw_WhenVmWasNotCreatedInsideHost() { final Vm vm0 = VmSimpleTest.createVm(CloudletScheduler.NULL); vm0.setCreated(false); final long expectedCurrentBwUsage = BW; assertEquals(expectedCurrentBwUsage, vm0.getCurrentRequestedBw()); } @Test public void testGetCurrentRequestedRam_WhenVmWasCreatedInsideHost() { final double currentRamUsagePercent = 0.5; final long expectedCurrentRamUsage = (long)(currentRamUsagePercent*RAM); final CloudletScheduler cloudletScheduler = createMock(CloudletScheduler.class); cloudletScheduler.setVm(EasyMock.anyObject()); EasyMock.expectLastCall().once(); expect(cloudletScheduler.getCurrentRequestedRamPercentUtilization()) .andReturn(currentRamUsagePercent); replay(cloudletScheduler); final Vm vm0 = VmSimpleTest.createVm(cloudletScheduler); vm0.setCreated(true); assertEquals(expectedCurrentRamUsage, vm0.getCurrentRequestedRam()); verify(cloudletScheduler); } @Test public void testGetCurrentRequestedRam_WhenVmWasNotCreatedInsideHost() { final Vm vm0 = VmSimpleTest.createVm(CloudletScheduler.NULL); vm0.setCreated(false); final long expectedCurrentRamUsage = RAM; assertEquals(expectedCurrentRamUsage, vm0.getCurrentRequestedRam()); } @Test public void testGetCurrentRequestedMips_ForTimeSharedScheduler_WhenVmWasCreatedInsideHost() { final CloudletScheduler cloudletScheduler = new CloudletSchedulerTimeShared(); final Vm vm = VmSimpleTest.createVm(cloudletScheduler); vm.setCreated(true); assertTrue(vm.getCurrentRequestedMips().isEmpty()); } }
gpl-3.0
gditzler/MassiveOnlineAnalysis
moa/src/moa-2013.08-sources/moa-src/src/main/java/moa/options/Option.java
2644
/* * Option.java * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * * 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 moa.options; import javax.swing.JComponent; import moa.MOAObject; /** * Interface representing an option or parameter. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision: 7 $ */ public interface Option extends MOAObject { /** * Gets the name of this option * * @return the name of this option */ public String getName(); /** * Gets the Command Line Interface text of this option * * @return the Command Line Interface text */ public char getCLIChar(); /** * Gets the purpose of this option * * @return the purpose of this option */ public String getPurpose(); /** * Gets the Command Line Interface text * * @return the Command Line Interface text */ public String getDefaultCLIString(); /** * Sets value of this option via the Command Line Interface text * * @param s the Command Line Interface text */ public void setValueViaCLIString(String s); /** * Gets the value of a Command Line Interface text as a string * * @return the string with the value of the Command Line Interface text */ public String getValueAsCLIString(); /** * Resets this option to the default value * */ public void resetToDefault(); /** * Gets the state of this option in human readable form * * @return the string with state of this option in human readable form */ public String getStateString(); /** * Gets a copy of this option * * @return the copy of this option */ public Option copy(); /** * Gets the GUI component to edit * * @return the component to edit */ public JComponent getEditComponent(); }
gpl-3.0
Twissi/Animator
src/main/java/org/hacklace/animator/ErrorElement.java
1016
/******************************************************************************* * This program is made available under the terms of the GPLv3 or higher * which accompanies it and is available at http://www.gnu.org/licenses/gpl.html ******************************************************************************/ package org.hacklace.animator; import org.hacklace.animator.enums.ErrorType; public class ErrorElement { private final ErrorType type; private final String message; public ErrorElement(ErrorType type, String message) { assert type != null; assert message != null; assert message.length() != 0; this.type = type; this.message = message; } public ErrorType getType() { return type; } public String getMessage() { return message; } public boolean isFailure() { return type.isFailure(); } public boolean isErrorOrWarning() { return type.isErrorOrWarning(); } @Override public String toString() { return "["+getType().getDescription()+"] "+getMessage(); } }
gpl-3.0
snavaneethan1/jaffa-framework
jaffa-soa/source/java/org/jaffa/modules/scheduler/services/configdomain/Task.java
2270
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.0 in JDK 1.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: 2007.12.07 at 03:53:59 PM PST // package org.jaffa.modules.scheduler.services.configdomain; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "task") public class Task { @XmlAttribute protected Boolean autoCreateDataBean; @XmlAttribute(required = true) protected String dataBean; @XmlAttribute(required = true) protected String type; /** * Gets the value of the autoCreateDataBean property. * * @return possible object is * {@link Boolean } */ public boolean isAutoCreateDataBean() { if (autoCreateDataBean == null) { return true; } else { return autoCreateDataBean; } } /** * Sets the value of the autoCreateDataBean property. * * @param value allowed object is * {@link Boolean } */ public void setAutoCreateDataBean(Boolean value) { this.autoCreateDataBean = value; } /** * Gets the value of the dataBean property. * * @return possible object is * {@link String } */ public String getDataBean() { return dataBean; } /** * Sets the value of the dataBean property. * * @param value allowed object is * {@link String } */ public void setDataBean(String value) { this.dataBean = 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; } }
gpl-3.0
simoneclr/First-order-LTL-monitoring
src/main/java/language/LocalAtom.java
125
package language; /** * Created by Simone Calciolari on 18/08/15. */ public interface LocalAtom extends AtomicFormula { }
gpl-3.0
mickare/WorldEdit
worldedit-core/src/main/java/com/sk89q/worldedit/command/RegionCommands.java
19029
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.command; import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.Logging; import com.sk89q.worldedit.*; import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.function.GroundFunction; import com.sk89q.worldedit.function.generator.FloraGenerator; import com.sk89q.worldedit.function.generator.ForestGenerator; import com.sk89q.worldedit.function.mask.ExistingBlockMask; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.NoiseFilter2D; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Patterns; import com.sk89q.worldedit.function.visitor.LayerVisitor; import com.sk89q.worldedit.internal.annotation.Direction; import com.sk89q.worldedit.internal.annotation.Selection; import com.sk89q.worldedit.internal.expression.ExpressionException; import com.sk89q.worldedit.math.convolution.GaussianKernel; import com.sk89q.worldedit.math.convolution.HeightMap; import com.sk89q.worldedit.math.convolution.HeightMapFilter; import com.sk89q.worldedit.math.noise.RandomNoise; import com.sk89q.worldedit.regions.ConvexPolyhedralRegion; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionOperationException; import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator.TreeType; import com.sk89q.worldedit.util.command.binding.Range; import com.sk89q.worldedit.util.command.binding.Switch; import com.sk89q.worldedit.util.command.binding.Text; import com.sk89q.worldedit.util.command.parametric.Optional; import java.util.ArrayList; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static com.sk89q.minecraft.util.commands.Logging.LogMode.*; import static com.sk89q.worldedit.regions.Regions.*; /** * Commands that operate on regions. */ public class RegionCommands { private final WorldEdit worldEdit; /** * Create a new instance. * * @param worldEdit reference to WorldEdit */ public RegionCommands(WorldEdit worldEdit) { checkNotNull(worldEdit); this.worldEdit = worldEdit; } @Command( aliases = { "/line" }, usage = "<block> [thickness]", desc = "Draws a line segment between cuboid selection corners", help = "Draws a line segment between cuboid selection corners.\n" + "Can only be used with cuboid selections.\n" + "Flags:\n" + " -h generates only a shell", flags = "h", min = 1, max = 2 ) @CommandPermissions("worldedit.region.line") @Logging(REGION) public void line(Player player, EditSession editSession, @Selection Region region, Pattern pattern, @Optional("0") @Range(min = 0) int thickness, @Switch('h') boolean shell) throws WorldEditException { if (!(region instanceof CuboidRegion)) { player.printError("//line only works with cuboid selections"); return; } CuboidRegion cuboidregion = (CuboidRegion) region; Vector pos1 = cuboidregion.getPos1(); Vector pos2 = cuboidregion.getPos2(); int blocksChanged = editSession.drawLine(Patterns.wrap(pattern), pos1, pos2, thickness, !shell); player.print(blocksChanged + " block(s) have been changed."); } @Command( aliases = { "/curve" }, usage = "<block> [thickness]", desc = "Draws a spline through selected points", help = "Draws a spline through selected points.\n" + "Can only be used with convex polyhedral selections.\n" + "Flags:\n" + " -h generates only a shell", flags = "h", min = 1, max = 2 ) @CommandPermissions("worldedit.region.curve") @Logging(REGION) public void curve(Player player, EditSession editSession, @Selection Region region, Pattern pattern, @Optional("0") @Range(min = 0) int thickness, @Switch('h') boolean shell) throws WorldEditException { if (!(region instanceof ConvexPolyhedralRegion)) { player.printError("//curve only works with convex polyhedral selections"); return; } ConvexPolyhedralRegion cpregion = (ConvexPolyhedralRegion) region; List<Vector> vectors = new ArrayList<Vector>(cpregion.getVertices()); int blocksChanged = editSession.drawSpline(Patterns.wrap(pattern), vectors, 0, 0, 0, 10, thickness, !shell); player.print(blocksChanged + " block(s) have been changed."); } @Command( aliases = { "/replace", "/re", "/rep" }, usage = "[from-block] <to-block>", desc = "Replace all blocks in the selection with another", flags = "f", min = 1, max = 2 ) @CommandPermissions("worldedit.region.replace") @Logging(REGION) public void replace(Player player, EditSession editSession, @Selection Region region, @Optional Mask from, Pattern to) throws WorldEditException { if (from == null) { from = new ExistingBlockMask(editSession); } int affected = editSession.replaceBlocks(region, from, Patterns.wrap(to)); player.print(affected + " block(s) have been replaced."); } @Command( aliases = { "/overlay" }, usage = "<block>", desc = "Set a block on top of blocks in the region", min = 1, max = 1 ) @CommandPermissions("worldedit.region.overlay") @Logging(REGION) public void overlay(Player player, EditSession editSession, @Selection Region region, Pattern pattern) throws WorldEditException { int affected = editSession.overlayCuboidBlocks(region, Patterns.wrap(pattern)); player.print(affected + " block(s) have been overlaid."); } @Command( aliases = { "/center", "/middle" }, usage = "<block>", desc = "Set the center block(s)", min = 1, max = 1 ) @Logging(REGION) @CommandPermissions("worldedit.region.center") public void center(Player player, EditSession editSession, @Selection Region region, Pattern pattern) throws WorldEditException { int affected = editSession.center(region, Patterns.wrap(pattern)); player.print("Center set ("+ affected + " blocks changed)"); } @Command( aliases = { "/naturalize" }, usage = "", desc = "3 layers of dirt on top then rock below", min = 0, max = 0 ) @CommandPermissions("worldedit.region.naturalize") @Logging(REGION) public void naturalize(Player player, EditSession editSession, @Selection Region region) throws WorldEditException { int affected = editSession.naturalizeCuboidBlocks(region); player.print(affected + " block(s) have been made to look more natural."); } @Command( aliases = { "/walls" }, usage = "<block>", desc = "Build the four sides of the selection", min = 1, max = 1 ) @CommandPermissions("worldedit.region.walls") @Logging(REGION) public void walls(Player player, EditSession editSession, @Selection Region region, Pattern pattern) throws WorldEditException { int affected = editSession.makeCuboidWalls(region, Patterns.wrap(pattern)); player.print(affected + " block(s) have been changed."); } @Command( aliases = { "/faces", "/outline" }, usage = "<block>", desc = "Build the walls, ceiling, and floor of a selection", min = 1, max = 1 ) @CommandPermissions("worldedit.region.faces") @Logging(REGION) public void faces(Player player, EditSession editSession, @Selection Region region, Pattern pattern) throws WorldEditException { int affected = editSession.makeCuboidFaces(region, Patterns.wrap(pattern)); player.print(affected + " block(s) have been changed."); } @Command( aliases = { "/smooth" }, usage = "[iterations]", flags = "n", desc = "Smooth the elevation in the selection", help = "Smooths the elevation in the selection.\n" + "The -n flag makes it only consider naturally occuring blocks.", min = 0, max = 1 ) @CommandPermissions("worldedit.region.smooth") @Logging(REGION) public void smooth(Player player, EditSession editSession, @Selection Region region, @Optional("1") int iterations, @Switch('n') boolean affectNatural) throws WorldEditException { HeightMap heightMap = new HeightMap(editSession, region, affectNatural); HeightMapFilter filter = new HeightMapFilter(new GaussianKernel(5, 1.0)); int affected = heightMap.applyFilter(filter, iterations); player.print("Terrain's height map smoothed. " + affected + " block(s) changed."); } @Command( aliases = { "/move" }, usage = "[count] [direction] [leave-id]", flags = "s", desc = "Move the contents of the selection", help = "Moves the contents of the selection.\n" + "The -s flag shifts the selection to the target location.\n" + "Optionally fills the old location with <leave-id>.", min = 0, max = 3 ) @CommandPermissions("worldedit.region.move") @Logging(ORIENTATION_REGION) public void move(Player player, EditSession editSession, LocalSession session, @Selection Region region, @Optional("1") @Range(min = 1) int count, @Optional(Direction.AIM) @Direction Vector direction, @Optional("air") BaseBlock replace, @Switch('s') boolean moveSelection) throws WorldEditException { int affected = editSession.moveRegion(region, direction, count, true, replace); if (moveSelection) { try { region.shift(direction.multiply(count)); session.getRegionSelector(player.getWorld()).learnChanges(); session.getRegionSelector(player.getWorld()).explainRegionAdjust(player, session); } catch (RegionOperationException e) { player.printError(e.getMessage()); } } player.print(affected + " blocks moved."); } @Command( aliases = { "/stack" }, usage = "[count] [direction]", flags = "sa", desc = "Repeat the contents of the selection", help = "Repeats the contents of the selection.\n" + "Flags:\n" + " -s shifts the selection to the last stacked copy\n" + " -a skips air blocks", min = 0, max = 2 ) @CommandPermissions("worldedit.region.stack") @Logging(ORIENTATION_REGION) public void stack(Player player, EditSession editSession, LocalSession session, @Selection Region region, @Optional("1") @Range(min = 1) int count, @Optional(Direction.AIM) @Direction Vector direction, @Switch('s') boolean moveSelection, @Switch('a') boolean ignoreAirBlocks) throws WorldEditException { int affected = editSession.stackCuboidRegion(region, direction, count, !ignoreAirBlocks); if (moveSelection) { try { final Vector size = region.getMaximumPoint().subtract(region.getMinimumPoint()); final Vector shiftVector = direction.multiply(count * (Math.abs(direction.dot(size)) + 1)); region.shift(shiftVector); session.getRegionSelector(player.getWorld()).learnChanges(); session.getRegionSelector(player.getWorld()).explainRegionAdjust(player, session); } catch (RegionOperationException e) { player.printError(e.getMessage()); } } player.print(affected + " blocks changed. Undo with //undo"); } @Command( aliases = { "/regen" }, usage = "", desc = "Regenerates the contents of the selection", help = "Regenerates the contents of the current selection.\n" + "This command might affect things outside the selection,\n" + "if they are within the same chunk.", min = 0, max = 0 ) @CommandPermissions("worldedit.regen") @Logging(REGION) public void regenerateChunk(Player player, LocalSession session, EditSession editSession, @Selection Region region) throws WorldEditException { Mask mask = session.getMask(); try { session.setMask((Mask) null); player.getWorld().regenerate(region, editSession); } finally { session.setMask(mask); } player.print("Region regenerated."); } @Command( aliases = { "/deform" }, usage = "<expression>", desc = "Deforms a selected region with an expression", help = "Deforms a selected region with an expression\n" + "The expression is executed for each block and is expected\n" + "to modify the variables x, y and z to point to a new block\n" + "to fetch. See also tinyurl.com/wesyntax.", flags = "ro", min = 1, max = -1 ) @CommandPermissions("worldedit.region.deform") @Logging(ALL) public void deform(Player player, LocalSession session, EditSession editSession, @Selection Region region, @Text String expression, @Switch('r') boolean useRawCoords, @Switch('o') boolean offset) throws WorldEditException { final Vector zero; Vector unit; if (useRawCoords) { zero = Vector.ZERO; unit = Vector.ONE; } else if (offset) { zero = session.getPlacementPosition(player); unit = Vector.ONE; } else { final Vector min = region.getMinimumPoint(); final Vector max = region.getMaximumPoint(); zero = max.add(min).multiply(0.5); unit = max.subtract(zero); if (unit.getX() == 0) unit = unit.setX(1.0); if (unit.getY() == 0) unit = unit.setY(1.0); if (unit.getZ() == 0) unit = unit.setZ(1.0); } try { final int affected = editSession.deformRegion(region, zero, unit, expression); player.findFreePosition(); player.print(affected + " block(s) have been deformed."); } catch (ExpressionException e) { player.printError(e.getMessage()); } } @Command( aliases = { "/hollow" }, usage = "[<thickness>[ <block>]]", desc = "Hollows out the object contained in this selection", help = "Hollows out the object contained in this selection.\n" + "Optionally fills the hollowed out part with the given block.\n" + "Thickness is measured in manhattan distance.", min = 0, max = 2 ) @CommandPermissions("worldedit.region.hollow") @Logging(REGION) public void hollow(Player player, EditSession editSession, @Selection Region region, @Optional("0") @Range(min = 0) int thickness, @Optional("air") Pattern pattern) throws WorldEditException { int affected = editSession.hollowOutRegion(region, thickness, Patterns.wrap(pattern)); player.print(affected + " block(s) have been changed."); } @Command( aliases = { "/forest" }, usage = "[type] [density]", desc = "Make a forest within the region", min = 0, max = 2 ) @CommandPermissions("worldedit.region.forest") @Logging(REGION) public void forest(Player player, EditSession editSession, @Selection Region region, @Optional("tree") TreeType type, @Optional("5") @Range(min = 0, max = 100) double density) throws WorldEditException { density = density / 100; ForestGenerator generator = new ForestGenerator(editSession, new TreeGenerator(type)); GroundFunction ground = new GroundFunction(new ExistingBlockMask(editSession), generator); LayerVisitor visitor = new LayerVisitor(asFlatRegion(region), minimumBlockY(region), maximumBlockY(region), ground); visitor.setMask(new NoiseFilter2D(new RandomNoise(), density)); Operations.completeLegacy(visitor); player.print(ground.getAffected() + " trees created."); } @Command( aliases = { "/flora" }, usage = "[density]", desc = "Make flora within the region", min = 0, max = 1 ) @CommandPermissions("worldedit.region.flora") @Logging(REGION) public void flora(Player player, EditSession editSession, @Selection Region region, @Optional("10") @Range(min = 0, max = 100) double density) throws WorldEditException { density = density / 100; FloraGenerator generator = new FloraGenerator(editSession); GroundFunction ground = new GroundFunction(new ExistingBlockMask(editSession), generator); LayerVisitor visitor = new LayerVisitor(asFlatRegion(region), minimumBlockY(region), maximumBlockY(region), ground); visitor.setMask(new NoiseFilter2D(new RandomNoise(), density)); Operations.completeLegacy(visitor); player.print(ground.getAffected() + " flora created."); } }
gpl-3.0
ckaestne/LEADT
workspace/argouml_critics/argouml-app/src/org/argouml/uml/diagram/ui/ActionAddExistingNode.java
4295
// $Id: ActionAddExistingNode.java 41 2010-04-03 20:04:12Z marcusvnac $ // Copyright (c) 1996-2008 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.diagram.ui; import java.awt.event.ActionEvent; import org.argouml.i18n.Translator; import org.argouml.model.Model; import org.argouml.ui.targetmanager.TargetManager; import org.argouml.uml.diagram.ArgoDiagram; import org.argouml.uml.diagram.DiagramUtils; import org.tigris.gef.base.Editor; import org.tigris.gef.base.Globals; import org.tigris.gef.graph.GraphModel; import org.tigris.gef.graph.MutableGraphModel; import org.tigris.gef.undo.UndoableAction; /** * ActionAddExistingNode enables pasting of an existing node into a Diagram. * * @author Eugenio Alvarez * Data Access Technologies. * TODO: Why do we have this class as well as ActionAddExistingNodes? */ public class ActionAddExistingNode extends UndoableAction { /** * The UML object to be added to the diagram. */ private Object object; /** * The Constructor. * * @param name the localized name of the action * @param o the node UML object to be added */ public ActionAddExistingNode(String name, Object o) { super(name); object = o; } /* * @see javax.swing.Action#isEnabled() */ public boolean isEnabled() { Object target = TargetManager.getInstance().getTarget(); ArgoDiagram dia = DiagramUtils.getActiveDiagram(); if (dia == null) { return false; } if (dia instanceof UMLDiagram && ((UMLDiagram) dia).doesAccept(object)) { return true; } MutableGraphModel gm = (MutableGraphModel) dia.getGraphModel(); return gm.canAddNode(target); } /* * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent ae) { super.actionPerformed(ae); Editor ce = Globals.curEditor(); GraphModel gm = ce.getGraphModel(); if (!(gm instanceof MutableGraphModel)) { return; } String instructions = null; if (object != null) { instructions = Translator.localize( "misc.message.click-on-diagram-to-add", new Object[] { Model.getFacade().toString(object), }); Globals.showStatus(instructions); } final ModeAddToDiagram placeMode = new ModeAddToDiagram( TargetManager.getInstance().getTargets(), instructions); Globals.mode(placeMode, false); } }
gpl-3.0
mbshopM/openconcerto
OpenConcerto/src/org/openconcerto/erp/generationDoc/provider/UserCreateInitialsValueProvider.java
1592
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. * * The contents of this file are subject to the terms of the GNU General Public License Version 3 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each file. */ package org.openconcerto.erp.generationDoc.provider; import org.openconcerto.erp.generationDoc.SpreadSheetCellValueContext; import org.openconcerto.erp.generationDoc.SpreadSheetCellValueProviderManager; import org.openconcerto.sql.model.SQLRowAccessor; public class UserCreateInitialsValueProvider extends UserInitialsValueProvider { @Override public Object getValue(SpreadSheetCellValueContext context) { final SQLRowAccessor rowUser = context.getRow().getForeign("ID_USER_COMMON_CREATE"); final String firstName = rowUser.getString("PRENOM"); final String name = rowUser.getString("NOM"); return getInitials(firstName, name); } public static void register() { SpreadSheetCellValueProviderManager.put("InitialesUtilisateurCreate", new UserCreateInitialsValueProvider()); SpreadSheetCellValueProviderManager.put("user.create.initials", new UserCreateInitialsValueProvider()); } }
gpl-3.0
hugobarzano/NoInventory-Android-Apps
NoinventoryNoNFCversion/app/src/test/java/com/noinventory/noinventory/ExampleUnitTest.java
320
package com.noinventory.noinventory; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
gpl-3.0
andiwand/svm
src/at/stefl/svm/enumeration/ActionType.java
7725
package at.stefl.svm.enumeration; import java.util.Map; import at.stefl.commons.util.InaccessibleSectionException; import at.stefl.commons.util.collection.CollectionUtil; import at.stefl.commons.util.object.ObjectTransformer; import at.stefl.svm.object.action.CommentAction; import at.stefl.svm.object.action.FillColorAction; import at.stefl.svm.object.action.FontAction; import at.stefl.svm.object.action.LineAction; import at.stefl.svm.object.action.LineColorAction; import at.stefl.svm.object.action.MapModeAction; import at.stefl.svm.object.action.NullAction; import at.stefl.svm.object.action.OverLineColorAction; import at.stefl.svm.object.action.PixelAction; import at.stefl.svm.object.action.PointAction; import at.stefl.svm.object.action.PolyLineAction; import at.stefl.svm.object.action.PolyPolygonAction; import at.stefl.svm.object.action.PolygonAction; import at.stefl.svm.object.action.PopAction; import at.stefl.svm.object.action.PushAction; import at.stefl.svm.object.action.RectangleAction; import at.stefl.svm.object.action.SVMAction; import at.stefl.svm.object.action.TextAction; import at.stefl.svm.object.action.TextAlignAction; import at.stefl.svm.object.action.TextArrayAction; import at.stefl.svm.object.action.TextColorAction; import at.stefl.svm.object.action.TextFillColorAction; import at.stefl.svm.object.action.TextLanguageAction; import at.stefl.svm.object.action.TextLineColorAction; import at.stefl.svm.object.action.UnsupportedAction; public enum ActionType { NULL(ActionTypeConstants.META_NULL_ACTION, NullAction.class), PIXEL(ActionTypeConstants.META_PIXEL_ACTION, PixelAction.class), POINT(ActionTypeConstants.META_POINT_ACTION, PointAction.class), LINE(ActionTypeConstants.META_LINE_ACTION, LineAction.class), RECT(ActionTypeConstants.META_RECT_ACTION, RectangleAction.class), ROUND_RECT(ActionTypeConstants.META_ROUNDRECT_ACTION), ELLIPSE(ActionTypeConstants.META_ELLIPSE_ACTION), ARC(ActionTypeConstants.META_ARC_ACTION), PIE(ActionTypeConstants.META_PIE_ACTION), CHORD(ActionTypeConstants.META_CHORD_ACTION), POLY_LINE(ActionTypeConstants.META_POLYLINE_ACTION, PolyLineAction.class), POLYGON(ActionTypeConstants.META_POLYGON_ACTION, PolygonAction.class), POLY_POLYGON(ActionTypeConstants.META_POLYPOLYGON_ACTION, PolyPolygonAction.class), TEXT(ActionTypeConstants.META_TEXT_ACTION, TextAction.class), TEXT_ARRAY(ActionTypeConstants.META_TEXTARRAY_ACTION, TextArrayAction.class), STRETCH_TEXT(ActionTypeConstants.META_STRETCHTEXT_ACTION), TEXT_RECT(ActionTypeConstants.META_TEXTRECT_ACTION), BMP(ActionTypeConstants.META_BMP_ACTION), BMP_SCALE(ActionTypeConstants.META_BMPSCALE_ACTION), BMP_SCALE_PART(ActionTypeConstants.META_BMPSCALEPART_ACTION), BMP_EX(ActionTypeConstants.META_BMPEX_ACTION), BMP_EX_SCALE(ActionTypeConstants.META_BMPEXSCALE_ACTION), BMP_EX_SCALE_PART(ActionTypeConstants.META_BMPEXSCALEPART_ACTION), MASK(ActionTypeConstants.META_MASK_ACTION), MASK_SCALE(ActionTypeConstants.META_MASKSCALE_ACTION), MASK_SCALE_PART(ActionTypeConstants.META_MASKSCALEPART_ACTION), GRADIENT(ActionTypeConstants.META_GRADIENT_ACTION), HATCH(ActionTypeConstants.META_HATCH_ACTION), WALLPAPER(ActionTypeConstants.META_WALLPAPER_ACTION), CLIP_REGION(ActionTypeConstants.META_CLIPREGION_ACTION), IS_ECT_RECT_CLIP_REGION(ActionTypeConstants.META_ISECTRECTCLIPREGION_ACTION), IS_ECT_REGI_ON_CLIP_REGION( ActionTypeConstants.META_ISECTREGIONCLIPREGION_ACTION), MOVE_CLIP_REGION(ActionTypeConstants.META_MOVECLIPREGION_ACTION), LINE_COLOR(ActionTypeConstants.META_LINECOLOR_ACTION, LineColorAction.class), FILL_COLOR(ActionTypeConstants.META_FILLCOLOR_ACTION, FillColorAction.class), TEXT_COLOR(ActionTypeConstants.META_TEXTCOLOR_ACTION, TextColorAction.class), TEXT_FILL_COLOR(ActionTypeConstants.META_TEXTFILLCOLOR_ACTION, TextFillColorAction.class), TEXT_ALIGN( ActionTypeConstants.META_TEXTALIGN_ACTION, TextAlignAction.class), MAP_MODE(ActionTypeConstants.META_MAPMODE_ACTION, MapModeAction.class), FONT(ActionTypeConstants.META_FONT_ACTION, FontAction.class), PUSH( ActionTypeConstants.META_PUSH_ACTION, PushAction.class), POP( ActionTypeConstants.META_POP_ACTION, PopAction.class), RASTER_OP( ActionTypeConstants.META_RASTEROP_ACTION), TRANSPARENT( ActionTypeConstants.META_TRANSPARENT_ACTION), EPS( ActionTypeConstants.META_EPS_ACTION), REF_POINT( ActionTypeConstants.META_REFPOINT_ACTION), TEXT_LINE_COLOR( ActionTypeConstants.META_TEXTLINECOLOR_ACTION, TextLineColorAction.class), TEXT_LINE( ActionTypeConstants.META_TEXTLINE_ACTION), FLOAT_TRANSPARENT( ActionTypeConstants.META_FLOATTRANSPARENT_ACTION), GRADIENT_EX( ActionTypeConstants.META_GRADIENTEX_ACTION), LAYOUT_MODE( ActionTypeConstants.META_LAYOUTMODE_ACTION), TEXT_LANGUAGE( ActionTypeConstants.META_TEXTLANGUAGE_ACTION, TextLanguageAction.class), OVERLINE_COLOR( ActionTypeConstants.META_OVERLINECOLOR_ACTION, OverLineColorAction.class), COMMENT( ActionTypeConstants.META_COMMENT_ACTION, CommentAction.class); private static final ObjectTransformer<ActionType, Integer> CODE_KEY_GENERATOR = new ObjectTransformer<ActionType, Integer>() { @Override public Integer transform(ActionType value) { return value.code; } }; private static final ObjectTransformer<ActionType, Class<? extends SVMAction>> CLASS_KEY_GENERATOR = new ObjectTransformer<ActionType, Class<? extends SVMAction>>() { @Override public Class<? extends SVMAction> transform(ActionType value) { return value.actionObjectClass; } }; // TODO: reduce to 1 loop private static final Map<Integer, ActionType> BY_CODE_MAP = CollectionUtil .toHashMap(CODE_KEY_GENERATOR, values()); private static final Map<Class<? extends SVMAction>, ActionType> BY_CLASS_MAP = CollectionUtil .toHashMap(CLASS_KEY_GENERATOR, values()); public static ActionType getByCode(int code) { return BY_CODE_MAP.get(code); } public static SVMAction newByCode(int code) { return getByCode(code).newActionObject(); } public static ActionType getByClass(Class<? extends SVMAction> clazz) { return BY_CLASS_MAP.get(clazz); } public static SVMAction newByClass(Class<? extends SVMAction> clazz) { return getByClass(clazz).newActionObject(); } private final int code; private final Class<? extends SVMAction> actionObjectClass; // TODO: remove me (debugging only) private ActionType(int code) { this(code, UnsupportedAction.class); } private ActionType(int code, Class<? extends SVMAction> actionObjectClass) { this.code = code; this.actionObjectClass = actionObjectClass; } public int getCode() { return code; } public Class<? extends SVMAction> getActionObjectClass() { return actionObjectClass; } public SVMAction newActionObject() { try { SVMAction result = actionObjectClass.newInstance(); // TODO: remove me (debugging only) if (result instanceof UnsupportedAction) ((UnsupportedAction) result) .setActionType(this); return result; } catch (Exception e) { throw new InaccessibleSectionException(); } } }
gpl-3.0
jcjordyn130/simpleirc
application/src/main/java/tk/jordynsmediagroup/simpleirc/model/Settings.java
15263
package tk.jordynsmediagroup.simpleirc.model; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.net.Uri; import android.preference.PreferenceManager; import tk.jordynsmediagroup.simpleirc.R; /** * The settings class is a helper class to access the different preferences via * small and simple methods. * <p/> * Note: As this class carries a Context instance as private member, instances * of this class should be thrown away not later than when the Context should be * gone. Otherwise this could leak memory. * */ public class Settings { private final SharedPreferences preferences; private final Resources resources; private int currentRelease; // This is static so that all instances of the Settings object will // keep in sync. /** * Create a new Settings instance * * @param context */ public Settings(Context context) { this.preferences = PreferenceManager.getDefaultSharedPreferences(context); this.resources = context.getApplicationContext().getResources(); try { this.currentRelease = context.getPackageManager().getPackageInfo( context.getPackageName(), 0).versionCode; } catch ( Exception ex ) { this.currentRelease = 99; } } /** * Prefix all messages with a timestamp? * * @return */ public boolean showTimestamp() { return preferences.getBoolean(resources .getString(R.string.key_show_timestamp), Boolean.parseBoolean(resources .getString(R.string.default_show_timestamp))); } /** * Show icons to highlight special events * * @return */ public boolean showIcons() { return preferences.getBoolean(resources.getString(R.string.key_show_icons), Boolean.parseBoolean(resources.getString(R.string.default_show_icons))); } /** * Show colors to highlight special events? * * @return */ public boolean showMessageColors() { return preferences .getBoolean(resources.getString(R.string.key_show_colors), Boolean .parseBoolean(resources.getString(R.string.default_show_colors))); } /** * Show colors to highlight nicknames? * * @return */ public boolean showColorsNick() { return preferences.getBoolean(resources .getString(R.string.key_show_colors_nick), Boolean .parseBoolean(resources.getString(R.string.default_show_colors_nick))); } /** * Use 24 hour format for timestamps? * * @return */ public boolean use24hFormat() { return preferences.getBoolean(resources.getString(R.string.key_24h_format), Boolean.parseBoolean(resources.getString(R.string.default_24h_format))); } /** * Include seconds in timestamps? * * @return */ public boolean includeSeconds() { return preferences.getBoolean(resources .getString(R.string.key_include_seconds), Boolean .parseBoolean(resources.getString(R.string.default_include_seconds))); } /** * Is reconnect on disconnect enabled? * * @return */ public boolean isReconnectEnabled() { return preferences.getBoolean(resources.getString(R.string.key_reconnect_error), Boolean.parseBoolean(resources.getString(R.string.default_reconnect_error))); } /** * Ignore the automatic MOTD? * * @return */ public boolean isIgnoreMOTDEnabled() { return preferences .getBoolean(resources.getString(R.string.key_ignore_motd), Boolean .parseBoolean(resources.getString(R.string.default_ignore_motd))); } /** * Get the quit message * * @return The message to display when the user disconnects */ public String getQuitMessage() { return preferences.getString(resources.getString(R.string.key_quitmessage), resources.getString(R.string.default_quitmessage)); } /** * Get the font size * * @return The font size for conversation messages */ public int getFontSize() { return Integer.parseInt(preferences.getString( resources.getString(R.string.key_fontsize), resources.getString(R.string.default_fontsize))); } /** * Is voice recognition enabled? * * @return True if voice recognition is enabled, false otherwise */ public boolean isVoiceRecognitionEnabled() { return preferences.getBoolean(resources .getString(R.string.key_voice_recognition), Boolean .parseBoolean(resources.getString(R.string.default_voice_recognition))); } /** * Play notification sound on highlight? * * @return True if sound should be played on highlight, false otherwise */ public boolean isSoundHighlightEnabled() { return preferences.getBoolean(resources .getString(R.string.key_sound_highlight), Boolean .parseBoolean(resources.getString(R.string.default_sound_highlight))); } /** * What notification tone to play? * * @return U */ public Uri getHighlightSoundLocation() { return Uri.parse(preferences.getString( resources.getString(R.string.key_sound_ring), "content://settings/system/notification_sound")); /* * return preferences.getBoolean( * resources.getString(R.string.key_sound_highlight), * Boolean.parseBoolean(resources * .getString(R.string.default_sound_highlight)) ); */ } /** * Vibrate on highlight? * * @return True if vibrate on highlight is enabled, false otherwise */ public boolean isVibrateHighlightEnabled() { return preferences.getBoolean(resources .getString(R.string.key_vibrate_highlight), Boolean .parseBoolean(resources.getString(R.string.default_vibrate_highlight))); } /** * Auto rejoin after kick? * * @return True if Auto rejoin after kick is enabled, false otherwise */ public boolean isAutoRejoinAfterKick() { return preferences.getBoolean(resources .getString(R.string.key_autorejoin_kick), Boolean.parseBoolean(resources .getString(R.string.default_autorejoin_kick))); } /** * LED light notification on highlight? * * @return True if LED light on highlight is enabled, false otherwise */ public boolean isLedHighlightEnabled() { return preferences.getBoolean(resources .getString(R.string.key_led_highlight), Boolean.parseBoolean(resources .getString(R.string.default_led_highlight))); } /** * Should join, part and quit messages be displayed? * * @return True if joins, parts and quits should be displayed, false otherwise */ public boolean showJoinPartAndQuit() { return preferences.getBoolean(resources .getString(R.string.key_show_joinpartquit), Boolean .parseBoolean(resources.getString(R.string.default_show_joinpartquit))); } /** * Should notices be shown in the server window instead in the focused window? * * @return True if notices should be shown in the server window */ public boolean showNoticeInServerWindow() { return preferences.getBoolean(resources .getString(R.string.key_notice_server_window), Boolean .parseBoolean(resources .getString(R.string.default_notice_server_window))); } /** * Render messages with color and style codes. * * @return True if colors should be rendered, false if they should be removed. */ public boolean showMircColors() { return preferences .getBoolean(resources.getString(R.string.key_mirc_colors), Boolean .parseBoolean(resources.getString(R.string.default_mirc_colors))); } /** * Keep screen on while in a ConversationActivity * * @return True if the screen should be kept on, false if the screen should be able to turn off */ public boolean keepScreenOn() { return preferences .getBoolean(resources.getString(R.string.key_keep_screen_on), Boolean .parseBoolean(resources.getString(R.string.default_keep_screen_on))); } /** * Goto new query(s) * * @return True if we should goto new query(s), false if we shouldn't goto new query(s) */ public boolean gotoNewQuery() { return preferences .getBoolean(resources.getString(R.string.key_goto_new_query), Boolean .parseBoolean(resources.getString(R.string.default_goto_new_query))); } /** * Render messages with graphical smilies. * * @return True if text smilies should be rendered as graphical smilies, false * otherwise. */ public boolean showGraphicalSmilies() { return preferences.getBoolean(resources .getString(R.string.key_graphical_smilies), Boolean .parseBoolean(resources.getString(R.string.default_graphical_smilies))); } public String getColorScheme() { return preferences.getString(resources.getString(R.string.key_colorscheme), resources.getString(R.string.default_colorscheme)); } public void setColorScheme(String val) { preferences.edit() .putString(resources.getString(R.string.key_colorscheme), val).commit(); } /** * Whether message text should be autocorrected. */ public boolean autoCorrectText() { return preferences.getBoolean(resources .getString(R.string.key_autocorrect_text), Boolean .parseBoolean(resources.getString(R.string.default_autocorrect_text))); } /** * Should IRC traffic be logged to the verbose log? * * @return */ public boolean debugTraffic() { return preferences.getBoolean(resources .getString(R.string.key_debug_traffic), Boolean.parseBoolean(resources .getString(R.string.default_debug_traffic))); } public boolean getAutorejoinKick() { return preferences.getBoolean(resources .getString(R.string.key_debug_traffic), Boolean.parseBoolean(resources .getString(R.string.default_debug_traffic))); } /** * Whether sentences in messages should be automatically capitalized. */ public boolean autoCapSentences() { return preferences.getBoolean(resources .getString(R.string.key_autocap_sentences), Boolean .parseBoolean(resources.getString(R.string.default_autocap_sentences))); } /** * Whether the fullscreen keyboard should be used in landscape mode. */ public boolean imeExtract() { return preferences .getBoolean(resources.getString(R.string.key_ime_extract), Boolean .parseBoolean(resources.getString(R.string.default_ime_extract))); } public boolean showChannelBar() { return preferences.getBoolean(resources .getString(R.string.key_show_channelbar), Boolean .parseBoolean(resources.getString(R.string.default_show_channelbar))); } public boolean reconnectTransient() { return preferences.getBoolean(resources .getString(R.string.key_reconnect_transient), Boolean.parseBoolean(resources .getString(R.string.default_reconnect_transient))); } public boolean reconnectLoss() { return preferences.getBoolean(resources .getString(R.string.key_reconnect_loss), Boolean.parseBoolean(resources .getString(R.string.default_reconnect_loss))); } public boolean logTraffic() { return preferences.getBoolean(resources .getString(R.string.key_log_traffic), Boolean.parseBoolean(resources .getString(R.string.default_log_traffic))); } public String getLogFile() { return preferences.getString(resources.getString(R.string.key_log_file), resources.getString(R.string.default_log_file)); } /** * Get the conversation history size. * * @return The conversation history size */ public int getHistorySize() { try { return Integer.parseInt(preferences.getString( resources.getString(R.string.key_history_size), resources.getString(R.string.default_history_size))); } catch ( NumberFormatException e ) { return Integer.parseInt(resources .getString(R.string.default_history_size)); } } public boolean getUseDarkColors() { return preferences.getBoolean(resources .getString(R.string.key_colorscheme_dark), Boolean .parseBoolean(resources.getString(R.string.default_colorscheme_dark))); } public int getLastRunVersion() { return preferences.getInt("LAST_RUN_VERSION", 0); } public void resetLastRunVersion() { preferences.edit().putInt("LAST_RUN_VERSION", 0).commit(); } public void updateLastRunVersion() { preferences.edit().putInt("LAST_RUN_VERSION", currentRelease).commit(); } public int getCurrentVersion() { return currentRelease; } private String getRandomNick(int len) { char[] valid_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890" .toCharArray(); String ret = ""; for( int i = 0; i < len; i++ ) { ret += valid_chars[(int)(Math.random() * valid_chars.length)]; } return ret; } public String getDefaultNick() { String def = preferences.getString(resources.getString(R.string.key_default_nickname), null); if( def == null ) { def = "SimpleIRC_" + getRandomNick(5); preferences.edit().putString(resources.getString(R.string.key_default_nickname), def).apply(); } return def; } public String getDefaultUsername() { return preferences.getString(resources.getString(R.string.key_default_username), resources.getString(R.string.default_default_username)); } public void setDefaultUsername(String name) { preferences.edit().putString(resources.getString(R.string.key_default_username), name).apply(); } public String getDefaultRealname() { return preferences.getString(resources.getString(R.string.key_default_realname), resources.getString(R.string.default_default_realname)); } public void setDefaultRealname(String name) { preferences.edit().putString(resources.getString(R.string.key_default_realname), name).apply(); } public int getHighlightLEDColor() { return preferences.getInt(resources.getString(R.string.key_led_color), 0xFFFFFFFF); } public MessageRenderParams getRenderParams() { MessageRenderParams params = new MessageRenderParams(); params.colorScheme = this.getColorScheme(); params.icons = this.showIcons(); params.mircColors = this.showMircColors(); params.messageColors = this.showMessageColors(); params.smileys = this.showGraphicalSmilies(); params.nickColors = this.showColorsNick(); params.timestamps = this.showTimestamp(); params.useDarkScheme = this.getUseDarkColors(); params.timestamp24Hour = this.use24hFormat(); params.timestampSeconds = this.includeSeconds(); return params; } public boolean tintActionbar() { return preferences.getBoolean( resources.getString(R.string.key_tint_actionbar), Boolean.parseBoolean(resources.getString(R.string.default_tint_actionbar)) ); } }
gpl-3.0
Mrkwtkr/shinsei
src/main/java/com/megathirio/shinsei/core/handler/FuelHandler.java
666
package com.megathirio.shinsei.core.handler; import com.megathirio.shinsei.init.ShinseiItems; import net.minecraft.item.ItemStack; import cpw.mods.fml.common.IFuelHandler; public class FuelHandler implements IFuelHandler{ //Fuel Setup @Override public int getBurnTime(ItemStack fuel) { /* Vanilla Burn Times: Wooden Slab - 150 Wood - 300 Coal Block - 16000 Wooden Tools - 200 Stick - 100 Coal - 1600 Lava Bucket 20000 Sapling - 100 Blaze Rod - 2400 */ //Fuel Burn Times if(fuel.getItem() == ShinseiItems.splitWood) return 800; if(fuel.getItem() == ShinseiItems.coke) return 2400; return 0; } }
gpl-3.0
MStefko/STEADIER-SAILOR
src/main/java/ch/epfl/leb/sass/models/samples/internal/UniformRefractiveIndex.java
2012
/* * Copyright (C) 2017-2018 Laboratory of Experimental Biophysics * Ecole Polytechnique Fédérale de Lausanne * * 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 ch.epfl.leb.sass.models.samples.internal; import ch.epfl.leb.sass.models.samples.RefractiveIndex; import org.apache.commons.math3.complex.Complex; /** * A sample with uniform and isotropic refractive index throughout all of space. * * @author Kyle M. Douglass */ public class UniformRefractiveIndex implements RefractiveIndex { private final Complex refractiveIndex; /** * Constructs a new UniformRefractiveIndex instance. * * The index of refraction is the same and isotropic everywhere in space. * * @param refractiveIndex The complex index of refraction. */ public UniformRefractiveIndex(Complex refractiveIndex) { this.refractiveIndex = refractiveIndex; } /** * Returns the (complex) refractive index at the position (x, y, z). * * z = 0 corresponds to the plane of the coverslip. * * @param x The x-position within the sample. * @param y The y-position within the sample. * @param z The z-position within the sample. * @return The complex refractive index at the position (x, y, z). */ @Override public Complex getN(double x, double y, double z) { return refractiveIndex; } }
gpl-3.0
neo4j-contrib/neo4j-mobile-android
neo4j-android/kernel-src/org/neo4j/graphdb/Direction.java
2364
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphdb; /** * Defines relationship directions used when getting relationships from a node * or when creating traversers. * <p> * A relationship has a direction from a node's point of view. If a node is the * start node of a relationship it will be an {@link #OUTGOING} relationship * from that node's point of view. If a node is the end node of a relationship * it will be an {@link #INCOMING} relationship from that node's point of view. * The {@link #BOTH} direction is used when direction is of no importance, such * as "give me all" or "traverse all" relationships that are either * {@link #OUTGOING} or {@link #INCOMING}. */ public enum Direction { /** * Defines outgoing relationships. */ OUTGOING, /** * Defines incoming relationships. */ INCOMING, /** * Defines both incoming and outgoing relationships. */ BOTH; /** * Reverses the direction returning {@link #INCOMING} if this equals * {@link #OUTGOING}, {@link #OUTGOING} if this equals {@link #INCOMING} or * {@link #BOTH} if this equals {@link #BOTH}. * * @return The reversed direction. */ public Direction reverse() { switch ( this ) { case OUTGOING: return INCOMING; case INCOMING: return OUTGOING; case BOTH: return BOTH; default: throw new IllegalStateException( "Unknown Direction " + "enum: " + this ); } } }
gpl-3.0
Toadwana/civbuddy
src/com/tj/civ/client/model/jso/CbCommodityConfigJSO.java
4869
/* * CivBuddy - A Civilization Tactics Guide * Copyright (c) 2010 Thomas Jensen * $Id$ * Date created: 2010-12-26 * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General * Public License, version 3, as published by the Free Software Foundation. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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.tj.civ.client.model.jso; import com.google.gwt.core.client.JavaScriptObject; /** * Describes a commodity as per the config file. * * @author tsjensen */ public final class CbCommodityConfigJSO extends JavaScriptObject { /** <code>true</code> if the commodity is affected by the 'Mining' card from * the <i>Advanced Civilization</i> game variant */ private static final String PROP_MINEABLE = "mineable"; //$NON-NLS-1$ /** * JSO Constructor. */ protected CbCommodityConfigJSO() { super(); } /** * Factory method. * @return a new instance with base and maxCount initialized to -1 */ public static CbCommodityConfigJSO create() { CbCommodityConfigJSO result = createObject().cast(); result.setNames(CbStringsI18nJSO.create()); return result; } /** * Getter. * @return locale-specific names of this commodity */ public native CbStringsI18nJSO getNames() /*-{ return this.names; }-*/; /** * Sets the locale-specific names of this commodity. * @param pNames the new values */ private native void setNames(final CbStringsI18nJSO pNames) /*-{ this.names = pNames; }-*/; /** * Determine the commodity name best matching the current locale. * @return the localized commodity name */ public String getLocalizedName() { return getNames().getStringI18n(); } /** * Getter. * @return maximum number of cards of this commodity available in the game */ public native int getMaxCount() /*-{ if (this.hasOwnProperty('maxCount')) { return this.maxCount; } else { return -1; } }-*/; /** * Sets the maximum number of cards of this commodity available in the game. * @param pMaxCount the new value */ public native void setMaxCount(final int pMaxCount) /*-{ this.maxCount = pMaxCount; }-*/; /** * Getter. * @return base value of this commodity */ public native int getBase() /*-{ if (this.hasOwnProperty('base')) { return this.base; } else { return -1; } }-*/; /** * Sets the base value of this commodity. * @param pBase the new value */ public native void setBase(final int pBase) /*-{ this.base = pBase; }-*/; /** * Getter. * @return <code>true</code> if this commodity is wine to which the western * expansion pack's special rules for wine apply */ public native boolean isWineSpecial() /*-{ if (this.hasOwnProperty('wine')) { return this.wine; } else { return false; } }-*/; /** * Sets the flag indicating that this commodity is wine to which the western * expansion pack's special rules for wine apply. * @param pWineSpecial the new value */ public native void setWineSpecial(final boolean pWineSpecial) /*-{ this.wine = pWineSpecial; }-*/; /** * Indicate whether this commodity is basically eligible for the bonus granted * by the 'Mining' card from the <i>Advanced Civilization</i> game variant. * @param pMineable the new value */ public native void setMineable(final boolean pMineable) /*-{ this[@com.tj.civ.client.model.jso.CbCommodityConfigJSO::PROP_MINEABLE] = pMineable; }-*/; /** * Determine if this card is basically eligible for the bonus granted by the * 'Mining' card from the <i>Advanced Civilization</i> game variant. * @return <code>true</code> if the flag is set accordingly. If the flag is not * present, <code>false</code> is assumed as default */ public native boolean isMineable() /*-{ if (this.hasOwnProperty(@com.tj.civ.client.model.jso.CbCommodityConfigJSO::PROP_MINEABLE)) { return this[@com.tj.civ.client.model.jso.CbCommodityConfigJSO::PROP_MINEABLE]; } else { return false; } }-*/; }
gpl-3.0
Aerylia/SE2Assignment
src/main/java/org/alcibiade/eternity/editor/solver/swap/AStarSolverMkI.java
8281
/* This file is part of Eternity II Editor. * * Eternity II Editor 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. * * Eternity II Editor 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 Eternity II Editor. If not, see <http://www.gnu.org/licenses/>. * * Eternity II Editor project is hosted on SourceForge: * http://sourceforge.net/projects/eternityii/ * and maintained by Yannick Kirschhoffer <alcibiade@alcibiade.org> */ package org.alcibiade.eternity.editor.solver.swap; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.alcibiade.eternity.editor.model.GridModel; import org.alcibiade.eternity.editor.model.QuadModel; import org.alcibiade.eternity.editor.solver.ClusterListener; import org.alcibiade.eternity.editor.solver.ClusterManager; import org.alcibiade.eternity.editor.solver.EternitySolver; import org.alcibiade.eternity.editor.solver.RandomFactory; public class AStarSolverMkI extends EternitySolver implements ClusterListener { private GridModel solutionGrid; // This is set to problemGrid.getSize()^2 for convenience. private int positions; // This is set to problemGrid.getSize() for convenience. private int gsize; private GridModel problemGrid; private long iterations = 0; private Random random; public AStarSolverMkI(GridModel problemGrid, GridModel solutionGrid, ClusterManager clusterManager) { super(clusterManager); this.solutionGrid = solutionGrid; this.problemGrid = problemGrid; solutionGrid.reset(); solutionGrid.setSize(problemGrid.getSize()); this.gsize = problemGrid.getSize(); this.positions = gsize * gsize; this.random = RandomFactory.getRandom(); } @Override public String getSolverName() { return "AStar Solver MkI $Revision: 245 $"; } @Override public long getIterations() { return iterations; } @Override public void run() { notifyStart(); clusterManager.showStartMessage(); moveLockedPieces(); boolean solved = solve(); if (solved) { clusterManager.submitSolution(solutionGrid); clusterManager.showStats(iterations); } notifyEnd(solved); } private void moveLockedPieces() { int gsize = solutionGrid.getSize(); int positions = gsize * gsize; for (int i = 0; i < positions; i++) { QuadModel piece = problemGrid.getQuad(i); if (piece.isLocked()) { piece.copyTo(solutionGrid.getQuad(i)); piece.clear(); } } for (int i = 0; i < positions; i++) { QuadModel piece = problemGrid.getQuad(i); if (!piece.isLocked()) { for (int j = 0; j < positions; j++) { QuadModel solPiece = solutionGrid.getQuad(j); if (solPiece.isClear() && solutionGrid.countSides(j) == piece.countDefaultPattern()) { piece.copyTo(solPiece); solutionGrid.optimizeQuadRotation(j); break; } } } } } @Override public void bestSolutionUpdated(int bestScore) { // Do nothing } private boolean solve() { // http://en.wikipedia.org/wiki/A* // System.out.println(solutionGrid.toQuadString()); boolean result = false; SortedSet<Path> openSet = new TreeSet<Path>(); openSet.add(new Path()); Set<Path> closedSet = new HashSet<Path>(); while (!openSet.isEmpty()) { if (interrupted) { return false; } if (slowmotion) { try { Thread.sleep(SLOWMOTION_DELAY); } catch (InterruptedException e) { e.printStackTrace(); } } // Lowest f_score Path x = openSet.first(); if (x.distance() == 0) { for (Swap s : x) { s.apply(); } return true; } openSet.remove(x); closedSet.add(x); // System.out.println("" + openSet.size() + ", " + closedSet.size() // + ", " + x); // Find neighbors Set<Path> neighbors = computeNeighbors(x); for (Path y : neighbors) { if (closedSet.contains(y)) { continue; } if (!openSet.contains(y)) { openSet.add(y); } } iterations++; } return result; } private Set<Path> computeNeighbors(Path p) { Set<Path> result = new HashSet<Path>(); if (p.size() < solutionGrid.getPositions() - 1) { for (int i = 0; i < positions; i++) { p.apply(); QuadModel quad = solutionGrid.getQuad(i); List<Integer> possibleIndices = new ArrayList<Integer>(); for (int j = 0; j < positions; j++) { if (i != j && solutionGrid.countSides(j) == quad.countDefaultPattern()) { possibleIndices.add(j); } } p.revert(); if (!possibleIndices.isEmpty()) { int randomIndex = random.nextInt(possibleIndices.size()); int dest = possibleIndices.get(randomIndex); result.add(new Path(p, new Swap(i, dest))); } } } return result; } protected class Path extends ArrayList<Swap> implements Comparable<Path> { private static final long serialVersionUID = 1L; private int score = 0; public Path() { // Do nothing score = _distance(); } public Path(Path p, Swap swap) { addAll(p); add(swap); score = _distance(); } public int distance() { return score; } private int _distance() { apply(); score = 0; score += solutionGrid.countConnections(); score -= solutionGrid.countPairs(); score *= score; if (score > 0) { score += size(); } revert(); return score; } public void revert() { for (int i = size() - 1; i >= 0; i--) { get(i).revert(); } } public void apply() { for (int i = 0; i < size(); i++) { get(i).apply(); } } @Override public String toString() { return super.toString() + " (score: " + score + ")"; } @Override public boolean equals(Object o) { boolean result = super.equals(o); return result; } @Override public int compareTo(Path o) { int result = score - o.score; if (result == 0) { result = size() - o.size(); } for (int i = 0; result == 0 && i < size(); i++) { Swap ms = get(i); Swap os = o.get(i); result = ms.getSrcIndex() - os.getSrcIndex(); if (result == 0) { result = ms.getDstIndex() - os.getDstIndex(); } } return result; } } protected class Swap { private int srcIndex; private int dstIndex; private int srcOrientation; private int dstOrientation; public Swap(int src, int dst) { this.srcIndex = src; this.dstIndex = dst; } public int getSrcIndex() { return srcIndex; } public int getDstIndex() { return dstIndex; } public void apply() { // System.out.println(solutionGrid.toQuadString()); // // System.out // .println("Swapping " + this + " // " + srcOrientation + "|" + // dstOrientation); solutionGrid.swap(srcIndex, dstIndex); srcOrientation = solutionGrid.optimizeQuadRotation(srcIndex); dstOrientation = solutionGrid.optimizeQuadRotation(dstIndex); // System.out.println(solutionGrid.toQuadString()); } public void revert() { // System.out.println(solutionGrid.toQuadString()); // // System.out.println("Reverting " + this + " // " + srcOrientation // + "|" // + dstOrientation); solutionGrid.swap(srcIndex, dstIndex); solutionGrid.getQuad(srcIndex).rotateCounterclockwise(dstOrientation); solutionGrid.getQuad(dstIndex).rotateCounterclockwise(srcOrientation); // System.out.println(solutionGrid.toQuadString()); } @Override public boolean equals(Object obj) { boolean result = false; if (obj instanceof Swap) { Swap os = (Swap) obj; result = (srcIndex == os.srcIndex && dstIndex == os.dstIndex) || (srcIndex == os.dstIndex && dstIndex == os.srcIndex); } return result; } @Override public int hashCode() { return srcIndex + dstIndex; } @Override public String toString() { return "" + srcIndex + "<->" + dstIndex; } } }
gpl-3.0
gallardo/alkacon-oamp
com.alkacon.opencms.v8.newsletter/src/com/alkacon/opencms/v8/newsletter/admin/CmsOrgUnitsAdminList.java
10902
/* * File : $Source: /alkacon/cvs/alkacon/com.alkacon.opencms.v8.newsletter/src/com/alkacon/opencms/v8/newsletter/admin/CmsOrgUnitsAdminList.java,v $ * Date : $Date: 2007/11/30 11:57:27 $ * Version: $Revision: 1.7 $ * * This file is part of the Alkacon OpenCms Add-On Module Package * * Copyright (c) 2007 Alkacon Software GmbH (http://www.alkacon.com) * * The Alkacon OpenCms Add-On Module Package 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. * * The Alkacon OpenCms Add-On Module Package 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 the Alkacon OpenCms Add-On Module Package. * If not, see http://www.gnu.org/licenses/. * * For further information about Alkacon Software GmbH, please see the * company website: http://www.alkacon.com. * * For further information about OpenCms, please see the * project website: http://www.opencms.org. */ package com.alkacon.opencms.v8.newsletter.admin; import com.alkacon.opencms.v8.newsletter.CmsNewsletterManager; import org.opencms.file.CmsObject; import org.opencms.file.CmsProject; import org.opencms.jsp.CmsJspActionElement; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.security.CmsOrganizationalUnit; import org.opencms.workplace.list.CmsListColumnDefinition; import org.opencms.workplace.list.CmsListDefaultAction; import org.opencms.workplace.list.CmsListDirectAction; import org.opencms.workplace.list.CmsListItemDetails; import org.opencms.workplace.list.CmsListItemDetailsFormatter; import org.opencms.workplace.list.CmsListMetadata; import org.opencms.workplace.list.CmsListSearchAction; import org.opencms.workplace.list.I_CmsListDirectAction; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.PageContext; /** * Newsletter organization units management view.<p> * * @author Michael Moossen * @author Andreas Zahner * * @version $Revision: 1.7 $ * * @since 7.0.3 */ public class CmsOrgUnitsAdminList extends org.opencms.workplace.tools.accounts.CmsOrgUnitsAdminList { /** Parth to the newsletter buttons. */ public static final String PATH_NL_BUTTONS = "tools/v8-newsletter/buttons/"; /** * Public constructor.<p> * * @param jsp an initialized JSP action element */ public CmsOrgUnitsAdminList(CmsJspActionElement jsp) { super(jsp); getList().setName(Messages.get().container(Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_NAME_0)); } /** * Public constructor with JSP variables.<p> * * @param context the JSP page context * @param req the JSP request * @param res the JSP response */ public CmsOrgUnitsAdminList(PageContext context, HttpServletRequest req, HttpServletResponse res) { this(new CmsJspActionElement(context, req, res)); } /** * @see org.opencms.workplace.tools.accounts.A_CmsOrgUnitsList#getGroupIcon() */ public String getGroupIcon() { return PATH_NL_BUTTONS + "v8-mailinglist.png"; } /** * @see org.opencms.workplace.tools.accounts.CmsOrgUnitsAdminList#getOverviewIcon() */ public String getOverviewIcon() { return PATH_NL_BUTTONS + "v8-newsletter_overview.png"; } /** * @see org.opencms.workplace.tools.accounts.A_CmsOrgUnitsList#getUserIcon() */ public String getUserIcon() { return PATH_NL_BUTTONS + "v8-subscriber.png"; } /** * @see org.opencms.workplace.tools.accounts.CmsOrgUnitsAdminList#hasMoreAdminOUs() */ public boolean hasMoreAdminOUs() throws CmsException { boolean result = super.hasMoreAdminOUs(); // delete default group "Users" Iterator it = CmsNewsletterManager.getOrgUnits(getCms()).iterator(); while (it.hasNext()) { CmsOrganizationalUnit ou = (CmsOrganizationalUnit)it.next(); String groupName = ou.getName() + OpenCms.getDefaultUsers().getGroupUsers(); try { getCms().readGroup(groupName); // in order to delete a group, we have to switch to an offline project CmsObject cms = OpenCms.initCmsObject(getCms()); String projectName = OpenCms.getModuleManager().getModule(CmsNewsletterManager.MODULE_NAME).getParameter( CmsNewsletterManager.MODULE_PARAM_PROJECT_NAME, "Offline"); CmsProject project = cms.readProject(projectName); cms.getRequestContext().setCurrentProject(project); getCms().deleteGroup(groupName); } catch (Exception e) { // ok } } return result; } /** * @see org.opencms.workplace.tools.accounts.CmsOrgUnitsAdminList#getForwardToolPath() */ protected String getForwardToolPath() { return "/v8-newsletter/orgunit"; } /** * @see org.opencms.workplace.tools.accounts.CmsOrgUnitsAdminList#getGroupsToolPath() */ protected String getGroupsToolPath() { return getCurrentToolPath() + "/orgunit/mailinglists"; } /** * @see org.opencms.workplace.tools.accounts.A_CmsOrgUnitsList#getOrgUnits() */ protected List getOrgUnits() throws CmsException { return CmsNewsletterManager.getOrgUnits(getCms()); } /** * @see org.opencms.workplace.tools.accounts.CmsOrgUnitsAdminList#getUsersToolPath() */ protected String getUsersToolPath() { return getCurrentToolPath() + "/orgunit/subscribers"; } /** * @see org.opencms.workplace.tools.accounts.CmsOrgUnitsAdminList#setColumns(org.opencms.workplace.list.CmsListMetadata) */ protected void setColumns(CmsListMetadata metadata) { super.setColumns(metadata); CmsListColumnDefinition overviewCol = metadata.getColumnDefinition(LIST_COLUMN_OVERVIEW); overviewCol.setName(Messages.get().container(Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_COLS_OVERVIEW_0)); overviewCol.setHelpText(Messages.get().container( Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_COLS_OVERVIEW_HELP_0)); overviewCol.removeDirectAction(LIST_ACTION_OVERVIEW); I_CmsListDirectAction overviewAction = new CmsListDirectAction(LIST_ACTION_OVERVIEW); overviewAction.setName(Messages.get().container( Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_ACTION_OVERVIEW_NAME_0)); overviewAction.setHelpText(Messages.get().container( Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_COLS_OVERVIEW_HELP_0)); overviewAction.setIconPath(getOverviewIcon()); overviewCol.addDirectAction(overviewAction); CmsListColumnDefinition subscribersCol = metadata.getColumnDefinition(LIST_COLUMN_USER); subscribersCol.setName(Messages.get().container(Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_COLS_USER_0)); subscribersCol.setHelpText(Messages.get().container( Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_COLS_USER_HELP_0)); I_CmsListDirectAction subscribersAction = subscribersCol.getDirectAction(LIST_ACTION_USER); subscribersAction.setName(Messages.get().container( Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_ACTION_USER_NAME_0)); subscribersAction.setHelpText(Messages.get().container( Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_COLS_USER_HELP_0)); CmsListColumnDefinition mailinglistsCol = metadata.getColumnDefinition(LIST_COLUMN_GROUP); mailinglistsCol.setName(Messages.get().container(Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_COLS_GROUP_0)); mailinglistsCol.setHelpText(Messages.get().container( Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_COLS_GROUP_HELP_0)); I_CmsListDirectAction mailinglistsAction = mailinglistsCol.getDirectAction(LIST_ACTION_GROUP); mailinglistsAction.setName(Messages.get().container( Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_ACTION_GROUP_NAME_0)); mailinglistsAction.setHelpText(Messages.get().container( Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_COLS_GROUP_HELP_0)); CmsListColumnDefinition descriptionCol = metadata.getColumnDefinition(LIST_COLUMN_DESCRIPTION); CmsListDefaultAction defAction = descriptionCol.getDefaultAction(LIST_DEFACTION_OVERVIEW); defAction.setName(Messages.get().container( Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_DEFACTION_OVERVIEW_NAME_0)); defAction.setHelpText(Messages.get().container( Messages.GUI_ALK_V8_NEWSLETTER_ORGUNITS_LIST_COLS_OVERVIEW_HELP_0)); } /** * @see org.opencms.workplace.tools.accounts.A_CmsOrgUnitsList#setIndependentActions(org.opencms.workplace.list.CmsListMetadata) */ protected void setIndependentActions(CmsListMetadata metadata) { // add mailing lists details CmsListItemDetails mailinglistsDetails = new CmsListItemDetails(LIST_DETAIL_GROUPS); mailinglistsDetails.setAtColumn(LIST_COLUMN_DESCRIPTION); mailinglistsDetails.setVisible(false); mailinglistsDetails.setShowActionName(Messages.get().container( Messages.GUI_ORGUNITS_DETAIL_SHOW_ALK_V8_MAILINGLISTS_NAME_0)); mailinglistsDetails.setShowActionHelpText(Messages.get().container( Messages.GUI_ORGUNITS_DETAIL_SHOW_ALK_V8_MAILINGLISTS_HELP_0)); mailinglistsDetails.setHideActionName(Messages.get().container( Messages.GUI_ORGUNITS_DETAIL_HIDE_ALK_V8_MAILINGLISTS_NAME_0)); mailinglistsDetails.setHideActionHelpText(Messages.get().container( Messages.GUI_ORGUNITS_DETAIL_HIDE_ALK_V8_MAILINGLISTS_HELP_0)); mailinglistsDetails.setName(Messages.get().container(Messages.GUI_ORGUNITS_DETAIL_ALK_V8_MAILINGLISTS_NAME_0)); mailinglistsDetails.setFormatter(new CmsListItemDetailsFormatter(Messages.get().container( Messages.GUI_ORGUNITS_DETAIL_ALK_V8_MAILINGLISTS_NAME_0))); metadata.addItemDetails(mailinglistsDetails); // makes the list searchable CmsListSearchAction searchAction = new CmsListSearchAction(metadata.getColumnDefinition(LIST_COLUMN_NAME)); searchAction.addColumn(metadata.getColumnDefinition(LIST_COLUMN_DESCRIPTION)); metadata.setSearchAction(searchAction); } }
gpl-3.0
guci314/playorm
src/main/java/com/alvazan/orm/layer9z/spi/db/mongodb/MongoDbUtil.java
2968
package com.alvazan.orm.layer9z.spi.db.mongodb; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Set; import com.alvazan.orm.api.z8spi.Key; import com.alvazan.orm.api.z8spi.Row; import com.alvazan.orm.api.z8spi.action.Column; import com.alvazan.orm.api.z8spi.action.IndexColumn; import com.alvazan.orm.api.z8spi.conv.StandardConverters; import com.alvazan.orm.api.z8spi.meta.DboColumnMeta; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; public class MongoDbUtil { static void processColumns(DBObject mdbRow, Row r) { Set<String> columns = mdbRow.keySet(); for (String col : columns) { if(!col.equalsIgnoreCase("_id")) { byte[] name = StandardConverters.convertFromString(byte[].class, col); byte[] val = StandardConverters.convertToBytes(mdbRow.get(col)); Column c = new Column(); c.setName(name); if (val.length != 0) c.setValue(val); r.put(c); } } } public static IndexColumn convertToIndexCol(DBObject col) { Object indValue = col.get("k"); Object pk = col.get("v"); IndexColumn c = new IndexColumn(); // c.setColumnName(columnName); Will we ever need this now? if (pk != null) { c.setPrimaryKey((byte[]) pk); } if (indValue != null) { c.setIndexedValue(StandardConverters.convertToBytes(indValue)); } c.setValue(null); return c; } public static BasicDBObject createRowQuery(Key from, Key to, DboColumnMeta colMeta) { BasicDBObject query = new BasicDBObject(); Object valFrom = null, valTo = null; if (colMeta != null) { if (from != null) { valFrom = colMeta.getStorageType().convertFromNoSql(from.getKey()); valFrom = checkForBigDecimal(valFrom); } if (to != null) { valTo = colMeta.getStorageType().convertFromNoSql(to.getKey()); valTo = checkForBigDecimal(valTo); } } else return query; if (from != null) { if (from.isInclusive()) query.append("$gte", valFrom); else query.append("$gt", valFrom); } if (to != null) { if (to.isInclusive()) query.append("$lte", valTo); else query.append("$lt", valTo); } return query; } public static Object checkForBigDecimal(Object val) { // This is a hack as MongoDb doesn't support BigDecimal. See https://jira.mongodb.org/browse/SCALA-23 if (val instanceof BigDecimal) { BigDecimal bigDec = (BigDecimal) val; return bigDec.doubleValue(); } if (val instanceof Boolean) { Boolean b = (Boolean) val; if (b) return 1; else return 0; } return val; } public static BasicDBObject createRowQueryFromValues(List<byte[]> values, DboColumnMeta colMeta) { BasicDBObject query = new BasicDBObject(); List<Object> valObjList = new ArrayList<Object>(); for (byte[] val : values) { Object valObj = colMeta.getStorageType().convertFromNoSql(val); valObj = checkForBigDecimal(valObj); valObjList.add(valObj); } query.put("$in", valObjList); return query; } }
mpl-2.0
servinglynk/hmis-lynk-open-source
hmis-model-v2014/src/main/java/com/servinglynk/hmis/warehouse/dao/SyncListDao.java
333
package com.servinglynk.hmis.warehouse.dao; import java.util.List; import com.servinglynk.hmis.warehouse.model.v2014.Sync; public interface SyncListDao extends ParentDao { public void addSync(Sync sync); public Sync getSync(String id); public List<Sync> getSyncs(); public Sync findLastSync(String status); }
mpl-2.0
jembi/openhim-encounter-orchestrator
src/main/java/org/hl7/v3/TransmucosalRoute.java
705
package org.hl7.v3; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for TransmucosalRoute. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="TransmucosalRoute"> * &lt;restriction base="{urn:hl7-org:v3}cs"> * &lt;enumeration value="TMUCTA"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "TransmucosalRoute") @XmlEnum public enum TransmucosalRoute { TMUCTA; public String value() { return name(); } public static TransmucosalRoute fromValue(String v) { return valueOf(v); } }
mpl-2.0
auroreallibe/Silverpeas-Core
core-web/src/test-awaiting/java/com/silverpeas/pdc/web/matchers/ClassifyPositionMatcher.java
3441
/* * Copyright (C) 2000 - 2016 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.pdc.web.matchers; import com.stratelia.silverpeas.pdc.model.ClassifyPosition; import com.stratelia.silverpeas.pdc.model.ClassifyValue; import java.util.Collections; import java.util.List; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * A matcher of Classify objects to be used in unit tests. */ public class ClassifyPositionMatcher extends TypeSafeMatcher<List<ClassifyPosition>> { private List<ClassifyPosition> expectedPositions; private String whatIsExpected = ""; @Factory public static Matcher<List<ClassifyPosition>> equalTo(final List<ClassifyPosition> expected) { return new ClassifyPositionMatcher().withExpectedClassifyPositions(expected); } @Override protected boolean matchesSafely(List<ClassifyPosition> actualPositions) { boolean matches = true; if (actualPositions.size() != expectedPositions.size()) { matches = false; } else { Collections.reverse(actualPositions); for (int p = 0; p < actualPositions.size(); p++) { List<ClassifyValue> actualValues = actualPositions.get(p).getListClassifyValue(); List<ClassifyValue> expectedValues = expectedPositions.get(p).getListClassifyValue(); if (actualValues.size() != expectedValues.size()) { matches = false; } else { for (int v = 0; v < actualValues.size(); v++) { ClassifyValue actual = actualValues.get(v); ClassifyValue expected = expectedValues.get(v); if (actual.getAxisId() != expected.getAxisId()) { matches = false; break; } if (!actual.getValue().equals(expected.getValue())) { matches = false; break; } } } } } if (!matches) { whatIsExpected = expectedPositions.toString(); } return matches; } @Override public void describeTo(Description description) { description.appendText(whatIsExpected); } private ClassifyPositionMatcher() { } protected ClassifyPositionMatcher withExpectedClassifyPositions( final List<ClassifyPosition> positions) { this.expectedPositions = positions; return this; } }
agpl-3.0
aborg0/RapidMiner-Unuk
src/com/rapidminer/gui/actions/OpenAction.java
7503
/* * RapidMiner * * Copyright (C) 2001-2013 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.actions; import java.awt.event.ActionEvent; import java.io.IOException; import com.rapidminer.Process; import com.rapidminer.ProcessLocation; import com.rapidminer.RepositoryProcessLocation; import com.rapidminer.gui.RapidMinerGUI; import com.rapidminer.gui.tools.ProgressThread; import com.rapidminer.gui.tools.ResourceAction; import com.rapidminer.gui.tools.SwingTools; import com.rapidminer.gui.tools.dialogs.ConfirmDialog; import com.rapidminer.operator.ResultObject; import com.rapidminer.repository.Entry; import com.rapidminer.repository.IOObjectEntry; import com.rapidminer.repository.MalformedRepositoryLocationException; import com.rapidminer.repository.ProcessEntry; import com.rapidminer.repository.RepositoryException; import com.rapidminer.repository.RepositoryLocation; import com.rapidminer.repository.gui.RepositoryLocationChooser; import com.rapidminer.tools.XMLException; /** * Start the corresponding action. * * @author Ingo Mierswa */ public class OpenAction extends ResourceAction { private static final long serialVersionUID = -323403851840397447L; public OpenAction() { super("open"); setCondition(EDIT_IN_PROGRESS, DONT_CARE); } @Override public void actionPerformed(ActionEvent e) { open(); } /** Loads the data held by the given entry (in the background) and opens it as a result. */ public static void showAsResult(final IOObjectEntry data) { if (data == null) { throw new IllegalArgumentException("data entry must not be null"); } final ProgressThread downloadProgressThread = new ProgressThread("download_from_repository") { @Override public void run() { try { ResultObject result = (ResultObject)data.retrieveData(this.getProgressListener()); if (isCancelled()) { return; } result.setSource(data.getLocation().toString()); RapidMinerGUI.getMainFrame().getResultDisplay().showResult(result); } catch (Exception e1) { SwingTools.showSimpleErrorMessage("cannot_fetch_data_from_repository", e1); } } }; downloadProgressThread.start(); } public static void open() { if (RapidMinerGUI.getMainFrame().close()) { String locationString = RepositoryLocationChooser.selectLocation(null, null, RapidMinerGUI.getMainFrame(), true, false); if (locationString != null) { try { RepositoryLocation location = new RepositoryLocation(locationString); Entry entry = location.locateEntry(); if (entry instanceof ProcessEntry) { open(new RepositoryProcessLocation(location), true); } else if (entry instanceof IOObjectEntry) { showAsResult((IOObjectEntry) entry); } else { SwingTools.showVerySimpleErrorMessage("no_data_or_process"); } } catch (MalformedRepositoryLocationException e) { SwingTools.showSimpleErrorMessage("while_loading", e, locationString, e.getMessage()); } catch (RepositoryException e) { SwingTools.showSimpleErrorMessage("while_loading", e, locationString, e.getMessage()); } } } } /** * This method will open the process specified by the process location. If showInfo is true, the description of the * process will be shown depending on the fact if this feature is enabled or disabled in the settings. So if * you don't want to silently load a process, this should be true. */ public static void open(final ProcessLocation processLocation, final boolean showInfo) { // ask for confirmation before stopping the currently running process and opening another one! if (RapidMinerGUI.getMainFrame().getProcessState() == Process.PROCESS_STATE_RUNNING || RapidMinerGUI.getMainFrame().getProcessState() == Process.PROCESS_STATE_PAUSED) { if (SwingTools.showConfirmDialog("close_running_process", ConfirmDialog.YES_NO_OPTION) == ConfirmDialog.NO_OPTION) { return; } } RapidMinerGUI.getMainFrame().stopProcess(); ProgressThread openProgressThread = new ProgressThread("open_file") { @Override public void run() { getProgressListener().setTotal(100); getProgressListener().setCompleted(10); try { Process process = processLocation.load(getProgressListener()); if (isCancelled()) { return; } process.setProcessLocation(processLocation); if (isCancelled()) { return; } RapidMinerGUI.getMainFrame().setOpenedProcess(process, showInfo, processLocation.toString()); } catch (XMLException ex) { try { RapidMinerGUI.getMainFrame().handleBrokenProxessXML(processLocation, processLocation.getRawXML(), ex); } catch (IOException e) { SwingTools.showSimpleErrorMessage("while_loading", e, processLocation, e.getMessage()); return; } } catch (Exception e) { SwingTools.showSimpleErrorMessage("while_loading", e, processLocation, e.getMessage()); return; } finally { getProgressListener().complete(); } } }; openProgressThread.start(); } public static void open(String openLocation, boolean showInfo) { try { final RepositoryLocation location = new RepositoryLocation(openLocation); Entry entry = location.locateEntry(); if (entry instanceof ProcessEntry) { open(new RepositoryProcessLocation(location), showInfo); } else if (entry instanceof IOObjectEntry){ OpenAction.showAsResult((IOObjectEntry) entry); } else { throw new RepositoryException("Cannot open entries of type "+entry.getType()+"."); } } catch (Exception e) { SwingTools.showSimpleErrorMessage("while_loading", e, openLocation, e.getMessage()); } } }
agpl-3.0
timoc/scaliendb
src/Application/Client/Java/ByteRangeParams.java
3154
package com.scalien.scaliendb; /** * ByteRangeParams is a convenient way to specify the byte[] parameters * for iteration when using * <a href="Table.html#getKeyIterator(com.scalien.scaliendb.ByteRangeParams)">Table.getKeyIterator(ByteRangeParams)</a>, * <a href="Table.html#getKeyValueIterator(com.scalien.scaliendb.ByteRangeParams)">Table.getKeyValueIterator(ByteRangeParams)</a> and * <a href="Table.html#count(com.scalien.scaliendb.ByteRangeParams)">Table.count(ByteRangeParams)</a>. * <p> * The supported parameters are: * <ul> * <li>prefix</li> * <li>start key</li> * <li>end key</li> * <li>count</li> * <li>direction</li> * </ul> * <p> * ByteRangeParams is convenient because is uses chaining, so you can write * expressions like <code>new ByteRangeParams().prefix(prefix).startKey(startKey).endKey(endKey).count(count)</code> * and it returns the ByteIterParam instance. Optionally call .backward() to get a backward iterator. * <p> * The default values are empty byte arrays and forward iteration. * <p> * @see Table#getKeyIterator(ByteRangeParams) * @see Table#getKeyValueIterator(ByteRangeParams) * @see Table#count(ByteRangeParams) */public class ByteRangeParams { public byte[] prefix = new byte[0]; public byte[] startKey = new byte[0]; public byte[] endKey = new byte[0]; public int count = -1; public boolean forwardDirection = true; /** * Specify the prefix parameter for iteration. * <p>Only keys starting with prefix will be returned by the iteration. * @param prefix The prefix parameter as a byte[]. * @return The ByteRangeParams instance, useful for chaining. */ public ByteRangeParams prefix(byte[] prefix) { this.prefix = prefix; return this; } /** * Specify the start key parameter for iteration. * <p>Iteration will start at start key, or the first key greater than start key. * @param startKey The start key parameter as a byte[]. * @return The ByteRangeParams instance, useful for chaining. */ public ByteRangeParams startKey(byte[] startKey) { this.startKey = startKey; return this; } /** * Specify the end key parameter for iteration * <p>Iteration will stop at end key, or the first key greater than end key. * @param endKey The end key parameter as a byte[]. * @return The ByteRangeParams instance, useful for chaining. */ public ByteRangeParams endKey(byte[] endKey) { this.endKey = endKey; return this; } /** * Specify the count parameter for iteration * <p>Iteration will stop after count elements. * @param count The count parameter. * @return The ByteRangeParams instance, useful for chaining. */ public ByteRangeParams count(int count) { this.count = count; return this; } /** * Iteration will proceed backwards * @return The StringRangeParams instance, useful for chaining. */ public ByteRangeParams backward() { this.forwardDirection = false; return this; } }
agpl-3.0
teoincontatto/engine
mongodb/mongodb-core/src/main/java/com/torodb/mongodb/commands/signatures/internal/ReplSetUpdatePositionCommand.java
7995
/* * ToroDB * Copyright © 2014 8Kdata Technology (www.8kdata.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.torodb.mongodb.commands.signatures.internal; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.torodb.mongodb.commands.pojos.MemberConfig; import com.torodb.mongodb.commands.signatures.internal.ReplSetUpdatePositionCommand.ReplSetUpdatePositionArgument; import com.torodb.mongodb.utils.DefaultIdUtils; import com.torodb.mongowp.OpTime; import com.torodb.mongowp.bson.BsonArray; import com.torodb.mongowp.bson.BsonDocument; import com.torodb.mongowp.bson.BsonObjectId; import com.torodb.mongowp.bson.BsonValue; import com.torodb.mongowp.commands.impl.AbstractNotAliasableCommand; import com.torodb.mongowp.commands.tools.Empty; import com.torodb.mongowp.exceptions.BadValueException; import com.torodb.mongowp.exceptions.NoSuchKeyException; import com.torodb.mongowp.exceptions.TypesMismatchException; import com.torodb.mongowp.fields.ArrayField; import com.torodb.mongowp.fields.DocField; import com.torodb.mongowp.fields.LongField; import com.torodb.mongowp.fields.ObjectIdField; import com.torodb.mongowp.fields.TimestampField; import com.torodb.mongowp.utils.BsonArrayBuilder; import com.torodb.mongowp.utils.BsonDocumentBuilder; import com.torodb.mongowp.utils.BsonReaderTool; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; //TODO: this command is not compatible with MongoDB 3.2.4+ public class ReplSetUpdatePositionCommand extends AbstractNotAliasableCommand<ReplSetUpdatePositionArgument, Empty> { public static final ReplSetUpdatePositionCommand INSTANCE = new ReplSetUpdatePositionCommand(); private static final String COMMAND_FIELD_NAME = "replSetUpdatePosition"; private ReplSetUpdatePositionCommand() { super(COMMAND_FIELD_NAME); } @Override public Class<? extends ReplSetUpdatePositionArgument> getArgClass() { return ReplSetUpdatePositionArgument.class; } @Override public ReplSetUpdatePositionArgument unmarshallArg(BsonDocument requestDoc) throws TypesMismatchException, NoSuchKeyException, BadValueException { return ReplSetUpdatePositionArgument.unmarshall(requestDoc); } @Override public BsonDocument marshallArg(ReplSetUpdatePositionArgument request) { return request.marshall(); } @Override public Class<? extends Empty> getResultClass() { return Empty.class; } @Override public BsonDocument marshallResult(Empty reply) { return null; } @Override public Empty unmarshallResult(BsonDocument resultDoc) { return Empty.getInstance(); } public static class ReplSetUpdatePositionArgument { private static final ArrayField UPDATE_ARRAY_FIELD = new ArrayField("optimes"); private static final ImmutableSet<String> VALID_FIELD_NAMES = ImmutableSet.of( COMMAND_FIELD_NAME, UPDATE_ARRAY_FIELD.getFieldName() ); private final ImmutableList<UpdateInfo> updates; public ReplSetUpdatePositionArgument( @Nonnull List<UpdateInfo> updates) { this.updates = ImmutableList.copyOf(updates); } @Nonnull public ImmutableList<UpdateInfo> getUpdates() throws IllegalStateException { return updates; } private static ReplSetUpdatePositionArgument unmarshall(BsonDocument doc) throws TypesMismatchException, NoSuchKeyException, BadValueException { if (doc.containsKey("handshake")) { throw new IllegalArgumentException("A handshake command wrapped " + "inside a replSetUpdatePosition has been recived, but it " + "has been treated by the replSetUpdatePosition command"); } BsonReaderTool.checkOnlyHasFields("UpdateInfoArgs", doc, VALID_FIELD_NAMES); ImmutableList.Builder<UpdateInfo> updateInfo = ImmutableList.builder(); BsonArray updateArray = BsonReaderTool.getArray(doc, UPDATE_ARRAY_FIELD); for (BsonValue<?> element : updateArray) { updateInfo.add(new UpdateInfo(element.asDocument())); } return new ReplSetUpdatePositionArgument(updateInfo.build()); } private BsonDocument marshall() { BsonDocumentBuilder updateInfo = new BsonDocumentBuilder(); BsonArrayBuilder updatesBuilder = new BsonArrayBuilder(updates.size()); for (UpdateInfo update : updates) { updatesBuilder.add(update.marshall()); } updateInfo.append(UPDATE_ARRAY_FIELD, updatesBuilder.build()); return updateInfo.build(); } public static class UpdateInfo { private static final ObjectIdField MEMBER_RID_FIELD = new ObjectIdField(DefaultIdUtils.ID_KEY); private static final DocField MEMBER_CONFIG_FIELD = new DocField("config"); private static final TimestampField OP_TIME_FIELD = new TimestampField("optime"); private static final LongField MEMBER_ID_FIELD = new LongField("memberId"); private static final LongField CONFIG_VERSION_FIELD = new LongField("cfgver"); private static final ImmutableSet<String> VALID_FIELD_NAMES = ImmutableSet.of( MEMBER_RID_FIELD.getFieldName(), MEMBER_CONFIG_FIELD.getFieldName(), OP_TIME_FIELD.getFieldName(), MEMBER_ID_FIELD.getFieldName(), CONFIG_VERSION_FIELD.getFieldName() ); private final BsonObjectId rid; private final OpTime ts; private final long cfgVer; private final long memberId; @Nullable private final MemberConfig config; public UpdateInfo(BsonObjectId rid, OpTime ts, long cfgVer, long memberId, MemberConfig config) { this.rid = rid; this.ts = ts; this.cfgVer = cfgVer; this.memberId = memberId; this.config = config; } public UpdateInfo(BsonDocument doc) throws BadValueException, TypesMismatchException, NoSuchKeyException { BsonReaderTool.checkOnlyHasFields("UpdateInfoArgs", doc, VALID_FIELD_NAMES); ts = new OpTime(BsonReaderTool.getTimestamp(doc, OP_TIME_FIELD)); cfgVer = BsonReaderTool.getLong(doc, CONFIG_VERSION_FIELD, -1); rid = BsonReaderTool.getObjectId(doc, MEMBER_RID_FIELD, null); memberId = BsonReaderTool.getLong(doc, MEMBER_ID_FIELD, -1); BsonDocument configDoc = BsonReaderTool.getDocument(doc, MEMBER_CONFIG_FIELD, null); if (configDoc != null) { this.config = MemberConfig.fromDocument(configDoc); } else { this.config = null; } } public BsonObjectId getRid() { return rid; } public OpTime getTs() { return ts; } public long getCfgVer() { return cfgVer; } public long getMemberId() { return memberId; } @Nullable public MemberConfig getConfig() { return config; } private BsonDocument marshall() { BsonDocumentBuilder updateInfo = new BsonDocumentBuilder(); updateInfo.append(MEMBER_RID_FIELD, rid); updateInfo.append(OP_TIME_FIELD, ts.getTimestamp()); updateInfo.append(MEMBER_ID_FIELD, memberId); updateInfo.append(CONFIG_VERSION_FIELD, cfgVer); if (config != null) { updateInfo.append(MEMBER_CONFIG_FIELD, config.toBson()); } return updateInfo.build(); } } } }
agpl-3.0
AlienQueen/alienlabs-skeleton-for-wicket-spring-hibernate
lib/fmj/src/net/sf/fmj/media/protocol/httpauth/DataSource.java
6459
package net.sf.fmj.media.protocol.httpauth; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import java.util.logging.Logger; import javax.media.MediaLocator; import javax.media.Time; import javax.media.protocol.ContentDescriptor; import javax.media.protocol.PullDataSource; import javax.media.protocol.PullSourceStream; import javax.media.protocol.SourceCloneable; import net.sf.fmj.utility.LoggerSingleton; import net.sf.fmj.utility.StringUtils; /** * This is a pseudo-protocol that allows the username and password for an http datasource to be specified in the URL. * Copied and modified from URLDataSource. * The syntax for an httpauth URL is derived from an http URL as follows: * http://myipcameraimage.com/cam * with username "user" and password "pass" would become * httpauth:user:pass@//myipcameraimage.com/cam * This is simply a convenience data source. It allows things like FMJ studio to play IP camera streams that are password protected, without having to prompt the user. * * @author Ken Larson * */ public class DataSource extends PullDataSource implements SourceCloneable { private static final Logger logger = LoggerSingleton.logger; private URLConnection conn; private boolean connected = false; private String contentTypeStr; private ContentDescriptor contentType; protected URLSourceStream[] sources; public DataSource() { super(); } public DataSource(URL url) { setLocator(new MediaLocator(url)); } public javax.media.protocol.DataSource createClone() { final DataSource d; try { d = new DataSource(getLocator().getURL()); } catch (MalformedURLException e) { logger.log(Level.WARNING, "" + e, e); return null; // according to the API, return null on failure. } if (connected) { try { d.connect(); } catch (IOException e) { logger.log(Level.WARNING, "" + e, e); return null; // according to the API, return null on failure. } } return d; } public PullSourceStream[] getStreams() { if (!connected) throw new Error("Unconnected source."); return sources; } /** Strips trailing ; and anything after it. Is generally only used for multipart content. */ private String stripTrailer(String contentType) { final int index = contentType.indexOf(";"); if (index < 0) return contentType; final String result = contentType.substring(0, index); return result; } public void connect() throws IOException { // we allow a re-connection even if we are connected, due to an oddity in the way Manager works. See comments there // in createPlayer(MediaLocator sourceLocator). // // if (connected) // return; // example: httpauth:guest:guest@// + real url without http: final String remainder = getLocator().getRemainder(); final int atIndex = remainder.indexOf('@'); if (atIndex < 0) throw new IOException("Invalid httpauth url: expected: @"); final int colonIndex = remainder.indexOf(':'); if (colonIndex < 0 || colonIndex > atIndex) throw new IOException("Invalid httpaut url: expected: :"); final String user = remainder.substring(0, colonIndex); final String pass = remainder.substring(colonIndex + 1, atIndex); final String realUrlStr = "http:" + getLocator().getRemainder().substring(atIndex + 1); conn = new URL(realUrlStr).openConnection(); if (conn instanceof HttpURLConnection) { // TODO: this is probably why JMF has explicit HTTP and FTP data sources - so we can check things explicitly. final HttpURLConnection huc = (HttpURLConnection) conn; if (user != null && !user.equals("")) { huc.setRequestProperty("Authorization", "Basic " + StringUtils.byteArrayToBase64String((user + ":" + pass).getBytes())); } huc.connect(); final int code = huc.getResponseCode(); if (!(code >= 200 && code < 300)) { huc.disconnect(); throw new IOException("HTTP response code: " + code); } // TODO: what is the right place to apply ContentDescriptor.mimeTypeToPackageName? contentTypeStr = ContentDescriptor.mimeTypeToPackageName(stripTrailer(conn.getContentType())); } else { conn.connect(); // TODO: what is the right place to apply ContentDescriptor.mimeTypeToPackageName? contentTypeStr = ContentDescriptor.mimeTypeToPackageName(conn.getContentType()); } contentType = new ContentDescriptor(contentTypeStr); sources = new URLSourceStream[1]; sources[0] = new URLSourceStream(); connected = true; } public String getContentType() { return contentTypeStr; } public void disconnect() { if (!connected) return; if (conn != null) { if (conn instanceof HttpURLConnection) { final HttpURLConnection huc = (HttpURLConnection) conn; huc.disconnect(); } // TODO: others } connected = false; } public void start() throws java.io.IOException { //throw new UnsupportedOperationException(); // TODO - what to do? } public void stop() throws java.io.IOException { //throw new UnsupportedOperationException(); // TODO - what to do? } public Time getDuration() { return Time.TIME_UNKNOWN; // TODO: any case where we know the duration? } public Object[] getControls() { return new Object[0]; } public Object getControl(String controlName) { return null; } class URLSourceStream implements PullSourceStream { private boolean endOfStream = false; public boolean endOfStream() { return endOfStream; } public ContentDescriptor getContentDescriptor() { return contentType; } public long getContentLength() { return conn.getContentLength(); // returns -1 if unknown, which is the same as LENGTH_UNKNOWN } public int read(byte[] buffer, int offset, int length) throws IOException { final int result = conn.getInputStream().read(buffer, offset, length); // TODO: does this handle the requirement of not returning 0 unless passed in 0? if (result == -1) // end of stream endOfStream = true; return result; } public boolean willReadBlock() { try { return conn.getInputStream().available() <= 0; } catch (IOException e) { return true; } } public Object getControl(String controlType) { return null; } public Object[] getControls() { return new Object[0]; } } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/clinicaladmin/vo/beans/TumourSerumMarkersVoBean.java
4395
//############################################################################# //# # //# 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.clinicaladmin.vo.beans; public class TumourSerumMarkersVoBean extends ims.vo.ValueObjectBean { public TumourSerumMarkersVoBean() { } public TumourSerumMarkersVoBean(ims.clinicaladmin.vo.TumourSerumMarkersVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.serummarkervalue = vo.getSerumMarkerValue(); this.serummarkerdescription = vo.getSerumMarkerDescription(); this.isactive = vo.getIsActive(); this.taxonomymap = vo.getTaxonomyMap() == null ? null : vo.getTaxonomyMap().getBeanCollection(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.clinicaladmin.vo.TumourSerumMarkersVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.serummarkervalue = vo.getSerumMarkerValue(); this.serummarkerdescription = vo.getSerumMarkerDescription(); this.isactive = vo.getIsActive(); this.taxonomymap = vo.getTaxonomyMap() == null ? null : vo.getTaxonomyMap().getBeanCollection(); } public ims.clinicaladmin.vo.TumourSerumMarkersVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.clinicaladmin.vo.TumourSerumMarkersVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.clinicaladmin.vo.TumourSerumMarkersVo vo = null; if(map != null) vo = (ims.clinicaladmin.vo.TumourSerumMarkersVo)map.getValueObject(this); if(vo == null) { vo = new ims.clinicaladmin.vo.TumourSerumMarkersVo(); 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 String getSerumMarkerValue() { return this.serummarkervalue; } public void setSerumMarkerValue(String value) { this.serummarkervalue = value; } public String getSerumMarkerDescription() { return this.serummarkerdescription; } public void setSerumMarkerDescription(String value) { this.serummarkerdescription = value; } public Boolean getIsActive() { return this.isactive; } public void setIsActive(Boolean value) { this.isactive = value; } public ims.core.vo.beans.TaxonomyMapBean[] getTaxonomyMap() { return this.taxonomymap; } public void setTaxonomyMap(ims.core.vo.beans.TaxonomyMapBean[] value) { this.taxonomymap = value; } private Integer id; private int version; private String serummarkervalue; private String serummarkerdescription; private Boolean isactive; private ims.core.vo.beans.TaxonomyMapBean[] taxonomymap; }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/domain/AssessmentQuestionShortVoAssembler.java
21307
//############################################################################# //# # //# 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:23 * */ package ims.core.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Alexie Ursache */ public class AssessmentQuestionShortVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.core.vo.AssessmentQuestionShortVo copy(ims.core.vo.AssessmentQuestionShortVo valueObjectDest, ims.core.vo.AssessmentQuestionShortVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_AssessmentQuestion(valueObjectSrc.getID_AssessmentQuestion()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // isMandatory valueObjectDest.setIsMandatory(valueObjectSrc.getIsMandatory()); // ActiveStatus valueObjectDest.setActiveStatus(valueObjectSrc.getActiveStatus()); // Sequence valueObjectDest.setSequence(valueObjectSrc.getSequence()); // allowsMultipleAnswers valueObjectDest.setAllowsMultipleAnswers(valueObjectSrc.getAllowsMultipleAnswers()); // isNonStandard valueObjectDest.setIsNonStandard(valueObjectSrc.getIsNonStandard()); // URL valueObjectDest.setURL(valueObjectSrc.getURL()); // Protocol valueObjectDest.setProtocol(valueObjectSrc.getProtocol()); // LegendText valueObjectDest.setLegendText(valueObjectSrc.getLegendText()); 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 #createAssessmentQuestionShortVoCollectionFromAssessmentQuestion(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.assessment.configuration.domain.objects.AssessmentQuestion objects. */ public static ims.core.vo.AssessmentQuestionShortVoCollection createAssessmentQuestionShortVoCollectionFromAssessmentQuestion(java.util.Set domainObjectSet) { return createAssessmentQuestionShortVoCollectionFromAssessmentQuestion(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.assessment.configuration.domain.objects.AssessmentQuestion objects. */ public static ims.core.vo.AssessmentQuestionShortVoCollection createAssessmentQuestionShortVoCollectionFromAssessmentQuestion(DomainObjectMap map, java.util.Set domainObjectSet) { ims.core.vo.AssessmentQuestionShortVoCollection voList = new ims.core.vo.AssessmentQuestionShortVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.assessment.configuration.domain.objects.AssessmentQuestion domainObject = (ims.assessment.configuration.domain.objects.AssessmentQuestion) iterator.next(); ims.core.vo.AssessmentQuestionShortVo 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.assessment.configuration.domain.objects.AssessmentQuestion objects. */ public static ims.core.vo.AssessmentQuestionShortVoCollection createAssessmentQuestionShortVoCollectionFromAssessmentQuestion(java.util.List domainObjectList) { return createAssessmentQuestionShortVoCollectionFromAssessmentQuestion(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.assessment.configuration.domain.objects.AssessmentQuestion objects. */ public static ims.core.vo.AssessmentQuestionShortVoCollection createAssessmentQuestionShortVoCollectionFromAssessmentQuestion(DomainObjectMap map, java.util.List domainObjectList) { ims.core.vo.AssessmentQuestionShortVoCollection voList = new ims.core.vo.AssessmentQuestionShortVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.assessment.configuration.domain.objects.AssessmentQuestion domainObject = (ims.assessment.configuration.domain.objects.AssessmentQuestion) domainObjectList.get(i); ims.core.vo.AssessmentQuestionShortVo 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.assessment.configuration.domain.objects.AssessmentQuestion 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 extractAssessmentQuestionSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.AssessmentQuestionShortVoCollection voCollection) { return extractAssessmentQuestionSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractAssessmentQuestionSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.AssessmentQuestionShortVoCollection 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.core.vo.AssessmentQuestionShortVo vo = voCollection.get(i); ims.assessment.configuration.domain.objects.AssessmentQuestion domainObject = AssessmentQuestionShortVoAssembler.extractAssessmentQuestion(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.assessment.configuration.domain.objects.AssessmentQuestion 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 extractAssessmentQuestionList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.AssessmentQuestionShortVoCollection voCollection) { return extractAssessmentQuestionList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractAssessmentQuestionList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.AssessmentQuestionShortVoCollection 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.core.vo.AssessmentQuestionShortVo vo = voCollection.get(i); ims.assessment.configuration.domain.objects.AssessmentQuestion domainObject = AssessmentQuestionShortVoAssembler.extractAssessmentQuestion(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.assessment.configuration.domain.objects.AssessmentQuestion object. * @param domainObject ims.assessment.configuration.domain.objects.AssessmentQuestion */ public static ims.core.vo.AssessmentQuestionShortVo create(ims.assessment.configuration.domain.objects.AssessmentQuestion domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.assessment.configuration.domain.objects.AssessmentQuestion object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.core.vo.AssessmentQuestionShortVo create(DomainObjectMap map, ims.assessment.configuration.domain.objects.AssessmentQuestion domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.core.vo.AssessmentQuestionShortVo valueObject = (ims.core.vo.AssessmentQuestionShortVo) map.getValueObject(domainObject, ims.core.vo.AssessmentQuestionShortVo.class); if ( null == valueObject ) { valueObject = new ims.core.vo.AssessmentQuestionShortVo(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.assessment.configuration.domain.objects.AssessmentQuestion */ public static ims.core.vo.AssessmentQuestionShortVo insert(ims.core.vo.AssessmentQuestionShortVo valueObject, ims.assessment.configuration.domain.objects.AssessmentQuestion 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.assessment.configuration.domain.objects.AssessmentQuestion */ public static ims.core.vo.AssessmentQuestionShortVo insert(DomainObjectMap map, ims.core.vo.AssessmentQuestionShortVo valueObject, ims.assessment.configuration.domain.objects.AssessmentQuestion domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_AssessmentQuestion(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; // isMandatory valueObject.setIsMandatory( domainObject.isIsMandatory() ); // ActiveStatus ims.domain.lookups.LookupInstance instance2 = domainObject.getActiveStatus(); 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.PreActiveActiveInactiveStatus voLookup2 = new ims.core.vo.lookups.PreActiveActiveInactiveStatus(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color); ims.core.vo.lookups.PreActiveActiveInactiveStatus 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.PreActiveActiveInactiveStatus(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color)); parentVoLookup2 = parentVoLookup2.getParent(); parent2 = parent2.getParent(); } valueObject.setActiveStatus(voLookup2); } // Sequence valueObject.setSequence(domainObject.getSequence()); // allowsMultipleAnswers valueObject.setAllowsMultipleAnswers( domainObject.isAllowsMultipleAnswers() ); // isNonStandard valueObject.setIsNonStandard( domainObject.isIsNonStandard() ); // URL valueObject.setURL(domainObject.getURL()); // Protocol valueObject.setProtocol(domainObject.getProtocol()); // LegendText valueObject.setLegendText(domainObject.getLegendText()); 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.assessment.configuration.domain.objects.AssessmentQuestion extractAssessmentQuestion(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.AssessmentQuestionShortVo valueObject) { return extractAssessmentQuestion(domainFactory, valueObject, new HashMap()); } public static ims.assessment.configuration.domain.objects.AssessmentQuestion extractAssessmentQuestion(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.AssessmentQuestionShortVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_AssessmentQuestion(); ims.assessment.configuration.domain.objects.AssessmentQuestion domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.assessment.configuration.domain.objects.AssessmentQuestion)domMap.get(valueObject); } // ims.core.vo.AssessmentQuestionShortVo ID_AssessmentQuestion field is unknown domainObject = new ims.assessment.configuration.domain.objects.AssessmentQuestion(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_AssessmentQuestion()); if (domMap.get(key) != null) { return (ims.assessment.configuration.domain.objects.AssessmentQuestion)domMap.get(key); } domainObject = (ims.assessment.configuration.domain.objects.AssessmentQuestion) domainFactory.getDomainObject(ims.assessment.configuration.domain.objects.AssessmentQuestion.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_AssessmentQuestion()); domainObject.setIsMandatory(valueObject.getIsMandatory()); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value2 = null; if ( null != valueObject.getActiveStatus() ) { value2 = domainFactory.getLookupInstance(valueObject.getActiveStatus().getID()); } domainObject.setActiveStatus(value2); domainObject.setSequence(valueObject.getSequence()); domainObject.setAllowsMultipleAnswers(valueObject.getAllowsMultipleAnswers()); domainObject.setIsNonStandard(valueObject.getIsNonStandard()); //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.getURL() != null && valueObject.getURL().equals("")) { valueObject.setURL(null); } domainObject.setURL(valueObject.getURL()); //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.getProtocol() != null && valueObject.getProtocol().equals("")) { valueObject.setProtocol(null); } domainObject.setProtocol(valueObject.getProtocol()); //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.getLegendText() != null && valueObject.getLegendText().equals("")) { valueObject.setLegendText(null); } domainObject.setLegendText(valueObject.getLegendText()); return domainObject; } }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/domain/base/impl/BaseSpecialtyOutlierInpatientListImpl.java
3388
//############################################################################# //# # //# 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.domain.base.impl; import ims.domain.impl.DomainImpl; public abstract class BaseSpecialtyOutlierInpatientListImpl extends DomainImpl implements ims.core.domain.SpecialtyOutlierInpatientList, ims.domain.impl.Transactional { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") public void validatelistInpatientEpisodes(ims.core.resource.place.vo.LocationRefVo wardRefVo) { } @SuppressWarnings("unused") public void validategetInpatientEpisodeLite(ims.core.admin.pas.vo.InpatientEpisodeRefVo inpatRef) { } @SuppressWarnings("unused") public void validategetPendingTranfer(ims.core.admin.pas.vo.PendingTransfersRefVo pendingTransferRefVo) { } @SuppressWarnings("unused") public void validatecancelTransfer(ims.core.vo.PendingTransfersLiteVo voPending, ims.core.resource.place.vo.LocationRefVo wardRef) { } @SuppressWarnings("unused") public void validategetSelectedBedSpaceState(ims.core.layout.vo.BedSpaceRefVo bedSpaceRef) { } @SuppressWarnings("unused") public void validategetPatientShort(ims.core.patient.vo.PatientRefVo patientRef) { } @SuppressWarnings("unused") public void validategetCareContextByPasEvent(ims.core.admin.pas.vo.PASEventRefVo pasEventRef) { } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/Rules/src/ims/rules/forms/rulesedit/GenForm.java
25438
//############################################################################# //# # //# 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.rules.forms.rulesedit; import ims.framework.*; import ims.framework.controls.*; import ims.framework.enumerations.*; import ims.framework.utils.RuntimeAnchoring; public class GenForm extends FormBridge { private static final long serialVersionUID = 1L; public boolean canProvideData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).canProvideData(); } public boolean hasData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).hasData(); } public IReportField[] getData(IReportSeed[] reportSeeds) { return getData(reportSeeds, false); } public IReportField[] getData(IReportSeed[] reportSeeds, boolean excludeNulls) { return new ReportDataProvider(reportSeeds, this.getFormReportFields(), excludeNulls).getData(); } private void validateContext(ims.framework.Context context) { if(context == null) return; } public boolean supportsRecordedInError() { return false; } public ims.vo.ValueObject getRecordedInErrorVo() { return null; } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context) throws Exception { setContext(loader, form, appForm, factory, context, Boolean.FALSE, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context, Boolean skipContextValidation) throws Exception { setContext(loader, form, appForm, factory, context, skipContextValidation, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, ims.framework.Context context, Boolean skipContextValidation, Integer startControlID, ims.framework.utils.SizeInfo runtimeSize, ims.framework.Control control, Integer startTabIndex) throws Exception { if(loader == null); // this is to avoid eclipse warning only. if(factory == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(appForm == null) throw new RuntimeException("Invalid application form"); if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(control == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); this.context = context; this.componentIdentifier = startControlID.toString(); this.formInfo = form.getFormInfo(); this.globalContext = new GlobalContext(context); if(skipContextValidation == null || !skipContextValidation.booleanValue()) { validateContext(context); } super.setContext(form); ims.framework.utils.SizeInfo designSize = new ims.framework.utils.SizeInfo(848, 632); if(runtimeSize == null) runtimeSize = designSize; form.setWidth(runtimeSize.getWidth()); form.setHeight(runtimeSize.getHeight()); super.setFormReferences(FormReferencesFlyweightFactory.getInstance().create(Forms.class)); super.setGlobalContext(ContextBridgeFlyweightFactory.getInstance().create(GlobalContextBridge.class, context, false)); // Custom Controls ims.framework.CustomComponent instance1 = factory.getEmptyCustomComponent(); RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 0, 0, 848, 600, ims.framework.enumerations.ControlAnchoring.ALL); ims.framework.FormUiLogic m_cc1RuleEditorForm = loader.loadComponent(103206, appForm, startControlID * 10 + 1000, anchoringHelper1.getSize(), instance1, -1, skipContextValidation); //ims.framework.Control m_cc1RuleEditorControl = factory.getControl(CustomComponent.class, new Object[] { control, new Integer(startControlID.intValue() + 1000), new Integer(0), new Integer(0), new Integer(848), new Integer(600), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL, new Integer(-1), m_cc1RuleEditorForm, instance1 } ); ims.framework.Control m_cc1RuleEditorControl = factory.getControl(CustomComponent.class, new Object[] { control, new Integer(startControlID.intValue() + 1001), new Integer(anchoringHelper1.getX()), new Integer(anchoringHelper1.getY()), new Integer(anchoringHelper1.getWidth()), new Integer(anchoringHelper1.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.ALL, new Integer(-1), m_cc1RuleEditorForm, instance1, Boolean.FALSE } ); super.addControl(m_cc1RuleEditorControl); Menu[] menus1 = m_cc1RuleEditorForm.getForm().getRegisteredMenus(); for(int x = 0; x < menus1.length; x++) { form.registerMenu(menus1[x]); } // Button Controls RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 8, 600, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1002), new Integer(anchoringHelper2.getX()), new Integer(anchoringHelper2.getY()), new Integer(anchoringHelper2.getWidth()), new Integer(anchoringHelper2.getHeight()), new Integer(-1), ControlState.ENABLED, ControlState.HIDDEN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "New", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 88, 600, 75, 24, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1003), new Integer(anchoringHelper3.getX()), new Integer(anchoringHelper3.getY()), new Integer(anchoringHelper3.getWidth()), new Integer(anchoringHelper3.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.HIDDEN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Edit", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 168, 600, 160, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1004), new Integer(anchoringHelper4.getX()), new Integer(anchoringHelper4.getY()), new Integer(anchoringHelper4.getWidth()), new Integer(anchoringHelper4.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Preview Rule Code and XML", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper5 = new RuntimeAnchoring(designSize, runtimeSize, 688, 600, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1005), new Integer(anchoringHelper5.getX()), new Integer(anchoringHelper5.getY()), new Integer(anchoringHelper5.getWidth()), new Integer(anchoringHelper5.getHeight()), new Integer(-1), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Save", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper6 = new RuntimeAnchoring(designSize, runtimeSize, 768, 600, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1006), new Integer(anchoringHelper6.getX()), new Integer(anchoringHelper6.getY()), new Integer(anchoringHelper6.getWidth()), new Integer(anchoringHelper6.getHeight()), new Integer(-1), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Cancel", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // Link Controls RuntimeAnchoring anchoringHelper7 = new RuntimeAnchoring(designSize, runtimeSize, 704, 4, 104, 17, ims.framework.enumerations.ControlAnchoring.TOPRIGHT); super.addControl(factory.getControl(Link.class, new Object[] { control, new Integer(startControlID.intValue() + 1007), new Integer(anchoringHelper7.getX()), new Integer(anchoringHelper7.getY()), new Integer(anchoringHelper7.getWidth()), new Integer(anchoringHelper7.getHeight()), new Integer(-1), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPRIGHT,"Return to Rules List", Boolean.FALSE, null})); } public Forms getForms() { return (Forms)super.getFormReferences(); } public ims.rules.forms.ruleseditorcomponent.IComponent cc1RuleEditor() { return (ims.rules.forms.ruleseditorcomponent.IComponent)((ims.framework.cn.controls.CustomComponent)super.getControl(0)).getLogic(); } public void setcc1RuleEditorValueChangedEvent(ims.framework.delegates.ValueChanged delegate) { ((CustomComponent)super.getControl(0)).setValueChangedEvent(delegate); } public void setcc1RuleEditorVisible(boolean value) { ((ims.framework.Control)super.getControl(0)).setVisible(value); } public boolean iscc1RuleEditorVisible() { return ((ims.framework.Control)super.getControl(0)).isVisible(); } public void setcc1RuleEditorEnabled(boolean value) { ((ims.framework.Control)super.getControl(0)).setEnabled(value); } public boolean iscc1RuleEditorEnabled() { return ((ims.framework.Control)super.getControl(0)).isEnabled(); } public Button btnNew() { return (Button)super.getControl(1); } public Button btnEdit() { return (Button)super.getControl(2); } public Button btnPreview() { return (Button)super.getControl(3); } public Button btnSave() { return (Button)super.getControl(4); } public Button btnCancel() { return (Button)super.getControl(5); } public Link lnkReturn() { return (Link)super.getControl(6); } public static class Forms implements java.io.Serializable { private static final long serialVersionUID = 1L; protected final class LocalFormName extends FormName { private static final long serialVersionUID = 1L; private LocalFormName(int name) { super(name); } } private Forms() { Rules = new RulesForms(); } public final class RulesForms implements java.io.Serializable { private static final long serialVersionUID = 1L; private RulesForms() { RuleCodePreview = new LocalFormName(137100); } public final FormName RuleCodePreview; } public RulesForms Rules; } public GlobalContext getGlobalContext() { return this.globalContext; } public static class GlobalContextBridge extends ContextBridge { private static final long serialVersionUID = 1L; } private IReportField[] getFormReportFields() { if(this.context == null) return null; if(this.reportFields == null) this.reportFields = new ReportFields(this.context, this.formInfo, this.componentIdentifier).getReportFields(); return this.reportFields; } private class ReportFields { public ReportFields(Context context, ims.framework.FormInfo formInfo, String componentIdentifier) { this.context = context; this.formInfo = formInfo; this.componentIdentifier = componentIdentifier; } public IReportField[] getReportFields() { String prefix = formInfo.getLocalVariablesPrefix(); IReportField[] fields = new IReportField[81]; fields[0] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ID", "ID_Patient"); fields[1] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SEX", "Sex"); fields[2] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOB", "Dob"); fields[3] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOD", "Dod"); fields[4] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-RELIGION", "Religion"); fields[5] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISACTIVE", "IsActive"); fields[6] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ETHNICORIGIN", "EthnicOrigin"); fields[7] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MARITALSTATUS", "MaritalStatus"); fields[8] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SCN", "SCN"); fields[9] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SOURCEOFINFORMATION", "SourceOfInformation"); fields[10] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFDEATH", "TimeOfDeath"); fields[11] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISQUICKREGISTRATIONPATIENT", "IsQuickRegistrationPatient"); fields[12] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-CURRENTRESPONSIBLECONSULTANT", "CurrentResponsibleConsultant"); fields[13] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-ID", "ID_Patient"); fields[14] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-SEX", "Sex"); fields[15] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-DOB", "Dob"); fields[16] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ID", "ID_ClinicalContact"); fields[17] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-SPECIALTY", "Specialty"); fields[18] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CONTACTTYPE", "ContactType"); fields[19] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-STARTDATETIME", "StartDateTime"); fields[20] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ENDDATETIME", "EndDateTime"); fields[21] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CARECONTEXT", "CareContext"); fields[22] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ISCLINICALNOTECREATED", "IsClinicalNoteCreated"); fields[23] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ID", "ID_Hcp"); fields[24] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-HCPTYPE", "HcpType"); fields[25] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISACTIVE", "IsActive"); fields[26] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPARESPONSIBLEHCP", "IsHCPaResponsibleHCP"); fields[27] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISARESPONSIBLEEDCLINICIAN", "IsAResponsibleEDClinician"); fields[28] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ID", "ID_CareContext"); fields[29] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-CONTEXT", "Context"); fields[30] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital"); fields[31] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ESTIMATEDDISCHARGEDATE", "EstimatedDischargeDate"); fields[32] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-STARTDATETIME", "StartDateTime"); fields[33] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ENDDATETIME", "EndDateTime"); fields[34] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-LOCATIONTYPE", "LocationType"); fields[35] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-RESPONSIBLEHCP", "ResponsibleHCP"); fields[36] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ID", "ID_EpisodeOfCare"); fields[37] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-CARESPELL", "CareSpell"); fields[38] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-SPECIALTY", "Specialty"); fields[39] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-RELATIONSHIP", "Relationship"); fields[40] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-STARTDATE", "StartDate"); fields[41] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ENDDATE", "EndDate"); fields[42] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[43] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALNOTE", "ClinicalNote"); fields[44] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTETYPE", "NoteType"); fields[45] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-DISCIPLINE", "Discipline"); fields[46] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALCONTACT", "ClinicalContact"); fields[47] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISDERIVEDNOTE", "IsDerivedNote"); fields[48] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEW", "ForReview"); fields[49] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[50] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-REVIEWINGDATETIME", "ReviewingDateTime"); fields[51] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISCORRECTED", "IsCorrected"); fields[52] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISTRANSCRIBED", "IsTranscribed"); fields[53] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-SOURCEOFNOTE", "SourceOfNote"); fields[54] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-RECORDINGDATETIME", "RecordingDateTime"); fields[55] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-INHOSPITALREPORT", "InHospitalReport"); fields[56] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CARECONTEXT", "CareContext"); fields[57] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[58] = new ims.framework.ReportField(this.context, "_cvp_STHK.AvailableBedsListFilter", "BO-1014100009-ID", "ID_BedSpaceState"); fields[59] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ID", "ID_PendingEmergencyAdmission"); fields[60] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ADMISSIONSTATUS", "AdmissionStatus"); fields[61] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ID", "ID_InpatientEpisode"); fields[62] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ESTDISCHARGEDATE", "EstDischargeDate"); fields[63] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[64] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEW", "ForReview"); fields[65] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[66] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[67] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-CARECONTEXT", "CareContext"); fields[68] = new ims.framework.ReportField(this.context, "_cvp_Core.PasEvent", "BO-1014100003-ID", "ID_PASEvent"); fields[69] = new ims.framework.ReportField(this.context, "_cvp_Correspondence.CorrespondenceDetails", "BO-1052100001-ID", "ID_CorrespondenceDetails"); fields[70] = new ims.framework.ReportField(this.context, "_cvp_CareUk.CatsReferral", "BO-1004100035-ID", "ID_CatsReferral"); fields[71] = new ims.framework.ReportField(this.context, "_cv_Rules.RuleToEdit", "BO-1004100040-ID", "ID_BusinessRule"); fields[72] = new ims.framework.ReportField(this.context, "_cv_Rules.RuleToEdit", "BO-1004100040-NAME", "Name"); fields[73] = new ims.framework.ReportField(this.context, "_cv_Rules.RuleToEdit", "BO-1004100040-DESCRIPTION", "Description"); fields[74] = new ims.framework.ReportField(this.context, "_cv_Rules.RuleToEdit", "BO-1004100040-CATEGORY", "Category"); fields[75] = new ims.framework.ReportField(this.context, "_cv_Rules.RuleToEdit", "BO-1004100040-VALIDFROM", "ValidFrom"); fields[76] = new ims.framework.ReportField(this.context, "_cv_Rules.RuleToEdit", "BO-1004100040-VALIDTO", "ValidTo"); fields[77] = new ims.framework.ReportField(this.context, "_cv_Rules.RuleToEdit", "BO-1004100040-PRIORITY", "Priority"); fields[78] = new ims.framework.ReportField(this.context, "_cv_Rules.RuleToEdit", "BO-1004100040-XMLCONTENT", "XmlContent"); fields[79] = new ims.framework.ReportField(this.context, "_cv_Rules.RuleToEdit", "BO-1004100040-ACTIVE", "Active"); fields[80] = new ims.framework.ReportField(this.context, "_cv_Rules.RuleToEdit", "BO-1004100040-ROOTENTITY", "RootEntity"); return fields; } protected Context context = null; protected ims.framework.FormInfo formInfo; protected String componentIdentifier; } public String getUniqueIdentifier() { return null; } private Context context = null; private ims.framework.FormInfo formInfo = null; private String componentIdentifier; private GlobalContext globalContext = null; private IReportField[] reportFields = null; }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/forms/transfers/ConfigFlags.java
3801
//############################################################################# //# # //# 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 package ims.core.forms.transfers; import java.io.Serializable; public final class ConfigFlags extends ims.framework.FormConfigFlags implements Serializable { private static final long serialVersionUID = 1L; public final DISPLAY_PATID_TYPEClass DISPLAY_PATID_TYPE; public final STALE_OBJECT_MESSAGEClass STALE_OBJECT_MESSAGE; public final CASE_SENSITIVE_PATIDClass CASE_SENSITIVE_PATID; public ConfigFlags(ims.framework.ConfigFlag configFlags) { super(configFlags); DISPLAY_PATID_TYPE = new DISPLAY_PATID_TYPEClass(configFlags); STALE_OBJECT_MESSAGE = new STALE_OBJECT_MESSAGEClass(configFlags); CASE_SENSITIVE_PATID = new CASE_SENSITIVE_PATIDClass(configFlags); } public final class DISPLAY_PATID_TYPEClass implements Serializable { private static final long serialVersionUID = 1L; private final ims.framework.ConfigFlag configFlags; public DISPLAY_PATID_TYPEClass(ims.framework.ConfigFlag configFlags) { this.configFlags = configFlags; } public String getValue() { return (String)configFlags.get("DISPLAY_PATID_TYPE"); } } public final class STALE_OBJECT_MESSAGEClass implements Serializable { private static final long serialVersionUID = 1L; private final ims.framework.ConfigFlag configFlags; public STALE_OBJECT_MESSAGEClass(ims.framework.ConfigFlag configFlags) { this.configFlags = configFlags; } public String getValue() { return (String)configFlags.get("STALE_OBJECT_MESSAGE"); } } public final class CASE_SENSITIVE_PATIDClass implements Serializable { private static final long serialVersionUID = 1L; private final ims.framework.ConfigFlag configFlags; public CASE_SENSITIVE_PATIDClass(ims.framework.ConfigFlag configFlags) { this.configFlags = configFlags; } public Boolean getValue() { return (Boolean)configFlags.get("CASE_SENSITIVE_PATID"); } } }
agpl-3.0
ozwillo/ozwillo-portal
src/test/java/org/oasis_eu/portal/services/RatingServiceTest.java
3186
package org.oasis_eu.portal.services; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.oasis_eu.portal.dao.RatingRepository; import org.oasis_eu.spring.kernel.model.UserInfo; import org.oasis_eu.spring.kernel.security.OpenIdCAuthentication; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * User: schambon * Date: 10/31/14 */ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) public class RatingServiceTest { static Logger logger = LoggerFactory.getLogger(RatingServiceTest.class); @Autowired private RatingRepository repository; @Autowired private RatingService ratingService; @BeforeEach public void setUp() { logger.warn("Emptying database"); repository.deleteAll(); } private void setAuthentication(String userId) { UserInfo dummy = new UserInfo(); dummy.setUserId(userId); OpenIdCAuthentication auth = mock(OpenIdCAuthentication.class); when(auth.getUserInfo()).thenReturn(dummy); SecurityContext sc = mock(SecurityContext.class); when(sc.getAuthentication()).thenReturn(auth); SecurityContextHolder.setContext(sc); } @Test public void testRating() { setAuthentication("toto"); ratingService.rate("application", "citizenkin", 4); assertEquals(4, ratingService.getRating("application", "citizenkin"), 0.01); } @Test public void testMultipleRating() { setAuthentication("toto"); ratingService.rate("application", "citizenkin", 3); assertThrows(IllegalArgumentException.class, () -> ratingService.rate("application", "citizenkin", 4)); } @Test public void testRatingTooLow() { setAuthentication("toto"); assertThrows(IllegalArgumentException.class, () -> ratingService.rate("application", "citizenkin", -1)); } @Test public void testRatingTooHigh() { setAuthentication("toto"); assertThrows(IllegalArgumentException.class, () -> ratingService.rate("application", "citizenkin", 6)); } @Test public void testAverage() { setAuthentication("toto"); ratingService.rate("application", "citizenkin", 4); setAuthentication("tata"); ratingService.rate("application", "citizenkin", 4); setAuthentication("titi"); ratingService.rate("application", "citizenkin", 3); setAuthentication("tutu"); ratingService.rate("application", "citizenkin", 4); // so now the average is at 3.75 - the service should respond with 4 assertEquals(4, ratingService.getRating("application", "citizenkin"), 0.01); // another rating at just 3.5 should bring the average to 3.7 - the service now rounds to 3.5 setAuthentication("tete"); ratingService.rate("application", "citizenkin", 3.5); assertEquals(3.5, ratingService.getRating("application", "citizenkin"), 0.01); } }
agpl-3.0
migue/voltdb
tests/test_apps/matviewbenchmark/src/matviewbenchmark/NoJoinedTableViewPhase.java
1751
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package matviewbenchmark; import org.voltdb.client.Client; import org.voltdb.client.NullCallback; public class NoJoinedTableViewPhase extends BenchmarkPhase { public NoJoinedTableViewPhase(Client client) { super(client, "2tables w/o view", "2t wo view", "noJoinedViewSrc1", true); } @Override public void insert(int txnid, int grp) throws Exception { m_client.callProcedure(new NullCallback(), m_insertProcStr, txnid, grp, grp, txnid, txnid, txnid); } }
agpl-3.0
ralfbecher/neo4j-extensions
neo4j-extensions-common/src/main/java/org/neo4j/extensions/common/types/NodeTypes.java
641
package org.neo4j.extensions.common.types; import org.neo4j.extensions.common.domain.User; /** * Node types. * * @author bradnussbaum * @since 2014.05.25 */ public enum NodeTypes { USER( User.class.getName(), User.class.getSimpleName() ); private String className; private String simpleClassName; private NodeTypes( String className, String simpleClassName ) { this.className = className; this.simpleClassName = simpleClassName; } public String getClassName() { return className; } public String getSimpleClassName() { return simpleClassName; } }
agpl-3.0