repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
SK-HOLDINGS-CC/NEXCORE-UML-Modeler | nexcore.tool.uml.model/src/java/nexcore/tool/uml/model/umldiagram/Map.java | 3108 | /**
* Copyright (c) 2015 SK holdings Co., Ltd. All rights reserved.
* This software is the confidential and proprietary information of SK holdings.
* You shall not disclose such confidential information and shall use it only in
* accordance with the terms of the license agreement you entered into with SK holdings.
* (http://www.eclipse.org/legal/epl-v10.html)
*/
package nexcore.tool.uml.model.umldiagram;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc --> A representation of the model object '
* <em><b>Map</b></em>'. <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link nexcore.tool.uml.model.umldiagram.Map#getKey <em>Key</em>}</li>
* <li>{@link nexcore.tool.uml.model.umldiagram.Map#getValue <em>Value</em>}</li>
* </ul>
* </p>
*
* @see nexcore.tool.uml.model.umldiagram.UMLDiagramPackage#getMap()
* @model
* @generated
*/
/**
* <ul>
* <li>업무 그룹명 : nexcore.tool.uml.model</li>
* <li>서브 업무명 : nexcore.tool.uml.model.umldiagram</li>
* <li>설 명 : Map</li>
* <li>작성일 : 2015. 10. 6.</li>
* <li>작성자 : 탁희수 </li>
* </ul>
*/
public interface Map extends EObject {
/**
* Returns the value of the '<em><b>Key</b></em>' attribute. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Key</em>' attribute isn't clear, there really
* should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Key</em>' attribute.
* @see #setKey(String)
* @see nexcore.tool.uml.model.umldiagram.UMLDiagramPackage#getMap_Key()
* @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
* @generated
*/
String getKey();
/**
* Sets the value of the '{@link nexcore.tool.uml.model.umldiagram.Map#getKey <em>Key</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @param value the new value of the '<em>Key</em>' attribute.
* @see #getKey()
* @generated
*/
void setKey(String value);
/**
* Returns the value of the '<em><b>Value</b></em>' attribute. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Value</em>' attribute isn't clear, there
* really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Value</em>' attribute.
* @see #setValue(String)
* @see nexcore.tool.uml.model.umldiagram.UMLDiagramPackage#getMap_Value()
* @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
* @generated
*/
String getValue();
/**
* Sets the value of the '{@link nexcore.tool.uml.model.umldiagram.Map#getValue <em>Value</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #getValue()
* @generated
*/
void setValue(String value);
} // Map
| epl-1.0 |
smkr/pyclipse | plugins/org.python.pydev/tests/org/python/pydev/editor/actions/PyAddBlockCommentTest.java | 3279 | /**
* Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package org.python.pydev.editor.actions;
import junit.framework.TestCase;
import org.eclipse.jface.text.Document;
import org.python.pydev.core.docutils.PySelection;
import org.python.pydev.editor.actions.PyFormatStd.FormatStd;
public class PyAddBlockCommentTest extends TestCase {
public void testBlock() throws Exception {
Document doc = null;
FormatStd std = new FormatStd();
doc = new Document("cc");
new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0));
PySelectionTest.checkStrEquals("" +
"#---------\r\n" +
"# cc\r\n" +
"#---------", doc.get());
doc = new Document("\t cc");
new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0));
PySelectionTest.checkStrEquals("" +
"\t #----\r\n" +
"\t # cc\r\n" +
"\t #----", doc.get());
doc = new Document("class Foo(object):");
new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0));
PySelectionTest.checkStrEquals("" +
"#---------\r\n" +
"# Foo\r\n" +
"#---------\r\n" +
"class Foo(object):",
doc.get());
doc = new Document("class Information( UserDict.UserDict, IInformation ):");
new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0));
PySelectionTest.checkStrEquals("" +
"#---------\r\n" +
"# Information\r\n" +
"#---------\r\n"
+
"class Information( UserDict.UserDict, IInformation ):", doc.get());
doc = new Document("def Information( (UserDict, IInformation) ):");
new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0));
PySelectionTest.checkStrEquals("" +
"#---------\r\n" +
"# Information\r\n" +
"#---------\r\n"
+
"def Information( (UserDict, IInformation) ):", doc.get());
//without class behavior
doc = new Document("class Foo(object):");
new PyAddBlockComment(std, 10, true, false, true).perform(new PySelection(doc, 0, 0, 0));
PySelectionTest.checkStrEquals("" +
"#---------\r\n" +
"# class Foo(object):\r\n" +
"#---------" +
"",
doc.get());
//aligned class
doc = new Document(" class Foo(object):");
new PyAddBlockComment(std, 10, true, true, true).perform(new PySelection(doc, 0, 0, 0));
PySelectionTest.checkStrEquals("" +
" #-----\r\n" +
" # Foo\r\n" +
" #-----\r\n"
+
" class Foo(object):" +
"", doc.get());
}
}
| epl-1.0 |
sabev/sap-services-registry-eclipse | org.eclipse.servicesregistry.core/src/org/eclipse/servicesregistry/core/config/persistency/IPreferencesController.java | 2878 | /*******************************************************************************
* Copyright (c) 2012 SAP AG and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* SAP AG - initial API and implementation
*******************************************************************************/
package org.eclipse.servicesregistry.core.config.persistency;
import java.util.Set;
import org.eclipse.servicesregistry.core.config.IServicesRegistrySystem;
/**
* Interface for the services registry preferences controller which bridges the preferences clients, preferences business logic and preferences storage
*
* @author Danail Branekov
*/
public interface IPreferencesController
{
/**
* Gets the currently available SR server configurations<br>
* Do note that this method will returns a "working copy" of the server configurations, i.e. the result will reflect invocations of the "create",
* "delete" and "edit" method of the interface
*
* @return a set of configurations or an empty set if none available
* @see #createNewConfiguration()
* @see #editConfiguration(IServicesRegistrySystem)
* @see #deleteConfiguration(IServicesRegistrySystem)
*/
public Set<IServicesRegistrySystem> getConfigurations();
/**
* Creates a new SR server configuration<br>
* Do note that the newly created configuration will not be persisted to the preference store without invoking
* {@link #storeConfigurations()}
*
* @return the newly created SR server config
* @throws ConfigCreationCanceledException
* when configuration creation has been canceled
*/
public IServicesRegistrySystem createNewConfiguration() throws ConfigCreationCanceledException;
/**
* Edit the SR configuration specified<br>
* Do note that the changes in the configuration will not be persisted to the preference store without invoking
* {@link #storeConfigurations()}
*
* @param config
* the configuration to edit
*/
public void editConfiguration(final IServicesRegistrySystem config);
/**
* Deletes the SR server configuration<br>
* Do note that the deleted configuration will not be persisted to the preference store without invoking {@link #storeConfigurations()}
*
* @param config
* the configuration to delete
*/
public void deleteConfiguration(final IServicesRegistrySystem config);
/**
* Stores the Sr configurations to the preference store
*
* @throws ConfigStoreException
* @throws ConfigLoadException
*/
public void storeConfigurations() throws ConfigStoreException, ConfigLoadException;
}
| epl-1.0 |
boniatillo-com/PhaserEditor | source/v2/phasereditor/phasereditor.scene.core/src/phasereditor/scene/core/codedom/FieldDeclDom.java | 1481 | // The MIT License (MIT)
//
// Copyright (c) 2015, 2018 Arian Fornaris
//
// 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 OR COPYRIGHT HOLDERS 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 phasereditor.scene.core.codedom;
/**
* @author arian
*
*/
public class FieldDeclDom extends MemberDeclDom {
private String _type;
public FieldDeclDom(String name, String type) {
super(name);
_type = type;
}
public String getType() {
return _type;
}
public void setType(String type) {
_type = type;
}
}
| epl-1.0 |
sehrgut/minecraft-smp-mocreatures | moCreatures/server/core/sources/net/minecraft/src/EntityMinecart.java | 27522 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
package net.minecraft.src;
import java.util.List;
import java.util.Random;
// Referenced classes of package net.minecraft.src:
// Entity, Vec3D, AxisAlignedBB, World,
// Item, EntityPlayer, EntityItem, MathHelper,
// InventoryPlayer, ItemStack, EntityLiving, IInventory,
// NBTTagCompound, BlockRail, NBTTagList, Block
public class EntityMinecart extends Entity
implements IInventory
{
public EntityMinecart(World world)
{
super(world);
cargoItems = new ItemStack[36];
damageTaken = 0;
field_9167_b = 0;
forwardDirection = 1;
field_469_aj = false;
preventEntitySpawning = true;
setSize(0.98F, 0.7F);
yOffset = height / 2.0F;
}
protected boolean func_25017_l()
{
return false;
}
protected void entityInit()
{
}
public AxisAlignedBB func_89_d(Entity entity)
{
return entity.boundingBox;
}
public AxisAlignedBB getBoundingBox()
{
return null;
}
public boolean canBePushed()
{
return true;
}
public EntityMinecart(World world, double d, double d1, double d2,
int i)
{
this(world);
setPosition(d, d1 + (double)yOffset, d2);
motionX = 0.0D;
motionY = 0.0D;
motionZ = 0.0D;
prevPosX = d;
prevPosY = d1;
prevPosZ = d2;
minecartType = i;
}
public double getMountedYOffset()
{
return (double)height * 0.0D - 0.30000001192092896D;
}
public boolean attackEntityFrom(Entity entity, int i)
{
if(worldObj.singleplayerWorld || isDead)
{
return true;
}
forwardDirection = -forwardDirection;
field_9167_b = 10;
setBeenAttacked();
damageTaken += i * 10;
if(damageTaken > 40)
{
dropItemWithOffset(Item.minecartEmpty.shiftedIndex, 1, 0.0F);
if(minecartType == 1)
{
dropItemWithOffset(Block.crate.blockID, 1, 0.0F);
} else
if(minecartType == 2)
{
dropItemWithOffset(Block.stoneOvenIdle.blockID, 1, 0.0F);
}
setEntityDead();
}
return true;
}
public boolean canBeCollidedWith()
{
return !isDead;
}
public void setEntityDead()
{
label0:
for(int i = 0; i < getSizeInventory(); i++)
{
ItemStack itemstack = getStackInSlot(i);
if(itemstack == null)
{
continue;
}
float f = rand.nextFloat() * 0.8F + 0.1F;
float f1 = rand.nextFloat() * 0.8F + 0.1F;
float f2 = rand.nextFloat() * 0.8F + 0.1F;
do
{
if(itemstack.stackSize <= 0)
{
continue label0;
}
int j = rand.nextInt(21) + 10;
if(j > itemstack.stackSize)
{
j = itemstack.stackSize;
}
itemstack.stackSize -= j;
EntityItem entityitem = new EntityItem(worldObj, posX + (double)f, posY + (double)f1, posZ + (double)f2, new ItemStack(itemstack.itemID, j, itemstack.getItemDamage()));
float f3 = 0.05F;
entityitem.motionX = (float)rand.nextGaussian() * f3;
entityitem.motionY = (float)rand.nextGaussian() * f3 + 0.2F;
entityitem.motionZ = (float)rand.nextGaussian() * f3;
worldObj.entityJoinedWorld(entityitem);
} while(true);
}
super.setEntityDead();
}
public void onUpdate()
{
if(field_9167_b > 0)
{
field_9167_b--;
}
if(damageTaken > 0)
{
damageTaken--;
}
if(worldObj.singleplayerWorld && field_9163_an > 0)
{
if(field_9163_an > 0)
{
double d = posX + (field_9162_ao - posX) / (double)field_9163_an;
double d1 = posY + (field_9161_ap - posY) / (double)field_9163_an;
double d3 = posZ + (field_9160_aq - posZ) / (double)field_9163_an;
double d4;
for(d4 = field_9159_ar - (double)rotationYaw; d4 < -180D; d4 += 360D) { }
for(; d4 >= 180D; d4 -= 360D) { }
rotationYaw += d4 / (double)field_9163_an;
rotationPitch += (field_9158_as - (double)rotationPitch) / (double)field_9163_an;
field_9163_an--;
setPosition(d, d1, d3);
setRotation(rotationYaw, rotationPitch);
} else
{
setPosition(posX, posY, posZ);
setRotation(rotationYaw, rotationPitch);
}
return;
}
prevPosX = posX;
prevPosY = posY;
prevPosZ = posZ;
motionY -= 0.039999999105930328D;
int i = MathHelper.floor_double(posX);
int j = MathHelper.floor_double(posY);
int k = MathHelper.floor_double(posZ);
if(BlockRail.func_27029_g(worldObj, i, j - 1, k))
{
j--;
}
double d2 = 0.40000000000000002D;
boolean flag = false;
double d5 = 0.0078125D;
int l = worldObj.getBlockId(i, j, k);
if(BlockRail.func_27030_c(l))
{
Vec3D vec3d = func_182_g(posX, posY, posZ);
int i1 = worldObj.getBlockMetadata(i, j, k);
posY = j;
boolean flag1 = false;
boolean flag2 = false;
if(l == Block.railPowered.blockID)
{
flag1 = (i1 & 8) != 0;
flag2 = !flag1;
}
if(((BlockRail)Block.blocksList[l]).func_27028_d())
{
i1 &= 7;
}
if(i1 >= 2 && i1 <= 5)
{
posY = j + 1;
}
if(i1 == 2)
{
motionX -= d5;
}
if(i1 == 3)
{
motionX += d5;
}
if(i1 == 4)
{
motionZ += d5;
}
if(i1 == 5)
{
motionZ -= d5;
}
int ai[][] = field_468_ak[i1];
double d9 = ai[1][0] - ai[0][0];
double d10 = ai[1][2] - ai[0][2];
double d11 = Math.sqrt(d9 * d9 + d10 * d10);
double d12 = motionX * d9 + motionZ * d10;
if(d12 < 0.0D)
{
d9 = -d9;
d10 = -d10;
}
double d13 = Math.sqrt(motionX * motionX + motionZ * motionZ);
motionX = (d13 * d9) / d11;
motionZ = (d13 * d10) / d11;
if(flag2)
{
double d16 = Math.sqrt(motionX * motionX + motionZ * motionZ);
if(d16 < 0.029999999999999999D)
{
motionX *= 0.0D;
motionY *= 0.0D;
motionZ *= 0.0D;
} else
{
motionX *= 0.5D;
motionY *= 0.0D;
motionZ *= 0.5D;
}
}
double d17 = 0.0D;
double d18 = (double)i + 0.5D + (double)ai[0][0] * 0.5D;
double d19 = (double)k + 0.5D + (double)ai[0][2] * 0.5D;
double d20 = (double)i + 0.5D + (double)ai[1][0] * 0.5D;
double d21 = (double)k + 0.5D + (double)ai[1][2] * 0.5D;
d9 = d20 - d18;
d10 = d21 - d19;
if(d9 == 0.0D)
{
posX = (double)i + 0.5D;
d17 = posZ - (double)k;
} else
if(d10 == 0.0D)
{
posZ = (double)k + 0.5D;
d17 = posX - (double)i;
} else
{
double d22 = posX - d18;
double d24 = posZ - d19;
double d26 = (d22 * d9 + d24 * d10) * 2D;
d17 = d26;
}
posX = d18 + d9 * d17;
posZ = d19 + d10 * d17;
setPosition(posX, posY + (double)yOffset, posZ);
double d23 = motionX;
double d25 = motionZ;
if(riddenByEntity != null)
{
d23 *= 0.75D;
d25 *= 0.75D;
}
if(d23 < -d2)
{
d23 = -d2;
}
if(d23 > d2)
{
d23 = d2;
}
if(d25 < -d2)
{
d25 = -d2;
}
if(d25 > d2)
{
d25 = d2;
}
moveEntity(d23, 0.0D, d25);
if(ai[0][1] != 0 && MathHelper.floor_double(posX) - i == ai[0][0] && MathHelper.floor_double(posZ) - k == ai[0][2])
{
setPosition(posX, posY + (double)ai[0][1], posZ);
} else
if(ai[1][1] != 0 && MathHelper.floor_double(posX) - i == ai[1][0] && MathHelper.floor_double(posZ) - k == ai[1][2])
{
setPosition(posX, posY + (double)ai[1][1], posZ);
}
if(riddenByEntity != null)
{
motionX *= 0.99699997901916504D;
motionY *= 0.0D;
motionZ *= 0.99699997901916504D;
} else
{
if(minecartType == 2)
{
double d27 = MathHelper.sqrt_double(pushX * pushX + pushZ * pushZ);
if(d27 > 0.01D)
{
flag = true;
pushX /= d27;
pushZ /= d27;
double d29 = 0.040000000000000001D;
motionX *= 0.80000001192092896D;
motionY *= 0.0D;
motionZ *= 0.80000001192092896D;
motionX += pushX * d29;
motionZ += pushZ * d29;
} else
{
motionX *= 0.89999997615814209D;
motionY *= 0.0D;
motionZ *= 0.89999997615814209D;
}
}
motionX *= 0.95999997854232788D;
motionY *= 0.0D;
motionZ *= 0.95999997854232788D;
}
Vec3D vec3d1 = func_182_g(posX, posY, posZ);
if(vec3d1 != null && vec3d != null)
{
double d28 = (vec3d.yCoord - vec3d1.yCoord) * 0.050000000000000003D;
double d14 = Math.sqrt(motionX * motionX + motionZ * motionZ);
if(d14 > 0.0D)
{
motionX = (motionX / d14) * (d14 + d28);
motionZ = (motionZ / d14) * (d14 + d28);
}
setPosition(posX, vec3d1.yCoord, posZ);
}
int k1 = MathHelper.floor_double(posX);
int l1 = MathHelper.floor_double(posZ);
if(k1 != i || l1 != k)
{
double d15 = Math.sqrt(motionX * motionX + motionZ * motionZ);
motionX = d15 * (double)(k1 - i);
motionZ = d15 * (double)(l1 - k);
}
if(minecartType == 2)
{
double d30 = MathHelper.sqrt_double(pushX * pushX + pushZ * pushZ);
if(d30 > 0.01D && motionX * motionX + motionZ * motionZ > 0.001D)
{
pushX /= d30;
pushZ /= d30;
if(pushX * motionX + pushZ * motionZ < 0.0D)
{
pushX = 0.0D;
pushZ = 0.0D;
} else
{
pushX = motionX;
pushZ = motionZ;
}
}
}
if(flag1)
{
double d31 = Math.sqrt(motionX * motionX + motionZ * motionZ);
if(d31 > 0.01D)
{
double d32 = 0.040000000000000001D;
motionX += (motionX / d31) * d32;
motionZ += (motionZ / d31) * d32;
} else
if(i1 == 1)
{
if(worldObj.isBlockOpaqueCube(i - 1, j, k))
{
motionX = 0.02D;
} else
if(worldObj.isBlockOpaqueCube(i + 1, j, k))
{
motionX = -0.02D;
}
} else
if(i1 == 0)
{
if(worldObj.isBlockOpaqueCube(i, j, k - 1))
{
motionZ = 0.02D;
} else
if(worldObj.isBlockOpaqueCube(i, j, k + 1))
{
motionZ = -0.02D;
}
}
}
} else
{
if(motionX < -d2)
{
motionX = -d2;
}
if(motionX > d2)
{
motionX = d2;
}
if(motionZ < -d2)
{
motionZ = -d2;
}
if(motionZ > d2)
{
motionZ = d2;
}
if(onGround)
{
motionX *= 0.5D;
motionY *= 0.5D;
motionZ *= 0.5D;
}
moveEntity(motionX, motionY, motionZ);
if(!onGround)
{
motionX *= 0.94999998807907104D;
motionY *= 0.94999998807907104D;
motionZ *= 0.94999998807907104D;
}
}
rotationPitch = 0.0F;
double d6 = prevPosX - posX;
double d7 = prevPosZ - posZ;
if(d6 * d6 + d7 * d7 > 0.001D)
{
rotationYaw = (float)((Math.atan2(d7, d6) * 180D) / 3.1415926535897931D);
if(field_469_aj)
{
rotationYaw += 180F;
}
}
double d8;
for(d8 = rotationYaw - prevRotationYaw; d8 >= 180D; d8 -= 360D) { }
for(; d8 < -180D; d8 += 360D) { }
if(d8 < -170D || d8 >= 170D)
{
rotationYaw += 180F;
field_469_aj = !field_469_aj;
}
setRotation(rotationYaw, rotationPitch);
List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox.expand(0.20000000298023224D, 0.0D, 0.20000000298023224D));
if(list != null && list.size() > 0)
{
for(int j1 = 0; j1 < list.size(); j1++)
{
Entity entity = (Entity)list.get(j1);
if(entity != riddenByEntity && entity.canBePushed() && (entity instanceof EntityMinecart))
{
entity.applyEntityCollision(this);
}
}
}
if(riddenByEntity != null && riddenByEntity.isDead)
{
riddenByEntity = null;
}
if(flag && rand.nextInt(4) == 0)
{
fuel--;
if(fuel < 0)
{
pushX = pushZ = 0.0D;
}
worldObj.spawnParticle("largesmoke", posX, posY + 0.80000000000000004D, posZ, 0.0D, 0.0D, 0.0D);
}
}
public Vec3D func_182_g(double d, double d1, double d2)
{
int i = MathHelper.floor_double(d);
int j = MathHelper.floor_double(d1);
int k = MathHelper.floor_double(d2);
if(BlockRail.func_27029_g(worldObj, i, j - 1, k))
{
j--;
}
int l = worldObj.getBlockId(i, j, k);
if(BlockRail.func_27030_c(l))
{
int i1 = worldObj.getBlockMetadata(i, j, k);
d1 = j;
if(((BlockRail)Block.blocksList[l]).func_27028_d())
{
i1 &= 7;
}
if(i1 >= 2 && i1 <= 5)
{
d1 = j + 1;
}
int ai[][] = field_468_ak[i1];
double d3 = 0.0D;
double d4 = (double)i + 0.5D + (double)ai[0][0] * 0.5D;
double d5 = (double)j + 0.5D + (double)ai[0][1] * 0.5D;
double d6 = (double)k + 0.5D + (double)ai[0][2] * 0.5D;
double d7 = (double)i + 0.5D + (double)ai[1][0] * 0.5D;
double d8 = (double)j + 0.5D + (double)ai[1][1] * 0.5D;
double d9 = (double)k + 0.5D + (double)ai[1][2] * 0.5D;
double d10 = d7 - d4;
double d11 = (d8 - d5) * 2D;
double d12 = d9 - d6;
if(d10 == 0.0D)
{
d = (double)i + 0.5D;
d3 = d2 - (double)k;
} else
if(d12 == 0.0D)
{
d2 = (double)k + 0.5D;
d3 = d - (double)i;
} else
{
double d13 = d - d4;
double d14 = d2 - d6;
double d15 = (d13 * d10 + d14 * d12) * 2D;
d3 = d15;
}
d = d4 + d10 * d3;
d1 = d5 + d11 * d3;
d2 = d6 + d12 * d3;
if(d11 < 0.0D)
{
d1++;
}
if(d11 > 0.0D)
{
d1 += 0.5D;
}
return Vec3D.createVector(d, d1, d2);
} else
{
return null;
}
}
protected void writeEntityToNBT(NBTTagCompound nbttagcompound)
{
nbttagcompound.setInteger("Type", minecartType);
if(minecartType == 2)
{
nbttagcompound.setDouble("PushX", pushX);
nbttagcompound.setDouble("PushZ", pushZ);
nbttagcompound.setShort("Fuel", (short)fuel);
} else
if(minecartType == 1)
{
NBTTagList nbttaglist = new NBTTagList();
for(int i = 0; i < cargoItems.length; i++)
{
if(cargoItems[i] != null)
{
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte)i);
cargoItems[i].writeToNBT(nbttagcompound1);
nbttaglist.setTag(nbttagcompound1);
}
}
nbttagcompound.setTag("Items", nbttaglist);
}
}
protected void readEntityFromNBT(NBTTagCompound nbttagcompound)
{
minecartType = nbttagcompound.getInteger("Type");
if(minecartType == 2)
{
pushX = nbttagcompound.getDouble("PushX");
pushZ = nbttagcompound.getDouble("PushZ");
fuel = nbttagcompound.getShort("Fuel");
} else
if(minecartType == 1)
{
NBTTagList nbttaglist = nbttagcompound.getTagList("Items");
cargoItems = new ItemStack[getSizeInventory()];
for(int i = 0; i < nbttaglist.tagCount(); i++)
{
NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.tagAt(i);
int j = nbttagcompound1.getByte("Slot") & 0xff;
if(j >= 0 && j < cargoItems.length)
{
cargoItems[j] = new ItemStack(nbttagcompound1);
}
}
}
}
public void applyEntityCollision(Entity entity)
{
if(worldObj.singleplayerWorld)
{
return;
}
if(entity == riddenByEntity)
{
return;
}
if((entity instanceof EntityLiving) && !(entity instanceof EntityPlayer) && minecartType == 0 && motionX * motionX + motionZ * motionZ > 0.01D && riddenByEntity == null && entity.ridingEntity == null)
{
entity.mountEntity(this);
}
double d = entity.posX - posX;
double d1 = entity.posZ - posZ;
double d2 = d * d + d1 * d1;
if(d2 >= 9.9999997473787516E-005D)
{
d2 = MathHelper.sqrt_double(d2);
d /= d2;
d1 /= d2;
double d3 = 1.0D / d2;
if(d3 > 1.0D)
{
d3 = 1.0D;
}
d *= d3;
d1 *= d3;
d *= 0.10000000149011612D;
d1 *= 0.10000000149011612D;
d *= 1.0F - entityCollisionReduction;
d1 *= 1.0F - entityCollisionReduction;
d *= 0.5D;
d1 *= 0.5D;
if(entity instanceof EntityMinecart)
{
double d4 = entity.motionX + motionX;
double d5 = entity.motionZ + motionZ;
if(((EntityMinecart)entity).minecartType == 2 && minecartType != 2)
{
motionX *= 0.20000000298023224D;
motionZ *= 0.20000000298023224D;
addVelocity(entity.motionX - d, 0.0D, entity.motionZ - d1);
entity.motionX *= 0.69999998807907104D;
entity.motionZ *= 0.69999998807907104D;
} else
if(((EntityMinecart)entity).minecartType != 2 && minecartType == 2)
{
entity.motionX *= 0.20000000298023224D;
entity.motionZ *= 0.20000000298023224D;
entity.addVelocity(motionX + d, 0.0D, motionZ + d1);
motionX *= 0.69999998807907104D;
motionZ *= 0.69999998807907104D;
} else
{
d4 /= 2D;
d5 /= 2D;
motionX *= 0.20000000298023224D;
motionZ *= 0.20000000298023224D;
addVelocity(d4 - d, 0.0D, d5 - d1);
entity.motionX *= 0.20000000298023224D;
entity.motionZ *= 0.20000000298023224D;
entity.addVelocity(d4 + d, 0.0D, d5 + d1);
}
} else
{
addVelocity(-d, 0.0D, -d1);
entity.addVelocity(d / 4D, 0.0D, d1 / 4D);
}
}
}
public int getSizeInventory()
{
return 27;
}
public ItemStack getStackInSlot(int i)
{
return cargoItems[i];
}
public ItemStack decrStackSize(int i, int j)
{
if(cargoItems[i] != null)
{
if(cargoItems[i].stackSize <= j)
{
ItemStack itemstack = cargoItems[i];
cargoItems[i] = null;
return itemstack;
}
ItemStack itemstack1 = cargoItems[i].splitStack(j);
if(cargoItems[i].stackSize == 0)
{
cargoItems[i] = null;
}
return itemstack1;
} else
{
return null;
}
}
public void setInventorySlotContents(int i, ItemStack itemstack)
{
cargoItems[i] = itemstack;
if(itemstack != null && itemstack.stackSize > getInventoryStackLimit())
{
itemstack.stackSize = getInventoryStackLimit();
}
}
public String getInvName()
{
return "Minecart";
}
public int getInventoryStackLimit()
{
return 64;
}
public void onInventoryChanged()
{
}
public boolean interact(EntityPlayer entityplayer)
{
if(minecartType == 0)
{
if(riddenByEntity != null && (riddenByEntity instanceof EntityPlayer) && riddenByEntity != entityplayer)
{
return true;
}
if(!worldObj.singleplayerWorld)
{
entityplayer.mountEntity(this);
}
} else
if(minecartType == 1)
{
if(!worldObj.singleplayerWorld)
{
entityplayer.displayGUIChest(this);
}
} else
if(minecartType == 2)
{
ItemStack itemstack = entityplayer.inventory.getCurrentItem();
if(itemstack != null && itemstack.itemID == Item.coal.shiftedIndex)
{
if(--itemstack.stackSize == 0)
{
entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, null);
}
fuel += 1200;
}
pushX = posX - entityplayer.posX;
pushZ = posZ - entityplayer.posZ;
}
return true;
}
public boolean canInteractWith(EntityPlayer entityplayer)
{
if(isDead)
{
return false;
}
return entityplayer.getDistanceSqToEntity(this) <= 64D;
}
private ItemStack cargoItems[];
public int damageTaken;
public int field_9167_b;
public int forwardDirection;
private boolean field_469_aj;
public int minecartType;
public int fuel;
public double pushX;
public double pushZ;
private static final int field_468_ak[][][] = {
{
{
0, 0, -1
}, {
0, 0, 1
}
}, {
{
-1, 0, 0
}, {
1, 0, 0
}
}, {
{
-1, -1, 0
}, {
1, 0, 0
}
}, {
{
-1, 0, 0
}, {
1, -1, 0
}
}, {
{
0, 0, -1
}, {
0, -1, 1
}
}, {
{
0, -1, -1
}, {
0, 0, 1
}
}, {
{
0, 0, 1
}, {
1, 0, 0
}
}, {
{
0, 0, 1
}, {
-1, 0, 0
}
}, {
{
0, 0, -1
}, {
-1, 0, 0
}
}, {
{
0, 0, -1
}, {
1, 0, 0
}
}
};
private int field_9163_an;
private double field_9162_ao;
private double field_9161_ap;
private double field_9160_aq;
private double field_9159_ar;
private double field_9158_as;
}
| epl-1.0 |
Serli/flux-file-watcher | flux-file-watcher-core/src/main/java/com/codenvy/flux/watcher/core/RepositoryEventType.java | 796 | /*******************************************************************************
* Copyright (c) 2014 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package com.codenvy.flux.watcher.core;
/**
* Type of events sent by a {@link com.codenvy.flux.watcher.core.Repository}.
*
* @author Kevin Pollet
*/
public enum RepositoryEventType {
PROJECT_RESOURCE_CREATED,
PROJECT_RESOURCE_MODIFIED,
PROJECT_RESOURCE_DELETED
}
| epl-1.0 |
viatra/VIATRA-Generator | Solvers/Alloy-Solver/hu.bme.mit.inf.dslreasoner.alloy.language/src-gen/hu/bme/mit/inf/dslreasoner/alloyLanguage/ALSOverride.java | 2742 | /**
*/
package hu.bme.mit.inf.dslreasoner.alloyLanguage;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>ALS Override</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSOverride#getLeftOperand <em>Left Operand</em>}</li>
* <li>{@link hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSOverride#getRightOperand <em>Right Operand</em>}</li>
* </ul>
*
* @see hu.bme.mit.inf.dslreasoner.alloyLanguage.AlloyLanguagePackage#getALSOverride()
* @model
* @generated
*/
public interface ALSOverride extends ALSTerm
{
/**
* Returns the value of the '<em><b>Left Operand</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Left Operand</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Left Operand</em>' containment reference.
* @see #setLeftOperand(ALSTerm)
* @see hu.bme.mit.inf.dslreasoner.alloyLanguage.AlloyLanguagePackage#getALSOverride_LeftOperand()
* @model containment="true"
* @generated
*/
ALSTerm getLeftOperand();
/**
* Sets the value of the '{@link hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSOverride#getLeftOperand <em>Left Operand</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Left Operand</em>' containment reference.
* @see #getLeftOperand()
* @generated
*/
void setLeftOperand(ALSTerm value);
/**
* Returns the value of the '<em><b>Right Operand</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Right Operand</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Right Operand</em>' containment reference.
* @see #setRightOperand(ALSTerm)
* @see hu.bme.mit.inf.dslreasoner.alloyLanguage.AlloyLanguagePackage#getALSOverride_RightOperand()
* @model containment="true"
* @generated
*/
ALSTerm getRightOperand();
/**
* Sets the value of the '{@link hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSOverride#getRightOperand <em>Right Operand</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Right Operand</em>' containment reference.
* @see #getRightOperand()
* @generated
*/
void setRightOperand(ALSTerm value);
} // ALSOverride
| epl-1.0 |
niuqg/controller | opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/data/ModificationMetadataTreeTest.java | 10396 | /*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.md.sal.dom.store.impl.tree.data;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.ID_QNAME;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.INNER_LIST_QNAME;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.NAME_QNAME;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.OUTER_LIST_PATH;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.OUTER_LIST_QNAME;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.TEST_PATH;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.TEST_QNAME;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.VALUE_QNAME;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntry;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntryBuilder;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapNodeBuilder;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.md.sal.dom.store.impl.TestModel;
import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataTree;
import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataTreeModification;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import com.google.common.base.Optional;
import com.google.common.primitives.UnsignedLong;
/**
*
* Schema structure of document is
*
* <pre>
* container root {
* list list-a {
* key leaf-a;
* leaf leaf-a;
* choice choice-a {
* case one {
* leaf one;
* }
* case two-three {
* leaf two;
* leaf three;
* }
* }
* list list-b {
* key leaf-b;
* leaf leaf-b;
* }
* }
* }
* </pre>
*
*/
public class ModificationMetadataTreeTest {
private static final Short ONE_ID = 1;
private static final Short TWO_ID = 2;
private static final String TWO_ONE_NAME = "one";
private static final String TWO_TWO_NAME = "two";
private static final InstanceIdentifier OUTER_LIST_1_PATH = InstanceIdentifier.builder(OUTER_LIST_PATH)
.nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, ONE_ID) //
.build();
private static final InstanceIdentifier OUTER_LIST_2_PATH = InstanceIdentifier.builder(OUTER_LIST_PATH)
.nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
.build();
private static final InstanceIdentifier TWO_TWO_PATH = InstanceIdentifier.builder(OUTER_LIST_2_PATH)
.node(INNER_LIST_QNAME) //
.nodeWithKey(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME) //
.build();
private static final InstanceIdentifier TWO_TWO_VALUE_PATH = InstanceIdentifier.builder(TWO_TWO_PATH)
.node(VALUE_QNAME) //
.build();
private static final MapEntryNode BAR_NODE = mapEntryBuilder(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
.withChild(mapNodeBuilder(INNER_LIST_QNAME) //
.withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_ONE_NAME)) //
.withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME)) //
.build()) //
.build();
private SchemaContext schemaContext;
private ModificationApplyOperation applyOper;
@Before
public void prepare() {
schemaContext = TestModel.createTestContext();
assertNotNull("Schema context must not be null.", schemaContext);
applyOper = SchemaAwareApplyOperation.from(schemaContext);
}
/**
* Returns a test document
*
* <pre>
* test
* outer-list
* id 1
* outer-list
* id 2
* inner-list
* name "one"
* inner-list
* name "two"
*
* </pre>
*
* @return
*/
public NormalizedNode<?, ?> createDocumentOne() {
return ImmutableContainerNodeBuilder
.create()
.withNodeIdentifier(new NodeIdentifier(schemaContext.getQName()))
.withChild(createTestContainer()).build();
}
private ContainerNode createTestContainer() {
return ImmutableContainerNodeBuilder
.create()
.withNodeIdentifier(new NodeIdentifier(TEST_QNAME))
.withChild(
mapNodeBuilder(OUTER_LIST_QNAME)
.withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID))
.withChild(BAR_NODE).build()).build();
}
@Test
public void basicReadWrites() {
DataTreeModification modificationTree = new InMemoryDataTreeModification(new InMemoryDataTreeSnapshot(schemaContext,
StoreMetadataNode.createRecursively(createDocumentOne(), UnsignedLong.valueOf(5)), applyOper),
new SchemaAwareApplyOperationRoot(schemaContext));
Optional<NormalizedNode<?, ?>> originalBarNode = modificationTree.readNode(OUTER_LIST_2_PATH);
assertTrue(originalBarNode.isPresent());
assertSame(BAR_NODE, originalBarNode.get());
// writes node to /outer-list/1/inner_list/two/value
modificationTree.write(TWO_TWO_VALUE_PATH, ImmutableNodes.leafNode(VALUE_QNAME, "test"));
// reads node to /outer-list/1/inner_list/two/value
// and checks if node is already present
Optional<NormalizedNode<?, ?>> barTwoCModified = modificationTree.readNode(TWO_TWO_VALUE_PATH);
assertTrue(barTwoCModified.isPresent());
assertEquals(ImmutableNodes.leafNode(VALUE_QNAME, "test"), barTwoCModified.get());
// delete node to /outer-list/1/inner_list/two/value
modificationTree.delete(TWO_TWO_VALUE_PATH);
Optional<NormalizedNode<?, ?>> barTwoCAfterDelete = modificationTree.readNode(TWO_TWO_VALUE_PATH);
assertFalse(barTwoCAfterDelete.isPresent());
}
public DataTreeModification createEmptyModificationTree() {
/**
* Creates empty Snapshot with associated schema context.
*/
DataTree t = InMemoryDataTreeFactory.getInstance().create();
t.setSchemaContext(schemaContext);
/**
*
* Creates Mutable Data Tree based on provided snapshot and schema
* context.
*
*/
return t.takeSnapshot().newModification();
}
@Test
public void createFromEmptyState() {
DataTreeModification modificationTree = createEmptyModificationTree();
/**
* Writes empty container node to /test
*
*/
modificationTree.write(TEST_PATH, ImmutableNodes.containerNode(TEST_QNAME));
/**
* Writes empty list node to /test/outer-list
*/
modificationTree.write(OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(OUTER_LIST_QNAME).build());
/**
* Reads list node from /test/outer-list
*/
Optional<NormalizedNode<?, ?>> potentialOuterList = modificationTree.readNode(OUTER_LIST_PATH);
assertTrue(potentialOuterList.isPresent());
/**
* Reads container node from /test and verifies that it contains test
* node
*/
Optional<NormalizedNode<?, ?>> potentialTest = modificationTree.readNode(TEST_PATH);
ContainerNode containerTest = assertPresentAndType(potentialTest, ContainerNode.class);
/**
*
* Gets list from returned snapshot of /test and verifies it contains
* outer-list
*
*/
assertPresentAndType(containerTest.getChild(new NodeIdentifier(OUTER_LIST_QNAME)), MapNode.class);
}
@Test
public void writeSubtreeReadChildren() {
DataTreeModification modificationTree = createEmptyModificationTree();
modificationTree.write(TEST_PATH, createTestContainer());
Optional<NormalizedNode<?, ?>> potential = modificationTree.readNode(TWO_TWO_PATH);
assertPresentAndType(potential, MapEntryNode.class);
}
@Test
public void writeSubtreeDeleteChildren() {
DataTreeModification modificationTree = createEmptyModificationTree();
modificationTree.write(TEST_PATH, createTestContainer());
// We verify data are present
Optional<NormalizedNode<?, ?>> potentialBeforeDelete = modificationTree.readNode(TWO_TWO_PATH);
assertPresentAndType(potentialBeforeDelete, MapEntryNode.class);
modificationTree.delete(TWO_TWO_PATH);
Optional<NormalizedNode<?, ?>> potentialAfterDelete = modificationTree.readNode(TWO_TWO_PATH);
assertFalse(potentialAfterDelete.isPresent());
}
private static <T> T assertPresentAndType(final Optional<?> potential, final Class<T> type) {
assertNotNull(potential);
assertTrue(potential.isPresent());
assertTrue(type.isInstance(potential.get()));
return type.cast(potential.get());
}
}
| epl-1.0 |
trajano/app-ms | ms-engine/src/test/java/net/trajano/ms/engine/test/VertxClientTest.java | 1822 | package net.trajano.ms.engine.test;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.dns.AddressResolverOptions;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import net.trajano.ms.engine.internal.resteasy.VertxClientEngine;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.junit.Test;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.Response;
import static org.junit.Assert.assertEquals;
public class VertxClientTest {
@Test
public void testWellKnown() {
final Vertx vertx = Vertx.vertx(new VertxOptions().setAddressResolverOptions(new AddressResolverOptions().setMaxQueries(10)));
final HttpClientOptions options = new HttpClientOptions()
.setPipelining(true);
final HttpClient httpClient = vertx.createHttpClient(options);
final Client client = new ResteasyClientBuilder().httpEngine(new VertxClientEngine(httpClient)).build();
String entity;
{
final Response response = client.target("https://accounts.google.com/.well-known/openid-configuration").request().get();
entity = response.readEntity(String.class);
response.close();
}
{
final Response response = client.target("https://accounts.google.com/.well-known/openid-configuration").request().get();
assertEquals(entity, response.readEntity(String.class));
response.close();
}
{
final Response response = client.target("https://accounts.google.com/.well-known/openid-configuration").request().get();
assertEquals(entity, response.readEntity(String.class));
response.close();
}
client.close();
httpClient.close();
}
}
| epl-1.0 |
happyspace/goclipse | plugin_ide.ui/src-lang/melnorme/util/swt/components/AbstractComponent.java | 3307 | /*******************************************************************************
* Copyright (c) 2014 Bruno Medeiros and other Contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Bruno Medeiros - initial API and implementation
*******************************************************************************/
package melnorme.util.swt.components;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import melnorme.util.swt.SWTLayoutUtil;
/**
* Common class for UI components, or composite widgets, using SWT.
* Can be created in two ways:
* the standard way - only one child control is created under parent.
* inlined - many child controls created under parent control. This allows more flexibility for more complex layouts.
*/
public abstract class AbstractComponent implements IWidgetComponent {
public AbstractComponent() {
_verifyContract();
}
protected void _verifyContract() {
}
@Override
public Composite createComponent(Composite parent) {
Composite topControl = createTopLevelControl(parent);
createContents(topControl);
updateComponentFromInput();
return topControl;
}
@Override
public void createComponentInlined(Composite parent) {
createContents(parent);
updateComponentFromInput();
}
protected final Composite createTopLevelControl(Composite parent) {
Composite topControl = doCreateTopLevelControl(parent);
topControl.setLayout(createTopLevelLayout().create());
return topControl;
}
protected Composite doCreateTopLevelControl(Composite parent) {
return new Composite(parent, SWT.NONE);
}
protected GridLayoutFactory createTopLevelLayout() {
return GridLayoutFactory.fillDefaults().numColumns(getPreferredLayoutColumns());
}
public abstract int getPreferredLayoutColumns();
protected abstract void createContents(Composite topControl);
/* ----------------- util ----------------- */
/** Do {@link #createComponent(Composite)}, and also set the layout data of created Control. */
public final Composite createComponent(Composite parent, Object layoutData) {
Composite control = createComponent(parent);
return SWTLayoutUtil.setLayoutData(control, layoutData);
}
/* ----------------- ----------------- */
/**
* Update the controls of the components from whatever is considerd the input, or source, of the control.
*/
protected abstract void updateComponentFromInput();
/* ----------------- Shortcut utils ----------------- */
protected static GridDataFactory gdSwtDefaults() {
return GridDataFactory.swtDefaults();
}
protected static GridDataFactory gdFillDefaults() {
return GridDataFactory.fillDefaults();
}
protected static GridLayoutFactory glSwtDefaults() {
return GridLayoutFactory.swtDefaults();
}
protected static GridLayoutFactory glFillDefaults() {
return GridLayoutFactory.fillDefaults();
}
} | epl-1.0 |
GazeboHub/ghub-portal-doc | doc/modelio/GHub Portal/mda/JavaDesigner/res/java/tomcat/java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java | 5635 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.util.http.fileupload.util;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An input stream, which limits its data size. This stream is
* used, if the content length is unknown.
*
* @version $Id: LimitedInputStream.java 1456935 2013-03-15 12:47:29Z markt $
*/
public abstract class LimitedInputStream extends FilterInputStream implements Closeable {
/**
* The maximum size of an item, in bytes.
*/
private final long sizeMax;
/**
* The current number of bytes.
*/
private long count;
/**
* Whether this stream is already closed.
*/
private boolean closed;
/**
* Creates a new instance.
*
* @param pIn The input stream, which shall be limited.
* @param pSizeMax The limit; no more than this number of bytes
* shall be returned by the source stream.
*/
public LimitedInputStream(InputStream pIn, long pSizeMax) {
super(pIn);
sizeMax = pSizeMax;
}
/**
* Called to indicate, that the input streams limit has
* been exceeded.
*
* @param pSizeMax The input streams limit, in bytes.
* @param pCount The actual number of bytes.
* @throws IOException The called method is expected
* to raise an IOException.
*/
protected abstract void raiseError(long pSizeMax, long pCount)
throws IOException;
/**
* Called to check, whether the input streams
* limit is reached.
*
* @throws IOException The given limit is exceeded.
*/
private void checkLimit() throws IOException {
if (count > sizeMax) {
raiseError(sizeMax, count);
}
}
/**
* Reads the next byte of data from this input stream. The value
* byte is returned as an <code>int</code> in the range
* <code>0</code> to <code>255</code>. If no byte is available
* because the end of the stream has been reached, the value
* <code>-1</code> is returned. This method blocks until input data
* is available, the end of the stream is detected, or an exception
* is thrown.
* <p>
* This method
* simply performs <code>in.read()</code> and returns the result.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterInputStream#in
*/
@Override
public int read() throws IOException {
int res = super.read();
if (res != -1) {
count++;
checkLimit();
}
return res;
}
/**
* Reads up to <code>len</code> bytes of data from this input stream
* into an array of bytes. If <code>len</code> is not zero, the method
* blocks until some input is available; otherwise, no
* bytes are read and <code>0</code> is returned.
* <p>
* This method simply performs <code>in.read(b, off, len)</code>
* and returns the result.
*
* @param b the buffer into which the data is read.
* @param off The start offset in the destination array
* <code>b</code>.
* @param len the maximum number of bytes read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @exception NullPointerException If <code>b</code> is <code>null</code>.
* @exception IndexOutOfBoundsException If <code>off</code> is negative,
* <code>len</code> is negative, or <code>len</code> is greater than
* <code>b.length - off</code>
* @exception IOException if an I/O error occurs.
* @see java.io.FilterInputStream#in
*/
@Override
public int read(byte[] b, int off, int len) throws IOException {
int res = super.read(b, off, len);
if (res > 0) {
count += res;
checkLimit();
}
return res;
}
/**
* Returns, whether this stream is already closed.
*
* @return True, if the stream is closed, otherwise false.
* @throws IOException An I/O error occurred.
*/
@Override
public boolean isClosed() throws IOException {
return closed;
}
/**
* Closes this input stream and releases any system resources
* associated with the stream.
* This
* method simply performs <code>in.close()</code>.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FilterInputStream#in
*/
@Override
public void close() throws IOException {
closed = true;
super.close();
}
}
| epl-1.0 |
prasser/jhc | src/swt/de/linearbits/jhc/GraphicsSWT.java | 9146 | /* ******************************************************************************
* Copyright (c) 2014 - 2015 Fabian Prasser.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Fabian Prasser - initial API and implementation
******************************************************************************/
package de.linearbits.jhc;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Transform;
/**
* This class implements graphics operations for SWT
*
* @author Fabian Prasser
*/
class GraphicsSWT implements Graphics<Image, Color> {
/** The antialias. */
private int antialias;
/** The canvas. */
private CanvasSWT canvas;
/** The gc. */
private GC gc;
/** The interpolation. */
private int interpolation;
/**
* Creates a new instance
*
* @param canvas the canvas
* @param gc the gc
*/
protected GraphicsSWT(CanvasSWT canvas, GC gc) {
this.canvas = canvas;
this.gc = gc;
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#disableAntialiasing()
*/
@Override
public void disableAntialiasing() {
gc.setAntialias(SWT.OFF);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#disableInterpolation()
*/
@Override
public void disableInterpolation() {
gc.setInterpolation(SWT.NONE);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawImage(java.lang.Object, int, int, int, int)
*/
@Override
public void drawImage(Image image, int x, int y, int width, int height) {
org.eclipse.swt.graphics.Rectangle bounds = image.getBounds();
gc.drawImage(image, 0, 0, bounds.width, bounds.height, x, y, width, height);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawLegend(de.linearbits.jhc.Gradient)
*/
@Override
public Image drawLegend(JHCGradient gradient) {
PixelsSWT pixels = new PixelsSWT(new Dimension(1, gradient.getSteps()), canvas.getDisplay(), gradient.getColor(0));
for (int i = 0; i < gradient.getSteps(); i++) {
pixels.set(0, i, gradient.getColor(i));
}
pixels.update();
return pixels.getImage();
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawLine(int, int, int, int)
*/
@Override
public void drawLine(int x1, int y1, int x2, int y2) {
gc.drawLine(x1, y1, x2, y2);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawRectangle(int, int, int, int)
*/
@Override
public void drawRectangle(int x, int y, int width, int height) {
gc.drawRectangle(x, y, width, height);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawRectangleFilled(int, int, int, int)
*/
@Override
public void drawRectangleFilled(int x, int y, int width, int height) {
gc.fillRectangle(x, y, width, height);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawStringAboveHorizontallyCentered(java.lang.String, int, int, int)
*/
@Override
public void drawStringAboveHorizontallyCentered(String string, int x, int y, int width) {
Point extent = gc.textExtent(string);
int yy = y - extent.y;
if (width >= extent.x) {
gc.setClipping(x, yy, width, extent.y);
int xx = x + (width - extent.x) / 2;
gc.drawText(string, xx, yy, true);
} else {
int postfixWidth = gc.textExtent(POSTFIX).x;
gc.setClipping(x, yy, width - postfixWidth, extent.y);
gc.drawText(string, x, yy, true);
gc.setClipping(x + width - postfixWidth, yy, postfixWidth, extent.y);
gc.drawText(POSTFIX, x + width - postfixWidth, yy, true);
}
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawStringBelowHorizontallyCentered(java.lang.String, int, int, int)
*/
@Override
public void drawStringBelowHorizontallyCentered(String string, int x, int y, int width) {
Point extent = gc.textExtent(string);
int descent = gc.getFontMetrics().getDescent();
if (width >= extent.x) {
gc.setClipping(x, y + descent, width, extent.y);
int xx = x + (width - extent.x) / 2;
gc.drawText(string, xx, y + descent, true);
} else {
int postfixWidth = gc.textExtent(POSTFIX).x;
gc.setClipping(x, y + descent, width - postfixWidth, extent.y);
gc.drawText(string, x, y + descent, true);
gc.setClipping(x + width - postfixWidth, y + descent, postfixWidth, extent.y);
gc.drawText(POSTFIX, x + width - postfixWidth, y + descent, true);
}
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawStringVerticallyCenteredLeftAligned(java.lang.String, int, int, int, int)
*/
@Override
public void drawStringVerticallyCenteredLeftAligned(String string, int x, int y, int width, int height) {
Point extent = gc.textExtent(string);
int yy = y + height / 2 - extent.y / 2;
if (width >= extent.x) {
gc.setClipping(x, yy, width, extent.y);
gc.drawText(string, x, yy, true);
} else {
int postfixWidth = gc.textExtent(POSTFIX).x;
gc.setClipping(x, yy, width - postfixWidth, extent.y);
gc.drawText(string, x, yy, true);
gc.setClipping(x + width - postfixWidth, yy, postfixWidth, extent.y);
gc.drawText(POSTFIX, x + width - postfixWidth, yy, true);
}
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#enableAntialiasing()
*/
@Override
public void enableAntialiasing() {
gc.setAntialias(SWT.ON);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#enableInterpolation()
*/
@Override
public void enableInterpolation() {
gc.setInterpolation(SWT.HIGH);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#getTextHeight(java.lang.String)
*/
@Override
public int getTextHeight(String string) {
return gc.textExtent(string).y;
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#getTextWidth(java.lang.String)
*/
@Override
public int getTextWidth(String string) {
return gc.textExtent(string).x;
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#init()
*/
@Override
public void init() {
gc.setFont(canvas.getFont());
antialias = gc.getAntialias();
interpolation = gc.getInterpolation();
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#resetAntialiasing()
*/
@Override
public void resetAntialiasing() {
gc.setAntialias(antialias);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#resetClipping()
*/
@Override
public void resetClipping() {
org.eclipse.swt.graphics.Rectangle bounds = canvas.getBounds();
gc.setClipping(0, 0, bounds.width, bounds.height);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#resetInterpolation()
*/
@Override
public void resetInterpolation() {
gc.setInterpolation(interpolation);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#resetRotation()
*/
@Override
public void resetRotation() {
gc.setTransform(null);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#setBackground(java.lang.Object)
*/
@Override
public void setBackground(Color color) {
gc.setBackground(color);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#setForeground(java.lang.Object)
*/
@Override
public void setForeground(Color color) {
gc.setForeground(color);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#setRotation(int)
*/
@Override
public void setRotation(int degrees) {
Transform tr = new Transform(canvas.getDisplay());
tr.rotate(degrees);
gc.setTransform(tr);
}
@Override
public void drawStringCentered(String string, int x, int y, int width, int height) {
Point extent = gc.textExtent(string);
int yy = y + (height - extent.y) / 2;
int xx = x + (width - extent.x) / 2;
gc.setClipping(xx, yy, extent.x, extent.y);
gc.drawText(string, xx, yy, true);
}
}
| epl-1.0 |
kerbyfc/slag | src/slag/java/org/productivity/java/syslog4j/impl/AbstractSyslogConfigIF.java | 1753 | package org.productivity.java.syslog4j.impl;
import java.util.List;
import org.productivity.java.syslog4j.SyslogConfigIF;
/**
* AbstractSyslogConfigIF provides an interface for all Abstract Syslog
* configuration implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author <syslog4j@productivity.org>
* @version $Id: AbstractSyslogConfigIF.java,v 1.7 2010/10/29 03:14:20 cvs Exp $
*/
public interface AbstractSyslogConfigIF extends SyslogConfigIF {
public Class getSyslogWriterClass();
public List getBackLogHandlers();
public List getMessageModifiers();
public byte[] getSplitMessageBeginText();
public void setSplitMessageBeginText(byte[] beginText);
public byte[] getSplitMessageEndText();
public void setSplitMessageEndText(byte[] endText);
public boolean isThreaded();
public void setThreaded(boolean threaded);
public boolean isUseDaemonThread();
public void setUseDaemonThread(boolean useDaemonThread);
public int getThreadPriority();
public void setThreadPriority(int threadPriority);
public long getThreadLoopInterval();
public void setThreadLoopInterval(long threadLoopInterval);
public long getMaxShutdownWait();
public void setMaxShutdownWait(long maxShutdownWait);
public int getWriteRetries();
public void setWriteRetries(int writeRetries);
public int getMaxQueueSize();
/**
* Use the (default) value of -1 to allow for a queue of indefinite depth (size).
*
* @param maxQueueSize
*/
public void setMaxQueueSize(int maxQueueSize);
}
| epl-1.0 |
rpau/AutoRefactor | samples/src/test/java/org/autorefactor/jdt/internal/ui/fix/samples_out/ReduceVariableScopeSample.java | 1996 | /*
* AutoRefactor - Eclipse plugin to automatically refactor Java code bases.
*
* Copyright (C) 2013 Jean-Noël Rouvignac - initial API and implementation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program under LICENSE-GNUGPL. If not, see
* <http://www.gnu.org/licenses/>.
*
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution under LICENSE-ECLIPSE, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.autorefactor.jdt.internal.ui.fix.samples_out;
import java.util.List;
public class ReduceVariableScopeSample {
public static void main(String[] args) {
// Push variable into for loops initializers
int i;
{
i = 0;
}
for (i = 0; i < args.length; i++) {
i = 0;
}
for (i = 0; i < args.length; i++)
i = 0;
for (Object obj : (List) null) {
i = 0;
}
for (Object obj : (List) null)
i = 0;
if (isOk()) {
i = 0;
}
if (isOk())
i = 0;
while (isOk()) {
i = 0;
}
while (isOk())
i = 0;
}
private static boolean isOk() {
return false;
}
private static void doIt() {
}
}
| epl-1.0 |
cschwer/com.zsmartsystems.zigbee | com.zsmartsystems.zigbee.dongle.telegesis/src/main/java/com/zsmartsystems/zigbee/dongle/telegesis/internal/protocol/TelegesisNackMessageEvent.java | 1675 | /**
* Copyright (c) 2016-2019 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.zsmartsystems.zigbee.dongle.telegesis.internal.protocol;
/**
* Class to implement the Telegesis command <b>Nack Message</b>.
* <p>
* Acknowledgement for message XX was not received
* <p>
* This class provides methods for processing Telegesis AT API commands.
* <p>
* Note that this code is autogenerated. Manual changes may be overwritten.
*
* @author Chris Jackson - Initial contribution of Java code generator
*/
public class TelegesisNackMessageEvent extends TelegesisFrame implements TelegesisEvent {
/**
* NACK response field
*/
private Integer messageId;
/**
*
* @return the messageId as {@link Integer}
*/
public Integer getMessageId() {
return messageId;
}
@Override
public void deserialize(int[] data) {
initialiseDeserializer(data);
// Deserialize the fields for the "NACK" response
if (testPrompt(data, "NACK:")) {
setDeserializer(5);
// Deserialize field "message ID"
messageId = deserializeInt8();
}
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder(205);
builder.append("TelegesisNackMessageEvent [messageId=");
builder.append(messageId);
builder.append(']');
return builder.toString();
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/inheritance/Vehicle.java | 4050 | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.jpa.inheritance;
import java.io.*;
import org.eclipse.persistence.tools.schemaframework.*;
import javax.persistence.*;
import static javax.persistence.GenerationType.*;
import static javax.persistence.CascadeType.*;
import static javax.persistence.FetchType.*;
import static javax.persistence.InheritanceType.*;
@Entity
@EntityListeners(org.eclipse.persistence.testing.models.jpa.inheritance.listeners.VehicleListener.class)
@Table(name="CMP3_VEHICLE")
@Inheritance(strategy=JOINED)
@DiscriminatorColumn(name="VEH_TYPE")
@DiscriminatorValue("V")
public abstract class Vehicle implements Serializable {
private Number id;
private Company owner;
private Integer passengerCapacity;
private VehicleDirectory directory;
public Vehicle() {}
public void change() {
return;
}
public abstract String getColor();
@Id
@GeneratedValue(strategy=TABLE, generator="VEHICLE_TABLE_GENERATOR")
@TableGenerator(
name="VEHICLE_TABLE_GENERATOR",
table="CMP3_INHERITANCE_SEQ",
pkColumnName="SEQ_NAME",
valueColumnName="SEQ_COUNT",
pkColumnValue="VEHICLE_SEQ")
@Column(name="ID")
public Number getId() {
return id;
}
@ManyToOne(cascade=PERSIST, fetch=LAZY)
@JoinColumn(name="OWNER_ID", referencedColumnName="ID")
public Company getOwner() {
return owner;
}
@Column(name="CAPACITY")
public Integer getPassengerCapacity() {
return passengerCapacity;
}
/**
* Return the view for Sybase.
*/
public static ViewDefinition oracleView() {
ViewDefinition definition = new ViewDefinition();
definition.setName("AllVehicles");
definition.setSelectClause("Select V.*, F.FUEL_CAP, F.FUEL_TYP, B.DESCRIP, B.DRIVER_ID, C.CDESCRIP" + " from VEHICLE V, FUEL_VEH F, BUS B, CAR C" + " where V.ID = F.ID (+) AND V.ID = B.ID (+) AND V.ID = C.ID (+)");
return definition;
}
public abstract void setColor(String color);
public void setId(Number id) {
this.id = id;
}
public void setOwner(Company ownerCompany) {
owner = ownerCompany;
}
public void setPassengerCapacity(Integer capacity) {
passengerCapacity = capacity;
}
@ManyToOne(cascade=PERSIST, fetch=LAZY)
@JoinColumn(name="DIRECTORY_ID", referencedColumnName="ID")
public VehicleDirectory getDirectory() {
return directory;
}
public void setDirectory(VehicleDirectory directory) {
this.directory = directory;
}
/**
* Return the view for Sybase.
*/
public static ViewDefinition sybaseView() {
ViewDefinition definition = new ViewDefinition();
definition.setName("AllVehicles");
definition.setSelectClause("Select V.*, F.FUEL_CAP, F.FUEL_TYP, B.DESCRIP, B.DRIVER_ID, C.CDESCRIP" + " from VEHICLE V, FUEL_VEH F, BUS B, CAR C" + " where V.ID *= F.ID AND V.ID *= B.ID AND V.ID *= C.ID");
return definition;
}
public String toString() {
return org.eclipse.persistence.internal.helper.Helper.getShortClassName(getClass()) + "(" + id + ")";
}
}
| epl-1.0 |
sunix/che-plugins | plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/server/rest/TagListWriter.java | 3244 | /*******************************************************************************
* Copyright (c) 2012-2015 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ext.git.server.rest;
import org.eclipse.che.ide.ext.git.shared.Tag;
import javax.inject.Singleton;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Writer to serialize list of git tags to plain text in form as command line git does.
*
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
* @version $Id: $
*/
@Singleton
@Provider
@Produces(MediaType.TEXT_PLAIN)
public final class TagListWriter implements MessageBodyWriter<Iterable<Tag>> {
/**
* @see MessageBodyWriter#isWriteable(Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType)
*/
@Override
public boolean isWriteable(Class< ? > type, Type genericType, Annotation[] annotations, MediaType mediaType) {
if (Iterable.class.isAssignableFrom(type) && (genericType instanceof ParameterizedType)) {
Type[] types = ((ParameterizedType)genericType).getActualTypeArguments();
return types.length == 1 && types[0] == Tag.class;
}
return false;
}
/**
* @see MessageBodyWriter#getSize(Object, Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType)
*/
@Override
public long getSize(Iterable<Tag> tags,
Class< ? > type,
Type genericType,
Annotation[] annotations,
MediaType mediaType) {
return -1;
}
/**
* @see MessageBodyWriter#writeTo(Object, Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType,
* javax.ws.rs.core.MultivaluedMap, java.io.OutputStream)
*/
@Override
public void writeTo(Iterable<Tag> tags,
Class< ? > type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException {
Writer writer = new OutputStreamWriter(entityStream);
for (Tag tag : tags) {
writer.write(tag.getName());
writer.write('\n');
}
writer.flush();
}
}
| epl-1.0 |
gazarenkov/che-sketch | plugins/plugin-docker/che-plugin-docker-machine/src/main/java/org/eclipse/che/plugin/docker/machine/DockerProcess.java | 9181 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.plugin.docker.machine;
import com.google.inject.assistedinject.Assisted;
import org.eclipse.che.api.core.ConflictException;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.model.workspace.config.Command;
import org.eclipse.che.api.core.util.LineConsumer;
import org.eclipse.che.api.core.util.ListLineConsumer;
import org.eclipse.che.api.core.util.ValueHolder;
import org.eclipse.che.api.machine.server.exception.MachineException;
import org.eclipse.che.api.machine.server.spi.InstanceProcess;
import org.eclipse.che.api.machine.server.spi.impl.AbstractMachineProcess;
import org.eclipse.che.commons.annotation.Nullable;
import org.eclipse.che.plugin.docker.client.DockerConnector;
import org.eclipse.che.plugin.docker.client.Exec;
import org.eclipse.che.plugin.docker.client.LogMessage;
import org.eclipse.che.plugin.docker.client.MessageProcessor;
import org.eclipse.che.plugin.docker.client.params.CreateExecParams;
import org.eclipse.che.plugin.docker.client.params.StartExecParams;
import javax.inject.Inject;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import static com.google.common.base.MoreObjects.firstNonNull;
import static java.lang.String.format;
/**
* Docker implementation of {@link InstanceProcess}
*
* @author andrew00x
* @author Alexander Garagatyi
*/
public class DockerProcess extends AbstractMachineProcess implements InstanceProcess {
private final DockerConnector docker;
private final String container;
private final String pidFilePath;
private final String commandLine;
private final String shellInvoker;
private volatile boolean started;
@Inject
public DockerProcess(DockerConnector docker,
@Assisted Command command,
@Assisted("container") String container,
@Nullable @Assisted("outputChannel") String outputChannel,
@Assisted("pid_file_path") String pidFilePath,
@Assisted int pid) {
super(command, pid, outputChannel);
this.docker = docker;
this.container = container;
this.commandLine = command.getCommandLine();
this.shellInvoker = firstNonNull(command.getAttributes().get("shell"), "/bin/sh");
this.pidFilePath = pidFilePath;
this.started = false;
}
@Override
public boolean isAlive() {
if (!started) {
return false;
}
try {
checkAlive();
return true;
} catch (MachineException | NotFoundException e) {
// when process is not found (may be finished or killed)
// when process is not running yet
// when docker is not accessible or responds in an unexpected way - should never happen
return false;
}
}
@Override
public void start() throws ConflictException, MachineException {
start(null);
}
@Override
public void start(LineConsumer output) throws ConflictException, MachineException {
if (started) {
throw new ConflictException("Process already started.");
}
started = true;
// Trap is invoked when bash session ends. Here we kill all sub-processes of shell and remove pid-file.
final String trap = format("trap '[ -z \"$(jobs -p)\" ] || kill $(jobs -p); [ -e %1$s ] && rm %1$s' EXIT", pidFilePath);
// 'echo' saves shell pid in file, then run command
final String shellCommand = trap + "; echo $$>" + pidFilePath + "; " + commandLine;
final String[] command = {shellInvoker, "-c", shellCommand};
Exec exec;
try {
exec = docker.createExec(CreateExecParams.create(container, command).withDetach(output == null));
} catch (IOException e) {
throw new MachineException(format("Error occurs while initializing command %s in docker container %s: %s",
Arrays.toString(command), container, e.getMessage()), e);
}
try {
docker.startExec(StartExecParams.create(exec.getId()), output == null ? null : new LogMessagePrinter(output));
} catch (IOException e) {
if (output != null && e instanceof SocketTimeoutException) {
throw new MachineException(getErrorMessage());
} else {
throw new MachineException(format("Error occurs while executing command %s: %s",
Arrays.toString(exec.getCommand()), e.getMessage()), e);
}
}
}
@Override
public void checkAlive() throws MachineException, NotFoundException {
// Read pid from file and run 'kill -0 [pid]' command.
final String isAliveCmd = format("[ -r %1$s ] && kill -0 $(cat %1$s) || echo 'Unable read PID file'", pidFilePath);
final ListLineConsumer output = new ListLineConsumer();
final String[] command = {"/bin/sh", "-c", isAliveCmd};
Exec exec;
try {
exec = docker.createExec(CreateExecParams.create(container, command).withDetach(false));
} catch (IOException e) {
throw new MachineException(format("Error occurs while initializing command %s in docker container %s: %s",
Arrays.toString(command), container, e.getMessage()), e);
}
try {
docker.startExec(StartExecParams.create(exec.getId()), new LogMessagePrinter(output));
} catch (IOException e) {
throw new MachineException(format("Error occurs while executing command %s in docker container %s: %s",
Arrays.toString(exec.getCommand()), container, e.getMessage()), e);
}
// 'kill -0 [pid]' is silent if process is running or print "No such process" message otherwise
if (!output.getText().isEmpty()) {
throw new NotFoundException(format("Process with pid %s not found", getPid()));
}
}
@Override
public void kill() throws MachineException {
if (started) {
// Read pid from file and run 'kill [pid]' command.
final String killCmd = format("[ -r %1$s ] && kill $(cat %1$s)", pidFilePath);
final String[] command = {"/bin/sh", "-c", killCmd};
Exec exec;
try {
exec = docker.createExec(CreateExecParams.create(container, command).withDetach(true));
} catch (IOException e) {
throw new MachineException(format("Error occurs while initializing command %s in docker container %s: %s",
Arrays.toString(command), container, e.getMessage()), e);
}
try {
docker.startExec(StartExecParams.create(exec.getId()), MessageProcessor.DEV_NULL);
} catch (IOException e) {
throw new MachineException(format("Error occurs while executing command %s in docker container %s: %s",
Arrays.toString(exec.getCommand()), container, e.getMessage()), e);
}
}
}
private String getErrorMessage() {
final StringBuilder errorMessage = new StringBuilder("Command output read timeout is reached.");
try {
// check if process is alive
final Exec checkProcessExec = docker.createExec(
CreateExecParams.create(container,
new String[] {"/bin/sh",
"-c",
format("if kill -0 $(cat %1$s 2>/dev/null) 2>/dev/null; then cat %1$s; fi",
pidFilePath)})
.withDetach(false));
ValueHolder<String> pidHolder = new ValueHolder<>();
docker.startExec(StartExecParams.create(checkProcessExec.getId()), message -> {
if (message.getType() == LogMessage.Type.STDOUT) {
pidHolder.set(message.getContent());
}
});
if (pidHolder.get() != null) {
errorMessage.append(" Process is still running and has id ").append(pidHolder.get()).append(" inside machine");
}
} catch (IOException ignore) {
}
return errorMessage.toString();
}
}
| epl-1.0 |
FTSRG/mondo-collab-framework | archive/mondo-access-control/CollaborationIncQuery/WTSpec.edit/src/WTSpec/provider/CtrlUnit115ItemProvider.java | 7434 | /**
*/
package WTSpec.provider;
import WTSpec.CtrlUnit115;
import WTSpec.WTSpecPackage;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
/**
* This is the item provider adapter for a {@link WTSpec.CtrlUnit115} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class CtrlUnit115ItemProvider extends wtcItemProvider {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CtrlUnit115ItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addInput__iWindSpeedRawPropertyDescriptor(object);
addOutput__oWindSpeedPropertyDescriptor(object);
addOutput__oWindSpeedAveragePropertyDescriptor(object);
addParameter__pNacelleSlopePropertyDescriptor(object);
addParameter__pNacelleOffsetPropertyDescriptor(object);
addParameter__pWindSpeedAveragePeriodPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Input iWind Speed Raw feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addInput__iWindSpeedRawPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Input__iWindSpeedRaw_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Input__iWindSpeedRaw_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__INPUT_IWIND_SPEED_RAW,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Output oWind Speed feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOutput__oWindSpeedPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Output__oWindSpeed_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Output__oWindSpeed_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__OUTPUT_OWIND_SPEED,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Output oWind Speed Average feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOutput__oWindSpeedAveragePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Output__oWindSpeedAverage_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Output__oWindSpeedAverage_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__OUTPUT_OWIND_SPEED_AVERAGE,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Parameter pNacelle Slope feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addParameter__pNacelleSlopePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Parameter__pNacelleSlope_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Parameter__pNacelleSlope_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__PARAMETER_PNACELLE_SLOPE,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Parameter pNacelle Offset feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addParameter__pNacelleOffsetPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Parameter__pNacelleOffset_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Parameter__pNacelleOffset_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__PARAMETER_PNACELLE_OFFSET,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Parameter pWind Speed Average Period feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addParameter__pWindSpeedAveragePeriodPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Parameter__pWindSpeedAveragePeriod_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Parameter__pWindSpeedAveragePeriod_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__PARAMETER_PWIND_SPEED_AVERAGE_PERIOD,
true,
false,
true,
null,
null,
null));
}
/**
* This returns CtrlUnit115.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/CtrlUnit115"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((CtrlUnit115)object).getSysId();
return label == null || label.length() == 0 ?
getString("_UI_CtrlUnit115_type") :
getString("_UI_CtrlUnit115_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| epl-1.0 |
LorenzoBettini/javamm | javamm.ui/src/javamm/ui/launch/JavammLaunchDelegate.java | 146 | package javamm.ui.launch;
import org.eclipse.jdt.launching.JavaLaunchDelegate;
public class JavammLaunchDelegate extends JavaLaunchDelegate {
}
| epl-1.0 |
arpitpanwar/Crawler | src/edu/upenn/cis455/storage/entity/WebPageEntity.java | 78 | package edu.upenn.cis455.storage.entity;
public interface WebPageEntity {
}
| epl-1.0 |
cbaerikebc/kapua | console/src/main/java/org/eclipse/kapua/app/console/client/ui/button/Button.java | 1547 | /*******************************************************************************
* Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech - initial API and implementation
*
*******************************************************************************/
package org.eclipse.kapua.app.console.client.ui.button;
import org.eclipse.kapua.app.console.client.resources.icons.KapuaIcon;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
public class Button extends com.extjs.gxt.ui.client.widget.button.Button {
private String originalText;
private KapuaIcon icon;
public Button(String text, KapuaIcon icon, SelectionListener<ButtonEvent> listener) {
super();
setText(text);
setIcon(icon);
addSelectionListener(listener);
}
@Override
public String getText() {
return originalText;
}
@Override
public void setText(String text) {
super.setText((icon != null ? icon.getInlineHTML() + " " : "") + text);
this.originalText = text;
}
public void setIcon(KapuaIcon icon) {
super.setText(icon.getInlineHTML() + " " + originalText);
this.icon = icon;
}
}
| epl-1.0 |
abstratt/textuml | plugins/com.abstratt.mdd.frontend.textuml.grammar/src-gen/com/abstratt/mdd/frontend/textuml/grammar/node/APackageVisibilityModifier.java | 1990 | /* This file was generated by SableCC (http://www.sablecc.org/). */
package com.abstratt.mdd.frontend.textuml.grammar.node;
import com.abstratt.mdd.frontend.textuml.grammar.analysis.*;
@SuppressWarnings("nls")
public final class APackageVisibilityModifier extends PVisibilityModifier
{
private TPackage _package_;
public APackageVisibilityModifier()
{
// Constructor
}
public APackageVisibilityModifier(
@SuppressWarnings("hiding") TPackage _package_)
{
// Constructor
setPackage(_package_);
}
@Override
public Object clone()
{
return new APackageVisibilityModifier(
cloneNode(this._package_));
}
public void apply(Switch sw)
{
((Analysis) sw).caseAPackageVisibilityModifier(this);
}
public TPackage getPackage()
{
return this._package_;
}
public void setPackage(TPackage node)
{
if(this._package_ != null)
{
this._package_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._package_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._package_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._package_ == child)
{
this._package_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._package_ == oldChild)
{
setPackage((TPackage) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
}
| epl-1.0 |
boyneg/GitLabLession | RacerStart.java | 3698 | /*
Start of Program
*/
import javax.swing.*;
import java.awt.event.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class RacerStart extends JFrame
{
public static boolean gameFreaky = false;
public static boolean buttonState = false;
private boolean gameInProgress;
public static void main(String[] args)
{
RacerStart rs = new RacerStart();
}
/*
* Sound that is played only when the user crashes their car
*/
public void playSoundCrash()
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResource("boo.wav"));
Clip mp3Clip = AudioSystem.getClip();
mp3Clip.open(audioInputStream);
mp3Clip.start();
}
catch(Exception e)
{
System.out.println("ERROR" + e);
}
}
/*
* Creates the interface for the game
*/
public RacerStart()
{
int startCordX = 4;
int stopCordX = startCordX;
int stopCordY = Racer.SCREEN_HEIGHT - 81;
int startCordY = stopCordY - 34;
int freakyCordX = Racer.SCREEN_WIDTH - 142;
int freakyCordY = stopCordY;
LeaderBoard l = new LeaderBoard();
JFrame window = new JFrame();
Racer r = new Racer();
window.setTitle("Totally not a racing game");
window.setSize(Racer.SCREEN_WIDTH, Racer.SCREEN_HEIGHT);
window.setContentPane(r.getPanel());
window.setVisible(true);
window.setLayout(null);
window.setResizable(false);
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton butStop = new JButton("STOP");
JButton butStart = new JButton("START");
JButton butFreaky = new JButton("FREAKY");
JLabel lblScoreDisplay = new JLabel(Integer.toString(r.getScore()));
lblScoreDisplay.setBounds(12, 12, 30, 10);
butStop.setBounds(stopCordX, stopCordY, 120, 30);
butStart.setBounds(startCordX, startCordY, 120, 30);
butFreaky.setBounds(freakyCordX, freakyCordY, 120, 30);
window.add(butStop);
window.add(butStart);
window.add(butFreaky);
window.add(lblScoreDisplay);
/*
* Action listeners for buttons
*/
butFreaky.addActionListener(e -> {
if(buttonState == false) // button looks normal
{
gameFreaky = true;
butFreaky.setBorder(BorderFactory.createLoweredBevelBorder());
buttonState = true;
}
else // button looks pressed
{
gameFreaky = false;
butFreaky.setBorder(null);
buttonState = false;
}
});
// Start and stop buttons
butStart.addActionListener(e -> {
r.start();
});
butStop.addActionListener(e -> {
r.stop();
});
gameInProgress = true;
r.start();
while(true)
{
if (r.hasCrashed() && gameInProgress)
{
r.stop();
l.showBoard();
playSoundCrash();
gameInProgress = false;
}
else if(!r.hasCrashed())
{
gameInProgress = true;
}
// Update the score as the game progresses
lblScoreDisplay.setText(Integer.toString(r.getScore()));
LeaderBoard.newScore = Integer.parseInt (lblScoreDisplay.getText());
r.update();
}
}
} | epl-1.0 |
chaopeng/chaosblog | src/main/java/me/chaopeng/chaosblog/utils/cli_utils/CliUtils.java | 1508 | package me.chaopeng.chaosblog.utils.cli_utils;
import org.apache.commons.cli.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
/**
* 命令行参数类
*
* @author chao
*/
public class CliUtils {
private static final Logger logger = LoggerFactory.getLogger(CliUtils.class);
private static Options opts = new Options();
private static HashMap<String, CliOptionHandler> handlers = new HashMap<String, CliOptionHandler>();
public static void setOption(String opt, Boolean hasArg, String description, CliOptionHandler handler) {
opts.addOption(opt, hasArg, description);
handlers.put(opt, handler);
}
public static void parser(String[] args) {
CommandLineParser parser = new DefaultParser();
try {
CommandLine cl = parser.parse(opts, args);
Option[] options = cl.getOptions();
for (Option option : options) {
CliOptionHandler handler = handlers.get(option.getOpt());
if (handler != null) {
try {
handler.call(option.getValues());
} catch (CliException e) {
logger.error("!!!", e);
}
}
}
} catch (ParseException e) {
logger.error("!!!", e);
}
}
public static void help() {
HelpFormatter hf = new HelpFormatter();
hf.printHelp("Options", opts);
}
}
| epl-1.0 |
jbuchberger/xiliary | com.codeaffine.eclipse.ui.test/src/com/codeaffine/eclipse/ui/progress/TestItem.java | 1537 | package com.codeaffine.eclipse.ui.progress;
import static com.codeaffine.eclipse.ui.progress.ThreadHelper.sleep;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.progress.IDeferredWorkbenchAdapter;
class TestItem implements IAdaptable {
static final int FETCH_CHILDREN_DELAY = 10;
private final TestItemAdapter testItemAdapter;
private final Collection<TestItem> children;
private final TestItem parent;
private final String name;
private boolean ignoreAdapter;
TestItem( TestItem parent, String name ) {
this.testItemAdapter = new TestItemAdapter();
this.children = new ArrayList<TestItem>();
this.parent = parent;
this.name = name;
}
String getName() {
return name;
}
TestItem getParent() {
return parent;
}
Collection<TestItem> getChildren() {
simulateFetchDelay();
return children;
}
@Override
@SuppressWarnings({
"unchecked",
"rawtypes"
})
public Object getAdapter( Class adapter ) {
Object result = null;
if( !ignoreAdapter && adapter == IDeferredWorkbenchAdapter.class ) {
result = testItemAdapter;
} else if( !ignoreAdapter && adapter == IWorkbenchAdapter.class ) {
result = testItemAdapter;
}
return result;
}
void ignoreAdpater() {
ignoreAdapter = true;
}
private void simulateFetchDelay() {
if( !children.isEmpty() ) {
sleep( FETCH_CHILDREN_DELAY );
}
}
} | epl-1.0 |
JonahSloan/Advanced-Java-Tools | src/net/ftp/FtpClient.java | 38154 | /*
* Note: this file is mostly a wrapper for the sun.net.ftp.FtpClient class.
*/
/*
* 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. 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 net.ftp;
import java.net.*;
import java.io.*;
import java.util.Date;
import java.util.List;
import utils.ClassUtils;
import java.util.Iterator;
/**
* A class that implements the FTP protocol according to
* RFCs <A href="http://www.ietf.org/rfc/rfc0959.txt">959</A>,
* <A href="http://www.ietf.org/rfc/rfc2228.txt">2228</A>,
* <A href="http://www.ietf.org/rfc/rfc2389.txt">2389</A>,
* <A href="http://www.ietf.org/rfc/rfc2428.txt">2428</A>,
* <A href="http://www.ietf.org/rfc/rfc3659.txt">3659</A>,
* <A href="http://www.ietf.org/rfc/rfc4217.txt">4217</A>.
* Which includes support for FTP over SSL/TLS (aka ftps).
*
* {@code FtpClient} provides all the functionalities of a typical FTP
* client, like storing or retrieving files, listing or creating directories.
* A typical usage would consist of connecting the client to the server,
* log in, issue a few commands then logout.
* Here is a code example:
*
* <pre>
* FtpClient cl = FtpClient.create();
* cl.connect("ftp.gnu.org").login("anonymous", "john.doe@mydomain.com".toCharArray())).changeDirectory("pub/gnu");
* Iterator<FtpDirEntry> dir = cl.listFiles();
* while (dir.hasNext()) {
* FtpDirEntry f = dir.next();
* System.err.println(f.getName());
* }
* cl.close();
* }
* </pre>
* <p>
* <b>Error reporting:</b> There are, mostly, two families of errors that
* can occur during an FTP session. The first kind are the network related
* issues
* like a connection reset, and they are usually fatal to the session, meaning,
* in all likelyhood the connection to the server has been lost and the session
* should be restarted from scratch. These errors are reported by throwing an
* {@link IOException}. The second kind are the errors reported by the FTP
* server,
* like when trying to download a non-existing file for example. These errors
* are usually non fatal to the session, meaning more commands can be sent to
* the
* server. In these cases, a {@link FtpProtocolException} is thrown.
* </p>
* <p>
* It should be noted that this is not a thread-safe API, as it wouldn't make
* too much sense, due to the very sequential nature of FTP, to provide a
* client able to be manipulated from multiple threads.
*
* @since 1.7
*/
public class FtpClient
{
private static final String ftpClientClassName = "sun.net.ftp.impl.FtpClient";
private static final Class<?> ftpClientClass;
private static final String ftpDirEntryClassName = "sun.net.ftp.FtpDirEntry";
static final Class<?> ftpDirEntryClass;
static {
try{
ftpClientClass = Class.forName(ftpClientClassName);
ftpDirEntryClass = Class.forName(ftpDirEntryClassName);
}
catch(ClassNotFoundException e){
throw new InternalError(e);
}
}
private static final int FTP_PORT = 21;
// /**
// * Returns the default FTP port number.
// *
// * @return the port number.
// */
// public static final int defaultPort(){
// return FTP_PORT;
// }
/**
* Creates an instance of FtpClient and connects it to the specified
* address.
*
* @param dest the {@code InetSocketAddress} to connect to.
* @return The created {@code FtpClient}
* @throws IOException if the connection fails
* @see #connect(java.net.SocketAddress)
*/
public static FtpClient create(InetSocketAddress dest)
throws FtpProtocolException, IOException{
FtpClient client = create();
if(dest != null){
client.connect(dest);
}
return client;
}
/**
* Creates an instance of {@code FtpClient} and connects it to the
* specified host on the default FTP port.
*
* @param dest the {@code String} containing the name of the host
* to connect to.
* @return The created {@code FtpClient}
* @throws IOException if the connection fails.
* @throws FtpProtocolException if the server rejected the connection
*/
public static FtpClient create(String dest)
throws FtpProtocolException, IOException{
return create(new InetSocketAddress(dest, FTP_PORT));
}
/**
* Creates an instance of FtpClient. The client is not connected to any
* server yet.
*
*/
public static FtpClient create(){
return new FtpClient();
}
/**
* Creates an instance of FtpClient. The client is not connected to any
* server yet.
*
*/
protected FtpClient(){
try{
client = ClassUtils.invokeStaticMethod(ftpClientClass, "create");
}
catch(Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Object client;
@SuppressWarnings("unchecked")
private <T,X extends Throwable> T invokeQualifiedMethod(String name, Object... refpairs) throws X{
return (T)normalize(ClassUtils.invokeMethod(ftpClientClass, this.client, name, refpairs));
}
private Object normalize(Object obj){
if(obj==null)
return null;
Class<?> cls = obj.getClass();
if(ftpClientClass.isAssignableFrom(cls)){
client = ftpClientClass.cast(obj);
return this;
}
else if(cls.getSimpleName().equals("FtpReplyCode")){
return ClassUtils.castEnumConstant(obj, FtpReplyCode.class);
}
else if(Iterator.class.isAssignableFrom(cls)){
try{
if(cls.getMethod("next").getReturnType().isAssignableFrom(ftpDirEntryClass)){
return new FtpFileIterator(Iterator.class.cast(obj));
}
}
catch(NoSuchMethodException | SecurityException e){
throw new InternalError(e);
}
}
return obj;
}
/**
* Transfers a file from the client to the server (aka a <I>put</I>)
* by sending the STOR command, and returns the {@code OutputStream}
* from the established data connection.
*
* A new file is created at the server site if the file specified does
* not already exist.
*
* {@link #completePending()} <b>has</b> to be called once the application
* is finished writing to the returned stream.
*
* @param name the name of the remote file to write.
* @return the {@link java.io.OutputStream} from the data connection or
* {@code null} if the command was unsuccessful.
* @throws IOException if an error occurred during the transmission.
* @throws FtpProtocolException if the command was rejected by the server
*/
public OutputStream putFileStream(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("putFileStream", String.class, name);
}
/**
* Transfers a file from the client to the server (aka a <I>put</I>)
* by sending the STOR or STOU command, depending on the
* {@code unique} argument. The content of the {@code InputStream}
* passed in argument is written into the remote file, overwriting any
* existing data.
*
* A new file is created at the server site if the file specified does
* not already exist.
*
* If {@code unique} is set to {@code true}, the resultant file
* is to be created under a name unique to that directory, meaning
* it will not overwrite an existing file, instead the server will
* generate a new, unique, file name.
* The name of the remote file can be retrieved, after completion of the
* transfer, by calling {@link #getLastFileName()}.
*
* <p>
* This method will block until the transfer is complete or an exception
* is thrown.
* </p>
*
* @param name the name of the remote file to write.
* @param local the {@code InputStream} that points to the data to
* transfer.
* @return this FtpClient
* @throws IOException if an error occurred during the transmission.
* @throws FtpProtocolException if the command was rejected by the server
*/
public FtpClient putFile(String name, InputStream local)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("putFile", String.class, name, InputStream.class, local);
}
/**
* Changes the current transfer type to binary.
*
* @return This FtpClient
* @throws IOException if an error occurs during the transmission.
* @throws FtpProtocolException if the command was rejected by the server
*/
public FtpClient setBinaryType() throws FtpProtocolException, IOException{
return invokeQualifiedMethod("setBinaryType");
}
/**
* Changes the current transfer type to ascii.
*
* @return This FtpClient
* @throws IOException if an error occurs during the transmission.
* @throws FtpProtocolException if the command was rejected by the server
*/
public FtpClient setAsciiType() throws FtpProtocolException, IOException{
return invokeQualifiedMethod("setAsciiType");
}
/**
* Set the transfer mode to <I>passive</I>. In that mode, data connections
* are established by having the client connect to the server.
* This is the recommended default mode as it will work best through
* firewalls and NATs.
*
* @return This FtpClient
* @see #setActiveMode()
*/
public FtpClient enablePassiveMode(boolean passive){
return invokeQualifiedMethod("enablePassiveMode", boolean.class, passive);
}
/**
* Gets the current transfer mode.
*
* @return the current <code>FtpTransferMode</code>
*/
public boolean isPassiveModeEnabled(){
return invokeQualifiedMethod("isPassiveModeEnabled");
}
/**
* Sets the timeout value to use when connecting to the server,
*
* @param timeout the timeout value, in milliseconds, to use for the connect
* operation. A value of zero or less, means use the default timeout.
*
* @return This FtpClient
*/
public FtpClient setConnectTimeout(int timeout){
return invokeQualifiedMethod("setConnectTimeout", int.class, timeout);
}
/**
* Returns the current connection timeout value.
*
* @return the value, in milliseconds, of the current connect timeout.
* @see #setConnectTimeout(int)
*/
public int getConnectTimeout(){
return invokeQualifiedMethod("getConnectTimeout");
}
/**
* Sets the timeout value to use when reading from the server,
*
* @param timeout the timeout value, in milliseconds, to use for the read
* operation. A value of zero or less, means use the default timeout.
* @return This FtpClient
*/
public FtpClient setReadTimeout(int timeout){
return invokeQualifiedMethod("setReadTimeout", int.class, timeout);
}
/**
* Returns the current read timeout value.
*
* @return the value, in milliseconds, of the current read timeout.
* @see #setReadTimeout(int)
*/
public int getReadTimeout(){
return invokeQualifiedMethod("getReadTimeout");
}
/**
* Set the {@code Proxy} to be used for the next connection.
* If the client is already connected, it doesn't affect the current
* connection. However it is not recommended to change this during a
* session.
*
* @param p the {@code Proxy} to use, or {@code null} for no proxy.
* @return This FtpClient
*/
public FtpClient setProxy(Proxy p){
return invokeQualifiedMethod("setProxy", Proxy.class, p);
}
/**
* Get the proxy of this FtpClient
*
* @return the <code>Proxy</code>, this client is using, or
* <code>null</code>
* if none is used.
* @see #setProxy(Proxy)
*/
public Proxy getProxy(){
return invokeQualifiedMethod("getProxy");
}
/**
* Tests whether this client is connected or not to a server.
*
* @return <code>true</code> if the client is connected.
*/
public boolean isConnected(){
return invokeQualifiedMethod("isConnected");
}
/**
* Retrieves the address of the FTP server this client is connected to.
*
* @return the {@link SocketAddress} of the server, or {@code null} if this
* client is not connected yet.
*/
public SocketAddress getServerAddress(){
return invokeQualifiedMethod("getServerAddress");
}
/**
* Connects the {@code FtpClient} to the specified destination server.
*
* @param dest the address of the destination server
* @return this FtpClient
* @throws IOException if connection failed.
* @throws SecurityException if there is a SecurityManager installed and it
* denied the authorization to connect to the destination.
* @throws FtpProtocolException
*/
public FtpClient connect(SocketAddress dest)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("connect", SocketAddress.class, dest);
}
/**
* Connects the FtpClient to the specified destination.
*
* @param dest the address of the destination server
* @throws IOException if connection failed.
*/
public FtpClient connect(SocketAddress dest, int timeout)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("connect", SocketAddress.class, dest, int.class, timeout);
}
/**
* Attempts to log on the server with the specified user name and password.
*
* @param user The user name
* @param password The password for that user
* @return <code>true</code> if the login was successful.
* @throws IOException if an error occurred during the transmission
*/
public FtpClient login(String user, char[] password)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("login", String.class, user, char[].class, password);
}
/**
* Attempts to log on the server with the specified user name, password and
* account name.
*
* @param user The user name
* @param password The password for that user.
* @param account The account name for that user.
* @return <code>true</code> if the login was successful.
* @throws IOException if an error occurs during the transmission.
*/
public FtpClient login(String user, char[] password, String account)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("login", String.class, user, char[].class, password, String.class, account);
}
/**
* Logs out the current user. This is in effect terminates the current
* session and the connection to the server will be closed.
*
*/
public void close() throws IOException{
invokeQualifiedMethod("close");
}
/**
* Checks whether the client is logged in to the server or not.
*
* @return <code>true</code> if the client has already completed a login.
*/
public boolean isLoggedIn(){
return invokeQualifiedMethod("isLoggedIn");
}
/**
* Changes to a specific directory on a remote FTP server
*
* @param remoteDirectory path of the directory to CD to.
* @return <code>true</code> if the operation was successful.
* @exception <code>FtpProtocolException</code>
*/
public FtpClient changeDirectory(String remoteDirectory)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("changeDirectory", String.class, remoteDirectory);
}
/**
* Changes to the parent directory, sending the CDUP command to the server.
*
* @return <code>true</code> if the command was successful.
* @throws IOException
*/
public FtpClient changeToParentDirectory()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("changeToParentDirectory");
}
/**
* Returns the server current working directory, or <code>null</code> if
* the PWD command failed.
*
* @return a <code>String</code> containing the current working directory,
* or <code>null</code>
* @throws IOException
*/
public String getWorkingDirectory()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getWorkingDirectory");
}
/**
* Sets the restart offset to the specified value. That value will be
* sent through a <code>REST</code> command to server before a file
* transfer and has the effect of resuming a file transfer from the
* specified point. After a transfer the restart offset is set back to
* zero.
*
* @param offset the offset in the remote file at which to start the next
* transfer. This must be a value greater than or equal to zero.
* @throws IllegalArgumentException if the offset is negative.
*/
public FtpClient setRestartOffset(long offset){
return invokeQualifiedMethod("setRestartOffset", long.class, offset);
}
/**
* Retrieves a file from the ftp server and writes it to the specified
* <code>OutputStream</code>.
* If the restart offset was set, then a <code>REST</code> command will be
* sent before the RETR in order to restart the tranfer from the specified
* offset.
* The <code>OutputStream</code> is not closed by this method at the end
* of the transfer.
*
* @param name a <code>String<code> containing the name of the file to
* retreive from the server.
* @param local the <code>OutputStream</code> the file should be written to.
* @throws IOException if the transfer fails.
*/
public FtpClient getFile(String name, OutputStream local)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getFile", String.class, name, OutputStream.class, local);
}
/**
* Retrieves a file from the ftp server, using the RETR command, and
* returns the InputStream from* the established data connection.
* {@link #completePending()} <b>has</b> to be called once the application
* is done reading from the returned stream.
*
* @param name the name of the remote file
* @return the {@link java.io.InputStream} from the data connection, or
* <code>null</code> if the command was unsuccessful.
* @throws IOException if an error occurred during the transmission.
*/
public InputStream getFileStream(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getFileStream", String.class, name);
}
/**
* Transfers a file from the client to the server (aka a <I>put</I>)
* by sending the STOR or STOU command, depending on the
* <code>unique</code> argument, and returns the <code>OutputStream</code>
* from the established data connection.
* {@link #completePending()} <b>has</b> to be called once the application
* is finished writing to the stream.
*
* A new file is created at the server site if the file specified does
* not already exist.
*
* If <code>unique</code> is set to <code>true</code>, the resultant file
* is to be created under a name unique to that directory, meaning
* it will not overwrite an existing file, instead the server will
* generate a new, unique, file name.
* The name of the remote file can be retrieved, after completion of the
* transfer, by calling {@link #getLastFileName()}.
*
* @param name the name of the remote file to write.
* @param unique <code>true</code> if the remote files should be unique,
* in which case the STOU command will be used.
* @return the {@link java.io.OutputStream} from the data connection or
* <code>null</code> if the command was unsuccessful.
* @throws IOException if an error occurred during the transmission.
*/
public OutputStream putFileStream(String name, boolean unique)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("putFileStream", String.class, name, boolean.class, unique);
}
/**
* Transfers a file from the client to the server (aka a <I>put</I>)
* by sending the STOR command. The content of the <code>InputStream</code>
* passed in argument is written into the remote file, overwriting any
* existing data.
*
* A new file is created at the server site if the file specified does
* not already exist.
*
* @param name the name of the remote file to write.
* @param local the <code>InputStream</code> that points to the data to
* transfer.
* @param unique <code>true</code> if the remote file should be unique
* (i.e. not already existing), <code>false</code> otherwise.
* @return <code>true</code> if the transfer was successful.
* @throws IOException if an error occurred during the transmission.
* @see #getLastFileName()
*/
public FtpClient putFile(String name, InputStream local, boolean unique)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("putFile", String.class, name, InputStream.class, local, boolean.class, unique);
}
/**
* Sends the APPE command to the server in order to transfer a data stream
* passed in argument and append it to the content of the specified remote
* file.
*
* @param name A <code>String</code> containing the name of the remote file
* to append to.
* @param local The <code>InputStream</code> providing access to the data
* to be appended.
* @return <code>true</code> if the transfer was successful.
* @throws IOException if an error occurred during the transmission.
*/
public FtpClient appendFile(String name, InputStream local)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("appendFile", String.class, name, InputStream.class, local);
}
/**
* Renames a file on the server.
*
* @param from the name of the file being renamed
* @param to the new name for the file
* @throws IOException if the command fails
*/
public FtpClient rename(String from, String to)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("rename", String.class, from, String.class, to);
}
/**
* Deletes a file on the server.
*
* @param name a <code>String</code> containing the name of the file
* to delete.
* @return <code>true</code> if the command was successful
* @throws IOException if an error occurred during the exchange
*/
public FtpClient deleteFile(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("deleteFile", String.class, name);
}
/**
* Creates a new directory on the server.
*
* @param name a <code>String</code> containing the name of the directory
* to create.
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during the exchange
*/
public FtpClient makeDirectory(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("makeDirectory", String.class, name);
}
/**
* Removes a directory on the server.
*
* @param name a <code>String</code> containing the name of the directory
* to remove.
*
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during the exchange.
*/
public FtpClient removeDirectory(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("removeDirectory", String.class, name);
}
/**
* Sends a No-operation command. It's useful for testing the connection
* status or as a <I>keep alive</I> mechanism.
*
* @throws FtpProtocolException if the command fails
*/
public FtpClient noop()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("noop");
}
/**
* Sends the STAT command to the server.
* This can be used while a data connection is open to get a status
* on the current transfer, in that case the parameter should be
* <code>null</code>.
* If used between file transfers, it may have a pathname as argument
* in which case it will work as the LIST command except no data
* connection will be created.
*
* @param name an optional <code>String</code> containing the pathname
* the STAT command should apply to.
* @return the response from the server or <code>null</code> if the
* command failed.
* @throws IOException if an error occurred during the transmission.
*/
public String getStatus(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getStatus", String.class, name);
}
/**
* Sends the FEAT command to the server and returns the list of supported
* features in the form of strings.
*
* The features are the supported commands, like AUTH TLS, PROT or PASV.
* See the RFCs for a complete list.
*
* Note that not all FTP servers support that command, in which case
* the method will return <code>null</code>
*
* @return a <code>List</code> of <code>Strings</code> describing the
* supported additional features, or <code>null</code>
* if the command is not supported.
* @throws IOException if an error occurs during the transmission.
*/
public List<String> getFeatures()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getFeatures");
}
/**
* sends the ABOR command to the server.
* It tells the server to stop the previous command or transfer.
*
* @return <code>true</code> if the command was successful.
* @throws IOException if an error occurred during the transmission.
*/
public FtpClient abort()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("abort");
}
/**
* Some methods do not wait until completion before returning, so this
* method can be called to wait until completion. This is typically the case
* with commands that trigger a transfer like {@link #getFileStream(String)}
* .
* So this method should be called before accessing information related to
* such a command.
* <p>
* This method will actually block reading on the command channel for a
* notification from the server that the command is finished. Such a
* notification often carries extra information concerning the completion
* of the pending action (e.g. number of bytes transfered).
* </p>
* <p>
* Note that this will return true immediately if no command or action
* is pending
* </p>
* <p>
* It should be also noted that most methods issuing commands to the ftp
* server will call this method if a previous command is pending.
* <p>
* Example of use:
*
* <pre>
* InputStream in = cl.getFileStream("file");
* ...
* cl.completePending();
* long size = cl.getLastTransferSize();
* </pre>
*
* On the other hand, it's not necessary in a case like:
*
* <pre>
* InputStream in = cl.getFileStream("file");
* // read content
* ...
* cl.logout();
* </pre>
* <p>
* Since {@link #logout()} will call completePending() if necessary.
* </p>
*
* @return <code>true</code> if the completion was successful or if no
* action was pending.
* @throws IOException
*/
public FtpClient completePending()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("completePending");
}
/**
* Reinitializes the USER parameters on the FTP server
*
* @throws FtpProtocolException if the command fails
*/
public FtpClient reInit()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("reInit");
}
/**
* Issues a LIST command to the server to get the current directory
* listing, and returns the InputStream from the data connection.
* {@link #completePending()} <b>has</b> to be called once the application
* is finished writing to the stream.
*
* @param path the pathname of the directory to list, or <code>null</code>
* for the current working directory.
* @return the <code>InputStream</code> from the resulting data connection
* @throws IOException if an error occurs during the transmission.
* @see #changeDirectory(String)
* @see #listFiles(String)
*/
public InputStream list(String path)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("list", String.class, path);
}
/**
* Issues a NLST path command to server to get the specified directory
* content. It differs from {@link #list(String)} method by the fact that
* it will only list the file names which would make the parsing of the
* somewhat easier.
*
* {@link #completePending()} <b>has</b> to be called once the application
* is finished writing to the stream.
*
* @param path a <code>String</code> containing the pathname of the
* directory to list or <code>null</code> for the current working
* directory.
* @return the <code>InputStream</code> from the resulting data connection
* @throws IOException if an error occurs during the transmission.
*/
public InputStream nameList(String path)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("nameList", String.class, path);
}
/**
* Issues the SIZE [path] command to the server to get the size of a
* specific file on the server.
* Note that this command may not be supported by the server. In which
* case -1 will be returned.
*
* @param path a <code>String</code> containing the pathname of the
* file.
* @return a <code>long</code> containing the size of the file or -1 if
* the server returned an error, which can be checked with
* {@link #getLastReplyCode()}.
* @throws IOException if an error occurs during the transmission.
*/
public long getSize(String path)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getSize", String.class, path);
}
/**
* Issues the MDTM [path] command to the server to get the modification
* time of a specific file on the server.
* Note that this command may not be supported by the server, in which
* case <code>null</code> will be returned.
*
* @param path a <code>String</code> containing the pathname of the file.
* @return a <code>Date</code> representing the last modification time
* or <code>null</code> if the server returned an error, which
* can be checked with {@link #getLastReplyCode()}.
* @throws IOException if an error occurs during the transmission.
*/
public Date getLastModified(String path)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getLastModified", String.class, path);
}
/**
* Issues a MLSD command to the server to get the specified directory
* listing and applies the current parser to create an Iterator of
* {@link java.net.ftp.FtpDirEntry}. Note that the Iterator returned is also
* a
* {@link java.io.Closeable}.
* If the server doesn't support the MLSD command, the LIST command is used
* instead.
*
* {@link #completePending()} <b>has</b> to be called once the application
* is finished iterating through the files.
*
* @param path the pathname of the directory to list or <code>null</code>
* for the current working directoty.
* @return a <code>Iterator</code> of files or <code>null</code> if the
* command failed.
* @throws IOException if an error occurred during the transmission
* @see #setDirParser(FtpDirParser)
* @see #changeDirectory(String)
*/
public Iterator<FtpDirEntry> listFiles(String path)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("listFiles", String.class, path);
}
/**
* Attempts to use Kerberos GSSAPI as an authentication mechanism with the
* ftp server. This will issue an <code>AUTH GSSAPI</code> command, and if
* it is accepted by the server, will followup with <code>ADAT</code>
* command to exchange the various tokens until authentification is
* successful. This conforms to Appendix I of RFC 2228.
*
* @return <code>true</code> if authentication was successful.
* @throws IOException if an error occurs during the transmission.
*/
public FtpClient useKerberos()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("useKerberos");
}
/**
* Returns the Welcome string the server sent during initial connection.
*
* @return a <code>String</code> containing the message the server
* returned during connection or <code>null</code>.
*/
public String getWelcomeMsg(){
return invokeQualifiedMethod("getWelcomeMsg");
}
/**
* Returns the last reply code sent by the server.
*
* @return the lastReplyCode
*/
public FtpReplyCode getLastReplyCode(){
return invokeQualifiedMethod("getLastReplyCode");
}
/**
* Returns the last response string sent by the server.
*
* @return the message string, which can be quite long, last returned
* by the server.
*/
public String getLastResponseString(){
return invokeQualifiedMethod("getLastResponseString");
}
/**
* Returns, when available, the size of the latest started transfer.
* This is retreived by parsing the response string received as an initial
* response to a RETR or similar request.
*
* @return the size of the latest transfer or -1 if either there was no
* transfer or the information was unavailable.
*/
public long getLastTransferSize(){
return invokeQualifiedMethod("getLastTransferSize");
}
/**
* Returns, when available, the remote name of the last transfered file.
* This is mainly useful for "put" operation when the unique flag was
* set since it allows to recover the unique file name created on the
* server which may be different from the one submitted with the command.
*
* @return the name the latest transfered file remote name, or
* <code>null</code> if that information is unavailable.
*/
public String getLastFileName(){
return invokeQualifiedMethod("getLastFileName");
}
/**
* Attempts to switch to a secure, encrypted connection. This is done by
* sending the "AUTH TLS" command.
* <p>
* See <a href="http://www.ietf.org/rfc/rfc4217.txt">RFC 4217</a>
* </p>
* If successful this will establish a secure command channel with the
* server, it will also make it so that all other transfers (e.g. a RETR
* command) will be done over an encrypted channel as well unless a
* {@link #reInit()} command or a {@link #endSecureSession()} command is
* issued.
*
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during the transmission.
* @see #endSecureSession()
*/
public FtpClient startSecureSession()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("startSecureSession");
}
/**
* Sends a <code>CCC</code> command followed by a <code>PROT C</code>
* command to the server terminating an encrypted session and reverting
* back to a non crypted transmission.
*
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during transmission.
* @see #startSecureSession()
*/
public FtpClient endSecureSession()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("endSecureSession");
}
/**
* Sends the "Allocate" (ALLO) command to the server telling it to
* pre-allocate the specified number of bytes for the next transfer.
*
* @param size The number of bytes to allocate.
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during the transmission.
*/
public FtpClient allocate(long size)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("allocate", long.class, size);
}
/**
* Sends the "Structure Mount" (SMNT) command to the server. This let the
* user mount a different file system data structure without altering his
* login or accounting information.
*
* @param struct a <code>String</code> containing the name of the
* structure to mount.
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during the transmission.
*/
public FtpClient structureMount(String struct)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("structureMount", String.class, struct);
}
/**
* Sends a SYST (System) command to the server and returns the String
* sent back by the server describing the operating system at the
* server.
*
* @return a <code>String</code> describing the OS, or <code>null</code>
* if the operation was not successful.
* @throws IOException if an error occurred during the transmission.
*/
public String getSystem()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getSystem");
}
/**
* Sends the HELP command to the server, with an optional command, like
* SITE, and returns the text sent back by the server.
*
* @param cmd the command for which the help is requested or
* <code>null</code> for the general help
* @return a <code>String</code> containing the text sent back by the
* server, or <code>null</code> if the command failed.
* @throws IOException if an error occurred during transmission
*/
public String getHelp(String cmd)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getHelp", String.class, cmd);
}
/**
* Sends the SITE command to the server. This is used by the server
* to provide services specific to his system that are essential
* to file transfer.
*
* @param cmd the command to be sent.
* @return <code>true</code> if the command was successful.
* @throws IOException if an error occurred during transmission
*/
public FtpClient siteCmd(String cmd)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("siteCmd", String.class, cmd);
}
private class FtpFileIterator implements Iterator<FtpDirEntry>, Closeable{
private final Iterator<?> it;
FtpFileIterator(Iterator<?> it){
if(!Closeable.class.isAssignableFrom(it.getClass()))
throw new InternalError("Argument \"it\" does not implement Closeable!");
this.it=it;
}
public void close() throws IOException{
Closeable.class.cast(it).close();
}
public boolean hasNext(){
return it.hasNext();
}
public FtpDirEntry next(){
return new FtpDirEntry(it.next());
}
public void remove(){
it.remove();
}
}
}
| epl-1.0 |
qqbbyq/controller | opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/concurrent_data_broker/DomConcurrentDataBrokerModuleFactory.java | 1546 | /*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.config.yang.config.concurrent_data_broker;
import org.opendaylight.controller.config.api.DependencyResolver;
import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
import org.opendaylight.controller.config.spi.Module;
import org.osgi.framework.BundleContext;
public class DomConcurrentDataBrokerModuleFactory extends AbstractDomConcurrentDataBrokerModuleFactory {
@Override
public Module createModule(String instanceName, DependencyResolver dependencyResolver, BundleContext bundleContext) {
DomConcurrentDataBrokerModule module = (DomConcurrentDataBrokerModule)super.createModule(instanceName,
dependencyResolver, bundleContext);
module.setBundleContext(bundleContext);
return module;
}
@Override
public Module createModule(String instanceName, DependencyResolver dependencyResolver, DynamicMBeanWithInstance old,
BundleContext bundleContext) throws Exception {
DomConcurrentDataBrokerModule module = (DomConcurrentDataBrokerModule)super.createModule(instanceName,
dependencyResolver, old, bundleContext);
module.setBundleContext(bundleContext);
return module;
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/weaving/SimpleObject.java | 3716 | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.weaving;
// J2SE imports
import java.io.Serializable;
// Persistence imports
import javax.persistence.*;
import static javax.persistence.GenerationType.*;
@Entity
@Table(name="SIMPLE")
public class SimpleObject implements Serializable {
// ensure we have at least one of each type of primitive
private int version;
private boolean booleanAttribute;
private char charAttribute;
private byte byteAttribute;
private short shortAttribute;
private long longAttribute;
private float floatAttribute;
private double doubleAttribute;
// have some objects, too
private Integer id; // PK
private String name;
private SimpleAggregate simpleAggregate;
public SimpleObject () {
}
@Id
@GeneratedValue(strategy=TABLE, generator="SIMPLE_TABLE_GENERATOR")
@TableGenerator(
name="SIMPLE_TABLE_GENERATOR",
table="SIMPLE_SEQ",
pkColumnName="SEQ_NAME",
valueColumnName="SEQ_COUNT",
pkColumnValue="SIMPLE_SEQ"
)
@Column(name="ID")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Version
@Column(name="VERSION")
public int getVersion() {
return version;
}
protected void setVersion(int version) {
this.version = version;
}
@Column(name="NAME", length=80)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isBooleanAttribute() {
return booleanAttribute;
}
public void setBooleanAttribute(boolean booleanAttribute) {
this.booleanAttribute = booleanAttribute;
}
public byte getByteAttribute() {
return byteAttribute;
}
public void setByteAttribute(byte byteAttribute) {
this.byteAttribute = byteAttribute;
}
public char getCharAttribute() {
return charAttribute;
}
public void setCharAttribute(char charAttribute) {
this.charAttribute = charAttribute;
}
public double getDoubleAttribute() {
return doubleAttribute;
}
public void setDoubleAttribute(double doubleAttribute) {
this.doubleAttribute = doubleAttribute;
}
public float getFloatAttribute() {
return floatAttribute;
}
public void setFloatAttribute(float floatAttribute) {
this.floatAttribute = floatAttribute;
}
public long getLongAttribute() {
return longAttribute;
}
public void setLongAttribute(long longAttribute) {
this.longAttribute = longAttribute;
}
public short getShortAttribute() {
return shortAttribute;
}
public void setShortAttribute(short shortAttribute) {
this.shortAttribute = shortAttribute;
}
@Embedded()
public SimpleAggregate getSimpleAggregate() {
return simpleAggregate;
}
public void setSimpleAggregate(SimpleAggregate simpleAggregate) {
this.simpleAggregate = simpleAggregate;
}
}
| epl-1.0 |
SK-HOLDINGS-CC/NEXCORE-UML-Modeler | nexcore.tool.uml.ui.analysis/src/java/nexcore/tool/uml/ui/analysis/activitydiagram/command/DeleteActivityPartitionNodeCommand.java | 5600 | /**
* Copyright (c) 2015 SK holdings Co., Ltd. All rights reserved.
* This software is the confidential and proprietary information of SK holdings.
* You shall not disclose such confidential information and shall use it only in
* accordance with the terms of the license agreement you entered into with SK holdings.
* (http://www.eclipse.org/legal/epl-v10.html)
*/
package nexcore.tool.uml.ui.analysis.activitydiagram.command;
import java.util.ArrayList;
import java.util.List;
import nexcore.tool.uml.manager.UMLManager;
import nexcore.tool.uml.model.umldiagram.AbstractConnection;
import nexcore.tool.uml.model.umldiagram.AbstractNode;
import nexcore.tool.uml.model.umldiagram.ContainerNode;
import nexcore.tool.uml.model.umldiagram.Diagram;
import nexcore.tool.uml.model.umldiagram.NodeType;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;
/**
* <ul>
* <li>업무 그룹명 : nexcore.tool.uml.ui.analysis</li>
* <li>서브 업무명 : nexcore.tool.uml.ui.analysis.activitydiagram.command</li>
* <li>설 명 : DeleteActivityPartitionNodeCommand</li>
* <li>작성일 : 2011. 7. 12.</li>
* <li>작성자 : Kang</li>
* </ul>
*/
public class DeleteActivityPartitionNodeCommand extends Command {
/**
* parent
*/
private AbstractNode parent;
/**
* 삭제할 노드
*/
private ContainerNode node;
/**
* @see org.eclipse.gef.commands.Command#execute()
*/
public void execute() {
Diagram diagram = null;
if( parent instanceof Diagram ) {
diagram = (Diagram) parent;
}
if( null == diagram ) {
return;
}
List<AbstractNode> nodeList = new ArrayList<AbstractNode>();
nodeList = node.getNodeList();
List<AbstractConnection> incomingList = new ArrayList<AbstractConnection>();
List<AbstractConnection> outgoingList = new ArrayList<AbstractConnection>();
List<ContainerNode> partitionList = new ArrayList<ContainerNode>();
for( AbstractNode abstractNode : nodeList ) {
incomingList.addAll( abstractNode.getIncomingConnectionList() );
outgoingList.addAll( abstractNode.getOutgoingConnectionList() );
}
for( AbstractConnection connection : incomingList ) {
diagram.getConnectionList().remove(connection);
node.getConnectionList().remove(connection);
UMLManager.deleteElement(connection.getUmlModel());
UMLManager.deleteElement(connection);
AbstractNode sourceNode = (AbstractNode) connection.getSource();
sourceNode.getOutgoingConnectionList().remove(connection);
}
for( AbstractConnection connection : outgoingList ) {
diagram.getConnectionList().remove(connection);
node.getConnectionList().remove(connection);
UMLManager.deleteElement(connection.getUmlModel());
UMLManager.deleteElement(connection);
AbstractNode targetNode = (AbstractNode) connection.getTarget();
targetNode.getIncomingConnectionList().remove(connection);
}
for( int i = nodeList.size() - 1; i >= 0; i-- ) {
AbstractNode abstractNode = nodeList.get(i);
diagram.getNodeList().remove(abstractNode);
node.getNodeList().remove(abstractNode);
UMLManager.deleteElement(abstractNode.getUmlModel());
UMLManager.deleteElement(abstractNode);
}
for( AbstractNode abstractNode : diagram.getNodeList() ) {
if( abstractNode instanceof ContainerNode ) {
ContainerNode containerNode = (ContainerNode) abstractNode;
if( NodeType.ACTIVITY_PARTITION.equals(containerNode.getNodeType()) ) {
partitionList.add(containerNode);
}
}
}
Rectangle bounds = new Rectangle();
bounds.setLocation( node.getX(), node.getY() );
bounds.setSize( node.getWidth(), node.getHeight() );
int indexOfCurrentNode = partitionList.indexOf(node);
UMLManager.deleteElement(node.getUmlModel());
UMLManager.deleteElement(node);
if( partitionList.size() - 1 != indexOfCurrentNode ) {
ContainerNode nextContainerNode = partitionList.get( indexOfCurrentNode + 1 );
nextContainerNode.setX(bounds.x);
nextContainerNode.setWidth( nextContainerNode.getWidth() + bounds.width );
}
}
/**
* @return the parent
*/
public AbstractNode getParent() {
return parent;
}
/**
* 삭제 액션 Diagram 설정
*
* @param model
* void
*/
public void setParent(Object model) {
if (model instanceof AbstractNode) {
parent = (AbstractNode) model;
} else {
parent = null;
}
}
/**
* 삭제할 node 반환
*
* @return the node
*/
public AbstractNode getNode() {
return node;
}
/**
* 삭제될 node 저장.
*
* @param model
* void
*/
public void setNode(Object model) {
if (model instanceof AbstractNode) {
node = (ContainerNode) model;
} else {
node = null;
}
}
}
| epl-1.0 |
forge/plugin-undo | src/main/jgit/org/jboss/forge/jgit/util/RawCharUtil.java | 3984 | /*
* Copyright (C) 2010, Google Inc.
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*/
package org.jboss.forge.jgit.util;
/**
* Utility class for character functions on raw bytes
* <p>
* Characters are assumed to be 8-bit US-ASCII.
*/
public class RawCharUtil {
private static final boolean[] WHITESPACE = new boolean[256];
static {
WHITESPACE['\r'] = true;
WHITESPACE['\n'] = true;
WHITESPACE['\t'] = true;
WHITESPACE[' '] = true;
}
/**
* Determine if an 8-bit US-ASCII encoded character is represents whitespace
*
* @param c
* the 8-bit US-ASCII encoded character
* @return true if c represents a whitespace character in 8-bit US-ASCII
*/
public static boolean isWhitespace(byte c) {
return WHITESPACE[c & 0xff];
}
/**
* Returns the new end point for the byte array passed in after trimming any
* trailing whitespace characters, as determined by the isWhitespace()
* function. start and end are assumed to be within the bounds of raw.
*
* @param raw
* the byte array containing the portion to trim whitespace for
* @param start
* the start of the section of bytes
* @param end
* the end of the section of bytes
* @return the new end point
*/
public static int trimTrailingWhitespace(byte[] raw, int start, int end) {
int ptr = end - 1;
while (start <= ptr && isWhitespace(raw[ptr]))
ptr--;
return ptr + 1;
}
/**
* Returns the new start point for the byte array passed in after trimming
* any leading whitespace characters, as determined by the isWhitespace()
* function. start and end are assumed to be within the bounds of raw.
*
* @param raw
* the byte array containing the portion to trim whitespace for
* @param start
* the start of the section of bytes
* @param end
* the end of the section of bytes
* @return the new start point
*/
public static int trimLeadingWhitespace(byte[] raw, int start, int end) {
while (start < end && isWhitespace(raw[start]))
start++;
return start;
}
private RawCharUtil() {
// This will never be called
}
}
| epl-1.0 |
occiware/OCCI-Studio | plugins/org.eclipse.cmf.occi.core.editor/src-gen/org/eclipse/cmf/occi/core/presentation/OCCIModelWizard.java | 17927 | /**
* Copyright (c) 2017 Inria
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* - Faiez Zalila <faiez.zalila@inria.fr>
*/
package org.eclipse.cmf.occi.core.presentation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.StringTokenizer;
import org.eclipse.emf.common.CommonPlugin;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.WizardNewFileCreationPage;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.cmf.occi.core.OCCIFactory;
import org.eclipse.cmf.occi.core.OCCIPackage;
import org.eclipse.cmf.occi.core.provider.OCCIEditPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
/**
* This is a simple wizard for creating a new model file.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class OCCIModelWizard extends Wizard implements INewWizard {
/**
* The supported extensions for created files.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<String> FILE_EXTENSIONS =
Collections.unmodifiableList(Arrays.asList(OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIEditorFilenameExtensions").split("\\s*,\\s*")));
/**
* A formatted list of supported file extensions, suitable for display.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final String FORMATTED_FILE_EXTENSIONS =
OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIEditorFilenameExtensions").replaceAll("\\s*,\\s*", ", ");
/**
* This caches an instance of the model package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OCCIPackage occiPackage = OCCIPackage.eINSTANCE;
/**
* This caches an instance of the model factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OCCIFactory occiFactory = occiPackage.getOCCIFactory();
/**
* This is the file creation page.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OCCIModelWizardNewFileCreationPage newFileCreationPage;
/**
* This is the initial object creation page.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OCCIModelWizardInitialObjectCreationPage initialObjectCreationPage;
/**
* Remember the selection during initialization for populating the default container.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IStructuredSelection selection;
/**
* Remember the workbench during initialization.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IWorkbench workbench;
/**
* Caches the names of the types that can be created as the root object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected List<String> initialObjectNames;
/**
* This just records the information.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void init(IWorkbench workbench, IStructuredSelection selection) {
this.workbench = workbench;
this.selection = selection;
setWindowTitle(OCCIEditorPlugin.INSTANCE.getString("_UI_Wizard_label"));
setDefaultPageImageDescriptor(ExtendedImageRegistry.INSTANCE.getImageDescriptor(OCCIEditorPlugin.INSTANCE.getImage("full/wizban/NewOCCI")));
}
/**
* Returns the names of the types that can be created as the root object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<String> getInitialObjectNames() {
if (initialObjectNames == null) {
initialObjectNames = new ArrayList<String>();
for (EClassifier eClassifier : occiPackage.getEClassifiers()) {
if (eClassifier instanceof EClass) {
EClass eClass = (EClass)eClassifier;
if (!eClass.isAbstract()) {
initialObjectNames.add(eClass.getName());
}
}
}
Collections.sort(initialObjectNames, CommonPlugin.INSTANCE.getComparator());
}
return initialObjectNames;
}
/**
* Create a new model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EObject createInitialModel() {
EClass eClass = (EClass)occiPackage.getEClassifier(initialObjectCreationPage.getInitialObjectName());
EObject rootObject = occiFactory.create(eClass);
return rootObject;
}
/**
* Do the work after everything is specified.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean performFinish() {
try {
// Remember the file.
//
final IFile modelFile = getModelFile();
// Do the work within an operation.
//
WorkspaceModifyOperation operation =
new WorkspaceModifyOperation() {
@Override
protected void execute(IProgressMonitor progressMonitor) {
try {
// Create a resource set
//
ResourceSet resourceSet = new ResourceSetImpl();
// Get the URI of the model file.
//
URI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString(), true);
// Create a resource for this file.
//
Resource resource = resourceSet.createResource(fileURI);
// Add the initial model object to the contents.
//
EObject rootObject = createInitialModel();
if (rootObject != null) {
resource.getContents().add(rootObject);
}
// Save the contents of the resource to the file system.
//
Map<Object, Object> options = new HashMap<Object, Object>();
options.put(XMLResource.OPTION_ENCODING, initialObjectCreationPage.getEncoding());
resource.save(options);
}
catch (Exception exception) {
OCCIEditorPlugin.INSTANCE.log(exception);
}
finally {
progressMonitor.done();
}
}
};
getContainer().run(false, false, operation);
// Select the new file resource in the current view.
//
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage page = workbenchWindow.getActivePage();
final IWorkbenchPart activePart = page.getActivePart();
if (activePart instanceof ISetSelectionTarget) {
final ISelection targetSelection = new StructuredSelection(modelFile);
getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
((ISetSelectionTarget)activePart).selectReveal(targetSelection);
}
});
}
// Open an editor on the new file.
//
try {
page.openEditor
(new FileEditorInput(modelFile),
workbench.getEditorRegistry().getDefaultEditor(modelFile.getFullPath().toString()).getId());
}
catch (PartInitException exception) {
MessageDialog.openError(workbenchWindow.getShell(), OCCIEditorPlugin.INSTANCE.getString("_UI_OpenEditorError_label"), exception.getMessage());
return false;
}
return true;
}
catch (Exception exception) {
OCCIEditorPlugin.INSTANCE.log(exception);
return false;
}
}
/**
* This is the one page of the wizard.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class OCCIModelWizardNewFileCreationPage extends WizardNewFileCreationPage {
/**
* Pass in the selection.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OCCIModelWizardNewFileCreationPage(String pageId, IStructuredSelection selection) {
super(pageId, selection);
}
/**
* The framework calls this to see if the file is correct.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected boolean validatePage() {
if (super.validatePage()) {
String extension = new Path(getFileName()).getFileExtension();
if (extension == null || !FILE_EXTENSIONS.contains(extension)) {
String key = FILE_EXTENSIONS.size() > 1 ? "_WARN_FilenameExtensions" : "_WARN_FilenameExtension";
setErrorMessage(OCCIEditorPlugin.INSTANCE.getString(key, new Object [] { FORMATTED_FILE_EXTENSIONS }));
return false;
}
return true;
}
return false;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IFile getModelFile() {
return ResourcesPlugin.getWorkspace().getRoot().getFile(getContainerFullPath().append(getFileName()));
}
}
/**
* This is the page where the type of object to create is selected.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class OCCIModelWizardInitialObjectCreationPage extends WizardPage {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Combo initialObjectField;
/**
* @generated
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*/
protected List<String> encodings;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Combo encodingField;
/**
* Pass in the selection.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OCCIModelWizardInitialObjectCreationPage(String pageId) {
super(pageId);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE); {
GridLayout layout = new GridLayout();
layout.numColumns = 1;
layout.verticalSpacing = 12;
composite.setLayout(layout);
GridData data = new GridData();
data.verticalAlignment = GridData.FILL;
data.grabExcessVerticalSpace = true;
data.horizontalAlignment = GridData.FILL;
composite.setLayoutData(data);
}
Label containerLabel = new Label(composite, SWT.LEFT);
{
containerLabel.setText(OCCIEditorPlugin.INSTANCE.getString("_UI_ModelObject"));
GridData data = new GridData();
data.horizontalAlignment = GridData.FILL;
containerLabel.setLayoutData(data);
}
initialObjectField = new Combo(composite, SWT.BORDER);
{
GridData data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.grabExcessHorizontalSpace = true;
initialObjectField.setLayoutData(data);
}
for (String objectName : getInitialObjectNames()) {
initialObjectField.add(getLabel(objectName));
}
if (initialObjectField.getItemCount() == 1) {
initialObjectField.select(0);
}
initialObjectField.addModifyListener(validator);
Label encodingLabel = new Label(composite, SWT.LEFT);
{
encodingLabel.setText(OCCIEditorPlugin.INSTANCE.getString("_UI_XMLEncoding"));
GridData data = new GridData();
data.horizontalAlignment = GridData.FILL;
encodingLabel.setLayoutData(data);
}
encodingField = new Combo(composite, SWT.BORDER);
{
GridData data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.grabExcessHorizontalSpace = true;
encodingField.setLayoutData(data);
}
for (String encoding : getEncodings()) {
encodingField.add(encoding);
}
encodingField.select(0);
encodingField.addModifyListener(validator);
setPageComplete(validatePage());
setControl(composite);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ModifyListener validator =
new ModifyListener() {
public void modifyText(ModifyEvent e) {
setPageComplete(validatePage());
}
};
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected boolean validatePage() {
return getInitialObjectName() != null && getEncodings().contains(encodingField.getText());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
if (initialObjectField.getItemCount() == 1) {
initialObjectField.clearSelection();
encodingField.setFocus();
}
else {
encodingField.clearSelection();
initialObjectField.setFocus();
}
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getInitialObjectName() {
String label = initialObjectField.getText();
for (String name : getInitialObjectNames()) {
if (getLabel(name).equals(label)) {
return name;
}
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getEncoding() {
return encodingField.getText();
}
/**
* Returns the label for the specified type name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected String getLabel(String typeName) {
try {
return OCCIEditPlugin.INSTANCE.getString("_UI_" + typeName + "_type");
}
catch(MissingResourceException mre) {
OCCIEditorPlugin.INSTANCE.log(mre);
}
return typeName;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<String> getEncodings() {
if (encodings == null) {
encodings = new ArrayList<String>();
for (StringTokenizer stringTokenizer = new StringTokenizer(OCCIEditorPlugin.INSTANCE.getString("_UI_XMLEncodingChoices")); stringTokenizer.hasMoreTokens(); ) {
encodings.add(stringTokenizer.nextToken());
}
}
return encodings;
}
}
/**
* The framework calls this to create the contents of the wizard.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void addPages() {
// Create a page, set the title, and the initial model file name.
//
newFileCreationPage = new OCCIModelWizardNewFileCreationPage("Whatever", selection);
newFileCreationPage.setTitle(OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIModelWizard_label"));
newFileCreationPage.setDescription(OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIModelWizard_description"));
newFileCreationPage.setFileName(OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIEditorFilenameDefaultBase") + "." + FILE_EXTENSIONS.get(0));
addPage(newFileCreationPage);
// Try and get the resource selection to determine a current directory for the file dialog.
//
if (selection != null && !selection.isEmpty()) {
// Get the resource...
//
Object selectedElement = selection.iterator().next();
if (selectedElement instanceof IResource) {
// Get the resource parent, if its a file.
//
IResource selectedResource = (IResource)selectedElement;
if (selectedResource.getType() == IResource.FILE) {
selectedResource = selectedResource.getParent();
}
// This gives us a directory...
//
if (selectedResource instanceof IFolder || selectedResource instanceof IProject) {
// Set this for the container.
//
newFileCreationPage.setContainerFullPath(selectedResource.getFullPath());
// Make up a unique new name here.
//
String defaultModelBaseFilename = OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIEditorFilenameDefaultBase");
String defaultModelFilenameExtension = FILE_EXTENSIONS.get(0);
String modelFilename = defaultModelBaseFilename + "." + defaultModelFilenameExtension;
for (int i = 1; ((IContainer)selectedResource).findMember(modelFilename) != null; ++i) {
modelFilename = defaultModelBaseFilename + i + "." + defaultModelFilenameExtension;
}
newFileCreationPage.setFileName(modelFilename);
}
}
}
initialObjectCreationPage = new OCCIModelWizardInitialObjectCreationPage("Whatever2");
initialObjectCreationPage.setTitle(OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIModelWizard_label"));
initialObjectCreationPage.setDescription(OCCIEditorPlugin.INSTANCE.getString("_UI_Wizard_initial_object_description"));
addPage(initialObjectCreationPage);
}
/**
* Get the file from the page.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IFile getModelFile() {
return newFileCreationPage.getModelFile();
}
}
| epl-1.0 |
SK-HOLDINGS-CC/NEXCORE-UML-Modeler | nexcore.tool.mda.model/src/java/nexcore/tool/mda/model/developer/operationbody/IMDAOperation.java | 3042 | /**
* Copyright (c) 2015 SK holdings Co., Ltd. All rights reserved.
* This software is the confidential and proprietary information of SK holdings.
* You shall not disclose such confidential information and shall use it only in
* accordance with the terms of the license agreement you entered into with SK holdings.
* (http://www.eclipse.org/legal/epl-v10.html)
*/
package nexcore.tool.mda.model.developer.operationbody;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>IMDA Operation</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link nexcore.tool.mda.model.developer.operationbody.IMDAOperation#getId <em>Id</em>}</li>
* <li>{@link nexcore.tool.mda.model.developer.operationbody.IMDAOperation#getName <em>Name</em>}</li>
* </ul>
* </p>
*
* @see nexcore.tool.mda.model.developer.operationbody.OperationbodyPackage#getIMDAOperation()
* @model interface="true" abstract="true"
* @generated
*/
public interface IMDAOperation extends EObject {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String copyright = "";
/**
* Returns the value of the '<em><b>Id</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Id</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Id</em>' attribute.
* @see #setId(String)
* @see nexcore.tool.mda.model.developer.operationbody.OperationbodyPackage#getIMDAOperation_Id()
* @model required="true"
* @generated
*/
String getId();
/**
* Sets the value of the '{@link nexcore.tool.mda.model.developer.operationbody.IMDAOperation#getId <em>Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Id</em>' attribute.
* @see #getId()
* @generated
*/
void setId(String value);
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see nexcore.tool.mda.model.developer.operationbody.OperationbodyPackage#getIMDAOperation_Name()
* @model required="true"
* @generated
*/
String getName();
/**
* Sets the value of the '{@link nexcore.tool.mda.model.developer.operationbody.IMDAOperation#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
} // IMDAOperation
| epl-1.0 |
peterkir/org.eclipse.oomph | plugins/org.eclipse.oomph.setup.edit/src/org/eclipse/oomph/setup/provider/InstallationTaskItemProvider.java | 5393 | /*
* Copyright (c) 2014, 2015 Eike Stepper (Berlin, Germany) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eike Stepper - initial API and implementation
*/
package org.eclipse.oomph.setup.provider;
import org.eclipse.oomph.setup.InstallationTask;
import org.eclipse.oomph.setup.SetupPackage;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
import java.util.Collection;
import java.util.List;
/**
* This is the item provider adapter for a {@link org.eclipse.oomph.setup.InstallationTask} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class InstallationTaskItemProvider extends SetupTaskItemProvider
{
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InstallationTaskItemProvider(AdapterFactory adapterFactory)
{
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object)
{
if (itemPropertyDescriptors == null)
{
super.getPropertyDescriptors(object);
addLocationPropertyDescriptor(object);
addRelativeProductFolderPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Location feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addLocationPropertyDescriptor(Object object)
{
itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(),
getString("_UI_InstallationTask_location_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_InstallationTask_location_feature", "_UI_InstallationTask_type"),
SetupPackage.Literals.INSTALLATION_TASK__LOCATION, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null));
}
/**
* This adds a property descriptor for the Relative Product Folder feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addRelativeProductFolderPropertyDescriptor(Object object)
{
itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(),
getString("_UI_InstallationTask_relativeProductFolder_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_InstallationTask_relativeProductFolder_feature", "_UI_InstallationTask_type"),
SetupPackage.Literals.INSTALLATION_TASK__RELATIVE_PRODUCT_FOLDER, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null));
}
/**
* This returns InstallationTask.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object)
{
return overlayImage(object, getResourceLocator().getImage("full/obj16/InstallationTask"));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected boolean shouldComposeCreationImage()
{
return true;
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object)
{
String label = ((InstallationTask)object).getLocation();
return label == null || label.length() == 0 ? getString("_UI_InstallationTask_type") : getString("_UI_InstallationTask_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification)
{
updateChildren(notification);
switch (notification.getFeatureID(InstallationTask.class))
{
case SetupPackage.INSTALLATION_TASK__LOCATION:
case SetupPackage.INSTALLATION_TASK__RELATIVE_PRODUCT_FOLDER:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object)
{
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| epl-1.0 |
Netcentric/access-control-validator | accesscontrolvalidator-bundle/src/main/java/biz/netcentric/aem/tools/acvalidator/gui/yaml/model/ConfigurationNode.java | 2809 | /*
* (C) Copyright 2015 Netcentric AG.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package biz.netcentric.aem.tools.acvalidator.gui.yaml.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import biz.netcentric.aem.tools.acvalidator.gui.yaml.parser.VariableHelper;
import biz.netcentric.aem.tools.acvalidator.gui.yaml.parser.YamlParserException;
/**
* Represents a node in the configuration file.
*
* @author Roland Gruber
*/
public abstract class ConfigurationNode {
private List<ConfigurationNode> subnodes = new ArrayList<>();
/**
* Returns the list of allowed subnode classes.
*
* @return classes
*/
public abstract List<Class> getAllowedSubnodeClasses();
/**
* Returns the subnodes.
*
* @return subnodes
*/
public List<ConfigurationNode> getSubnodes() {
return subnodes;
}
/**
* Returns the list of possible properties.
*
* @return properties
*/
public abstract List<Property> getProperties();
/**
* Allows to set properties with custom names.
*
* @return custom properties allowed
*/
public boolean allowsCustomProperties() {
return false;
}
/**
* Allows to set a custom name.
*
* @return custom name allowed
*/
public boolean allowsCustomName() {
return false;
}
/**
* Adds a subnode.
*
* @param node subnode
*/
public void addSubnode(ConfigurationNode node) {
subnodes.add(node);
}
/**
* Removes a subnode.
*
* @param node subnode
*/
public void removeSubnode(ConfigurationNode node) {
subnodes.remove(node);
}
/**
* Returns the node name.
*
* @return node name
*/
public abstract String getNodeName();
/**
* Unrolls the node by replacing variables and extracting loops.
*
* @param variables variables
* @return list of unrolled nodes
* @throws YamlParserException error during unroll
*/
public List<ConfigurationNode> unroll(Map<String, String> variables) throws YamlParserException {
for (Property property : getProperties()) {
property.setValue(VariableHelper.replace(property.getValue(), variables));
}
List<ConfigurationNode> subnodesNew = new ArrayList<>();
for (ConfigurationNode subnode : getSubnodes()) {
subnodesNew.addAll(subnode.unroll(variables));
}
subnodes = subnodesNew;
return Arrays.asList(this);
}
protected List<Property> copyProperties(ConfigurationNode node) {
List<Property> copy = new ArrayList<>();
for (Property property : node.getProperties()) {
copy.add(new Property(property.getName(), property.getValue()));
}
return copy;
}
}
| epl-1.0 |
niuqg/controller | opendaylight/md-sal/model/model-flow-base/src/main/yang-gen-sal/org/opendaylight/yang/gen/v1/urn/opendaylight/action/types/rev131112/action/action/pop/mpls/action/_case/PopMplsActionBuilder.java | 7204 | package org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case;
import java.util.Map;
import org.opendaylight.yangtools.yang.binding.Augmentation;
import java.util.HashMap;
import java.util.List;
import com.google.common.collect.Range;
import java.util.ArrayList;
import java.util.Collections;
public class PopMplsActionBuilder {
private Integer _ethernetType;
private final Map<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> augmentation = new HashMap<>();
public PopMplsActionBuilder() {
}
public Integer getEthernetType() {
return _ethernetType;
}
@SuppressWarnings("unchecked")
public <E extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> E getAugmentation(Class<E> augmentationType) {
if (augmentationType == null) {
throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!");
}
return (E) augmentation.get(augmentationType);
}
public PopMplsActionBuilder setEthernetType(Integer value) {
if (value != null) {
boolean isValidRange = false;
List<Range<Integer>> rangeConstraints = new ArrayList<>();
rangeConstraints.add(Range.closed(new Integer("0"), new Integer("65535")));
for (Range<Integer> r : rangeConstraints) {
if (r.contains(value)) {
isValidRange = true;
}
}
if (!isValidRange) {
throw new IllegalArgumentException(String.format("Invalid range: %s, expected: %s.", value, rangeConstraints));
}
}
this._ethernetType = value;
return this;
}
public PopMplsActionBuilder addAugmentation(Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> augmentationType, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction> augmentation) {
this.augmentation.put(augmentationType, augmentation);
return this;
}
public PopMplsAction build() {
return new PopMplsActionImpl(this);
}
private static final class PopMplsActionImpl implements PopMplsAction {
public Class<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction> getImplementedInterface() {
return org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction.class;
}
private final Integer _ethernetType;
private final Map<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> augmentation;
private PopMplsActionImpl(PopMplsActionBuilder builder) {
this._ethernetType = builder.getEthernetType();
switch (builder.augmentation.size()) {
case 0:
this.augmentation = Collections.emptyMap();
break;
case 1:
final Map.Entry<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> e = builder.augmentation.entrySet().iterator().next();
this.augmentation = Collections.<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>>singletonMap(e.getKey(), e.getValue());
break;
default :
this.augmentation = new HashMap<>(builder.augmentation);
}
}
@Override
public Integer getEthernetType() {
return _ethernetType;
}
@SuppressWarnings("unchecked")
@Override
public <E extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> E getAugmentation(Class<E> augmentationType) {
if (augmentationType == null) {
throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!");
}
return (E) augmentation.get(augmentationType);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((_ethernetType == null) ? 0 : _ethernetType.hashCode());
result = prime * result + ((augmentation == null) ? 0 : augmentation.hashCode());
return result;
}
@Override
public boolean equals(java.lang.Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PopMplsActionImpl other = (PopMplsActionImpl) obj;
if (_ethernetType == null) {
if (other._ethernetType != null) {
return false;
}
} else if(!_ethernetType.equals(other._ethernetType)) {
return false;
}
if (augmentation == null) {
if (other.augmentation != null) {
return false;
}
} else if(!augmentation.equals(other.augmentation)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("PopMplsAction [");
boolean first = true;
if (_ethernetType != null) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append("_ethernetType=");
builder.append(_ethernetType);
}
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append("augmentation=");
builder.append(augmentation.values());
return builder.append(']').toString();
}
}
}
| epl-1.0 |
DavidGutknecht/elexis-3-base | bundles/at.medevit.ch.artikelstamm.ui/src/at/medevit/ch/artikelstamm/ui/internal/IntToStringConverterSelbstbehalt.java | 461 | package at.medevit.ch.artikelstamm.ui.internal;
import org.eclipse.core.databinding.conversion.Converter;
public class IntToStringConverterSelbstbehalt extends Converter {
public IntToStringConverterSelbstbehalt(){
super(Integer.class, String.class);
}
@Override
public Object convert(Object fromObject){
if (fromObject instanceof Integer) {
int value = (Integer) fromObject;
if (value >= 0)
return value + "";
}
return null;
}
}
| epl-1.0 |
jasonCarNormal0101/StockAdviser | lib/hamcrest-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsArray.java | 3007 | package org.hamcrest.collection;
import java.util.Arrays;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
/**
* Matcher for array whose elements satisfy a sequence of matchers.
* The array size must equal the number of element matchers.
*/
public class IsArray<T> extends TypeSafeMatcher<T[]> {
private final Matcher<? super T>[] elementMatchers;
public IsArray(Matcher<? super T>[] elementMatchers) {
this.elementMatchers = elementMatchers.clone();
}
@Override
public boolean matchesSafely(T[] array) {
if (array.length != elementMatchers.length) return false;
for (int i = 0; i < array.length; i++) {
if (!elementMatchers[i].matches(array[i])) return false;
}
return true;
}
@Override
public void describeMismatchSafely(T[] actual, Description mismatchDescription) {
if (actual.length != elementMatchers.length) {
mismatchDescription.appendText("array length was " + actual.length);
return;
}
for (int i = 0; i < actual.length; i++) {
if (!elementMatchers[i].matches(actual[i])) {
mismatchDescription.appendText("element " + i + " was ").appendValue(actual[i]);
return;
}
}
}
@Override
public void describeTo(Description description) {
description.appendList(descriptionStart(), descriptionSeparator(), descriptionEnd(),
Arrays.asList(elementMatchers));
}
/**
* Returns the string that starts the description.
*
* Can be overridden in subclasses to customise how the matcher is
* described.
*/
protected String descriptionStart() {
return "[";
}
/**
* Returns the string that separates the elements in the description.
*
* Can be overridden in subclasses to customise how the matcher is
* described.
*/
protected String descriptionSeparator() {
return ", ";
}
/**
* Returns the string that ends the description.
*
* Can be overridden in subclasses to customise how the matcher is
* described.
*/
protected String descriptionEnd() {
return "]";
}
/**
* Creates a matcher that matches arrays whose elements are satisfied by the specified matchers. Matches
* positively only if the number of matchers specified is equal to the length of the examined array and
* each matcher[i] is satisfied by array[i].
* <p/>
* For example:
* <pre>assertThat(new Integer[]{1,2,3}, is(array(equalTo(1), equalTo(2), equalTo(3))))</pre>
*
* @param elementMatchers
* the matchers that the elements of examined arrays should satisfy
*/
@Factory
public static <T> IsArray<T> array(Matcher<? super T>... elementMatchers) {
return new IsArray<T>(elementMatchers);
}
}
| epl-1.0 |
michele-loreti/jResp | core/org.cmg.jresp.pastry/pastry-2.1/src/org/mpisws/p2p/transport/peerreview/replay/playback/ReplaySocket.java | 6880 | /*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
This software is provided by RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS 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.
*******************************************************************************/
package org.mpisws.p2p.transport.peerreview.replay.playback;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import org.mpisws.p2p.transport.ClosedChannelException;
import org.mpisws.p2p.transport.P2PSocket;
import org.mpisws.p2p.transport.P2PSocketReceiver;
import org.mpisws.p2p.transport.SocketCallback;
import org.mpisws.p2p.transport.SocketRequestHandle;
public class ReplaySocket<Identifier> implements P2PSocket<Identifier>, SocketRequestHandle<Identifier> {
protected Identifier identifier;
protected int socketId;
protected ReplayVerifier<Identifier> verifier;
boolean closed = false;
boolean outputShutdown = false;
Map<String, Object> options;
/**
* TODO: Make extensible by putting into a factory.
*
* @param identifier
* @param socketId
* @param verifier
*/
public ReplaySocket(Identifier identifier, int socketId, ReplayVerifier<Identifier> verifier, Map<String, Object> options) {
this.identifier = identifier;
this.socketId = socketId;
this.verifier = verifier;
this.options = options;
}
@Override
public Identifier getIdentifier() {
return identifier;
}
@Override
public Map<String, Object> getOptions() {
return options;
}
@Override
public long read(ByteBuffer dst) throws IOException {
// if (closed) throw new ClosedChannelException("Socket already closed.");
return verifier.readSocket(socketId, dst);
}
@Override
public long write(ByteBuffer src) throws IOException {
// if (closed || outputClosed) throw new ClosedChannelException("Socket already closed.");
return verifier.writeSocket(socketId, src);
}
P2PSocketReceiver<Identifier> reader;
P2PSocketReceiver<Identifier> writer;
@Override
public void register(boolean wantToRead, boolean wantToWrite, P2PSocketReceiver<Identifier> receiver) {
if (closed) {
receiver.receiveException(this, new ClosedChannelException("Socket "+this+" already closed."));
return;
}
if (wantToWrite && outputShutdown) {
receiver.receiveException(this, new ClosedChannelException("Socket "+this+" already shutdown output."));
return;
}
if (wantToWrite) {
if (writer != null) {
if (writer != receiver) throw new IllegalStateException("Already registered "+writer+" for writing, you can't register "+receiver+" for writing as well!");
}
}
if (wantToRead) {
if (reader != null) {
if (reader != receiver) throw new IllegalStateException("Already registered "+reader+" for reading, you can't register "+receiver+" for reading as well!");
}
reader = receiver;
}
if (wantToWrite) {
writer = receiver;
}
}
public void notifyIO(boolean canRead, boolean canWrite) throws IOException {
if (!canRead && !canWrite) {
throw new IOException("I can't read or write. canRead:"+canRead+" canWrite:"+canWrite);
}
if (canRead && canWrite) {
if (writer != reader) throw new IllegalStateException("weader != writer canRead:"+canRead+" canWrite:"+canWrite);
P2PSocketReceiver<Identifier> temp = writer;
writer = null;
reader = null;
temp.receiveSelectResult(this, canRead, canWrite);
return;
}
if (canRead) {
if (reader == null) throw new IllegalStateException("reader:"+reader+" canRead:"+canRead);
P2PSocketReceiver<Identifier> temp = reader;
reader = null;
temp.receiveSelectResult(this, canRead, canWrite);
return;
}
if (canWrite) {
if (writer == null) throw new IllegalStateException("writer:"+writer+" canWrite:"+canWrite);
P2PSocketReceiver<Identifier> temp = writer;
writer = null;
temp.receiveSelectResult(this, canRead, canWrite);
return;
}
}
@Override
public void close() {
closed = true;
verifier.close(socketId);
}
SocketCallback<Identifier> deliverSocketToMe;
public void setDeliverSocketToMe(SocketCallback<Identifier> deliverSocketToMe) {
this.deliverSocketToMe = deliverSocketToMe;
}
public void socketOpened() {
deliverSocketToMe.receiveResult(this, this);
deliverSocketToMe = null;
}
@Override
public void shutdownOutput() {
outputShutdown = true;
verifier.shutdownOutput(socketId);
// throw new RuntimeException("Not implemented.");
}
public void receiveException(IOException ioe) {
if (deliverSocketToMe != null) {
deliverSocketToMe.receiveException(this, ioe);
return;
}
if (writer != null) {
if (writer == reader) {
writer.receiveException(this, ioe);
writer = null;
reader = null;
} else {
writer.receiveException(this, ioe);
writer = null;
}
}
if (reader != null) {
reader.receiveException(this, ioe);
reader = null;
}
}
@Override
public boolean cancel() {
throw new RuntimeException("Not implemented.");
}
}
| epl-1.0 |
cschwer/com.zsmartsystems.zigbee | com.zsmartsystems.zigbee/src/main/java/com/zsmartsystems/zigbee/zcl/clusters/general/ConfigureReportingResponse.java | 5846 | /**
* Copyright (c) 2016-2019 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.zsmartsystems.zigbee.zcl.clusters.general;
import javax.annotation.Generated;
import com.zsmartsystems.zigbee.zcl.ZclCommand;
import com.zsmartsystems.zigbee.zcl.ZclFieldSerializer;
import com.zsmartsystems.zigbee.zcl.ZclFieldDeserializer;
import com.zsmartsystems.zigbee.zcl.protocol.ZclDataType;
import com.zsmartsystems.zigbee.zcl.protocol.ZclCommandDirection;
import java.util.List;
import com.zsmartsystems.zigbee.zcl.ZclStatus;
import com.zsmartsystems.zigbee.zcl.field.AttributeStatusRecord;
/**
* Configure Reporting Response value object class.
* <p>
* Cluster: <b>General</b>. Command is sent <b>TO</b> the server.
* This command is a <b>generic</b> command used across the profile.
* <p>
* The Configure Reporting Response command is generated in response to a
* Configure Reporting command.
* <p>
* Code is auto-generated. Modifications may be overwritten!
*/
@Generated(value = "com.zsmartsystems.zigbee.autocode.ZclProtocolCodeGenerator", date = "2018-04-26T19:23:24Z")
public class ConfigureReportingResponse extends ZclCommand {
/**
* Status command message field.
* <p>
* Status is only provided if the command was successful, and the
* attribute status records are not included for successfully
* written attributes, in order to save bandwidth.
*/
private ZclStatus status;
/**
* Records command message field.
* <p>
* Note that attribute status records are not included for successfully
* configured attributes in order to save bandwidth. In the case of successful
* configuration of all attributes, only a single attribute status record SHALL
* be included in the command, with the status field set to SUCCESS and the direction and
* attribute identifier fields omitted.
*/
private List<AttributeStatusRecord> records;
/**
* Default constructor.
*/
public ConfigureReportingResponse() {
genericCommand = true;
commandId = 7;
commandDirection = ZclCommandDirection.CLIENT_TO_SERVER;
}
/**
* Sets the cluster ID for <i>generic</i> commands. {@link ConfigureReportingResponse} is a <i>generic</i> command.
* <p>
* For commands that are not <i>generic</i>, this method will do nothing as the cluster ID is fixed.
* To test if a command is <i>generic</i>, use the {@link #isGenericCommand} method.
*
* @param clusterId the cluster ID used for <i>generic</i> commands as an {@link Integer}
*/
@Override
public void setClusterId(Integer clusterId) {
this.clusterId = clusterId;
}
/**
* Gets Status.
*
* Status is only provided if the command was successful, and the
* attribute status records are not included for successfully
* written attributes, in order to save bandwidth.
*
* @return the Status
*/
public ZclStatus getStatus() {
return status;
}
/**
* Sets Status.
*
* Status is only provided if the command was successful, and the
* attribute status records are not included for successfully
* written attributes, in order to save bandwidth.
*
* @param status the Status
*/
public void setStatus(final ZclStatus status) {
this.status = status;
}
/**
* Gets Records.
*
* Note that attribute status records are not included for successfully
* configured attributes in order to save bandwidth. In the case of successful
* configuration of all attributes, only a single attribute status record SHALL
* be included in the command, with the status field set to SUCCESS and the direction and
* attribute identifier fields omitted.
*
* @return the Records
*/
public List<AttributeStatusRecord> getRecords() {
return records;
}
/**
* Sets Records.
*
* Note that attribute status records are not included for successfully
* configured attributes in order to save bandwidth. In the case of successful
* configuration of all attributes, only a single attribute status record SHALL
* be included in the command, with the status field set to SUCCESS and the direction and
* attribute identifier fields omitted.
*
* @param records the Records
*/
public void setRecords(final List<AttributeStatusRecord> records) {
this.records = records;
}
@Override
public void serialize(final ZclFieldSerializer serializer) {
if (status == ZclStatus.SUCCESS) {
serializer.serialize(status, ZclDataType.ZCL_STATUS);
return;
}
serializer.serialize(records, ZclDataType.N_X_ATTRIBUTE_STATUS_RECORD);
}
@Override
public void deserialize(final ZclFieldDeserializer deserializer) {
if (deserializer.getRemainingLength() == 1) {
status = (ZclStatus) deserializer.deserialize(ZclDataType.ZCL_STATUS);
return;
}
records = (List<AttributeStatusRecord>) deserializer.deserialize(ZclDataType.N_X_ATTRIBUTE_STATUS_RECORD);
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder(82);
builder.append("ConfigureReportingResponse [");
builder.append(super.toString());
builder.append(", status=");
builder.append(status);
builder.append(", records=");
builder.append(records);
builder.append(']');
return builder.toString();
}
}
| epl-1.0 |
lee-jir-lu/CrazyC | gen/com/crazyc/BuildConfig.java | 152 | /** Automatically generated file. DO NOT MODIFY */
package com.crazyc;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | epl-1.0 |
Cirrus-Link/Sparkplug | client_libraries/java/src/main/java/com/cirruslink/sparkplug/message/model/Parameter.java | 2232 | /*
* Licensed Materials - Property of Cirrus Link Solutions
* Copyright (c) 2016 Cirrus Link Solutions LLC - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
*/
package com.cirruslink.sparkplug.message.model;
import java.util.Objects;
import com.cirruslink.sparkplug.SparkplugInvalidTypeException;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
/**
* A class to represent a parameter associated with a template.
*/
public class Parameter {
/**
* The name of the parameter
*/
@JsonProperty("name")
private String name;
/**
* The data type of the parameter
*/
@JsonProperty("type")
private ParameterDataType type;
/**
* The value of the parameter
*/
@JsonProperty("value")
private Object value;
/**
* Constructs a Parameter instance.
*
* @param name The name of the parameter.
* @param type The type of the parameter.
* @param value The value of the parameter.
* @throws SparkplugInvalidTypeException
*/
public Parameter(String name, ParameterDataType type, Object value) throws SparkplugInvalidTypeException {
this.name = name;
this.type = type;
this.value = value;
this.type.checkType(value);
}
@JsonGetter("name")
public String getName() {
return name;
}
@JsonSetter("name")
public void setName(String name) {
this.name = name;
}
public ParameterDataType getType() {
return type;
}
public void setType(ParameterDataType type) {
this.type = type;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || this.getClass() != object.getClass()) {
return false;
}
Parameter param = (Parameter) object;
return Objects.equals(name, param.getName())
&& Objects.equals(type, param.getType())
&& Objects.equals(value, param.getValue());
}
@Override
public String toString() {
return "Parameter [name=" + name + ", type=" + type + ", value=" + value + "]";
}
}
| epl-1.0 |
abstratt/textuml | plugins/com.abstratt.mdd.frontend.textuml.grammar/src-gen/com/abstratt/mdd/frontend/textuml/grammar/node/ATransitionEffect.java | 2810 | /* This file was generated by SableCC (http://www.sablecc.org/). */
package com.abstratt.mdd.frontend.textuml.grammar.node;
import com.abstratt.mdd.frontend.textuml.grammar.analysis.*;
@SuppressWarnings("nls")
public final class ATransitionEffect extends PTransitionEffect
{
private TDo _do_;
private PSimpleBlock _simpleBlock_;
public ATransitionEffect()
{
// Constructor
}
public ATransitionEffect(
@SuppressWarnings("hiding") TDo _do_,
@SuppressWarnings("hiding") PSimpleBlock _simpleBlock_)
{
// Constructor
setDo(_do_);
setSimpleBlock(_simpleBlock_);
}
@Override
public Object clone()
{
return new ATransitionEffect(
cloneNode(this._do_),
cloneNode(this._simpleBlock_));
}
public void apply(Switch sw)
{
((Analysis) sw).caseATransitionEffect(this);
}
public TDo getDo()
{
return this._do_;
}
public void setDo(TDo node)
{
if(this._do_ != null)
{
this._do_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._do_ = node;
}
public PSimpleBlock getSimpleBlock()
{
return this._simpleBlock_;
}
public void setSimpleBlock(PSimpleBlock node)
{
if(this._simpleBlock_ != null)
{
this._simpleBlock_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._simpleBlock_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._do_)
+ toString(this._simpleBlock_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._do_ == child)
{
this._do_ = null;
return;
}
if(this._simpleBlock_ == child)
{
this._simpleBlock_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._do_ == oldChild)
{
setDo((TDo) newChild);
return;
}
if(this._simpleBlock_ == oldChild)
{
setSimpleBlock((PSimpleBlock) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
}
| epl-1.0 |
khatchad/Rejuvenate-Pointcut | uk.ac.lancs.comp.khatchad.rejuvenatepc.ui/src/uk/ac/lancs/comp/khatchad/rejuvenatepc/ui/views/DoubleClickAction.java | 1120 | package uk.ac.lancs.comp.khatchad.rejuvenatepc.ui.views;
import org.eclipse.contribution.xref.internal.ui.utils.XRefUIUtils;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Shell;
import uk.ac.lancs.comp.khatchad.rejuvenatepc.core.model.Suggestion;
public class DoubleClickAction extends Action {
private Shell shell;
private TableViewer viewer;
public DoubleClickAction(Shell shell, TableViewer viewer) {
this.shell = shell;
this.viewer = viewer;
}
@SuppressWarnings({ "restriction", "unchecked" })
@Override
public void run() {
ISelection selection = viewer.getSelection();
if (selection instanceof IStructuredSelection) {
Object sel =
((IStructuredSelection) selection).getFirstElement();
if ( sel instanceof Suggestion ) {
Suggestion<IJavaElement> suggestion = (Suggestion<IJavaElement>)sel;
XRefUIUtils.revealInEditor(suggestion.getSuggestion());
}
}
}
}
| epl-1.0 |
diverse-project/kcvl | fr.inria.diverse.kcvl.metamodel.edit/src/main/java/org/omg/CVLMetamodelMaster/cvl/provider/ObjectHandleItemProvider.java | 3826 | /**
*/
package org.omg.CVLMetamodelMaster.cvl.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
import org.omg.CVLMetamodelMaster.cvl.CvlPackage;
import org.omg.CVLMetamodelMaster.cvl.ObjectHandle;
/**
* This is the item provider adapter for a {@link org.omg.CVLMetamodelMaster.cvl.ObjectHandle} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class ObjectHandleItemProvider extends BaseModelHandleItemProvider {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ObjectHandleItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addMOFRefPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the MOF Ref feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addMOFRefPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_ObjectHandle_MOFRef_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_ObjectHandle_MOFRef_feature", "_UI_ObjectHandle_type"),
CvlPackage.Literals.OBJECT_HANDLE__MOF_REF,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This returns ObjectHandle.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/ObjectHandle"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((ObjectHandle)object).getReferenceString();
return label == null || label.length() == 0 ?
getString("_UI_ObjectHandle_type") :
getString("_UI_ObjectHandle_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(ObjectHandle.class)) {
case CvlPackage.OBJECT_HANDLE__MOF_REF:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| epl-1.0 |
nagyistoce/icafe | src/cafe/image/jpeg/COMBuilder.java | 796 | /**
* Copyright (c) 2014-2015 by Wen Yu.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Any modifications to this file must keep this entire header intact.
*/
package cafe.image.jpeg;
/**
* JPEG COM segment builder
*
* @author Wen Yu, yuwen_66@yahoo.com
* @version 1.0 10/11/2013
*/
public class COMBuilder extends SegmentBuilder {
private String comment;
public COMBuilder() {
super(Marker.COM);
}
public COMBuilder comment(String comment) {
this.comment = comment;
return this;
}
@Override
protected byte[] buildData() {
return comment.getBytes();
}
}
| epl-1.0 |
wo-amlangwang/ice | org.eclipse.ice.reactor.perspective/src/org/eclipse/ice/reactor/perspective/ReactorsPerspective.java | 1442 | /*******************************************************************************
* Copyright (c) 2014 UT-Battelle, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Initial API and implementation and/or initial documentation - Jay Jay Billings,
* Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson,
* Claire Saunders, Matthew Wang, Anna Wojtowicz
*******************************************************************************/
package org.eclipse.ice.reactor.perspective;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
/**
* This class implements IPerspectiveFactory to create the Visualization
* Perspective.
*
* @author Taylor Patterson
*
*/
public class ReactorsPerspective implements IPerspectiveFactory {
/**
* The ID of this perspective.
*/
public static final String ID = "org.eclipse.ice.reactors.perspective.ReactorsPerspective";
/*
* (non-Javadoc)
* @see org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui.IPageLayout)
*/
@Override
public void createInitialLayout(IPageLayout layout) {
// Add the perspective to the layout
layout.addPerspectiveShortcut(ReactorsPerspective.ID);
return;
}
}
| epl-1.0 |
trajano/doxdb | doxdb-rest/src/main/java/net/trajano/doxdb/rest/DoxIDMapper.java | 416 | package net.trajano.doxdb.rest;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.Provider;
import net.trajano.doxdb.DoxID;
@Provider
public class DoxIDMapper implements
ParamConverter<DoxID> {
@Override
public DoxID fromString(final String s) {
return new DoxID(s);
}
@Override
public String toString(final DoxID doxid) {
return doxid.toString();
}
}
| epl-1.0 |
bonhamcm/pwm | src/main/java/password/pwm/util/Helper.java | 21609 | /*
* Password Management Servlets (PWM)
* http://www.pwm-project.org
*
* Copyright (c) 2006-2009 Novell, Inc.
* Copyright (c) 2009-2016 The PWM Project
*
* 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 password.pwm.util;
import com.novell.ldapchai.ChaiUser;
import com.novell.ldapchai.exception.ChaiOperationException;
import com.novell.ldapchai.exception.ChaiUnavailableException;
import org.apache.commons.csv.CSVPrinter;
import password.pwm.PwmApplication;
import password.pwm.PwmApplicationMode;
import password.pwm.PwmConstants;
import password.pwm.bean.FormNonce;
import password.pwm.bean.SessionLabel;
import password.pwm.config.FormConfiguration;
import password.pwm.config.PwmSetting;
import password.pwm.error.ErrorInformation;
import password.pwm.error.PwmError;
import password.pwm.error.PwmOperationalException;
import password.pwm.error.PwmUnrecoverableException;
import password.pwm.http.PwmRequest;
import password.pwm.http.PwmSession;
import password.pwm.util.logging.PwmLogger;
import password.pwm.util.macro.MacroMachine;
import java.io.*;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.regex.Pattern;
/**
* A collection of static methods used throughout PWM
*
* @author Jason D. Rivard
*/
public class
Helper {
// ------------------------------ FIELDS ------------------------------
private static final PwmLogger LOGGER = PwmLogger.forClass(Helper.class);
// -------------------------- STATIC METHODS --------------------------
private Helper() {
}
/**
* Convert a byte[] array to readable string format. This makes the "hex" readable
*
* @param in byte[] buffer to convert to string format
* @return result String buffer in String format
*/
public static String byteArrayToHexString(final byte in[]) {
final String pseudo[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
if (in == null || in.length <= 0) {
return "";
}
final StringBuilder out = new StringBuilder(in.length * 2);
for (final byte b : in) {
byte ch = (byte) (b & 0xF0); // strip off high nibble
ch = (byte) (ch >>> 4); // shift the bits down
ch = (byte) (ch & 0x0F); // must do this is high order bit is on!
out.append(pseudo[(int) ch]); // convert the nibble to a String Character
ch = (byte) (b & 0x0F); // strip off low nibble
out.append(pseudo[(int) ch]); // convert the nibble to a String Character
}
return out.toString();
}
/**
* Pause the calling thread the specified amount of time.
*
* @param sleepTimeMS - a time duration in milliseconds
* @return time actually spent sleeping
*/
public static long pause(final long sleepTimeMS) {
final long startTime = System.currentTimeMillis();
do {
try {
final long sleepTime = sleepTimeMS - (System.currentTimeMillis() - startTime);
Thread.sleep(sleepTime > 0 ? sleepTime : 5);
} catch (InterruptedException e) {
//who cares
}
} while ((System.currentTimeMillis() - startTime) < sleepTimeMS);
return System.currentTimeMillis() - startTime;
}
/**
* Writes a Map of form values to ldap onto the supplied user object.
* The map key must be a string of attribute names.
* <p/>
* Any ldap operation exceptions are not reported (but logged).
*
* @param pwmSession for looking up session info
* @param theUser User to write to
* @param formValues A map with {@link password.pwm.config.FormConfiguration} keys and String values.
* @throws ChaiUnavailableException if the directory is unavailable
* @throws PwmOperationalException if their is an unexpected ldap problem
*/
public static void writeFormValuesToLdap(
final PwmApplication pwmApplication,
final PwmSession pwmSession,
final ChaiUser theUser,
final Map<FormConfiguration,String> formValues,
final boolean expandMacros
)
throws ChaiUnavailableException, PwmOperationalException, PwmUnrecoverableException
{
final Map<String,String> tempMap = new HashMap<>();
for (final FormConfiguration formItem : formValues.keySet()) {
if (!formItem.isReadonly()) {
tempMap.put(formItem.getName(),formValues.get(formItem));
}
}
final MacroMachine macroMachine = pwmSession.getSessionManager().getMacroMachine(pwmApplication);
writeMapToLdap(theUser, tempMap, macroMachine, expandMacros);
}
/**
* Writes a Map of values to ldap onto the supplied user object.
* The map key must be a string of attribute names.
* <p/>
* Any ldap operation exceptions are not reported (but logged).
*
* @param theUser User to write to
* @param valueMap A map with String keys and String values.
* @throws ChaiUnavailableException if the directory is unavailable
* @throws PwmOperationalException if their is an unexpected ldap problem
*/
public static void writeMapToLdap(
final ChaiUser theUser,
final Map<String,String> valueMap,
final MacroMachine macroMachine,
final boolean expandMacros
)
throws PwmOperationalException, ChaiUnavailableException
{
final Map<String,String> currentValues;
try {
currentValues = theUser.readStringAttributes(valueMap.keySet());
} catch (ChaiOperationException e) {
final String errorMsg = "error reading existing values on user " + theUser.getEntryDN() + " prior to replacing values, error: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
final PwmOperationalException newException = new PwmOperationalException(errorInformation);
newException.initCause(e);
throw newException;
}
for (final String attrName : valueMap.keySet()) {
String attrValue = valueMap.get(attrName) != null ? valueMap.get(attrName) : "";
if (expandMacros) {
attrValue = macroMachine.expandMacros(attrValue);
}
if (!attrValue.equals(currentValues.get(attrName))) {
if (attrValue.length() > 0) {
try {
theUser.writeStringAttribute(attrName, attrValue);
LOGGER.info("set attribute on user " + theUser.getEntryDN() + " (" + attrName + "=" + attrValue + ")");
} catch (ChaiOperationException e) {
final String errorMsg = "error setting '" + attrName + "' attribute on user " + theUser.getEntryDN() + ", error: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
final PwmOperationalException newException = new PwmOperationalException(errorInformation);
newException.initCause(e);
throw newException;
}
} else {
if (currentValues.get(attrName) != null && currentValues.get(attrName).length() > 0) {
try {
theUser.deleteAttribute(attrName, null);
LOGGER.info("deleted attribute value on user " + theUser.getEntryDN() + " (" + attrName + ")");
} catch (ChaiOperationException e) {
final String errorMsg = "error removing '" + attrName + "' attribute value on user " + theUser.getEntryDN() + ", error: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
final PwmOperationalException newException = new PwmOperationalException(errorInformation);
newException.initCause(e);
throw newException;
}
}
}
} else {
LOGGER.debug("skipping attribute modify for attribute '" + attrName + "', no change in value");
}
}
}
public static String binaryArrayToHex(final byte[] buf) {
final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
final char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i) {
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
public static String formatDiskSize(final long diskSize) {
final float COUNT = 1000;
if (diskSize < 1) {
return "n/a";
}
if (diskSize == 0) {
return "0";
}
final NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
if (diskSize > COUNT * COUNT * COUNT) {
final StringBuilder sb = new StringBuilder();
sb.append(nf.format(diskSize / COUNT / COUNT / COUNT));
sb.append(" GB");
return sb.toString();
}
if (diskSize > COUNT * COUNT) {
final StringBuilder sb = new StringBuilder();
sb.append(nf.format(diskSize / COUNT / COUNT));
sb.append(" MB");
return sb.toString();
}
return NumberFormat.getInstance().format(diskSize) + " bytes";
}
static public String buildPwmFormID(final PwmRequest pwmRequest) throws PwmUnrecoverableException {
final FormNonce formID = new FormNonce(
pwmRequest.getPwmSession().getLoginInfoBean().getGuid(),
new Date(),
pwmRequest.getPwmSession().getLoginInfoBean().getReqCounter()
);
return pwmRequest.getPwmApplication().getSecureService().encryptObjectToString(formID);
}
public static void rotateBackups(final File inputFile, final int maxRotate) {
if (maxRotate < 1) {
return;
}
for (int i = maxRotate; i >= 0; i--) {
final File thisFile = (i == 0) ? inputFile : new File(inputFile.getAbsolutePath() + "-" + i);
final File youngerFile = (i <= 1) ? inputFile : new File(inputFile.getAbsolutePath() + "-" + (i - 1));
if (i == maxRotate) {
if (thisFile.exists()) {
LOGGER.debug("deleting old backup file: " + thisFile.getAbsolutePath());
if (!thisFile.delete()) {
LOGGER.error("unable to delete old backup file: " + thisFile.getAbsolutePath());
}
}
} else if (i == 0 || youngerFile.exists()) {
final File destFile = new File(inputFile.getAbsolutePath() + "-" + (i + 1));
LOGGER.debug("backup file " + thisFile.getAbsolutePath() + " renamed to " + destFile.getAbsolutePath());
if (!thisFile.renameTo(destFile)) {
LOGGER.debug("unable to rename file " + thisFile.getAbsolutePath() + " to " + destFile.getAbsolutePath());
}
}
}
}
public static Date nextZuluZeroTime() {
final Calendar nextZuluMidnight = GregorianCalendar.getInstance(TimeZone.getTimeZone("Zulu"));
nextZuluMidnight.set(Calendar.HOUR_OF_DAY,0);
nextZuluMidnight.set(Calendar.MINUTE,0);
nextZuluMidnight.set(Calendar.SECOND, 0);
nextZuluMidnight.add(Calendar.HOUR, 24);
return nextZuluMidnight.getTime();
}
public static String makeThreadName(final PwmApplication pwmApplication, final Class theClass) {
String instanceName = "-";
if (pwmApplication != null && pwmApplication.getInstanceID() != null) {
instanceName = pwmApplication.getInstanceID();
}
return PwmConstants.PWM_APP_NAME + "-" + instanceName + "-" + theClass.getSimpleName();
}
public static void checkUrlAgainstWhitelist(
final PwmApplication pwmApplication,
final SessionLabel sessionLabel,
final String inputURL
)
throws PwmOperationalException
{
LOGGER.trace(sessionLabel, "beginning test of requested redirect URL: " + inputURL);
if (inputURL == null || inputURL.isEmpty()) {
return;
}
final URI inputURI;
try {
inputURI = URI.create(inputURL);
} catch (IllegalArgumentException e) {
LOGGER.error(sessionLabel, "unable to parse requested redirect url '" + inputURL + "', error: " + e.getMessage());
// dont put input uri in error response
final String errorMsg = "unable to parse url: " + e.getMessage();
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL,errorMsg));
}
{ // check to make sure we werent handed a non-http uri.
final String scheme = inputURI.getScheme();
if (scheme != null && !scheme.isEmpty() && !scheme.equalsIgnoreCase("http") && !scheme.equals("https")) {
final String errorMsg = "unsupported url scheme";
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL,errorMsg));
}
}
if (inputURI.getHost() != null && !inputURI.getHost().isEmpty()) { // disallow localhost uri
try {
InetAddress inetAddress = InetAddress.getByName(inputURI.getHost());
if (inetAddress.isLoopbackAddress()) {
final String errorMsg = "redirect to loopback host is not permitted";
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL,errorMsg));
}
} catch (UnknownHostException e) {
/* noop */
}
}
final StringBuilder sb = new StringBuilder();
if (inputURI.getScheme() != null) {
sb.append(inputURI.getScheme());
sb.append("://");
}
if (inputURI.getHost() != null) {
sb.append(inputURI.getHost());
}
if (inputURI.getPort() != -1) {
sb.append(":");
sb.append(inputURI.getPort());
}
if (inputURI.getPath() != null) {
sb.append(inputURI.getPath());
}
final String testURI = sb.toString();
LOGGER.trace(sessionLabel, "preparing to whitelist test parsed and decoded URL: " + testURI);
final String REGEX_PREFIX = "regex:";
final List<String> whiteList = pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.SECURITY_REDIRECT_WHITELIST);
for (final String loopFragment : whiteList) {
if (loopFragment.startsWith(REGEX_PREFIX)) {
try {
final String strPattern = loopFragment.substring(REGEX_PREFIX.length(), loopFragment.length());
final Pattern pattern = Pattern.compile(strPattern);
if (pattern.matcher(testURI).matches()) {
LOGGER.debug(sessionLabel, "positive URL match for regex pattern: " + strPattern);
return;
} else {
LOGGER.trace(sessionLabel, "negative URL match for regex pattern: " + strPattern);
}
} catch (Exception e) {
LOGGER.error(sessionLabel, "error while testing URL match for regex pattern: '" + loopFragment + "', error: " + e.getMessage());;
}
} else {
if (testURI.startsWith(loopFragment)) {
LOGGER.debug(sessionLabel, "positive URL match for pattern: " + loopFragment);
return;
} else {
LOGGER.trace(sessionLabel, "negative URL match for pattern: " + loopFragment);
}
}
}
final String errorMsg = testURI + " is not a match for any configured redirect whitelist, see setting: " + PwmSetting.SECURITY_REDIRECT_WHITELIST.toMenuLocationDebug(null,PwmConstants.DEFAULT_LOCALE);
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL,errorMsg));
}
public static boolean determineIfDetailErrorMsgShown(final PwmApplication pwmApplication) {
if (pwmApplication == null) {
return false;
}
PwmApplicationMode mode = pwmApplication.getApplicationMode();
if (mode == PwmApplicationMode.CONFIGURATION || mode == PwmApplicationMode.NEW) {
return true;
}
if (mode == PwmApplicationMode.RUNNING) {
if (pwmApplication.getConfig() != null) {
if (pwmApplication.getConfig().readSettingAsBoolean(PwmSetting.DISPLAY_SHOW_DETAILED_ERRORS)) {
return true;
}
}
}
return false;
}
public static CSVPrinter makeCsvPrinter(final OutputStream outputStream)
throws IOException
{
return new CSVPrinter(new OutputStreamWriter(outputStream,PwmConstants.DEFAULT_CHARSET), PwmConstants.DEFAULT_CSV_FORMAT);
}
public static <E extends Enum<E>> E readEnumFromString(Class<E> enumClass, E defaultValue, String input) {
if (input == null) {
return defaultValue;
}
try {
Method valueOfMethod = enumClass.getMethod("valueOf", String.class);
Object result = valueOfMethod.invoke(null, input);
return (E) result;
} catch (IllegalArgumentException e) {
LOGGER.trace("input=" + input + " does not exist in enumClass=" + enumClass.getSimpleName());
} catch (Exception e) {
LOGGER.warn("unexpected error translating input=" + input + " to enumClass=" + enumClass.getSimpleName());
}
return defaultValue;
}
public static Properties newSortedProperties() {
return new Properties() {
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<>(super.keySet()));
}
};
}
public static ThreadFactory makePwmThreadFactory(final String namePrefix, final boolean daemon) {
return new ThreadFactory() {
private final ThreadFactory realThreadFactory = Executors.defaultThreadFactory();
@Override
public Thread newThread(final Runnable r) {
final Thread t = realThreadFactory.newThread(r);
t.setDaemon(daemon);
if (namePrefix != null) {
final String newName = namePrefix + t.getName();
t.setName(newName);
}
return t;
}
};
}
public static String throwableToString(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
pw.flush();
return sw.toString();
}
/**
* Converts an exception to a string message. Handles cases where the message in the exception is null
* and/or there are multiple nested cause exceptions.
* @param e The exception to convert to a string
* @return A string containing any meaningful extractable cause information, suitable for debugging.
*/
public static String readHostileExceptionMessage(Throwable e) {
String errorMsg = e.getClass().getName();
if (e.getMessage() != null) {
errorMsg += ": " + e.getMessage();
}
Throwable cause = e.getCause();
int safetyCounter = 0;
while (cause != null && safetyCounter < 10) {
safetyCounter++;
errorMsg += ", cause:" + cause.getClass().getName();
if (cause.getMessage() != null) {
errorMsg += ": " + cause.getMessage();
}
cause = cause.getCause();
}
return errorMsg;
}
public static <E extends Enum<E>> boolean enumArrayContainsValue(final E[] enumArray, final E enumValue) {
return !(enumArray == null || enumArray.length == 0) && Arrays.asList(enumArray).contains(enumValue);
}
}
| gpl-2.0 |
kawzar/tdp | src/java/com/myapp/struts/LoginAction.java | 1684 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.myapp.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class LoginAction extends org.apache.struts.action.Action {
/* forward name="success" path="" */
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginActionForm data = (LoginActionForm)form;
String username = data.getUsername();
String pass = data.getPass();
if ((username.equals("admin")) && (pass.equals("admin")))
{ HttpSession session = request.getSession(true);
session.setAttribute("user", "admin");
return mapping.findForward(SUCCESS);
} else {
return mapping.findForward(FAILURE);
}
}
}
| gpl-2.0 |
digitgopher/danielle | Danielle_1.java | 68662 | /*
* Project Danielle (v.1)
* Daniel Tixier
* Started 3/8/2013.
*
* Major shell work completed 3/19.
* Major GUI work completed 3/29.
* Major initial bid/play logic completed 3/31.
* Major debugging started 3/31, break took from 4/2 - 4/16.
* Worked on displaying card pics, completed 4/21.
* Running prototype 4/21
* Master background with exit button and scores 4/22
* Major renovations (bidding nil, redealing, catching wrong input exception, slimming main method)completed 4/23
*
*
* Danielle is a heuristic-based, pseudo AI (with GUI implementation) that plays a hand of the 4-player
* card game Spades. It considers itself as sitting in the West position.
*/
package danielle_1;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
public class Danielle_1 {
static final int TWO_SPADES = 0;
static final int THREE_SPADES = 1;
static final int FOUR_SPADES = 2;
static final int FIVE_SPADES = 3;
static final int SIX_SPADES = 4;
static final int SEVEN_SPADES = 5;
static final int EIGHT_SPADES = 6;
static final int NINE_SPADES = 7;
static final int TEN_SPADES = 8;
static final int JACK_SPADES = 9;
static final int QUEEN_SPADES = 10;
static final int KING_SPADES = 11;
static final int ACE_SPADES = 12;
static final int TWO_HEARTS = 13;
static final int THREE_HEARTS = 14;
static final int FOUR_HEARTS = 15;
static final int FIVE_HEARTS = 16;
static final int SIX_HEARTS = 17;
static final int SEVEN_HEARTS = 18;
static final int EIGHT_HEARTS = 19;
static final int NINE_HEARTS = 20;
static final int TEN_HEARTS = 21;
static final int JACK_HEARTS = 22;
static final int QUEEN_HEARTS = 23;
static final int KING_HEARTS = 24;
static final int ACE_HEARTS = 25;
static final int TWO_CLUBS = 26;
static final int THREE_CLUBS = 27;
static final int FOUR_CLUBS = 28;
static final int FIVE_CLUBS = 29;
static final int SIX_CLUBS = 30;
static final int SEVEN_CLUBS = 31;
static final int EIGHT_CLUBS = 32;
static final int NINE_CLUBS = 33;
static final int TEN_CLUBS = 34;
static final int JACK_CLUBS = 35;
static final int QUEEN_CLUBS = 36;
static final int KING_CLUBS = 37;
static final int ACE_CLUBS = 38;
static final int TWO_DIAMONDS = 39;
static final int THREE_DIAMONDS = 40;
static final int FOUR_DIAMONDS = 41;
static final int FIVE_DIAMONDS = 42;
static final int SIX_DIAMONDS = 43;
static final int SEVEN_DIAMONDS = 44;
static final int EIGHT_DIAMONDS = 45;
static final int NINE_DIAMONDS = 46;
static final int TEN_DIAMONDS = 47;
static final int JACK_DIAMONDS = 48;
static final int QUEEN_DIAMONDS = 49;
static final int KING_DIAMONDS = 50;
static final int ACE_DIAMONDS = 51;
static char[] dd = new char[52];
static ImageIcon[] cardPictureIcon = new ImageIcon[52];
static ArrayList<JLabel> cardPictureLabel = new ArrayList<>();
static JFrame background = new JFrame();
static JPanel statusPanel = new JPanel();
static JLabel scoresLabel = new JLabel();
static JLabel bidsLabel = new JLabel();
static JLabel tricksLabel = new JLabel();
static final int W = 0, N = 1, E = 2, S = 3;
static boolean isWnil, isNnil, isEnil, isSnil, isWsetnil, isNsetnil, isEsetnil, isSsetnil;
static int bidW, bidN, bidE, bidS, ourBid, theirBid, ourTricks, theirTricks;
// Leader Constant, Bidding Constant, and High Card
static int lc, bc, hc;
static int[] currentTrick = new int[4];// represents a trick
// Names of players
static String partner = "", opponentN = "", opponentS = "";
static int we = 0, they = 0, ourBags = 0, theirBags = 0;
static int winningPointValue;
//@SuppressWarnings("empty-statement")
public static void main(String[] args) {
// Add a try-catch structure to let the user know that something went wrong when running external to netbeans.
try{
// Initialize the 52 card pictures
for (int i = 0; i < 52; i++) {
cardPictureIcon[i] = new ImageIcon(Danielle_1.class.getResource("cardPictures/"+(i)+".png"));
}
// Initialize the 52 card labels
for (int i = 0; i < 52; i++) {
cardPictureLabel.add(new JLabel(cardPictureIcon[i]));
}
// Other variables
String winningTeam = "Danielle and "+partner;
// Set properties of the main frame for the program
background.setTitle("Danielle_1.1");
background.setSize(660, 600);
background.setLocationRelativeTo(null);
background.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
background.setVisible(true);
background.setLayout(new BorderLayout());
// Make a button to close the program.
JButton closeButton = new JButton("Close Danielle_1.1");
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int option = JOptionPane.showConfirmDialog(background, "Exit the program?");
if(option == JOptionPane.YES_OPTION)
System.exit(0);
}
});
background.add(closeButton,BorderLayout.SOUTH);
statusPanel.setLayout(new BorderLayout());
statusPanel.add(scoresLabel, BorderLayout.NORTH);
statusPanel.add(bidsLabel, BorderLayout.CENTER);
statusPanel.add(tricksLabel, BorderLayout.SOUTH);
background.add(statusPanel, BorderLayout.NORTH);
// Get names
partner = JOptionPane.showInputDialog(null, "Enter name of partner.");
opponentN = JOptionPane.showInputDialog(null, "Enter name of opponent North.");
opponentS = JOptionPane.showInputDialog(null, "Enter name of opponent South.");
// Who bids first switches every deal, vs. who leads switches every trick.
String bcAsString = JOptionPane.showInputDialog(null, "Who bids first?\nEnter name as entered previously.");
bc = W;// Default Danielle bids
if(bcAsString.equalsIgnoreCase("Danielle"))
bc = W;
else if(bcAsString.equalsIgnoreCase(opponentN))
bc = N;
else if(bcAsString.equalsIgnoreCase(partner))
bc = E;
else if(bcAsString.equalsIgnoreCase(opponentS))
bc = S;
else{
JOptionPane.showMessageDialog(null, "You entered \"Who bids first?\" wrong. Now I have to start over.", "Fail Box", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
// What are we playing to?
String wpvAsString = JOptionPane.showInputDialog(null, "What are we playing to? (Ex: 500)");
winningPointValue = Integer.parseInt(wpvAsString);
int highestScore = 0;
while(highestScore < winningPointValue){
// Reset everything to 0 for the new hand.
// Reset tricks taken to 0.
ourTricks = 0; theirTricks = 0;
// Set leader constant equal to whoever bid first, since we are starting a new hand
lc = bc;
hc = 0;// The ever-changing high card
// int[] currentTrick = new int[4];// represents a trick
isWnil = false; isNnil = false; isEnil = false; isSnil = false; isWsetnil = false; isNsetnil = false; isEsetnil = false; isSsetnil = false;
ourBid = 0;
theirBid = 0;
// Loop in case Danielle calls a redeal
while(true){
// Reset all the cards to no information
for (int i = 0; i < 52; i++) {
dd[i] = '\u0000';
}
HandInputFrame hif = new HandInputFrame('W');
hif.setTitle("Input Danielle's Hand");
hif.setLocationRelativeTo(null);
hif.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
hif.setVisible(true);
// Give time to enter values into frame
while(hif.isVisible()){
System.out.print("");
}
bidW = bidding();
// Call a redeal now if you are going to call it.
if(bidW != -2)
break;
else
JOptionPane.showMessageDialog(null, "Danielle calls redeal. New hand!! Yes!!");
}
DisplayCardsFrame dcf = new DisplayCardsFrame();
// Bidding can't be exported to a method easily because of the continue aspect of a redeal.
String s; // To use in getting values from inputdialogs
// Other bids, switching on order of dealer, so input in the right order.
switch(bc){
case W:
// Danielle bids
if(bidW == -1){
JOptionPane.showMessageDialog(null, "Danielle bids nil");
ourBid += 1;// To get back to 0 when added up later.
isWnil = true;
}
else
JOptionPane.showMessageDialog(null, "Danielle bids "+bidW);
s = JOptionPane.showInputDialog(null, "What does "+opponentN+" bid?", "Input "+opponentN+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidN = Integer.parseInt(s);
if(bidN == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidN == -1){
isNnil = true;
theirBid += 1;
}
s = JOptionPane.showInputDialog(null, "What does "+partner+" bid?", "Input "+partner+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidE = Integer.parseInt(s);
if(bidE == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidE == -1){
isEnil = true;
ourBid +=1;
}
s = JOptionPane.showInputDialog(null, "What does "+opponentS+" bid?", "Input "+opponentS+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidS = Integer.parseInt(s);
if(bidS == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidS == -1){
isSnil = true;
theirBid +=1;
}
break;
case N:
s = JOptionPane.showInputDialog(null, "What does "+opponentN+" bid?", "Input "+opponentN+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidN = Integer.parseInt(s);
if(bidN == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidN == -1){
isNnil = true;
theirBid += 1;
}
s = JOptionPane.showInputDialog(null, "What does "+partner+" bid?", "Input "+partner+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidE = Integer.parseInt(s);
if(bidE == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidE == -1){
isEnil = true;
ourBid +=1;
}
s = JOptionPane.showInputDialog(null, "What does "+opponentS+" bid?", "Input "+opponentS+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidS = Integer.parseInt(s);
if(bidS == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidS == -1){
isSnil = true;
theirBid +=1;
}
// Danielle bids
if(bidW == -1){
JOptionPane.showMessageDialog(null, "Danielle bids nil");
ourBid += 1;// To get back to 0 when added up later.
isWnil = true;
}
else
JOptionPane.showMessageDialog(null, "Danielle bids "+bidW);
break;
case E:
s = JOptionPane.showInputDialog(null, "What does "+partner+" bid?", "Input "+partner+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidE = Integer.parseInt(s);
if(bidE == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidE == -1){
isEnil = true;
ourBid += 1;
}
s = JOptionPane.showInputDialog(null, "What does "+opponentS+" bid?", "Input "+opponentS+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidS = Integer.parseInt(s);
if(bidS == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidS == -1){
isSnil = true;
theirBid += 1;
}
// Danielle bids
if(bidW == -1){
JOptionPane.showMessageDialog(null, "Danielle bids nil");
ourBid += 1;// To get back to 0 when added up later.
isWnil = true;
}
else
JOptionPane.showMessageDialog(null, "Danielle bids "+bidW);
s = JOptionPane.showInputDialog(null, "What does "+opponentN+" bid?", "Input "+opponentN+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidN = Integer.parseInt(s);
if(bidN == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidN == -1){
isNnil = true;
theirBid += 1;
}
break;
case S:
s = JOptionPane.showInputDialog(null, "What does "+opponentS+" bid?", "Input "+opponentS+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidS = Integer.parseInt(s);
if(bidS == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidS == -1){
isSnil = true;
theirBid += 1;
}
// Danielle bids
if(bidW == -1){
JOptionPane.showMessageDialog(null, "Danielle bids nil");
ourBid += 1;// To get back to 0 when added up later.
isWnil = true;
}
else
JOptionPane.showMessageDialog(null, "Danielle bids "+bidW);
s = JOptionPane.showInputDialog(null, "What does "+opponentN+" bid?", "Input "+opponentN+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidN = Integer.parseInt(s);
if(bidN == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidN == -1){
isNnil = true;
theirBid += 1;
}
s = JOptionPane.showInputDialog(null, "What does "+partner+" bid?", "Input "+partner+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidE = Integer.parseInt(s);
if(bidE == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidE == -1){
isEnil = true;
ourBid += 1;
}
break;
default:
System.out.println("Order of bidding is wrong somewhow.");
bidS = 0;bidE = 0; bidN = 0;// Make the compiler happy
break;
}// End bids!
// Refresh status lines
scoresLabel.setText(scoreLine());
bidsLabel.setText(bidLine());
tricksLabel.setText(trickLine());
// Combine bidding to simplify things later.
ourBid += bidW + bidE;
theirBid += bidS + bidN;
// For loop represents each trick
for (int i = 0; i < 13; i++) {
// Set all the cards played in the currentTrick to "not played" value of -1
for (int j = 0; j < currentTrick.length; j++) {
currentTrick[j] = -1;
}
// Get cards played, switching on leader so order is correct
switch(lc){
case W:
currentTrick[W] = daniellePlays(/*lc, isWnil, isNnil, isEnil, isSnil, isWsetnil, isNsetnil, isEsetnil, isSsetnil,currentTrick, ourTricks, theirTricks, ourBid, theirBid*/);
// Always refresh the hand view before showing which card played, for aesthetics
dcf.dispose();
dcf = new DisplayCardsFrame();
JOptionPane.showMessageDialog(null, cardPictureIcon[currentTrick[W]],"Danielle plays card #"+currentTrick[W], JOptionPane.PLAIN_MESSAGE);
hc = currentTrick[W];
currentTrick[N] = humanPlays('N');
currentTrick[E] = humanPlays('E');
currentTrick[S] = humanPlays('S');
break;
case N:
currentTrick[N] = humanPlays('N');
hc = currentTrick[N];
currentTrick[E] = humanPlays('E');
currentTrick[S] = humanPlays('S');
currentTrick[W] = daniellePlays(/*lc, isWnil, isNnil, isEnil, isSnil, isWsetnil, isNsetnil, isEsetnil, isSsetnil, currentTrick, ourTricks, theirTricks, ourBid, theirBid*/);
dcf.dispose();
dcf = new DisplayCardsFrame();
JOptionPane.showMessageDialog(null, cardPictureIcon[currentTrick[W]],"Danielle plays card #"+currentTrick[W], JOptionPane.PLAIN_MESSAGE);
break;
case E:
currentTrick[E] = humanPlays('E');
hc = currentTrick[E];
currentTrick[S] = humanPlays('S');
currentTrick[W] = daniellePlays(/*lc, isWnil, isNnil, isEnil, isSnil, isWsetnil, isNsetnil, isEsetnil, isSsetnil, currentTrick, ourTricks, theirTricks, ourBid, theirBid*/);
dcf.dispose();
dcf = new DisplayCardsFrame();
JOptionPane.showMessageDialog(null, cardPictureIcon[currentTrick[W]],"Danielle plays card #"+currentTrick[W], JOptionPane.PLAIN_MESSAGE);
currentTrick[N] = humanPlays('N');
break;
case S:
currentTrick[S] = humanPlays('S');
hc = currentTrick[S];
currentTrick[W] = daniellePlays(/*lc, isWnil, isNnil, isEnil, isSnil, isWsetnil, isNsetnil, isEsetnil, isSsetnil, currentTrick, ourTricks, theirTricks, ourBid, theirBid*/);
dcf.dispose();
dcf = new DisplayCardsFrame();
JOptionPane.showMessageDialog(null, cardPictureIcon[currentTrick[W]],"Danielle plays card #"+currentTrick[W], JOptionPane.PLAIN_MESSAGE);
currentTrick[N] = humanPlays('N');
currentTrick[E] = humanPlays('E');
break;
default:
System.out.println("Order of playing logic isnt working");
break;
}
//Danielle assesses situation, changes how playing?
determineTrickResult(i);
// For troubleshooting...
for (int j = 0; j < dd.length; j++) {
System.out.println("dd["+j+"] = "+dd[j]);
}
// Refresh status lines
scoresLabel.setText(scoreLine());
bidsLabel.setText(bidLine());
tricksLabel.setText(trickLine());
}
// Output scores
updateScore();
JOptionPane.showMessageDialog(null, "Scores:\nDanielle and "+partner+": "+(we + ourBags)+"\n"+opponentN+" and "+opponentS+": "+(they + theirBags));
// Determine if the game is over
if(we + ourBags > they + theirBags){
highestScore = we + ourBags;
winningTeam = "Danielle and "+partner;
}
else{
highestScore = they + theirBags;
winningTeam = opponentN+" and "+opponentS;
}
// Have the next person deal
bc = (bc + 1) % 4;
// Refresh status lines
scoresLabel.setText(scoreLine());
bidsLabel.setText(bidLine());
tricksLabel.setText(trickLine());
}
//Output the winning team
JOptionPane.showMessageDialog(null, "Winning team: "+ winningTeam);
System.exit(0);
}catch(NumberFormatException e){
background.add(new JLabel("Exception Thrown. Since something went wrong, probably user error, exit and start over."), BorderLayout.CENTER);
// Re-size so it displays the new label.
background.setSize(661, 600);
}
}
/** Update all scoring variables.
* Scoring can't handle: *2 nils on same team,
* two-for more than 10,
* nil and 24T on same team*/
private static void updateScore() {
//Scoring E & W
// Neither is nil, no 24T
if(bidW != -1 && bidE != -1 && bidW + bidE < 10){
if(ourTricks == bidW + bidE)
we += (bidW + bidE) * 10;
else if(ourTricks < bidW + bidE)
we -= (bidW + bidE) * 10;
else{// ourTricks > bidW + bidE
we += (bidW + bidE) * 10;
ourBags += ourTricks - (bidW + bidE);
if(ourBags >= 10){
we -= 100;
ourBags -= 10;
}
}
}
// They go 24T
else if(bidW + bidE >= 10){
if(ourTricks >= bidW + bidE){
we += 200;
ourBags += ourTricks - (bidW + bidE);
}
else // don't make it
we -= 200;
}
// W is nil
else if(bidW == -1){
if(isWsetnil)
we -= 100;
else // W makes nil
we += 100;
if(ourTricks == bidE)
we += bidE * 10;
else if(ourTricks < bidE)
we -= bidE * 10;
else{// ourTricks > bidE
we += bidE * 10;
ourBags += ourTricks - bidE;
if(ourBags >= 10){
we -= 100;
ourBags -= 10;
}
}
}
// E is nil
else if(bidE == -1){
if(isEsetnil)
we -= 100;
else // E makes nil
we += 100;
if(ourTricks == bidW)
we += bidW * 10;
else if(ourTricks < bidW)
we -= bidW * 10;
else{// ourTricks > bidW
we += bidW * 10;
ourBags += ourTricks - bidW;
if(ourBags >= 10){
we -= 100;
ourBags -= 10;
}
}
}
// error message if none of above fit the situation
else
System.out.println("Scoring with E & W isn't working.");
//Scoring N & S
// Neither is nil, no 24T
if(bidN != -1 && bidS != -1 && bidN + bidS < 10){
if(theirTricks == bidN + bidS)
they += (bidN + bidS) * 10;
else if(theirTricks < bidN + bidS)
they -= (bidN + bidS) * 10;
else{// theirTricks > bidN + bidS
they += (bidN + bidS) * 10;
theirBags += theirTricks - (bidN + bidS);
if(theirBags >= 10){
they -= 100;
theirBags -= 10;
}
}
}
// They go 24T
else if(bidN + bidS >= 10){
if(theirTricks >= bidN + bidS){
they += 200;
theirBags += theirTricks - (bidN + bidS);
}
else // don't make it
they -= 200;
}
// N is nil
else if(bidN == -1){
if(isNsetnil)
they -= 100;
else // N makes nil
they += 100;
if(theirTricks == bidS)
they += bidS * 10;
else if(theirTricks < bidS)
they -= bidS * 10;
else{// theirTricks > bidS
they += bidS * 10;
theirBags += theirTricks - bidS;
if(theirBags >= 10){
they -= 100;
theirBags -= 10;
}
}
}
// S is nil
else if(bidS == -1){
if(isSsetnil)
they -= 100;
else // S makes nil
they += 100;
if(theirTricks == bidN)
they += bidN * 10;
else if(theirTricks < bidN)
they -= bidN * 10;
else{// theirTricks > bidN
they += bidN * 10;
theirBags += theirTricks - bidN;
if(theirBags >= 10){
they -= 100;
theirBags -= 10;
}
}
}
// error message if none of above fit the situation
else
System.out.println("Scoring with N & S isn't working.");
}
/** Determines who won and dishes out the consequences.
* int passed is the current trick, just to display it.*/
private static void determineTrickResult(int i) {
// Determine who won
for (int j = 0; j < 4; j++) {
if(hc >= 13 && hc < 26 /* a heart is led */ && ((currentTrick[j] > hc && currentTrick[j] < 26) || currentTrick[j] < 13))/* a bigger heart or a spade */
hc = currentTrick[j];
else if(hc >= 26 && hc < 39 /* a club is led */ && ((currentTrick[j] > hc && currentTrick[j] < 39) || currentTrick[j] < 13))/* a bigger club or a spade */
hc = currentTrick[j];
else if(hc >= 39 /* a diamond is led */ && (currentTrick[j] > hc || currentTrick[j] < 13))/* a bigger diamond or a spade */
hc = currentTrick[j];
else if(currentTrick[j] > hc && currentTrick[j] < 13)// a bigger spade
hc = currentTrick[j];
}
// Define consequenses for winning: leading next trick, increment tricks won, determine if set nil or not, output a dialog box
if(hc == currentTrick[W]){
lc = W;
ourTricks++;
if(isWnil){
isWnil = false;
isWsetnil = true;
}
JOptionPane.showMessageDialog(null, "Danielle won trick "+(i+1)+"!\nTake it please..." , "Trick over", JOptionPane.INFORMATION_MESSAGE);
}
else if(hc == currentTrick[N]){
lc = N;
theirTricks++;
if(isNnil){
isNnil = false;
isNsetnil = true;
}
JOptionPane.showMessageDialog(null, opponentN+" won trick "+(i+1)+"!\nTake it please..." , "Trick over", JOptionPane.INFORMATION_MESSAGE);
}
else if(hc == currentTrick[E]){
lc = E;
ourTricks++;
if(isEnil){
isEnil = false;
isEsetnil = true;
}
JOptionPane.showMessageDialog(null, partner+" won trick "+(i+1)+"!\nTake it please..." , "Trick over", JOptionPane.INFORMATION_MESSAGE);
}
else if(hc == currentTrick[S]){
lc = S;
theirTricks++;
if(isSnil){
isSnil = false;
isSsetnil = true;
}
JOptionPane.showMessageDialog(null, opponentS+" won trick "+(i+1)+"!\nTake it please..." , "Trick over", JOptionPane.INFORMATION_MESSAGE);
}
else
System.out.println("something is wrong in setting the winning trick");
}
// Class to view cards
public static class DisplayCardsFrame extends JFrame{
final int widthOfFrame;
DisplayCardsPanel dcpanel = new DisplayCardsPanel();
public DisplayCardsFrame(){
widthOfFrame = 350;
add(dcpanel);
setTitle("Danielle's Hand");
setSize(widthOfFrame, cardPictureIcon[1].getIconHeight()+50);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setVisible(true);
// setResizable(false); Not using this command because it messes it up
// It does not like repainting at all.
}
}
public static class DisplayCardsPanel extends JPanel{
final int widthOfFrame;
int x;
public DisplayCardsPanel() {
widthOfFrame = 350;
setLayout(null);
setSize(widthOfFrame, cardPictureIcon[1].getIconHeight()+50);
x = widthOfFrame - cardPictureIcon[1].getIconWidth()*2;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 51; i >= 0; i--) {
// If the card is held by 'W', add it to the frame
if(dd[i] == 'W'){
cardPictureLabel.get(i).setBounds(x,0,cardPictureLabel.get(i).getPreferredSize().width,cardPictureLabel.get(i).getPreferredSize().height);
add(cardPictureLabel.get(i));
x-=15;
}
}
}
}
/** Class to create a frame to input the cards with GUI instead of using a Scanner.
* Used for entering 13 card hand, as well as each played card. */
public static class HandInputFrame extends JFrame{
// Make button for each number
JCheckBox[] cbAll = new JCheckBox[52];
JButton ok = new JButton("OK");
JPanel colorPanel = new JPanel();
char player;
// Frame Constructor
public HandInputFrame(char player){
cbAll[0] = new JCheckBox("2 Spades");
cbAll[1] = new JCheckBox("3 Spades");
cbAll[2] = new JCheckBox("4 Spades");
cbAll[3] = new JCheckBox("5 Spades");
cbAll[4] = new JCheckBox("6 Spades");
cbAll[5] = new JCheckBox("7 Spades");
cbAll[6] = new JCheckBox("8 Spades");
cbAll[7] = new JCheckBox("9 Spades");
cbAll[8] = new JCheckBox("10 Spades");
cbAll[9] = new JCheckBox("Jack Spades");
cbAll[10] = new JCheckBox("Queen Spades");
cbAll[11] = new JCheckBox("King Spades");
cbAll[12] = new JCheckBox("Ace Spades");
cbAll[13] = new JCheckBox("2 Hearts");
cbAll[14] = new JCheckBox("3 Hearts");
cbAll[15] = new JCheckBox("4 Hearts");
cbAll[16] = new JCheckBox("5 Hearts");
cbAll[17] = new JCheckBox("6 Hearts");
cbAll[18] = new JCheckBox("7 Hearts");
cbAll[19] = new JCheckBox("8 Hearts");
cbAll[20] = new JCheckBox("9 Hearts");
cbAll[21] = new JCheckBox("10 Hearts");
cbAll[22] = new JCheckBox("Jack Hearts");
cbAll[23] = new JCheckBox("Queen Hearts");
cbAll[24] = new JCheckBox("King Hearts");
cbAll[25] = new JCheckBox("Ace Hearts");
cbAll[26] = new JCheckBox("2 Clubs");
cbAll[27] = new JCheckBox("3 Clubs");
cbAll[28] = new JCheckBox("4 Clubs");
cbAll[29] = new JCheckBox("5 Clubs");
cbAll[30] = new JCheckBox("6 Clubs");
cbAll[31] = new JCheckBox("7 Clubs");
cbAll[32] = new JCheckBox("8 Clubs");
cbAll[33] = new JCheckBox("9 Clubs");
cbAll[34] = new JCheckBox("10 Clubs");
cbAll[35] = new JCheckBox("Jack Clubs");
cbAll[36] = new JCheckBox("Queen Clubs");
cbAll[37] = new JCheckBox("King Clubs");
cbAll[38] = new JCheckBox("Ace Clubs");
cbAll[39] = new JCheckBox("2 Diamonds");
cbAll[40] = new JCheckBox("3 Diamonds");
cbAll[41] = new JCheckBox("4 Diamonds");
cbAll[42] = new JCheckBox("5 Diamonds");
cbAll[43] = new JCheckBox("6 Diamonds");
cbAll[44] = new JCheckBox("7 Diamonds");
cbAll[45] = new JCheckBox("8 Diamonds");
cbAll[46] = new JCheckBox("9 Diamonds");
cbAll[47] = new JCheckBox("10 Diamonds");
cbAll[48] = new JCheckBox("Jack Diamonds");
cbAll[49] = new JCheckBox("Queen Diamonds");
cbAll[50] = new JCheckBox("King Diamonds");
cbAll[51] = new JCheckBox("Ace Diamonds");
StatusListener colorListener = new StatusListener(colorPanel, player);
// If playing a card, only let one box be checked.
boolean ensureOnlyOneBoxChecked = (player == 'W') ? false : true;
if(ensureOnlyOneBoxChecked){
ButtonGroup group = new ButtonGroup();
// Since only one card can be played, don't let more than one box be checked
for (int i = 0; i < cbAll.length; i++) {
group.add(cbAll[i]);
}
}
// Set a display label that changes color with status.
// Yellow = not enough selected (inputing Danielle's hand only)
// Red = Too many selected, or singleton card selected has already been played
// Green = The right amount of cards selected, or that the singleton card has not been played by anyone and is not held by Danielle.
for (int i = 0; i < cbAll.length; i++) {
cbAll[i].addItemListener(colorListener);
}
setLayout(new FlowLayout());
JPanel pSpades = new JPanel(new GridLayout(13,1));
JPanel pHearts = new JPanel(new GridLayout(13,1));
JPanel pClubs = new JPanel(new GridLayout(13,1));
JPanel pDiamonds = new JPanel(new GridLayout(13,1));
JPanel rightPanel = new JPanel(new GridLayout(2, 1));
PlayCardListener listener = new PlayCardListener(player, this);
ok.addActionListener(listener);
// Add spade boxes to the 1st column panel
for (int i = 0; i < 13; i++) {
pSpades.add(cbAll[i]);
}
// Add heart boxes to the 2nd column panel
for (int i = 13; i < 26; i++) {
pHearts.add(cbAll[i]);
}
// Add club boxes to the 3rd column panel
for (int i = 26; i < 39; i++) {
pClubs.add(cbAll[i]);
}
// Add diamond boxes to the 4th column panel
for (int i = 39; i < 52; i++) {
pDiamonds.add(cbAll[i]);
}
colorPanel.setPreferredSize(new Dimension(35, 150));
ok.setBorder(new BevelBorder(BevelBorder.RAISED, Color.black, Color.black));
rightPanel.add(colorPanel);
rightPanel.add(ok);
//p1.setVisible(true);
add(pSpades);
add(pHearts);
add(pClubs);
add(pDiamonds);
add(rightPanel);
pack();
}
private class StatusListener implements ItemListener{
int numChecked = 0;
JPanel jpn;
char player;
public StatusListener(JPanel jpn, char player) {
this.jpn = jpn;
this.player = player;
}
@Override
public void itemStateChanged(ItemEvent ie) {
if(ie.getStateChange() == ItemEvent.SELECTED)
numChecked++;
else
numChecked--;
// Color the panel
if(player != 'W'){
jpn.setBackground(Color.green);
// For checkboxes 0-51, if it is selected, and the card slot it represents has something in it, paint the side red because the card can't be played.
for (int i = 0; i < 52; i++) {
if(ie.getStateChange() == ItemEvent.SELECTED && ie.getItem().equals(cbAll[i]) && dd[i] != '\u0000')
jpn.setBackground(Color.red);
}
}
else{
if(numChecked == 0)
jpn.setBackground(Color.lightGray);
else if(numChecked < 13)
jpn.setBackground(Color.yellow);
else if(numChecked > 13)
jpn.setBackground(Color.red);
else
jpn.setBackground(Color.green);
}
}
}
private class PlayCardListener implements ActionListener {
char x;
HandInputFrame f;
// Variable to make sure they don't accidently skip a play
boolean canClose = false;
public PlayCardListener(char x, HandInputFrame f) {
this.x = x;
this.f = f;
}
public PlayCardListener(HandInputFrame f) {
x = 'W';
this.f = f;
}
@Override
public void actionPerformed(ActionEvent ae) {
// Get the selected card
for (int i = 0; i < 52; i++) {
if(cbAll[i].isSelected()){
dd[i] = x;
canClose = true;
}
}
// Close the window that the listener's button is in
if(canClose)
f.dispose();
else
JOptionPane.showMessageDialog(rootPane, "A card must be played.");
}
}
}// End HandInputFrame
/**Bidding characteristics:
-Only takes its own hand into consideration - simply takes what it thinks it can take (effectively it is West, bidding first, as if score is not a factor)
-Bid nil as often as possible.
-If bidding 4 or more, consider (go into more decisions to decide) bidding one extra.?
*Define winners: the tricks it is bidding on. Base these off of covers/length of spades
*Aces, kings, and all spades have a chance to be winners.*/
public static int bidding() {
int bid = 0;
// First determine whether or not to bid nil
if(canGoNil())
return -1;// Option #1
// For a normal hand, bid on the high cards
// Bid on Aces and kings
if(dd[ACE_HEARTS] == 'W'){
bid++;
if(dd[KING_HEARTS] == 'W')
bid++;
}
else if(dd[KING_HEARTS] == 'W' && numberOfSuit('W', "Hearts") > 2)
bid++;
if(dd[ACE_CLUBS] == 'W'){
bid++;
if(dd[KING_CLUBS] == 'W')
bid++;
}
else if(dd[KING_CLUBS] == 'W' && numberOfSuit('W', "Clubs") > 2)
bid++;
if(dd[ACE_DIAMONDS] == 'W'){
bid++;
if(dd[KING_DIAMONDS] == 'W')
bid++;
}
else if(dd[KING_DIAMONDS] == 'W' && numberOfSuit('W', "Diamonds") > 2)
bid++;
// Bid on spades...
if(dd[ACE_SPADES] == 'W' && dd[KING_SPADES] == 'W' &&
dd[QUEEN_SPADES] == 'W' && dd[JACK_SPADES] == 'W')
bid += (numberOfSuit('W', "Spades"));
else if(dd[ACE_SPADES] == 'W' && dd[KING_SPADES] == 'W' &&
dd[QUEEN_SPADES] == 'W' && numberOfSuit('W', "Spades") > 3)
bid += (numberOfSuit('W', "Spades") - 1);
else if(dd[ACE_SPADES] == 'W' && dd[KING_SPADES] == 'W' &&
dd[QUEEN_SPADES] == 'W')
bid += 3;
else if((dd[ACE_SPADES] == 'W' || dd[KING_SPADES] == 'W') &&
numberOfSuit('W', "Spades") > 2)
bid += numberOfSuit('W', "Spades") - 2;
else if(dd[ACE_SPADES] == 'W' || dd[KING_SPADES] == 'W')
bid++;
else if(numberOfSuit('W', "Spades") > 3)
bid += (numberOfSuit('W', "Spades") - 3);
else if(numberOfSuit('W', "Spades") > 0 && (numberOfSuit('W', "Hearts") < 2 || numberOfSuit('W', "Clubs") < 2 || numberOfSuit('W', "Diamonds") < 2))
bid += 1;
// If can't bid nil or bid 4 or more or go nil(decided above), redeal
if(bid < 4 && (numberOfSuit('W',"Diamonds") >= 7 || numberOfSuit('W', "Hearts") >= 7
|| numberOfSuit('W', "Clubs") >= 7 || numberOfSuit('W', "Spades") == 0)){
System.out.println("$$$$");return -2; // Option #redeal
}
return bid;// Option normal
}
/** Determines if Danielle can go nil or not.*/
public static boolean canGoNil() {
//exception, too good of a hand to go nil
boolean a_k_spades = false;
boolean nilableSpades = false;
boolean badEnoughForNil = true;
boolean nilableHearts = false;
boolean nilableClubs = false;
boolean nilableDiamonds = false;
// Get the cards Danielle has in each suit
int[] hearts = inSuit("Hearts");
int[] spades = inSuit("Spades");
int[] clubs = inSuit("Clubs");
int[] diamonds = inSuit("Diamonds");
// Determine nilable spades.
// If has Ace or King, no chance at nil.
if(dd[ACE_SPADES] == 'W' || dd[KING_SPADES] == 'W')//no A or K of spades
a_k_spades = true;
if(!a_k_spades && numberOfSuit('W', "Spades") < 5){//&& 4 spades or less,
if(numberOfSuit('W', "Spades") == 4 && getHigh('W', QUEEN_SPADES) <= NINE_SPADES &&
getHigh('W', NINE_SPADES) <= FIVE_SPADES)//including Q-9-5-x or less
nilableSpades = true;
else if(numberOfSuit('W', "Spades") == 3 && getHigh('W', QUEEN_SPADES)
<= NINE_SPADES && getHigh('W', NINE_SPADES) <= FIVE_SPADES)//including Q-9-5 or less, this line of code is redundant
nilableSpades = true;
else if(numberOfSuit('W', "Spades") == 2 && getHigh('W', QUEEN_SPADES) <= NINE_SPADES)
nilableSpades = true;//including Q-9 or less
else // holds 1 or 0 spades
nilableSpades = true;
}
// Nilable suit criteria, must be equal to or lower than these values
//>5 x-x-9-6-5-3
//5 x-x-8-5-3
//4 x-J-7-4
//3 Q-7-4
//2 10-5
//1 9
// Check whichever length of HEARTS Danielle has for the nilable suit criteria.
if(hearts.length > 5 && hearts[0] <= THREE_HEARTS && hearts[1] <= FIVE_HEARTS && hearts[2] <= SIX_HEARTS && hearts[3] <= NINE_HEARTS)
nilableHearts = true;
else if (hearts.length == 5 && hearts[0] <= THREE_HEARTS && hearts[1] <= FIVE_HEARTS && hearts[2] <= EIGHT_HEARTS)
nilableHearts = true;
else if (hearts.length == 4 && hearts[0] <= FOUR_HEARTS && hearts[1] <= SEVEN_HEARTS && hearts[2] <= JACK_HEARTS)
nilableHearts = true;
else if (hearts.length == 3 && hearts[0] <= FOUR_HEARTS && hearts[1] <= SEVEN_HEARTS && hearts[2] <= QUEEN_HEARTS)
nilableHearts = true;
else if (hearts.length == 2 && hearts[0] <= FIVE_HEARTS && hearts[1] <= TEN_HEARTS)
nilableHearts = true;
else if (hearts.length == 1 && hearts[0] <= NINE_HEARTS)
nilableHearts = true;
else if (hearts.length == 0)
nilableHearts = true;
// Check whichever length of CLUBS Danielle has for the nilable suit criteria.
if(clubs.length > 5 && clubs[0] <= THREE_CLUBS && clubs[1] <= FIVE_CLUBS && clubs[2] <= SIX_CLUBS && clubs[3] <= NINE_CLUBS)
nilableClubs = true;
else if (clubs.length == 5 && clubs[0] <= THREE_CLUBS && clubs[1] <= FIVE_CLUBS && clubs[2] <= EIGHT_CLUBS)
nilableClubs = true;
else if (clubs.length == 4 && clubs[0] <= FOUR_CLUBS && clubs[1] <= SEVEN_CLUBS && clubs[2] <= JACK_CLUBS)
nilableClubs = true;
else if (clubs.length == 3 && clubs[0] <= FOUR_CLUBS && clubs[1] <= SEVEN_CLUBS && clubs[2] <= QUEEN_CLUBS)
nilableClubs = true;
else if (clubs.length == 2 && clubs[0] <= FIVE_CLUBS && clubs[1] <= TEN_CLUBS)
nilableClubs = true;
else if (clubs.length == 1 && clubs[0] <= NINE_CLUBS)
nilableClubs = true;
else if (clubs.length == 0)
nilableClubs = true;
// Check whichever length of DIAMONDS Danielle has for the nilable suit criteria.
if(diamonds.length > 5 && diamonds[0] <= THREE_DIAMONDS && diamonds[1] <= FIVE_DIAMONDS && diamonds[2] <= SIX_DIAMONDS && diamonds[3] <= NINE_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 5 && diamonds[0] <= THREE_DIAMONDS && diamonds[1] <= FIVE_DIAMONDS && diamonds[2] <= EIGHT_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 4 && diamonds[0] <= FOUR_DIAMONDS && diamonds[1] <= SEVEN_DIAMONDS && diamonds[2] <= JACK_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 3 && diamonds[0] <= FOUR_DIAMONDS && diamonds[1] <= SEVEN_DIAMONDS && diamonds[2] <= QUEEN_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 2 && diamonds[0] <= FIVE_DIAMONDS && diamonds[1] <= TEN_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 1 && diamonds[0] <= NINE_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 0)
nilableDiamonds = true;
// Don't go nil with more than 2 Aces/Kings
if(numberOfAcesAndKings() > 2)
badEnoughForNil = false;
// Return
if(nilableSpades && nilableHearts && nilableClubs && nilableDiamonds && badEnoughForNil)
return true;
else
return false;
}
/** Returns highest in a suit. Works the same way as numberOfSuit.*/
public static int getHigh(char player, String suit){
int num = -1;
switch (suit) {
case "Spades":
for (int i = 0; i < 13; i++) {
if(dd[i] == player)
num = i;
}
break;
case "Hearts":
for (int i = 13; i < 26; i++) {
if(dd[i] == player)
num = i;
}
break;
case "Clubs":
for (int i = 26; i < 39; i++) {
if(dd[i] == player)
num = i;
}
break;
case "Diamonds":
for (int i = 39; i < 52; i++) {
if(dd[i] == player)
num = i;
}
break;
default:
System.out.println("getHigh isnt working");
break;
}
return num;
}
/** Returns highest in a suit below or equal to a specified card.
If no cards held are below or equal to the specified card, returns -1.*/
public static int getHigh(char player, int card){
int num = -1;
if(card < 13){
for (int i = 0; i <= card; i++) {
if(dd[i] == player)
num = i;
}
}
else if(card < 26){
for (int i = 13; i <= card; i++) {
if(dd[i] == player)
num = i;
}
}
else if(card < 39){
for (int i = 26; i <= card; i++) {
if(dd[i] == player)
num = i;
}
}
else if(card < 52){
for (int i = 39; i <= card; i++) {
if(dd[i] == player)
num = i;
}
}
else
System.out.println("getHigh isnt working");
System.out.println("getHigh is returning: "+num);
return num;
}
/** Returns lowest in a suit above or equal to a specified card.*/
public static int getLow(char player, int card){
int num = -1;
if(card < 13){
for (int i = 12; i >= card; i--) {
if(dd[i] == player)
num = i;
}
}
else if(card < 26){
for (int i = 25; i >= card; i--) {
if(dd[i] == player)
num = i;
}
}
else if(card < 39){
for (int i = 38; i >= card; i--) {
if(dd[i] == player)
num = i;
}
}
else if(card < 52){
for (int i = 51; i >= card; i--) {
if(dd[i] == player)
num = i;
}
}
else
System.out.println("getLow isnt working");
System.out.println("getLow is returning: "+num);
return num;
}
/** Returns the number of cards or a given suit in a given hand, that Danielle knows.
// *For example, if asking for hearts of North, it returns the number of hearts that North has played.
// Used in bidding. Returns 0 if no cards held.*/
public static int numberOfSuit(char player, String suit){
int num = 0;
switch (suit) {
case "Spades":
for (int i = 0; i < 13; i++) {
if(dd[i] == player)
num++;
}
break;
case "Hearts":
for (int i = 13; i < 26; i++) {
if(dd[i] == player)
num++;
}
break;
case "Clubs":
for (int i = 26; i < 39; i++) {
if(dd[i] == player)
num++;
}
break;
case "Diamonds":
for (int i = 39; i < 52; i++) {
if(dd[i] == player)
num++;
}
break;
default:
System.out.println("numberOfSuit isnt working");
break;
}
return num;
}
// North makes a play
public static int humanPlays(char x){
String name = "";
if(x == 'E')
name = partner;
else if(x == 'N')
name = opponentN;
else if(x == 'S')
name = opponentS;
else
name = "Janky, lol";
char[] tempdd = dd.clone();
HandInputFrame hif = new HandInputFrame(x);
hif.setTitle(name+": Input "+name+"'s Play. Single Card Only!");
hif.setLocationRelativeTo(null);
hif.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
hif.setVisible(true);
// Wait for button to be pressed on the frame
while(hif.isVisible()){
System.out.print("");
}
for (int i = 0; i < tempdd.length; i++)
if(tempdd[i] != dd[i]){
System.out.println(name+" plays dd["+i+"], so this slot now equals: "+dd[i]);
return i;
}
// If it didn't return anything, something is wrong
System.out.println("Something is wrong in humanPlays. Had to terminate. Oops.");
System.exit(x);
return -10;
}
/** method with all the logic for how Danielle plays!*/
public static int daniellePlays(/*int lc, boolean isWnil, boolean isNnil,
boolean isEnil, boolean isSnil, boolean isWsetnil,boolean isNsetnil,
boolean isEsetnil, boolean isSsetnil, int[] currentTrick,
int ourTricks, int theirTricks, int ourBid, int theirBid*/) {
int x;
if(isWnil && !isWsetnil){
x = sluff(lc, currentTrick);
dd[x] = 'P';
return x;
}
else if(isNnil && !isNsetnil || isSnil && !isSsetnil){
x = sluff(lc, currentTrick);
dd[x] = 'P';
return x;
}
else if(ourTricks >= ourBid){
x = sluff(lc, currentTrick);
dd[x] = 'P';
return x;
}
else{//no need to sluff
x = win(lc, currentTrick);
dd[x] = 'P';
return x;
}
}
/** Play to sluff*/
public static int sluff(int lc, int[] currentTrick){
int x = -10;
switch(lc){
case W:// Danielle plays first
if(numberOfSuit('W', "Hearts") > 0 || numberOfSuit('W', "Clubs") > 0 || numberOfSuit('W', "Diamonds") > 0)
return absoluteLowest();
else
return getLow('W', TWO_SPADES);
case N:// Danielle plays last
// Find highest card in suit played
for (int i = 0; i < currentTrick.length; i++) {
if(currentTrick[i] > x && currentTrick[i] <= highInSuitConst(currentTrick[lc]))
x = currentTrick[i];
}
x = getHigh('W', x);
if(x != -1)// sluff in suit
return x;
else// does not have anything in the suit lower than x
if(getHigh('W', highInSuitConst(currentTrick[lc])) == -1)// has no card in suit
return absoluteHighest();
else// has a card in suit, so has to play it
return getLow('W', lowInSuitConst(currentTrick[lc]));
case E:// Danielle plays 3rd
// Find highest card played so far
if(currentTrick[S] > currentTrick[E] && currentTrick[S] <= highInSuitConst(currentTrick[E]))
x = currentTrick[S];
else
x = currentTrick[E];
x = getHigh('W', x);
if(x != -1)// can play under in suit
return x;
else// has nothing lower than what has been played
x = getHigh('W', highInSuitConst(currentTrick[lc]));
if(x != -1)// play the lowest it can anyway
return getLow('W', currentTrick[lc]);// 2nd parameter is the only thing that represents suit, and it doesn't matter because W has nothing lower in the hand anyway.
else// nothing in the suit
if(numberOfSuit('W', "Hearts") > 0 || numberOfSuit('W', "Clubs") > 0 || numberOfSuit('W', "Diamonds") > 0)
return absoluteHighest();
else
return getLow('W', TWO_SPADES);// if you have to play a spade, play a low one
case S:// Danielle plays 2nd
x = getHigh('W', currentTrick[S]);
if(x != -1)// can play under in suit
return x;
else// has nothing lower than what has been played
x = getHigh('W', highInSuitConst(currentTrick[lc]));
if(x != -1)// play the lowest it can anyway
return getLow('W', currentTrick[S]);// 2nd parameter is the only thing that represents suit, and it doesn't matter because W has nothing lower in the hand anyway.
else// nothing in the suit
if(numberOfSuit('W', "Hearts") > 0 || numberOfSuit('W', "Clubs") > 0 || numberOfSuit('W', "Diamonds") > 0)
return absoluteHighest();
else
return getLow('W', TWO_SPADES);// if you have to play a spade, play a low one
default:
System.out.println("daniellePlays method getting to default. Check it out.");
break;
}
return x;// Shouldn't ever get to this point.
}
/** Play to win */
public static int win(int lc, int[] currentTrick){
boolean canWinInSuit = true;
boolean alreadyRuffedThisTrick = false;
boolean spadesBroken = false;
int extra;
if(lc == W){
for (int i = 0; i < 13; i++) {
if(dd[i] != '\u0000' && dd[i] != 'W'){
spadesBroken = true;
break;
}
}
if(spadesBroken){
if(numberOfSuit('W', "Spades") > 0)
return getHigh('W', highInSuitConst(0));
else
return absoluteHighest();
}
else{
if(numberOfSuit('W', "Hearts") > 0 || numberOfSuit('W', "Clubs") > 0 || numberOfSuit('W', "Diamonds") > 0)
return absoluteHighest();
else// has to break spades
return getHigh('W', highInSuitConst(0));
}
}// End lc == 'W'
else{
int x = getHigh('W', highInSuitConst(currentTrick[lc]));
if(x != -1){// has a card in the suit led
for (int i = 0; i < currentTrick.length; i++) {
if(x < currentTrick[i])
canWinInSuit = false;
}
if(canWinInSuit)
return x;
else// have to play something lower, so go all the way low
return getLow('W', lowInSuitConst(currentTrick[lc]));
}
else{// has no card in the suit led; x == -1
for (int i = 0; i < currentTrick.length; i++) {
if(currentTrick[i] >= 0 && currentTrick[i] < 13){
extra = currentTrick[i];
if(extra > x)
x = extra;// x represents the highest spade played
alreadyRuffedThisTrick = true;
}
}
if(alreadyRuffedThisTrick)// select the lowest spade that will win
x = getLow('W', x);
else// nobody has spaded in
x = getLow('W', lowInSuitConst(TWO_SPADES));
if(x != -1)// W has a spade
return x;
else// has not spades
return absoluteLowest();
}
}
}
/** Returns the high card in the suit of the given card.*/
public static int highInSuitConst(int lc){
if(lc < 13)
return 12;
else if(lc < 26)
return 25;
else if(lc < 39)
return 38;
else
return 51;
}
/** Returns the low card in the suit of the given card.*/
public static int lowInSuitConst(int lc){
if(lc < 13)
return 0;
else if(lc < 26)
return 13;
else if(lc < 39)
return 26;
else
return 39;
}
/**Return the lowest card by number in W's hand, does not return a spade.*/
public static int absoluteLowest(){
int x = 52;
for (int i = dd.length - 1; i >= dd.length - 13; i--) // check each decreasing number
for (int j = i; j >= 13; j = j-13) //check each suit
if(dd[j] == 'W')
x = j;
if(x == 52)
System.out.println("absoluteLowest did not go lower than 52.");
System.out.println("absoluteLowest returning: "+x);
return x;
}
/** return the highest card by number in W's hand, does not return a spade*/
public static int absoluteHighest(){
int x = -10;
for (int i = 13; i < 26; i++) // check each increasing number
for (int j = i; j <= 51; j = j+13) //check each suit
if(dd[j] == 'W')
x = j;
if(x == 52)
System.out.println("absoluteHighest did not go higher than -10.");
System.out.println("absoluteHighest is returning: "+x);
return x;
}
/** Returns a string that represents the current scores.*/
public static String scoreLine(){
return "Scores - Danielle & "+partner+": "+(we + ourBags)+" "+opponentN+" & "+opponentS+": "+(they + theirBags)+" Game to: "+winningPointValue;
}
/** Returns a string that represents the current bids.*/
public static String bidLine(){
return "Bids - Danielle: "+bidW+" "+partner+": "+bidE+" "+opponentN+": "+bidN+" "+opponentS+": "+bidS;
}
/** Returns a string that represents the current tricks taken.*/
public static String trickLine(){
return "Taken - Danielle & "+partner+": "+ourTricks+" "+opponentN+" & "+opponentS+": "+theirTricks;
}
/** Returns an int array with all the cards in specified suit held by Danielle.
* [0] contains the lowest card, [length -1] contains the highest card.*/
public static int[] inSuit(String suit){
int[] nums = new int[numberOfSuit('W', suit)];
int count = 0;
switch (suit) {
case "Spades":
for (int i = 0; i < 13; i++) {
if(dd[i] == 'W'){
nums[count] = i;
count++;
}
}
break;
case "Hearts":
for (int i = 13; i < 26; i++) {
if(dd[i] == 'W'){
nums[count] = i;
count++;
}
}
break;
case "Clubs":
for (int i = 26; i < 39; i++) {
if(dd[i] == 'W'){
nums[count] = i;
count++;
}
}
break;
case "Diamonds":
for (int i = 39; i < 52; i++) {
if(dd[i] == 'W'){
nums[count] = i;
count++;
}
}
break;
default:
System.out.println("inSuit is getting to default");
break;
}
return nums;
}
/** Returns how many Aces and Kings Danielle has.*/
public static int numberOfAcesAndKings(){
int num = 0;
if(dd[ACE_CLUBS] == 'W')
num++;
if(dd[ACE_DIAMONDS] == 'W')
num++;
if(dd[ACE_HEARTS] == 'W')
num++;
if(dd[ACE_SPADES] == 'W')
num++;
if(dd[KING_CLUBS] == 'W')
num++;
if(dd[KING_DIAMONDS] == 'W')
num++;
if(dd[KING_HEARTS] == 'W')
num++;
if(dd[KING_SPADES] == 'W')
num++;
return num;
}
}
| gpl-2.0 |
BunnyWei/truffle-llvmir | graal/com.oracle.graal.lir.sparc/src/com/oracle/graal/lir/sparc/SPARCBitManipulationOp.java | 6018 | /*
* Copyright (c) 2012, 2014, 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.lir.sparc;
import static com.oracle.graal.api.code.ValueUtil.*;
import static com.oracle.graal.asm.sparc.SPARCAssembler.*;
import static com.oracle.graal.lir.LIRInstruction.OperandFlag.*;
import static com.oracle.graal.sparc.SPARC.*;
import com.oracle.graal.api.code.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.asm.sparc.*;
import com.oracle.graal.compiler.common.*;
import com.oracle.graal.lir.*;
import com.oracle.graal.lir.asm.*;
import com.oracle.graal.lir.gen.*;
public final class SPARCBitManipulationOp extends SPARCLIRInstruction {
public static final LIRInstructionClass<SPARCBitManipulationOp> TYPE = LIRInstructionClass.create(SPARCBitManipulationOp.class);
public enum IntrinsicOpcode {
IPOPCNT,
LPOPCNT,
IBSR,
LBSR,
BSF;
}
@Opcode private final IntrinsicOpcode opcode;
@Def protected AllocatableValue result;
@Alive({REG}) protected AllocatableValue input;
@Temp({REG}) protected Value scratch;
public SPARCBitManipulationOp(IntrinsicOpcode opcode, AllocatableValue result, AllocatableValue input, LIRGeneratorTool gen) {
super(TYPE);
this.opcode = opcode;
this.result = result;
this.input = input;
scratch = gen.newVariable(LIRKind.derive(input));
}
@Override
public void emitCode(CompilationResultBuilder crb, SPARCMacroAssembler masm) {
Register dst = asIntReg(result);
if (isRegister(input)) {
Register src = asRegister(input);
switch (opcode) {
case IPOPCNT:
// clear upper word for 64 bit POPC
masm.srl(src, g0, dst);
masm.popc(dst, dst);
break;
case LPOPCNT:
masm.popc(src, dst);
break;
case BSF:
Kind tkind = input.getKind();
if (tkind == Kind.Int) {
masm.sub(src, 1, dst);
masm.andn(dst, src, dst);
masm.srl(dst, g0, dst);
masm.popc(dst, dst);
} else if (tkind == Kind.Long) {
masm.sub(src, 1, dst);
masm.andn(dst, src, dst);
masm.popc(dst, dst);
} else {
throw GraalInternalError.shouldNotReachHere("missing: " + tkind);
}
break;
case IBSR: {
Kind ikind = input.getKind();
assert ikind == Kind.Int;
Register tmp = asRegister(scratch);
assert !tmp.equals(dst);
masm.srl(src, 1, tmp);
masm.srl(src, 0, dst);
masm.or(dst, tmp, dst);
masm.srl(dst, 2, tmp);
masm.or(dst, tmp, dst);
masm.srl(dst, 4, tmp);
masm.or(dst, tmp, dst);
masm.srl(dst, 8, tmp);
masm.or(dst, tmp, dst);
masm.srl(dst, 16, tmp);
masm.or(dst, tmp, dst);
masm.popc(dst, dst);
masm.sub(dst, 1, dst);
break;
}
case LBSR: {
Kind lkind = input.getKind();
assert lkind == Kind.Long;
Register tmp = asRegister(scratch);
assert !tmp.equals(dst);
masm.srlx(src, 1, tmp);
masm.or(src, tmp, dst);
masm.srlx(dst, 2, tmp);
masm.or(dst, tmp, dst);
masm.srlx(dst, 4, tmp);
masm.or(dst, tmp, dst);
masm.srlx(dst, 8, tmp);
masm.or(dst, tmp, dst);
masm.srlx(dst, 16, tmp);
masm.or(dst, tmp, dst);
masm.srlx(dst, 32, tmp);
masm.or(dst, tmp, dst);
masm.popc(dst, dst);
masm.sub(dst, 1, dst); // This is required to fit the given structure.
break;
}
default:
throw GraalInternalError.shouldNotReachHere();
}
} else if (isConstant(input) && isSimm13(crb.asIntConst(input))) {
switch (opcode) {
case IPOPCNT:
masm.popc(crb.asIntConst(input), dst);
break;
case LPOPCNT:
masm.popc(crb.asIntConst(input), dst);
break;
default:
throw GraalInternalError.shouldNotReachHere();
}
} else {
throw GraalInternalError.shouldNotReachHere();
}
}
}
| gpl-2.0 |
joeyliu616/business-atom | sms/sms-client-impl-emay/src/main/java/com/aoe/sms/client/impl/emay/sp/ResultInfo.java | 529 | package com.aoe.sms.client.impl.emay.sp;
public class ResultInfo {
private String code;
private String message;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "ResultInfo [code=" + code + ", message=" + message + "]";
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshall.java | 1540 | /*
* Copyright 1999-2008 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.
*/
/**
*
*/
import java.rmi.Remote;
import java.rmi.RemoteException;
/*
* Interface with methods to exercise RMI parameter marshalling
* and unmarshalling.
*/
interface CheckUnmarshal extends java.rmi.Remote {
public PoisonPill getPoisonPill() throws RemoteException;
public Object ping() throws RemoteException;
public void passRuntimeExceptionParameter(
RuntimeExceptionParameter rep)
throws RemoteException;
}
| gpl-2.0 |
mur47x111/GraalVM | graal/com.oracle.graal.compiler.test/src/com/oracle/graal/compiler/test/inlining/InliningTest.java | 18211 | /*
* 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.
*
* 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.test.inlining;
import jdk.internal.jvmci.code.*;
import com.oracle.graal.debug.*;
import com.oracle.graal.debug.Debug.*;
import jdk.internal.jvmci.meta.*;
import org.junit.*;
import com.oracle.graal.compiler.test.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.graphbuilderconf.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.StructuredGraph.AllowAssumptions;
import com.oracle.graal.phases.*;
import com.oracle.graal.phases.common.*;
import com.oracle.graal.phases.common.inlining.*;
import com.oracle.graal.phases.tiers.*;
public class InliningTest extends GraalCompilerTest {
@Test
public void testInvokeStaticInlining() {
assertInlined(getGraph("invokeStaticSnippet", false));
assertInlined(getGraph("invokeStaticOnInstanceSnippet", false));
}
@SuppressWarnings("all")
public static Boolean invokeStaticSnippet(boolean value) {
return Boolean.valueOf(value);
}
@SuppressWarnings("all")
public static Boolean invokeStaticOnInstanceSnippet(Boolean obj, boolean value) {
return obj.valueOf(value);
}
@Test
public void testStaticBindableInlining() {
assertInlined(getGraph("invokeConstructorSnippet", false));
assertInlined(getGraph("invokeFinalMethodSnippet", false));
assertInlined(getGraph("invokeMethodOnFinalClassSnippet", false));
assertInlined(getGraph("invokeMethodOnStaticFinalFieldSnippet", false));
}
@Ignore("would need read elimination/EA before inlining")
@Test
public void testDependentStaticBindableInlining() {
assertInlined(getGraph("invokeMethodOnFinalFieldSnippet", false));
assertInlined(getGraph("invokeMethodOnFieldSnippet", false));
}
@Test
public void testStaticBindableInliningIP() {
assertManyMethodInfopoints(assertInlined(getGraph("invokeConstructorSnippet", true)));
assertManyMethodInfopoints(assertInlined(getGraph("invokeFinalMethodSnippet", true)));
assertManyMethodInfopoints(assertInlined(getGraph("invokeMethodOnFinalClassSnippet", true)));
assertManyMethodInfopoints(assertInlined(getGraph("invokeMethodOnStaticFinalFieldSnippet", true)));
}
@Ignore("would need read elimination/EA before inlining")
@Test
public void testDependentStaticBindableInliningIP() {
assertManyMethodInfopoints(assertInlined(getGraph("invokeMethodOnFinalFieldSnippet", true)));
assertManyMethodInfopoints(assertInlined(getGraph("invokeMethodOnFieldSnippet", true)));
}
@SuppressWarnings("all")
public static Object invokeConstructorSnippet(int value) {
return new SuperClass(value);
}
@SuppressWarnings("all")
public static int invokeFinalMethodSnippet(SuperClass superClass, SubClassA subClassA, FinalSubClass finalSubClass) {
return superClass.publicFinalMethod() + subClassA.publicFinalMethod() + finalSubClass.publicFinalMethod() + superClass.protectedFinalMethod() + subClassA.protectedFinalMethod() +
finalSubClass.protectedFinalMethod();
}
@SuppressWarnings("all")
public static int invokeMethodOnFinalClassSnippet(FinalSubClass finalSubClass) {
return finalSubClass.publicFinalMethod() + finalSubClass.publicNotOverriddenMethod() + finalSubClass.publicOverriddenMethod() + finalSubClass.protectedFinalMethod() +
finalSubClass.protectedNotOverriddenMethod() + finalSubClass.protectedOverriddenMethod();
}
@SuppressWarnings("all")
public static int invokeMethodOnStaticFinalFieldSnippet() {
return StaticFinalFields.NumberStaticFinalField.intValue() + StaticFinalFields.SuperClassStaticFinalField.publicOverriddenMethod() +
StaticFinalFields.FinalSubClassStaticFinalField.publicOverriddenMethod() + StaticFinalFields.SingleImplementorStaticFinalField.publicOverriddenMethod() +
StaticFinalFields.MultipleImplementorsStaticFinalField.publicOverriddenMethod() + StaticFinalFields.SubClassAStaticFinalField.publicOverriddenMethod() +
StaticFinalFields.SubClassBStaticFinalField.publicOverriddenMethod() + StaticFinalFields.SubClassCStaticFinalField.publicOverriddenMethod();
}
@SuppressWarnings("all")
public static int invokeMethodOnFinalFieldSnippet() {
FinalFields fields = new FinalFields();
return fields.numberFinalField.intValue() + fields.superClassFinalField.publicOverriddenMethod() + fields.finalSubClassFinalField.publicOverriddenMethod() +
fields.singleImplementorFinalField.publicOverriddenMethod() + fields.multipleImplementorsFinalField.publicOverriddenMethod() +
fields.subClassAFinalField.publicOverriddenMethod() + fields.subClassBFinalField.publicOverriddenMethod() + fields.subClassCFinalField.publicOverriddenMethod();
}
@SuppressWarnings("all")
public static int invokeMethodOnFieldSnippet() {
Fields fields = new Fields();
return fields.numberField.intValue() + fields.superClassField.publicOverriddenMethod() + fields.finalSubClassField.publicOverriddenMethod() +
fields.singleImplementorField.publicOverriddenMethod() + fields.multipleImplementorsField.publicOverriddenMethod() + fields.subClassAField.publicOverriddenMethod() +
fields.subClassBField.publicOverriddenMethod() + fields.subClassCField.publicOverriddenMethod();
}
public interface Attributes {
int getLength();
}
public class NullAttributes implements Attributes {
@Override
public int getLength() {
return 0;
}
}
public class TenAttributes implements Attributes {
@Override
public int getLength() {
return 10;
}
}
public int getAttributesLength(Attributes a) {
return a.getLength();
}
@Test
public void testGuardedInline() {
NullAttributes nullAttributes = new NullAttributes();
for (int i = 0; i < 10000; i++) {
getAttributesLength(nullAttributes);
}
getAttributesLength(new TenAttributes());
test("getAttributesLength", nullAttributes);
test("getAttributesLength", (Object) null);
}
@Test
public void testClassHierarchyAnalysis() {
assertInlined(getGraph("invokeLeafClassMethodSnippet", false));
assertInlined(getGraph("invokeConcreteMethodSnippet", false));
assertInlined(getGraph("invokeSingleImplementorInterfaceSnippet", false));
// assertInlined(getGraph("invokeConcreteInterfaceMethodSnippet", false));
assertNotInlined(getGraph("invokeOverriddenPublicMethodSnippet", false));
assertNotInlined(getGraph("invokeOverriddenProtectedMethodSnippet", false));
assertNotInlined(getGraph("invokeOverriddenInterfaceMethodSnippet", false));
}
@Test
public void testClassHierarchyAnalysisIP() {
assertManyMethodInfopoints(assertInlined(getGraph("invokeLeafClassMethodSnippet", true)));
assertManyMethodInfopoints(assertInlined(getGraph("invokeConcreteMethodSnippet", true)));
assertManyMethodInfopoints(assertInlined(getGraph("invokeSingleImplementorInterfaceSnippet", true)));
//@formatter:off
// assertInlineInfopoints(assertInlined(getGraph("invokeConcreteInterfaceMethodSnippet", true)));
//@formatter:on
assertFewMethodInfopoints(assertNotInlined(getGraph("invokeOverriddenPublicMethodSnippet", true)));
assertFewMethodInfopoints(assertNotInlined(getGraph("invokeOverriddenProtectedMethodSnippet", true)));
assertFewMethodInfopoints(assertNotInlined(getGraph("invokeOverriddenInterfaceMethodSnippet", true)));
}
@SuppressWarnings("all")
public static int invokeLeafClassMethodSnippet(SubClassA subClassA) {
return subClassA.publicFinalMethod() + subClassA.publicNotOverriddenMethod() + subClassA.publicOverriddenMethod();
}
@SuppressWarnings("all")
public static int invokeConcreteMethodSnippet(SuperClass superClass) {
return superClass.publicNotOverriddenMethod() + superClass.protectedNotOverriddenMethod();
}
@SuppressWarnings("all")
public static int invokeSingleImplementorInterfaceSnippet(SingleImplementorInterface testInterface) {
return testInterface.publicNotOverriddenMethod() + testInterface.publicOverriddenMethod();
}
@SuppressWarnings("all")
public static int invokeConcreteInterfaceMethodSnippet(MultipleImplementorsInterface testInterface) {
return testInterface.publicNotOverriddenMethod();
}
@SuppressWarnings("all")
public static int invokeOverriddenInterfaceMethodSnippet(MultipleImplementorsInterface testInterface) {
return testInterface.publicOverriddenMethod();
}
@SuppressWarnings("all")
public static int invokeOverriddenPublicMethodSnippet(SuperClass superClass) {
return superClass.publicOverriddenMethod();
}
@SuppressWarnings("all")
public static int invokeOverriddenProtectedMethodSnippet(SuperClass superClass) {
return superClass.protectedOverriddenMethod();
}
private StructuredGraph getGraph(final String snippet, final boolean eagerInfopointMode) {
try (Scope s = Debug.scope("InliningTest", new DebugDumpScope(snippet))) {
ResolvedJavaMethod method = getResolvedJavaMethod(snippet);
StructuredGraph graph = eagerInfopointMode ? parseDebug(method, AllowAssumptions.YES) : parseEager(method, AllowAssumptions.YES);
PhaseSuite<HighTierContext> graphBuilderSuite = eagerInfopointMode ? getCustomGraphBuilderSuite(GraphBuilderConfiguration.getFullDebugDefault(getDefaultGraphBuilderPlugins()))
: getDefaultGraphBuilderSuite();
HighTierContext context = new HighTierContext(getProviders(), graphBuilderSuite, OptimisticOptimizations.ALL);
Debug.dump(graph, "Graph");
new CanonicalizerPhase().apply(graph, context);
new InliningPhase(new CanonicalizerPhase()).apply(graph, context);
Debug.dump(graph, "Graph");
new CanonicalizerPhase().apply(graph, context);
new DeadCodeEliminationPhase().apply(graph);
return graph;
} catch (Throwable e) {
throw Debug.handle(e);
}
}
private static StructuredGraph assertInlined(StructuredGraph graph) {
return assertNotInGraph(graph, Invoke.class);
}
private static StructuredGraph assertNotInlined(StructuredGraph graph) {
return assertInGraph(graph, Invoke.class);
}
private static StructuredGraph assertNotInGraph(StructuredGraph graph, Class<?> clazz) {
for (Node node : graph.getNodes()) {
if (clazz.isInstance(node)) {
fail(node.toString());
}
}
return graph;
}
private static StructuredGraph assertInGraph(StructuredGraph graph, Class<?> clazz) {
for (Node node : graph.getNodes()) {
if (clazz.isInstance(node)) {
return graph;
}
}
fail("Graph does not contain a node of class " + clazz.getName());
return graph;
}
private static int[] countMethodInfopoints(StructuredGraph graph) {
int start = 0;
int end = 0;
for (FullInfopointNode ipn : graph.getNodes().filter(FullInfopointNode.class)) {
if (ipn.getReason() == InfopointReason.METHOD_START) {
++start;
} else if (ipn.getReason() == InfopointReason.METHOD_END) {
++end;
}
}
return new int[]{start, end};
}
private static StructuredGraph assertManyMethodInfopoints(StructuredGraph graph) {
int[] counts = countMethodInfopoints(graph);
if (counts[0] <= 1 || counts[1] <= 1) {
fail(String.format("Graph contains too few required method boundary infopoints: %d starts, %d ends.", counts[0], counts[1]));
}
return graph;
}
private static StructuredGraph assertFewMethodInfopoints(StructuredGraph graph) {
int[] counts = countMethodInfopoints(graph);
if (counts[0] > 1 || counts[1] > 1) {
fail(String.format("Graph contains too many method boundary infopoints: %d starts, %d ends.", counts[0], counts[1]));
}
return graph;
}
// some interfaces and classes for testing
private interface MultipleImplementorsInterface {
int publicNotOverriddenMethod();
int publicOverriddenMethod();
}
private interface SingleImplementorInterface {
int publicNotOverriddenMethod();
int publicOverriddenMethod();
}
private static class SuperClass implements MultipleImplementorsInterface {
protected int value;
public SuperClass(int value) {
this.value = value;
}
public int publicNotOverriddenMethod() {
return value;
}
public int publicOverriddenMethod() {
return value;
}
protected int protectedNotOverriddenMethod() {
return value;
}
protected int protectedOverriddenMethod() {
return value;
}
public final int publicFinalMethod() {
return value + 255;
}
protected final int protectedFinalMethod() {
return value + 255;
}
}
private static class SubClassA extends SuperClass implements SingleImplementorInterface {
public SubClassA(int value) {
super(value);
}
@Override
public int publicOverriddenMethod() {
return value + 2;
}
@Override
protected int protectedOverriddenMethod() {
return value * 2;
}
}
private static class SubClassB extends SuperClass {
public SubClassB(int value) {
super(value);
}
@Override
public int publicOverriddenMethod() {
return value + 3;
}
@Override
protected int protectedOverriddenMethod() {
return value * 3;
}
}
private static class SubClassC extends SuperClass {
public SubClassC(int value) {
super(value);
}
@Override
public int publicOverriddenMethod() {
return value + 4;
}
@Override
protected int protectedOverriddenMethod() {
return value * 4;
}
}
private static final class FinalSubClass extends SuperClass {
public FinalSubClass(int value) {
super(value);
}
@Override
public int publicOverriddenMethod() {
return value + 5;
}
@Override
protected int protectedOverriddenMethod() {
return value * 5;
}
}
private static final class StaticFinalFields {
private static final Number NumberStaticFinalField = new Integer(1);
private static final SuperClass SuperClassStaticFinalField = new SubClassA(2);
private static final FinalSubClass FinalSubClassStaticFinalField = new FinalSubClass(3);
private static final SingleImplementorInterface SingleImplementorStaticFinalField = new SubClassA(4);
private static final MultipleImplementorsInterface MultipleImplementorsStaticFinalField = new SubClassC(5);
private static final SubClassA SubClassAStaticFinalField = new SubClassA(6);
private static final SubClassB SubClassBStaticFinalField = new SubClassB(7);
private static final SubClassC SubClassCStaticFinalField = new SubClassC(8);
}
private static final class FinalFields {
private final Number numberFinalField = new Integer(1);
private final SuperClass superClassFinalField = new SubClassA(2);
private final FinalSubClass finalSubClassFinalField = new FinalSubClass(3);
private final SingleImplementorInterface singleImplementorFinalField = new SubClassA(4);
private final MultipleImplementorsInterface multipleImplementorsFinalField = new SubClassC(5);
private final SubClassA subClassAFinalField = new SubClassA(6);
private final SubClassB subClassBFinalField = new SubClassB(7);
private final SubClassC subClassCFinalField = new SubClassC(8);
}
private static final class Fields {
private Number numberField = new Integer(1);
private SuperClass superClassField = new SubClassA(2);
private FinalSubClass finalSubClassField = new FinalSubClass(3);
private SingleImplementorInterface singleImplementorField = new SubClassA(4);
private MultipleImplementorsInterface multipleImplementorsField = new SubClassC(5);
private SubClassA subClassAField = new SubClassA(6);
private SubClassB subClassBField = new SubClassB(7);
private SubClassC subClassCField = new SubClassC(8);
}
}
| gpl-2.0 |
ykro/androidmooc-clase2 | Demo 8 - navigation drawer pasando contenido a fragmentos/src/com/ug/telescopio/fragments/CountriesListFragment.java | 4216 | package com.ug.telescopio.fragments;
import java.util.ArrayList;
import java.util.Arrays;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.ug.telescopio.R;
import com.ug.telescopio.activities.CountryDetailActivity;
public class CountriesListFragment extends Fragment implements OnItemClickListener {
String country = "";
ListView list;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] array_countries = new String[]{"Brasil", "Mxico", "Colombia", "Argentina",
"Per", "Venezuela", "Chile", "Ecuador",
"Guatemala", "Cuba"};
ArrayList<String> countries = new ArrayList<String>(Arrays.asList(array_countries));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1,
countries);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
registerForContextMenu(list);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_countries_list, container, false);
list = (ListView)view.findViewById(R.id.listView);
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu){
boolean landscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
MenuItem share = menu.getItem(menu.size()-1);
share.setVisible(landscape);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_help:
return true;
case R.id.action_share:
if (!country.equals("")) {
String url = "http://es.m.wikipedia.org/wiki/" + country;
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, getResources().getText(R.string.msg_share) + " " + country + " " + url);
intent.setType("text/plain");
startActivity(Intent.createChooser(intent, getResources().getText(R.string.action_share)));
}
return true;
default :
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) menuInfo;
country = ((TextView) info.targetView).getText().toString();
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.main, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return onOptionsItemSelected(item);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg3) {
country = adapterView.getItemAtPosition(position).toString();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
FragmentManager manager = getActivity().getSupportFragmentManager();
CountryInfoFragment fragment = (CountryInfoFragment) manager.findFragmentById(R.id.fragmentCountryInfo);
fragment.loadWebViewContent(country);
getActivity().invalidateOptionsMenu();
} else {
Intent intent = new Intent(getActivity().getApplicationContext(), CountryDetailActivity.class);
intent.putExtra(CountryDetailActivity.COUNTRY, country);
startActivity(intent);
}
}
}
| gpl-2.0 |
damirkusar/jvoicebridge | softphone/src/com/sun/mc/softphone/media/alsa/AlsaAudioServiceProvider.java | 2986 | /*
* Copyright 2007 Sun Microsystems, Inc.
*
* This file is part of jVoiceBridge.
*
* jVoiceBridge is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation and distributed hereunder
* to you.
*
* jVoiceBridge 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/>.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied this
* code.
*/
package com.sun.mc.softphone.media.alsa;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.prefs.Preferences;
import com.sun.voip.Logger;
import com.sun.mc.softphone.media.AudioServiceProvider;
import com.sun.mc.softphone.media.Microphone;
import com.sun.mc.softphone.media.NativeLibUtil;
import com.sun.mc.softphone.media.Speaker;
public class AlsaAudioServiceProvider implements AudioServiceProvider {
private static final String ALSA_I386_NAME = "libMediaFrameworkI386.so";
private static final String ALSA_AMD64_NAME = "libMediaFrameworkAmd64.so";
private static AudioDriver audioDriver;
private Microphone microphone;
private Speaker speaker;
public AlsaAudioServiceProvider() throws IOException {
audioDriver = new AudioDriverAlsa();
if (System.getProperty("os.arch").contains("amd64")) {
NativeLibUtil.loadLibrary(getClass(), ALSA_AMD64_NAME);
} else {
NativeLibUtil.loadLibrary(getClass(), ALSA_I386_NAME);
}
}
public void initialize(int speakerSampleRate, int speakerChannels,
int microphoneSampleRate, int microphoneChannels,
int microphoneBufferSize, int speakerBufferSize)
throws IOException {
shutdown(); // stop old driver if running
Logger.println("Initializing audio driver to " + speakerSampleRate
+ "/" + speakerChannels + " bufferSize " + speakerBufferSize);
synchronized (audioDriver) {
speaker = new SpeakerAlsaImpl(speakerSampleRate, speakerChannels,
speakerBufferSize, audioDriver);
microphone = new MicrophoneAlsaImpl(microphoneSampleRate,
microphoneChannels, microphoneBufferSize, audioDriver);
}
}
public void shutdown() {
synchronized (audioDriver) {
audioDriver.stop();
}
}
public Microphone getMicrophone() {
return microphone;
}
public String[] getMicrophoneList() {
return audioDriver.getAvailableOutputDevices();
}
public Speaker getSpeaker() {
return speaker;
}
public String[] getSpeakerList() {
return audioDriver.getAvailableInputDevices();
}
}
| gpl-2.0 |
lamsfoundation/lams | 3rdParty_sources/spring/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMap.java | 4502 | /*
* Copyright 2002-2017 the original author or authors.
*
* 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.springframework.web.servlet.mvc.support;
import java.util.Collection;
import java.util.Map;
import org.springframework.ui.ModelMap;
import org.springframework.validation.DataBinder;
/**
* A {@link ModelMap} implementation of {@link RedirectAttributes} that formats
* values as Strings using a {@link DataBinder}. Also provides a place to store
* flash attributes so they can survive a redirect without the need to be
* embedded in the redirect URL.
*
* @author Rossen Stoyanchev
* @since 3.1
*/
@SuppressWarnings("serial")
public class RedirectAttributesModelMap extends ModelMap implements RedirectAttributes {
private final DataBinder dataBinder;
private final ModelMap flashAttributes = new ModelMap();
/**
* Default constructor without a DataBinder.
* Attribute values are converted to String via {@link #toString()}.
*/
public RedirectAttributesModelMap() {
this(null);
}
/**
* Constructor with a DataBinder.
* @param dataBinder used to format attribute values as Strings
*/
public RedirectAttributesModelMap(DataBinder dataBinder) {
this.dataBinder = dataBinder;
}
/**
* Return the attributes candidate for flash storage or an empty Map.
*/
@Override
public Map<String, ?> getFlashAttributes() {
return this.flashAttributes;
}
/**
* {@inheritDoc}
* <p>Formats the attribute value as a String before adding it.
*/
@Override
public RedirectAttributesModelMap addAttribute(String attributeName, Object attributeValue) {
super.addAttribute(attributeName, formatValue(attributeValue));
return this;
}
private String formatValue(Object value) {
if (value == null) {
return null;
}
return (this.dataBinder != null ? this.dataBinder.convertIfNecessary(value, String.class) : value.toString());
}
/**
* {@inheritDoc}
* <p>Formats the attribute value as a String before adding it.
*/
@Override
public RedirectAttributesModelMap addAttribute(Object attributeValue) {
super.addAttribute(attributeValue);
return this;
}
/**
* {@inheritDoc}
* <p>Each attribute value is formatted as a String before being added.
*/
@Override
public RedirectAttributesModelMap addAllAttributes(Collection<?> attributeValues) {
super.addAllAttributes(attributeValues);
return this;
}
/**
* {@inheritDoc}
* <p>Each attribute value is formatted as a String before being added.
*/
@Override
public RedirectAttributesModelMap addAllAttributes(Map<String, ?> attributes) {
if (attributes != null) {
for (String key : attributes.keySet()) {
addAttribute(key, attributes.get(key));
}
}
return this;
}
/**
* {@inheritDoc}
* <p>Each attribute value is formatted as a String before being merged.
*/
@Override
public RedirectAttributesModelMap mergeAttributes(Map<String, ?> attributes) {
if (attributes != null) {
for (String key : attributes.keySet()) {
if (!containsKey(key)) {
addAttribute(key, attributes.get(key));
}
}
}
return this;
}
@Override
public Map<String, Object> asMap() {
return this;
}
/**
* {@inheritDoc}
* <p>The value is formatted as a String before being added.
*/
@Override
public Object put(String key, Object value) {
return super.put(key, formatValue(value));
}
/**
* {@inheritDoc}
* <p>Each value is formatted as a String before being added.
*/
@Override
public void putAll(Map<? extends String, ? extends Object> map) {
if (map != null) {
for (String key : map.keySet()) {
put(key, formatValue(map.get(key)));
}
}
}
@Override
public RedirectAttributes addFlashAttribute(String attributeName, Object attributeValue) {
this.flashAttributes.addAttribute(attributeName, attributeValue);
return this;
}
@Override
public RedirectAttributes addFlashAttribute(Object attributeValue) {
this.flashAttributes.addAttribute(attributeValue);
return this;
}
}
| gpl-2.0 |
alevincenzi/goos | src/auctionsniper/ui/Column.java | 904 | package auctionsniper.ui;
import auctionsniper.SniperSnapshot;
import auctionsniper.SniperState;
public enum Column {
ITEM_IDENTIFIER("Item") {
@Override
public Object
valueIn(SniperSnapshot snapshot) {
return snapshot.itemId;
}
},
LAST_PRICE("Last Price") {
@Override
public Object
valueIn(SniperSnapshot snapshot) {
return snapshot.lastPrice;
}
},
LAST_BID("Last Bid") {
@Override
public Object
valueIn(SniperSnapshot snapshot) {
return snapshot.lastBid;
}
},
SNIPER_STATE("State") {
@Override
public Object
valueIn(SniperSnapshot snapshot) {
return SniperState.textFor(snapshot.state);
}
};
abstract public Object valueIn(SniperSnapshot snapshot);
public final String name;
private
Column(String name) {
this.name = name;
}
public static Column
at(int offset) {
return values()[offset];
}
}
| gpl-2.0 |
Biodiscus/Corendon | src/nl/itopia/corendon/utils/Validation.java | 1228 | package nl.itopia.corendon.utils;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import nl.itopia.corendon.data.ChooseItem;
/**
*
* @author Wies Kueter
*/
public class Validation {
@FXML private TextField usernameInputfield, firstnameInputfield, lastnameInputfield, passwordInputfield, repeatpasswordInputfield, contactdetailsInputfield, notesInputfield;
@FXML private ChoiceBox<ChooseItem> roleDropdownmenu, airportDropdownmenu;
@FXML private Button addButton, cancelButton;
public static boolean minMax(String field, int min, int max) {
if(field.length() >= min && field.length() <= max) {
return true;
}
return false;
}
public static boolean min(String field, int min) {
return field.length() >= min;
}
public static boolean max(String field, int max) {
return field.length() <= max;
}
public static void errorMessage(TextField field, String message) {
field.setText("");
field.setPromptText(message);
field.getStyleClass().add("error_prompt");
}
}
| gpl-2.0 |
Matt529/SmashBrawlManager | src/us/matthewcrocco/smashbrawl/Config.java | 7267 | package us.matthewcrocco.smashbrawl;
import org.joda.time.DateTime;
import us.matthewcrocco.smashbrawl.gui.GuiUtils;
import us.matthewcrocco.smashbrawl.util.Console;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.Properties;
import javafx.scene.control.Alert;
import javafx.scene.control.TextInputDialog;
public class Config {
private static final Properties settings;
private static String apiKey;
private static String eventName;
private static String databaseServer;
private static long timeoutWait;
private static long dbUpdateTime;
static {
try {
// Loading Config
Path p = Paths.get(".", "config", Strings.SETTINGS_FILENAME_DATABASE);
if (!Files.exists(p))
throw new FileNotFoundException("[CONFIG] Failed to Locate " + Strings.SETTINGS_FILENAME_DATABASE + "!");
// Load Settings from Config File as Properties
settings = new Properties();
settings.load(Files.newInputStream(p));
apiKey = settings.getProperty(Strings.SETTINGS_KEY_APIKEY);
if (apiKey == null)
throw new IllegalStateException("An API Key Must be Provided!");
dbUpdateTime = determineUpdateTime(settings.getProperty(Strings.SETTINGS_KEY_UPDATE_FREQ, "NORMAL").trim());
timeoutWait = determineTimeout(settings.getProperty(Strings.SETTINGS_KEY_TIMEOUT, "10s").trim());
Console.debug("Update Frequency : " + dbUpdateTime);
Console.debug("Timeout Length : " + timeoutWait);
databaseServer = settings.getProperty(Strings.SETTINGS_KEY_SERVERHOST, "default").trim();
eventName = settings.getProperty(Strings.SETTINGS_KEY_COLLECTION, "request").trim();
} catch (IOException e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* Validates Data that was loaded in Initialization. Being called more than once
* causes nothing to occur. The validation is only ever done once in an instance.
*/
public static void load() {
eventName();
serverHost();
}
public static long updateTimeMillis() {
return dbUpdateTime;
}
public static long timeoutLengthMillis() {
return timeoutWait;
}
/**
* Retrieve Orchestrate API Key
*
* @return
*/
public static String apiKey() {
return apiKey;
}
/**
* Retrieve the Event Name (Name of Database Table)
*
* @return
*/
public static String eventName() {
if (eventName.isEmpty())
eventName = "request";
if (eventName.equalsIgnoreCase("auto") || eventName.equalsIgnoreCase("request")) {
DateTime time = DateTime.now();
String defEventName = String.format("EVENT_%s_%s_%s", time.getDayOfMonth(), time.getMonthOfYear(), time.getYearOfEra());
if (eventName.equalsIgnoreCase("auto")) {
eventName = defEventName;
} else if (eventName.equalsIgnoreCase("request")) {
while (true) {
TextInputDialog prompt = new TextInputDialog(defEventName);
prompt.initOwner(null);
prompt.setTitle("DB Name Request");
prompt.setContentText("Name of Event: ");
Optional<String> input = prompt.showAndWait();
eventName = input.orElse(defEventName);
if (eventName.trim().isEmpty()) {
Alert alert = GuiUtils.buildAlert(Alert.AlertType.ERROR, "Config Error: Invalid DB Name!", "Bad db.properties Value!", "Something must be entered for the Event Name!");
alert.initOwner(null);
alert.showAndWait();
} else
break;
}
}
Console.debug("Event Name set to " + eventName);
}
return eventName;
}
/**
* Retrieve the Orchestrate Server Hostname
*
* @return
*/
public static String serverHost() {
if (databaseServer.equalsIgnoreCase("default") || databaseServer.equalsIgnoreCase("east"))
databaseServer = Strings.SETTINGS_SERVERHOST_EAST;
else if (databaseServer.equalsIgnoreCase("west"))
databaseServer = Strings.SETTINGS_SERVERHOST_WEST;
return databaseServer;
}
private static long determineTimeout(String value) {
if (value.equalsIgnoreCase("never") || value.equalsIgnoreCase("-1"))
return Long.MAX_VALUE;
if (!Character.isDigit(value.charAt(0))) {
GuiUtils.buildAlert(Alert.AlertType.WARNING, "Config Error: Bad Timeout Value!", "Bad db.properties Value!", value + " is not a valid timeout config value! Defaulting to 10s").show();
Console.bigWarning("Invalid Timeout Value: " + value + " --- Defaulting to 10 second timeout");
return 10_000;
}
int i = 0;
while (Character.isDigit(value.charAt(i)))
i++;
long timeout = Long.parseLong(value.substring(0, i));
if (value.endsWith("ms") || value.endsWith("millis") || value.endsWith("milliseconds")) {
return timeout;
} else if (value.endsWith("s") || value.endsWith("seconds")) {
// seconds * millis per second = seconds * 1000
return timeout * 1000;
} else if (value.endsWith("m") || value.endsWith("min") || value.endsWith("mins") || value.endsWith("minutes")) {
// minutes * seconds per minutes * millis per second
// minutes * 60 * 1000 = minutes * 60,000
return timeout * 60_000;
} else if (value.endsWith("h") || value.endsWith("hr") || value.endsWith("hrs") || value.endsWith("hours")) {
// hours * minutes per hour * seconds per minutes * millis per second
// hours * 60 * 60 * 1000 = hours * 3,600,000
return timeout * 3_600_000;
}
GuiUtils.buildAlert(Alert.AlertType.WARNING, "Config Error: Bad Timeout Length!", "Bad db.properties Value!", "Invalid Timeout Length! Must be in ms, s, min or hr. Defaulting to 10s.").show();
Console.bigWarning("Bad Timeout Length! Must be ms, s, min or hr... defaulting to 10s");
return 10_000;
}
private static long determineUpdateTime(String updateFreq) {
switch (updateFreq.toUpperCase()) {
case "RARELY":
return 10_000;
case "NORMAL":
return 5_000;
case "OFTEN":
return 3_000;
case "ALWAYS":
return 2_000;
case "ASAP":
return 1_000;
default:
GuiUtils.buildAlert(Alert.AlertType.WARNING, "Config Error: Bad Update Frequency!", "Bad db.properties Value!", "Invalid Frequency Value! Defaulting to OFTEN");
Console.bigWarning("Bad Update Freqency! - " + updateFreq + "... Defaulting to OFTEN");
return 3_000;
}
}
}
| gpl-2.0 |
asiekierka/Statues | src/main/java/info/jbcs/minecraft/statues/TileEntityStatue.java | 3891 | /**
* TileEntity class of the statue
*/
package info.jbcs.minecraft.statues;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import pl.asie.lib.block.TileEntityInventory;
import java.util.Random;
public class TileEntityStatue extends TileEntityInventory {
private EntityPlayer clientPlayer;
public String skinName = "";
public StatueParameters pose = new StatueParameters();
public Block block = Blocks.stone;
public int meta = 0;
public int facing = 0;
boolean updated = true;
void randomize(Random rand){
}
@Override
public int getSizeInventory() {
return 6;
}
public EntityStatuePlayer getStatue(){
if(clientPlayer==null){
EntityStatuePlayer player=new EntityStatuePlayer(worldObj, skinName);
player.ticksExisted=10;
player.pose=pose;
player.applySkin(skinName, block, facing, meta);
clientPlayer=player;
for(int i = 0; i < 6; i++) {
this.onInventoryUpdate(i);
}
}
return (EntityStatuePlayer)clientPlayer;
}
@Override
public void readFromNBT(NBTTagCompound nbttagcompound) {
super.readFromNBT(nbttagcompound);
skinName = nbttagcompound.getString("skin");
pose.readFromNBT(nbttagcompound);
block=Block.getBlockById(nbttagcompound.getShort("blockId"));
if(block==null) block=Blocks.stone;
meta=nbttagcompound.getByte("meta");
facing=nbttagcompound.getByte("face");
updateModel();
}
@Override
public void writeToNBT(NBTTagCompound nbttagcompound) {
super.writeToNBT(nbttagcompound);
nbttagcompound.setString("skin", skinName);
pose.writeToNBT(nbttagcompound);
nbttagcompound.setShort("blockId",(short)Block.getIdFromBlock(block));
nbttagcompound.setByte("meta",(byte)meta);
nbttagcompound.setByte("face",(byte)facing);
}
@Override
public void openInventory() {
}
@Override
public void closeInventory() {
}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack) {
return true;
}
@Override
public Packet getDescriptionPacket() {
if ((worldObj.getBlockMetadata(xCoord, yCoord, zCoord) & 4) != 0)
return null;
NBTTagCompound tag = new NBTTagCompound();
writeToNBT(tag);
return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tag);
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) {
readFromNBT(pkt.func_148857_g());
if(worldObj.isRemote && Minecraft.getMinecraft().currentScreen instanceof GuiStatue){
GuiStatue gui=(GuiStatue) Minecraft.getMinecraft().currentScreen;
pose.itemLeftA=gui.ila;
pose.itemRightA=gui.ira;
}
}
@Override
public ItemStack getStackInSlotOnClosing(int i) {
return null;
}
public void updateModel() {
if(clientPlayer!=null && worldObj!=null && worldObj.isRemote){
((EntityStatuePlayer)clientPlayer).applySkin(skinName, block, facing, meta);
}
updated=false;
}
@Override
public void updateEntity(){
if(updated) return;
updated=true;
}
@Override
public boolean hasCustomInventoryName() {
return false;
}
@Override
public void onInventoryUpdate(int slot) {
if(clientPlayer != null) {
clientPlayer.inventory.mainInventory[0]=getStackInSlot(4);
clientPlayer.inventory.mainInventory[1]=getStackInSlot(5);
clientPlayer.inventory.armorInventory[0]=getStackInSlot(3);
clientPlayer.inventory.armorInventory[1]=getStackInSlot(2);
clientPlayer.inventory.armorInventory[2]=getStackInSlot(1);
clientPlayer.inventory.armorInventory[3]=getStackInSlot(0);
}
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}
| gpl-2.0 |
hexbinary/landing | src/main/java/oscar/oscarDemographic/data/DemographicRelationship.java | 7383 | /**
* Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* 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.
*
* This software was written for the
* Department of Family Medicine
* McMaster University
* Hamilton
* Ontario, Canada
*/
package oscar.oscarDemographic.data;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.oscarehr.common.dao.RelationshipsDao;
import org.oscarehr.common.model.Relationships;
import org.oscarehr.util.MiscUtils;
import org.oscarehr.util.SpringUtils;
import oscar.util.ConversionUtils;
/**
*
* @author Jay Gallagher
*/
public class DemographicRelationship {
public DemographicRelationship() {
}
/**
* @param facilityId can be null
*/
public void addDemographicRelationship(String demographic, String linkingDemographic, String relationship, boolean sdm, boolean emergency, String notes, String providerNo, Integer facilityId) {
Relationships relationships = new Relationships();
relationships.setFacilityId(facilityId);
relationships.setDemographicNo(ConversionUtils.fromIntString(demographic));
relationships.setRelationDemographicNo(ConversionUtils.fromIntString(linkingDemographic));
relationships.setRelation(relationship);
relationships.setSubDecisionMaker(ConversionUtils.toBoolString(sdm));
relationships.setEmergencyContact(ConversionUtils.toBoolString(emergency));
relationships.setNotes(notes);
relationships.setCreator(providerNo);
relationships.setCreationDate(new Date());
RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class);
dao.persist(relationships);
}
public void deleteDemographicRelationship(String id) {
RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class);
Relationships relationships = dao.find(ConversionUtils.fromIntString(id));
if (relationships == null) MiscUtils.getLogger().error("Unable to find demographic relationship to delete");
relationships.setDeleted(ConversionUtils.toBoolString(Boolean.TRUE));
dao.merge(relationships);
}
public ArrayList<Map<String, String>> getDemographicRelationships(String demographic) {
RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class);
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
List<Relationships> relationships = dao.findByDemographicNumber(ConversionUtils.fromIntString(demographic));
if (relationships.isEmpty()) {
MiscUtils.getLogger().warn("Unable to find demographic relationship for demographic " + demographic);
return list;
}
for (Relationships r : relationships) {
HashMap<String, String> h = new HashMap<String, String>();
h.put("id", r.getId().toString());
h.put("demographic_no", String.valueOf(r.getRelationDemographicNo()));
h.put("relation", r.getRelation());
h.put("sub_decision_maker", r.getSubDecisionMaker());
h.put("emergency_contact", r.getEmergencyContact());
h.put("notes", r.getNotes());
list.add(h);
}
return list;
}
public ArrayList<Map<String, String>> getDemographicRelationshipsByID(String id) {
RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class);
Relationships r = dao.findActive(ConversionUtils.fromIntString(id));
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
if (r == null) {
MiscUtils.getLogger().warn("Unable to find demographic relationship for ID " + id);
return list;
}
Map<String, String> h = new HashMap<String, String>();
h.put("demographic_no", ConversionUtils.toIntString(r.getDemographicNo()));
h.put("relation_demographic_no", ConversionUtils.toIntString(r.getRelationDemographicNo()));
h.put("relation", r.getRelation());
h.put("sub_decision_maker", r.getSubDecisionMaker());
h.put("emergency_contact", r.getEmergencyContact());
h.put("notes", r.getNotes());
list.add(h);
return list;
}
public String getSDM(String demographic) {
RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class);
List<Relationships> rs = dao.findActiveSubDecisionMaker(ConversionUtils.fromIntString(demographic));
String result = null;
for (Relationships r : rs)
result = ConversionUtils.toIntString(r.getRelationDemographicNo());
return result;
}
public List<Map<String, Object>> getDemographicRelationshipsWithNamePhone(String demographic_no) {
RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class);
List<Relationships> rs = dao.findActiveSubDecisionMaker(ConversionUtils.fromIntString(demographic_no));
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (Relationships r : rs) {
HashMap<String, Object> h = new HashMap<String, Object>();
String demo = ConversionUtils.toIntString(r.getRelationDemographicNo());
DemographicData dd = new DemographicData();
org.oscarehr.common.model.Demographic demographic = dd.getDemographic(demo);
h.put("lastName", demographic.getLastName());
h.put("firstName", demographic.getFirstName());
h.put("phone", demographic.getPhone());
h.put("demographicNo", demo);
h.put("relation", r.getRelation());
h.put("subDecisionMaker", ConversionUtils.fromBoolString(r.getSubDecisionMaker()));
h.put("emergencyContact", ConversionUtils.fromBoolString(r.getEmergencyContact()));
h.put("notes", r.getNotes());
h.put("age", demographic.getAge());
list.add(h);
}
return list;
}
public List<Map<String, Object>> getDemographicRelationshipsWithNamePhone(String demographic_no, Integer facilityId) {
RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class);
List<Relationships> rs = dao.findActiveByDemographicNumberAndFacility(ConversionUtils.fromIntString(demographic_no), facilityId);
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (Relationships r : rs) {
HashMap<String, Object> h = new HashMap<String, Object>();
String demo = ConversionUtils.toIntString(r.getRelationDemographicNo());
DemographicData dd = new DemographicData();
org.oscarehr.common.model.Demographic demographic = dd.getDemographic(demo);
h.put("lastName", demographic.getLastName());
h.put("firstName", demographic.getFirstName());
h.put("phone", demographic.getPhone());
h.put("demographicNo", demo);
h.put("relation", r.getRelation());
h.put("subDecisionMaker", ConversionUtils.fromBoolString(r.getSubDecisionMaker()));
h.put("emergencyContact", ConversionUtils.fromBoolString(r.getEmergencyContact()));
h.put("notes", r.getNotes());
h.put("age", demographic.getAge());
list.add(h);
}
return list;
}
}
| gpl-2.0 |
peterbartha/j2eecm | edu.bme.vik.iit.j2eecm.diagram/src/components/diagram/edit/parts/DataReleationshipEditPart.java | 3130 | package components.diagram.edit.parts;
import org.eclipse.draw2d.Connection;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ConnectionNodeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ITreeBranchEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.draw2d.ui.figures.PolylineConnectionEx;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.notation.View;
import components.diagram.edit.policies.DataReleationshipItemSemanticEditPolicy;
/**
* @generated
*/
public class DataReleationshipEditPart extends ConnectionNodeEditPart implements
ITreeBranchEditPart {
/**
* @generated
*/
public static final int VISUAL_ID = 4002;
/**
* @generated
*/
public DataReleationshipEditPart(View view) {
super(view);
}
/**
* @generated
*/
protected void createDefaultEditPolicies() {
super.createDefaultEditPolicies();
installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
new DataReleationshipItemSemanticEditPolicy());
}
/**
* @generated
*/
protected boolean addFixedChild(EditPart childEditPart) {
if (childEditPart instanceof DataReleationshipProtocolEditPart) {
((DataReleationshipProtocolEditPart) childEditPart)
.setLabel(getPrimaryShape()
.getFigureDataReleationshipProtocolFigure());
return true;
}
return false;
}
/**
* @generated
*/
protected void addChildVisual(EditPart childEditPart, int index) {
if (addFixedChild(childEditPart)) {
return;
}
super.addChildVisual(childEditPart, index);
}
/**
* @generated
*/
protected boolean removeFixedChild(EditPart childEditPart) {
if (childEditPart instanceof DataReleationshipProtocolEditPart) {
return true;
}
return false;
}
/**
* @generated
*/
protected void removeChildVisual(EditPart childEditPart) {
if (removeFixedChild(childEditPart)) {
return;
}
super.removeChildVisual(childEditPart);
}
/**
* Creates figure for this edit part.
*
* Body of this method does not depend on settings in generation model
* so you may safely remove <i>generated</i> tag and modify it.
*
* @generated
*/
protected Connection createConnectionFigure() {
return new DataReleationshipFigure();
}
/**
* @generated
*/
public DataReleationshipFigure getPrimaryShape() {
return (DataReleationshipFigure) getFigure();
}
/**
* @generated
*/
public class DataReleationshipFigure extends PolylineConnectionEx {
/**
* @generated
*/
private WrappingLabel fFigureDataReleationshipProtocolFigure;
/**
* @generated
*/
public DataReleationshipFigure() {
createContents();
}
/**
* @generated
*/
private void createContents() {
fFigureDataReleationshipProtocolFigure = new WrappingLabel();
fFigureDataReleationshipProtocolFigure.setText("<...>");
this.add(fFigureDataReleationshipProtocolFigure);
}
/**
* @generated
*/
public WrappingLabel getFigureDataReleationshipProtocolFigure() {
return fFigureDataReleationshipProtocolFigure;
}
}
}
| gpl-2.0 |
BiglySoftware/BiglyBT | uis/src/com/biglybt/ui/swt/views/tableitems/peers/ColumnPeerNetwork.java | 2088 | /*
* Copyright (C) Azureus Software, Inc, 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 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 ( see the LICENSE file ).
*
* 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.biglybt.ui.swt.views.tableitems.peers;
import com.biglybt.core.peer.impl.PEPeerTransport;
import com.biglybt.pif.ui.tables.TableCell;
import com.biglybt.pif.ui.tables.TableCellRefreshListener;
import com.biglybt.pif.ui.tables.TableColumnInfo;
import com.biglybt.ui.swt.views.table.CoreTableColumnSWT;
import com.biglybt.core.peermanager.peerdb.PeerItem;
public class ColumnPeerNetwork
extends CoreTableColumnSWT
implements TableCellRefreshListener
{
/** Default Constructor */
public ColumnPeerNetwork(String table_id) {
super("network", POSITION_INVISIBLE, 65, table_id);
setRefreshInterval(INTERVAL_INVALID_ONLY);
}
@Override
public void fillTableColumnInfo(TableColumnInfo info) {
info.addCategories(new String[] {
CAT_PROTOCOL,
CAT_CONNECTION,
});
}
@Override
public void refresh(TableCell cell) {
Object ds = cell.getDataSource();
String text = "";
Comparable val = null;
if (ds instanceof PEPeerTransport) {
PEPeerTransport peer = (PEPeerTransport) ds;
PeerItem identity = peer.getPeerItemIdentity();
if (identity != null) {
val = text = identity.getNetwork();
}
}
if( !cell.setSortValue( val ) && cell.isValid() ) {
return;
}
cell.setText( text );
}
}
| gpl-2.0 |
jaimedelgado/Xtext | src/org/soaplab/text_mining/kwic/KwicService.java | 2933 |
package org.soaplab.text_mining.kwic;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.9-b130926.1035
* Generated source version: 2.2
*
*/
@WebServiceClient(name = "kwicService", targetNamespace = "http://soaplab.org/text_mining/kwic", wsdlLocation = "http://ws04.iula.upf.edu/soaplab2-axis/typed/services/text_mining.kwic?wsdl")
public class KwicService
extends Service
{
private final static URL KWICSERVICE_WSDL_LOCATION;
private final static WebServiceException KWICSERVICE_EXCEPTION;
private final static QName KWICSERVICE_QNAME = new QName("http://soaplab.org/text_mining/kwic", "kwicService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://ws04.iula.upf.edu/soaplab2-axis/typed/services/text_mining.kwic?wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
KWICSERVICE_WSDL_LOCATION = url;
KWICSERVICE_EXCEPTION = e;
}
public KwicService() {
super(__getWsdlLocation(), KWICSERVICE_QNAME);
}
public KwicService(WebServiceFeature... features) {
super(__getWsdlLocation(), KWICSERVICE_QNAME, features);
}
public KwicService(URL wsdlLocation) {
super(wsdlLocation, KWICSERVICE_QNAME);
}
public KwicService(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, KWICSERVICE_QNAME, features);
}
public KwicService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public KwicService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns Kwic
*/
@WebEndpoint(name = "kwicPort")
public Kwic getKwicPort() {
return super.getPort(new QName("http://soaplab.org/text_mining/kwic", "kwicPort"), Kwic.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns Kwic
*/
@WebEndpoint(name = "kwicPort")
public Kwic getKwicPort(WebServiceFeature... features) {
return super.getPort(new QName("http://soaplab.org/text_mining/kwic", "kwicPort"), Kwic.class, features);
}
private static URL __getWsdlLocation() {
if (KWICSERVICE_EXCEPTION!= null) {
throw KWICSERVICE_EXCEPTION;
}
return KWICSERVICE_WSDL_LOCATION;
}
}
| gpl-2.0 |
Piasy/Graduate | src/GpsEvaluate/Android-client/Gps-Demo/app/src/main/java/com/example/piasy/startup/MyActivity.java | 7171 | package com.example.piasy.startup;
import com.example.piasy.startup.location.PaintBoardFragment;
import com.example.piasy.startup.sensors.LogBoardFragment;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class MyActivity extends FragmentActivity implements SensorEventListener, Controller {
private static final int MODE_NONE = 0;
private static final int MODE_SENSOR = 1;
private static final int MODE_LOCATION = 2;
private int mode = MODE_NONE;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mode = MODE_LOCATION;
switch (mode) {
case MODE_SENSOR:
measureSensors();
break;
case MODE_LOCATION:
measureLocation();
break;
default:
break;
}
mStarted = true;
}
PaintBoardFragment mPainter;
LocationManager mLocationManager;
LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
mPainter.updateLocation(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
private void measureLocation() {
mPainter = new PaintBoardFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mPainter, mPainter.getClass().getName()).commit();
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
}
LogBoardFragment mLogger;
SensorManager mSensorManager;
Sensor mAccelerometer, mGravity, mGyroscope, mLinearAcc;
private void measureSensors() {
mLogger = new LogBoardFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mLogger, mLogger.getClass().getName()).commit();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mGravity = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
mLinearAcc = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, mGravity, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, mLinearAcc, SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void onStart() {
super.onStart();
Log.d("xjltest", "MyActivity onStart");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("xjltest", "MyActivity onRestart");
}
@Override
protected void onResume() {
super.onResume();
Log.d("xjltest", "MyActivity onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.d("xjltest", "MyActivity onPause");
}
@Override
protected void onStop() {
super.onStop();
Log.d("xjltest", "MyActivity onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("xjltest", "MyActivity onDestroy");
if (mSensorManager != null) {
mSensorManager.unregisterListener(this);
}
if (mLocationManager != null) {
mLocationManager.removeUpdates(mLocationListener);
}
}
@Override
protected void onUserLeaveHint() {
super.onUserLeaveHint();
}
float [] mLastGravity = null;
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.equals(mAccelerometer)) {
mLogger.log("ACCELEROMETER: x = " + cutBit(event.values[0], 2) + " m/s^2, "
+ "y = " + cutBit(event.values[1], 2) + " m/s^2, "
+ "z = " + cutBit(event.values[2], 2) + " m/s^2.");
if (mLastGravity != null) {
mLogger.log("REAL: x = " + cutBit(event.values[0] - mLastGravity[0], 2) + " m/s^2, "
+ "y = " + cutBit(event.values[1] - mLastGravity[1], 2) + " m/s^2, "
+ "z = " + cutBit(event.values[2] - mLastGravity[2], 2) + " m/s^2.");
}
} else if (event.sensor.equals(mGravity)) {
mLogger.log("GRAVITY: x = " + cutBit(event.values[0], 2) + " m/s^2, "
+ "y = " + cutBit(event.values[1], 2) + " m/s^2, "
+ "z = " + cutBit(event.values[2], 2) + " m/s^2.");
mLastGravity = event.values;
} else if (event.sensor.equals(mLinearAcc)) {
mLogger.log("LINEAR_ACC: x = " + cutBit(event.values[0], 2) + " m/s^2, "
+ "y = " + cutBit(event.values[1], 2) + " m/s^2, "
+ "z = " + cutBit(event.values[2], 2) + " m/s^2.");
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private float cutBit(float num, int bit) {
return new BigDecimal(num).setScale(bit, RoundingMode.UP).floatValue();
}
boolean mStarted = false;
@Override
public void start() {
if (mStarted) {
return;
}
switch (mode) {
case MODE_SENSOR:
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, mGravity, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, mLinearAcc, SensorManager.SENSOR_DELAY_UI);
break;
case MODE_LOCATION:
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
break;
default:
break;
}
mStarted = true;
}
@Override
public void stop() {
if (!mStarted) {
return;
}
switch (mode) {
case MODE_SENSOR:
mSensorManager.unregisterListener(this);
break;
case MODE_LOCATION:
mLocationManager.removeUpdates(mLocationListener);
break;
default:
break;
}
mStarted = false;
}
}
| gpl-2.0 |
yyuu/libmysql-java | src/com/mysql/jdbc/ResultSetRow.java | 42740 | /*
Copyright 2007 MySQL AB, 2008 Sun Microsystems
All rights reserved. Use is subject to license terms.
The MySQL Connector/J is licensed under the terms of the GPL,
like most MySQL Connectors. There are special exceptions to the
terms and conditions of the GPL as it is applied to this software,
see the FLOSS License Exception available on mysql.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., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
package com.mysql.jdbc;
import java.io.InputStream;
import java.io.Reader;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Calendar;
import java.util.StringTokenizer;
import java.util.TimeZone;
/**
* Classes that implement this interface represent one row of data from the
* MySQL server that might be stored in different ways depending on whether the
* result set was streaming (so they wrap a reusable packet), or whether the
* result set was cached or via a server-side cursor (so they represent a
* byte[][]).
*
* Notice that <strong>no</strong> bounds checking is expected for implementors
* of this interface, it happens in ResultSetImpl.
*
* @version $Id: $
*/
public abstract class ResultSetRow {
protected ExceptionInterceptor exceptionInterceptor;
protected ResultSetRow(ExceptionInterceptor exceptionInterceptor) {
this.exceptionInterceptor = exceptionInterceptor;
}
/**
* The metadata of the fields of this result set.
*/
protected Field[] metadata;
/**
* Called during navigation to next row to close all open
* streams.
*/
public abstract void closeOpenStreams();
/**
* Returns data at the given index as an InputStream with no
* character conversion.
*
* @param columnIndex
* of the column value (starting at 0) to return.
* @return the value at the given index as an InputStream or null
* if null.
*
* @throws SQLException if an error occurs while retrieving the value.
*/
public abstract InputStream getBinaryInputStream(int columnIndex)
throws SQLException;
/**
* Returns the value at the given column (index starts at 0) "raw" (i.e.
* as-returned by the server).
*
* @param index
* of the column value (starting at 0) to return.
* @return the value for the given column (including NULL if it is)
* @throws SQLException
* if an error occurs while retrieving the value.
*/
public abstract byte[] getColumnValue(int index) throws SQLException;
protected final java.sql.Date getDateFast(int columnIndex,
byte[] dateAsBytes, int offset, int length, ConnectionImpl conn,
ResultSetImpl rs, Calendar targetCalendar) throws SQLException {
int year = 0;
int month = 0;
int day = 0;
try {
if (dateAsBytes == null) {
return null;
}
boolean allZeroDate = true;
boolean onlyTimePresent = false;
for (int i = 0; i < length; i++) {
if (dateAsBytes[offset + i] == ':') {
onlyTimePresent = true;
break;
}
}
for (int i = 0; i < length; i++) {
byte b = dateAsBytes[offset + i];
if (b == ' ' || b == '-' || b == '/') {
onlyTimePresent = false;
}
if (b != '0' && b != ' ' && b != ':' && b != '-' && b != '/'
&& b != '.') {
allZeroDate = false;
break;
}
}
if (!onlyTimePresent && allZeroDate) {
if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL
.equals(conn.getZeroDateTimeBehavior())) {
return null;
} else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION
.equals(conn.getZeroDateTimeBehavior())) {
throw SQLError.createSQLException("Value '"
+ new String(dateAsBytes)
+ "' can not be represented as java.sql.Date",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
}
// We're left with the case of 'round' to a date Java _can_
// represent, which is '0001-01-01'.
return rs.fastDateCreate(targetCalendar, 1, 1, 1);
} else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_TIMESTAMP) {
// Convert from TIMESTAMP
switch (length) {
case 29:
case 21:
case 19: { // java.sql.Timestamp format
year = StringUtils.getInt(dateAsBytes, offset + 0,
offset + 4);
month = StringUtils.getInt(dateAsBytes, offset + 5,
offset + 7);
day = StringUtils.getInt(dateAsBytes, offset + 8,
offset + 10);
return rs.fastDateCreate(targetCalendar, year, month, day);
}
case 14:
case 8: {
year = StringUtils.getInt(dateAsBytes, offset + 0,
offset + 4);
month = StringUtils.getInt(dateAsBytes, offset + 4,
offset + 6);
day = StringUtils.getInt(dateAsBytes, offset + 6,
offset + 8);
return rs.fastDateCreate(targetCalendar, year, month, day);
}
case 12:
case 10:
case 6: {
year = StringUtils.getInt(dateAsBytes, offset + 0,
offset + 2);
if (year <= 69) {
year = year + 100;
}
month = StringUtils.getInt(dateAsBytes, offset + 2,
offset + 4);
day = StringUtils.getInt(dateAsBytes, offset + 4,
offset + 6);
return rs.fastDateCreate(targetCalendar, year + 1900, month, day);
}
case 4: {
year = StringUtils.getInt(dateAsBytes, offset + 0,
offset + 4);
if (year <= 69) {
year = year + 100;
}
month = StringUtils.getInt(dateAsBytes, offset + 2,
offset + 4);
return rs.fastDateCreate(targetCalendar, year + 1900, month, 1);
}
case 2: {
year = StringUtils.getInt(dateAsBytes, offset + 0,
offset + 2);
if (year <= 69) {
year = year + 100;
}
return rs.fastDateCreate(targetCalendar, year + 1900, 1, 1);
}
default:
throw SQLError
.createSQLException(
Messages
.getString(
"ResultSet.Bad_format_for_Date",
new Object[] {
new String(
dateAsBytes),
Constants
.integerValueOf(columnIndex + 1) }),
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); //$NON-NLS-1$
} /* endswitch */
} else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR) {
if (length == 2 || length == 1) {
year = StringUtils.getInt(dateAsBytes, offset, offset
+ length);
if (year <= 69) {
year = year + 100;
}
year += 1900;
} else {
year = StringUtils.getInt(dateAsBytes, offset + 0,
offset + 4);
}
return rs.fastDateCreate(targetCalendar, year, 1, 1);
} else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_TIME) {
return rs.fastDateCreate(targetCalendar, 1970, 1, 1); // Return EPOCH
} else {
if (length < 10) {
if (length == 8) {
return rs.fastDateCreate(targetCalendar, 1970, 1, 1); // Return
// EPOCH for
// TIME
}
throw SQLError
.createSQLException(
Messages
.getString(
"ResultSet.Bad_format_for_Date",
new Object[] {
new String(
dateAsBytes),
Constants
.integerValueOf(columnIndex + 1) }),
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); //$NON-NLS-1$
}
if (length != 18) {
year = StringUtils.getInt(dateAsBytes, offset + 0,
offset + 4);
month = StringUtils.getInt(dateAsBytes, offset + 5,
offset + 7);
day = StringUtils.getInt(dateAsBytes, offset + 8,
offset + 10);
} else {
// JDK-1.3 timestamp format, not real easy to parse
// positionally :p
StringTokenizer st = new StringTokenizer(new String(
dateAsBytes, offset, length, "ISO8859_1"), "- ");
year = Integer.parseInt(st.nextToken());
month = Integer.parseInt(st.nextToken());
day = Integer.parseInt(st.nextToken());
}
}
return rs.fastDateCreate(targetCalendar, year, month, day);
} catch (SQLException sqlEx) {
throw sqlEx; // don't re-wrap
} catch (Exception e) {
SQLException sqlEx = SQLError.createSQLException(Messages.getString(
"ResultSet.Bad_format_for_Date", new Object[] {
new String(dateAsBytes),
Constants.integerValueOf(columnIndex + 1) }),
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); //$NON-NLS-1$
sqlEx.initCause(e);
throw sqlEx;
}
}
public abstract java.sql.Date getDateFast(int columnIndex,
ConnectionImpl conn, ResultSetImpl rs, Calendar targetCalendar) throws SQLException;
/**
* Returns the value at the given column (index starts at 0) as an int. *
*
* @param index
* of the column value (starting at 0) to return.
* @return the value for the given column (returns 0 if NULL, use isNull()
* to determine if the value was actually NULL)
* @throws SQLException
* if an error occurs while retrieving the value.
*/
public abstract int getInt(int columnIndex) throws SQLException;
/**
* Returns the value at the given column (index starts at 0) as a long. *
*
* @param index
* of the column value (starting at 0) to return.
* @return the value for the given column (returns 0 if NULL, use isNull()
* to determine if the value was actually NULL)
* @throws SQLException
* if an error occurs while retrieving the value.
*/
public abstract long getLong(int columnIndex) throws SQLException;
protected java.sql.Date getNativeDate(int columnIndex, byte[] bits,
int offset, int length, ConnectionImpl conn, ResultSetImpl rs, Calendar cal)
throws SQLException {
int year = 0;
int month = 0;
int day = 0;
if (length != 0) {
year = (bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8);
month = bits[offset + 2];
day = bits[offset + 3];
}
if (length == 0 || ((year == 0) && (month == 0) && (day == 0))) {
if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL
.equals(conn.getZeroDateTimeBehavior())) {
return null;
} else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION
.equals(conn.getZeroDateTimeBehavior())) {
throw SQLError
.createSQLException(
"Value '0000-00-00' can not be represented as java.sql.Date",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
}
year = 1;
month = 1;
day = 1;
}
if (!rs.useLegacyDatetimeCode) {
return TimeUtil.fastDateCreate(year, month, day, cal);
}
return rs.fastDateCreate(cal == null ? rs.getCalendarInstanceForSessionOrNew() : cal, year,
month, day);
}
public abstract Date getNativeDate(int columnIndex, ConnectionImpl conn,
ResultSetImpl rs, Calendar cal) throws SQLException;
protected Object getNativeDateTimeValue(int columnIndex, byte[] bits,
int offset, int length, Calendar targetCalendar, int jdbcType,
int mysqlType, TimeZone tz, boolean rollForward, ConnectionImpl conn,
ResultSetImpl rs) throws SQLException {
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int seconds = 0;
int nanos = 0;
if (bits == null) {
return null;
}
Calendar sessionCalendar = conn.getUseJDBCCompliantTimezoneShift() ? conn
.getUtcCalendar()
: rs.getCalendarInstanceForSessionOrNew();
boolean populatedFromDateTimeValue = false;
switch (mysqlType) {
case MysqlDefs.FIELD_TYPE_DATETIME:
case MysqlDefs.FIELD_TYPE_TIMESTAMP:
populatedFromDateTimeValue = true;
if (length != 0) {
year = (bits[offset + 0] & 0xff)
| ((bits[offset + 1] & 0xff) << 8);
month = bits[offset + 2];
day = bits[offset + 3];
if (length > 4) {
hour = bits[offset + 4];
minute = bits[offset + 5];
seconds = bits[offset + 6];
}
if (length > 7) {
// MySQL uses microseconds
nanos = ((bits[offset + 7] & 0xff)
| ((bits[offset + 8] & 0xff) << 8)
| ((bits[offset + 9] & 0xff) << 16) | ((bits[offset + 10] & 0xff) << 24)) * 1000;
}
}
break;
case MysqlDefs.FIELD_TYPE_DATE:
populatedFromDateTimeValue = true;
if (bits.length != 0) {
year = (bits[offset + 0] & 0xff)
| ((bits[offset + 1] & 0xff) << 8);
month = bits[offset + 2];
day = bits[offset + 3];
}
break;
case MysqlDefs.FIELD_TYPE_TIME:
populatedFromDateTimeValue = true;
if (bits.length != 0) {
// bits[0] // skip tm->neg
// binaryData.readLong(); // skip daysPart
hour = bits[offset + 5];
minute = bits[offset + 6];
seconds = bits[offset + 7];
}
year = 1970;
month = 1;
day = 1;
break;
default:
populatedFromDateTimeValue = false;
}
switch (jdbcType) {
case Types.TIME:
if (populatedFromDateTimeValue) {
if (!rs.useLegacyDatetimeCode) {
return TimeUtil.fastTimeCreate(hour, minute, seconds, targetCalendar, this.exceptionInterceptor);
}
Time time = TimeUtil.fastTimeCreate(rs
.getCalendarInstanceForSessionOrNew(), hour, minute,
seconds, this.exceptionInterceptor);
Time adjustedTime = TimeUtil.changeTimezone(conn,
sessionCalendar, targetCalendar, time, conn
.getServerTimezoneTZ(), tz, rollForward);
return adjustedTime;
}
return rs.getNativeTimeViaParseConversion(columnIndex + 1,
targetCalendar, tz, rollForward);
case Types.DATE:
if (populatedFromDateTimeValue) {
if ((year == 0) && (month == 0) && (day == 0)) {
if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL
.equals(conn.getZeroDateTimeBehavior())) {
return null;
} else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION
.equals(conn.getZeroDateTimeBehavior())) {
throw new SQLException(
"Value '0000-00-00' can not be represented as java.sql.Date",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
}
year = 1;
month = 1;
day = 1;
}
if (!rs.useLegacyDatetimeCode) {
return TimeUtil.fastDateCreate(year, month, day, targetCalendar);
}
return rs
.fastDateCreate(
rs.getCalendarInstanceForSessionOrNew(), year,
month, day);
}
return rs.getNativeDateViaParseConversion(columnIndex + 1);
case Types.TIMESTAMP:
if (populatedFromDateTimeValue) {
if ((year == 0) && (month == 0) && (day == 0)) {
if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL
.equals(conn.getZeroDateTimeBehavior())) {
return null;
} else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION
.equals(conn.getZeroDateTimeBehavior())) {
throw new SQLException(
"Value '0000-00-00' can not be represented as java.sql.Timestamp",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
}
year = 1;
month = 1;
day = 1;
}
if (!rs.useLegacyDatetimeCode) {
return TimeUtil.fastTimestampCreate(tz, year, month, day, hour, minute,
seconds, nanos);
}
Timestamp ts = rs.fastTimestampCreate(rs
.getCalendarInstanceForSessionOrNew(), year, month,
day, hour, minute, seconds, nanos);
Timestamp adjustedTs = TimeUtil.changeTimezone(conn,
sessionCalendar, targetCalendar, ts, conn
.getServerTimezoneTZ(), tz, rollForward);
return adjustedTs;
}
return rs.getNativeTimestampViaParseConversion(columnIndex + 1,
targetCalendar, tz, rollForward);
default:
throw new SQLException(
"Internal error - conversion method doesn't support this type",
SQLError.SQL_STATE_GENERAL_ERROR);
}
}
public abstract Object getNativeDateTimeValue(int columnIndex,
Calendar targetCalendar, int jdbcType, int mysqlType,
TimeZone tz, boolean rollForward, ConnectionImpl conn, ResultSetImpl rs)
throws SQLException;
protected double getNativeDouble(byte[] bits, int offset) {
long valueAsLong = (bits[offset + 0] & 0xff)
| ((long) (bits[offset + 1] & 0xff) << 8)
| ((long) (bits[offset + 2] & 0xff) << 16)
| ((long) (bits[offset + 3] & 0xff) << 24)
| ((long) (bits[offset + 4] & 0xff) << 32)
| ((long) (bits[offset + 5] & 0xff) << 40)
| ((long) (bits[offset + 6] & 0xff) << 48)
| ((long) (bits[offset + 7] & 0xff) << 56);
return Double.longBitsToDouble(valueAsLong);
}
public abstract double getNativeDouble(int columnIndex) throws SQLException;
protected float getNativeFloat(byte[] bits, int offset) {
int asInt = (bits[offset + 0] & 0xff)
| ((bits[offset + 1] & 0xff) << 8)
| ((bits[offset + 2] & 0xff) << 16)
| ((bits[offset + 3] & 0xff) << 24);
return Float.intBitsToFloat(asInt);
}
public abstract float getNativeFloat(int columnIndex) throws SQLException;
protected int getNativeInt(byte[] bits, int offset) {
int valueAsInt = (bits[offset + 0] & 0xff)
| ((bits[offset + 1] & 0xff) << 8)
| ((bits[offset + 2] & 0xff) << 16)
| ((bits[offset + 3] & 0xff) << 24);
return valueAsInt;
}
public abstract int getNativeInt(int columnIndex) throws SQLException;
protected long getNativeLong(byte[] bits, int offset) {
long valueAsLong = (bits[offset + 0] & 0xff)
| ((long) (bits[offset + 1] & 0xff) << 8)
| ((long) (bits[offset + 2] & 0xff) << 16)
| ((long) (bits[offset + 3] & 0xff) << 24)
| ((long) (bits[offset + 4] & 0xff) << 32)
| ((long) (bits[offset + 5] & 0xff) << 40)
| ((long) (bits[offset + 6] & 0xff) << 48)
| ((long) (bits[offset + 7] & 0xff) << 56);
return valueAsLong;
}
public abstract long getNativeLong(int columnIndex) throws SQLException;
protected short getNativeShort(byte[] bits, int offset) {
short asShort = (short) ((bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8));
return asShort;
}
public abstract short getNativeShort(int columnIndex) throws SQLException;
protected Time getNativeTime(int columnIndex, byte[] bits, int offset,
int length, Calendar targetCalendar, TimeZone tz,
boolean rollForward, ConnectionImpl conn, ResultSetImpl rs)
throws SQLException {
int hour = 0;
int minute = 0;
int seconds = 0;
if (length != 0) {
// bits[0] // skip tm->neg
// binaryData.readLong(); // skip daysPart
hour = bits[offset + 5];
minute = bits[offset + 6];
seconds = bits[offset + 7];
}
if (!rs.useLegacyDatetimeCode) {
return TimeUtil.fastTimeCreate(hour, minute, seconds, targetCalendar, this.exceptionInterceptor);
}
Calendar sessionCalendar = rs.getCalendarInstanceForSessionOrNew();
synchronized (sessionCalendar) {
Time time = TimeUtil.fastTimeCreate(sessionCalendar, hour, minute,
seconds, this.exceptionInterceptor);
Time adjustedTime = TimeUtil.changeTimezone(conn, sessionCalendar,
targetCalendar, time, conn.getServerTimezoneTZ(), tz,
rollForward);
return adjustedTime;
}
}
public abstract Time getNativeTime(int columnIndex,
Calendar targetCalendar, TimeZone tz, boolean rollForward,
ConnectionImpl conn, ResultSetImpl rs) throws SQLException;
protected Timestamp getNativeTimestamp(byte[] bits, int offset, int length,
Calendar targetCalendar, TimeZone tz, boolean rollForward,
ConnectionImpl conn, ResultSetImpl rs) throws SQLException {
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int seconds = 0;
int nanos = 0;
if (length != 0) {
year = (bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8);
month = bits[offset + 2];
day = bits[offset + 3];
if (length > 4) {
hour = bits[offset + 4];
minute = bits[offset + 5];
seconds = bits[offset + 6];
}
if (length > 7) {
// MySQL uses microseconds
nanos = ((bits[offset + 7] & 0xff)
| ((bits[offset + 8] & 0xff) << 8)
| ((bits[offset + 9] & 0xff) << 16) | ((bits[offset + 10] & 0xff) << 24)) * 1000;
}
}
if (length == 0 || ((year == 0) && (month == 0) && (day == 0))) {
if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL
.equals(conn.getZeroDateTimeBehavior())) {
return null;
} else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION
.equals(conn.getZeroDateTimeBehavior())) {
throw SQLError
.createSQLException(
"Value '0000-00-00' can not be represented as java.sql.Timestamp",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
}
year = 1;
month = 1;
day = 1;
}
if (!rs.useLegacyDatetimeCode) {
return TimeUtil.fastTimestampCreate(tz, year, month,
day, hour, minute, seconds, nanos);
}
Calendar sessionCalendar = conn.getUseJDBCCompliantTimezoneShift() ? conn
.getUtcCalendar()
: rs.getCalendarInstanceForSessionOrNew();
synchronized (sessionCalendar) {
Timestamp ts = rs.fastTimestampCreate(sessionCalendar, year, month,
day, hour, minute, seconds, nanos);
Timestamp adjustedTs = TimeUtil.changeTimezone(conn,
sessionCalendar, targetCalendar, ts, conn
.getServerTimezoneTZ(), tz, rollForward);
return adjustedTs;
}
}
public abstract Timestamp getNativeTimestamp(int columnIndex,
Calendar targetCalendar, TimeZone tz, boolean rollForward,
ConnectionImpl conn, ResultSetImpl rs) throws SQLException;
public abstract Reader getReader(int columnIndex) throws SQLException;
/**
* Returns the value at the given column (index starts at 0) as a
* java.lang.String with the requested encoding, using the given
* ConnectionImpl to find character converters.
*
* @param index
* of the column value (starting at 0) to return.
* @param encoding
* the Java name for the character encoding
* @param conn
* the connection that created this result set row
*
* @return the value for the given column (including NULL if it is) as a
* String
*
* @throws SQLException
* if an error occurs while retrieving the value.
*/
public abstract String getString(int index, String encoding,
ConnectionImpl conn) throws SQLException;
/**
* Convenience method for turning a byte[] into a string with the given
* encoding.
*
* @param encoding
* the Java encoding name for the byte[] -> char conversion
* @param conn
* the ConnectionImpl that created the result set
* @param value
* the String value as a series of bytes, encoded using
* "encoding"
* @param offset
* where to start the decoding
* @param length
* how many bytes to decode
*
* @return the String as decoded from bytes with the given encoding
*
* @throws SQLException
* if an error occurs
*/
protected String getString(String encoding, ConnectionImpl conn,
byte[] value, int offset, int length) throws SQLException {
String stringVal = null;
if ((conn != null) && conn.getUseUnicode()) {
try {
if (encoding == null) {
stringVal = new String(value);
} else {
SingleByteCharsetConverter converter = conn
.getCharsetConverter(encoding);
if (converter != null) {
stringVal = converter.toString(value, offset, length);
} else {
stringVal = new String(value, offset, length, encoding);
}
}
} catch (java.io.UnsupportedEncodingException E) {
throw SQLError
.createSQLException(
Messages
.getString("ResultSet.Unsupported_character_encoding____101") //$NON-NLS-1$
+ encoding + "'.", "0S100", this.exceptionInterceptor);
}
} else {
stringVal = StringUtils.toAsciiString(value, offset, length);
}
return stringVal;
}
protected Time getTimeFast(int columnIndex, byte[] timeAsBytes, int offset,
int length, Calendar targetCalendar, TimeZone tz,
boolean rollForward, ConnectionImpl conn, ResultSetImpl rs)
throws SQLException {
int hr = 0;
int min = 0;
int sec = 0;
try {
if (timeAsBytes == null) {
return null;
}
boolean allZeroTime = true;
boolean onlyTimePresent = false;
for (int i = 0; i < length; i++) {
if (timeAsBytes[offset + i] == ':') {
onlyTimePresent = true;
break;
}
}
for (int i = 0; i < length; i++) {
byte b = timeAsBytes[offset + i];
if (b == ' ' || b == '-' || b == '/') {
onlyTimePresent = false;
}
if (b != '0' && b != ' ' && b != ':' && b != '-' && b != '/'
&& b != '.') {
allZeroTime = false;
break;
}
}
if (!onlyTimePresent && allZeroTime) {
if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL
.equals(conn.getZeroDateTimeBehavior())) {
return null;
} else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION
.equals(conn.getZeroDateTimeBehavior())) {
throw SQLError.createSQLException("Value '"
+ new String(timeAsBytes)
+ "' can not be represented as java.sql.Time",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
}
// We're left with the case of 'round' to a time Java _can_
// represent, which is '00:00:00'
return rs.fastTimeCreate(targetCalendar, 0, 0, 0);
}
Field timeColField = this.metadata[columnIndex];
if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_TIMESTAMP) {
switch (length) {
case 19: { // YYYY-MM-DD hh:mm:ss
hr = StringUtils.getInt(timeAsBytes, offset + length - 8,
offset + length - 6);
min = StringUtils.getInt(timeAsBytes, offset + length - 5,
offset + length - 3);
sec = StringUtils.getInt(timeAsBytes, offset + length - 2,
offset + length);
}
break;
case 14:
case 12: {
hr = StringUtils.getInt(timeAsBytes, offset + length - 6,
offset + length - 4);
min = StringUtils.getInt(timeAsBytes, offset + length - 4,
offset + length - 2);
sec = StringUtils.getInt(timeAsBytes, offset + length - 2,
offset + length);
}
break;
case 10: {
hr = StringUtils
.getInt(timeAsBytes, offset + 6, offset + 8);
min = StringUtils.getInt(timeAsBytes, offset + 8,
offset + 10);
sec = 0;
}
break;
default:
throw SQLError
.createSQLException(
Messages
.getString("ResultSet.Timestamp_too_small_to_convert_to_Time_value_in_column__257") //$NON-NLS-1$
+ (columnIndex + 1)
+ "("
+ timeColField + ").",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
} /* endswitch */
SQLWarning precisionLost = new SQLWarning(
Messages
.getString("ResultSet.Precision_lost_converting_TIMESTAMP_to_Time_with_getTime()_on_column__261") //$NON-NLS-1$
+ columnIndex + "(" + timeColField + ").");
/*
* if (this.warningChain == null) { this.warningChain =
* precisionLost; } else {
* this.warningChain.setNextWarning(precisionLost); }
*/
} else if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_DATETIME) {
hr = StringUtils.getInt(timeAsBytes, offset + 11, offset + 13);
min = StringUtils.getInt(timeAsBytes, offset + 14, offset + 16);
sec = StringUtils.getInt(timeAsBytes, offset + 17, offset + 19);
SQLWarning precisionLost = new SQLWarning(
Messages
.getString("ResultSet.Precision_lost_converting_DATETIME_to_Time_with_getTime()_on_column__264") //$NON-NLS-1$
+ (columnIndex + 1) + "(" + timeColField + ").");
/*
* if (this.warningChain == null) { this.warningChain =
* precisionLost; } else {
* this.warningChain.setNextWarning(precisionLost); }
*/
} else if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_DATE) {
return rs.fastTimeCreate(null, 0, 0, 0); // midnight on the
// given
// date
} else {
// convert a String to a Time
if ((length != 5) && (length != 8)) {
throw SQLError.createSQLException(Messages
.getString("ResultSet.Bad_format_for_Time____267") //$NON-NLS-1$
+ new String(timeAsBytes)
+ Messages.getString("ResultSet.___in_column__268")
+ (columnIndex + 1),
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
}
hr = StringUtils.getInt(timeAsBytes, offset + 0, offset + 2);
min = StringUtils.getInt(timeAsBytes, offset + 3, offset + 5);
sec = (length == 5) ? 0 : StringUtils.getInt(timeAsBytes,
offset + 6, offset + 8);
}
Calendar sessionCalendar = rs.getCalendarInstanceForSessionOrNew();
if (!rs.useLegacyDatetimeCode) {
return rs.fastTimeCreate(targetCalendar, hr, min, sec);
}
synchronized (sessionCalendar) {
return TimeUtil.changeTimezone(conn, sessionCalendar,
targetCalendar, rs.fastTimeCreate(sessionCalendar, hr,
min, sec), conn.getServerTimezoneTZ(), tz,
rollForward);
}
} catch (Exception ex) {
SQLException sqlEx = SQLError.createSQLException(ex.toString(),
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
sqlEx.initCause(ex);
throw sqlEx;
}
}
public abstract Time getTimeFast(int columnIndex, Calendar targetCalendar,
TimeZone tz, boolean rollForward, ConnectionImpl conn,
ResultSetImpl rs) throws SQLException;
protected Timestamp getTimestampFast(int columnIndex,
byte[] timestampAsBytes, int offset, int length,
Calendar targetCalendar, TimeZone tz, boolean rollForward,
ConnectionImpl conn, ResultSetImpl rs) throws SQLException {
try {
Calendar sessionCalendar = conn.getUseJDBCCompliantTimezoneShift() ? conn
.getUtcCalendar()
: rs.getCalendarInstanceForSessionOrNew();
synchronized (sessionCalendar) {
boolean allZeroTimestamp = true;
boolean onlyTimePresent = false;
for (int i = 0; i < length; i++) {
if (timestampAsBytes[offset + i] == ':') {
onlyTimePresent = true;
break;
}
}
for (int i = 0; i < length; i++) {
byte b = timestampAsBytes[offset + i];
if (b == ' ' || b == '-' || b == '/') {
onlyTimePresent = false;
}
if (b != '0' && b != ' ' && b != ':' && b != '-'
&& b != '/' && b != '.') {
allZeroTimestamp = false;
break;
}
}
if (!onlyTimePresent && allZeroTimestamp) {
if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL
.equals(conn.getZeroDateTimeBehavior())) {
return null;
} else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION
.equals(conn.getZeroDateTimeBehavior())) {
throw SQLError
.createSQLException(
"Value '"
+ timestampAsBytes
+ "' can not be represented as java.sql.Timestamp",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
}
if (!rs.useLegacyDatetimeCode) {
return TimeUtil.fastTimestampCreate(tz, 1, 1, 1, 0, 0, 0, 0);
}
// We're left with the case of 'round' to a date Java _can_
// represent, which is '0001-01-01'.
return rs.fastTimestampCreate(null, 1, 1, 1, 0, 0, 0, 0);
} else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR) {
if (!rs.useLegacyDatetimeCode) {
return TimeUtil.fastTimestampCreate(tz, StringUtils
.getInt(timestampAsBytes, offset, 4), 1, 1, 0,
0, 0, 0);
}
return TimeUtil.changeTimezone(conn, sessionCalendar,
targetCalendar, rs.fastTimestampCreate(
sessionCalendar, StringUtils.getInt(
timestampAsBytes, offset, 4), 1, 1,
0, 0, 0, 0), conn.getServerTimezoneTZ(),
tz, rollForward);
} else {
if (timestampAsBytes[offset + length - 1] == '.') {
length--;
}
// Convert from TIMESTAMP or DATE
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minutes = 0;
int seconds = 0;
int nanos = 0;
switch (length) {
case 29:
case 26:
case 25:
case 24:
case 23:
case 22:
case 21:
case 20:
case 19: {
year = StringUtils.getInt(timestampAsBytes,
offset + 0, offset + 4);
month = StringUtils.getInt(timestampAsBytes,
offset + 5, offset + 7);
day = StringUtils.getInt(timestampAsBytes,
offset + 8, offset + 10);
hour = StringUtils.getInt(timestampAsBytes,
offset + 11, offset + 13);
minutes = StringUtils.getInt(timestampAsBytes,
offset + 14, offset + 16);
seconds = StringUtils.getInt(timestampAsBytes,
offset + 17, offset + 19);
nanos = 0;
if (length > 19) {
int decimalIndex = -1;
for (int i = 0; i < length; i++) {
if (timestampAsBytes[offset + i] == '.') {
decimalIndex = i;
}
}
if (decimalIndex != -1) {
if ((decimalIndex + 2) <= length) {
nanos = StringUtils.getInt(
timestampAsBytes, decimalIndex + 1,
offset + length);
int numDigits = (offset + length) - (decimalIndex + 1);
if (numDigits < 9) {
int factor = (int)(Math.pow(10, 9 - numDigits));
nanos = nanos * factor;
}
} else {
throw new IllegalArgumentException(); // re-thrown
// further
// down
// with
// a
// much better error message
}
}
}
break;
}
case 14: {
year = StringUtils.getInt(timestampAsBytes,
offset + 0, offset + 4);
month = StringUtils.getInt(timestampAsBytes,
offset + 4, offset + 6);
day = StringUtils.getInt(timestampAsBytes,
offset + 6, offset + 8);
hour = StringUtils.getInt(timestampAsBytes,
offset + 8, offset + 10);
minutes = StringUtils.getInt(timestampAsBytes,
offset + 10, offset + 12);
seconds = StringUtils.getInt(timestampAsBytes,
offset + 12, offset + 14);
break;
}
case 12: {
year = StringUtils.getInt(timestampAsBytes,
offset + 0, offset + 2);
if (year <= 69) {
year = (year + 100);
}
year += 1900;
month = StringUtils.getInt(timestampAsBytes,
offset + 2, offset + 4);
day = StringUtils.getInt(timestampAsBytes,
offset + 4, offset + 6);
hour = StringUtils.getInt(timestampAsBytes,
offset + 6, offset + 8);
minutes = StringUtils.getInt(timestampAsBytes,
offset + 8, offset + 10);
seconds = StringUtils.getInt(timestampAsBytes,
offset + 10, offset + 12);
break;
}
case 10: {
boolean hasDash = false;
for (int i = 0; i < length; i++) {
if (timestampAsBytes[offset + i] == '-') {
hasDash = true;
break;
}
}
if ((this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_DATE)
|| hasDash) {
year = StringUtils.getInt(timestampAsBytes,
offset + 0, offset + 4);
month = StringUtils.getInt(timestampAsBytes,
offset + 5, offset + 7);
day = StringUtils.getInt(timestampAsBytes,
offset + 8, offset + 10);
hour = 0;
minutes = 0;
} else {
year = StringUtils.getInt(timestampAsBytes,
offset + 0, offset + 2);
if (year <= 69) {
year = (year + 100);
}
month = StringUtils.getInt(timestampAsBytes,
offset + 2, offset + 4);
day = StringUtils.getInt(timestampAsBytes,
offset + 4, offset + 6);
hour = StringUtils.getInt(timestampAsBytes,
offset + 6, offset + 8);
minutes = StringUtils.getInt(timestampAsBytes,
offset + 8, offset + 10);
year += 1900; // two-digit year
}
break;
}
case 8: {
boolean hasColon = false;
for (int i = 0; i < length; i++) {
if (timestampAsBytes[offset + i] == ':') {
hasColon = true;
break;
}
}
if (hasColon) {
hour = StringUtils.getInt(timestampAsBytes,
offset + 0, offset + 2);
minutes = StringUtils.getInt(timestampAsBytes,
offset + 3, offset + 5);
seconds = StringUtils.getInt(timestampAsBytes,
offset + 6, offset + 8);
year = 1970;
month = 1;
day = 1;
break;
}
year = StringUtils.getInt(timestampAsBytes,
offset + 0, offset + 4);
month = StringUtils.getInt(timestampAsBytes,
offset + 4, offset + 6);
day = StringUtils.getInt(timestampAsBytes,
offset + 6, offset + 8);
year -= 1900;
month--;
break;
}
case 6: {
year = StringUtils.getInt(timestampAsBytes,
offset + 0, offset + 2);
if (year <= 69) {
year = (year + 100);
}
year += 1900;
month = StringUtils.getInt(timestampAsBytes,
offset + 2, offset + 4);
day = StringUtils.getInt(timestampAsBytes,
offset + 4, offset + 6);
break;
}
case 4: {
year = StringUtils.getInt(timestampAsBytes,
offset + 0, offset + 2);
if (year <= 69) {
year = (year + 100);
}
month = StringUtils.getInt(timestampAsBytes,
offset + 2, offset + 4);
day = 1;
break;
}
case 2: {
year = StringUtils.getInt(timestampAsBytes,
offset + 0, offset + 2);
if (year <= 69) {
year = (year + 100);
}
year += 1900;
month = 1;
day = 1;
break;
}
default:
throw new java.sql.SQLException(
"Bad format for Timestamp '"
+ new String(timestampAsBytes)
+ "' in column " + (columnIndex + 1)
+ ".",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
}
if (!rs.useLegacyDatetimeCode) {
return TimeUtil.fastTimestampCreate(tz,
year, month,
day, hour, minutes, seconds,
nanos);
}
return TimeUtil
.changeTimezone(conn, sessionCalendar,
targetCalendar, rs.fastTimestampCreate(
sessionCalendar, year, month,
day, hour, minutes, seconds,
nanos), conn
.getServerTimezoneTZ(), tz,
rollForward);
}
}
} catch (Exception e) {
SQLException sqlEx = SQLError.createSQLException("Cannot convert value '"
+ getString(columnIndex, "ISO8859_1", conn)
+ "' from column " + (columnIndex + 1) + " to TIMESTAMP.",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
sqlEx.initCause(e);
throw sqlEx;
}
}
public abstract Timestamp getTimestampFast(int columnIndex,
Calendar targetCalendar, TimeZone tz, boolean rollForward,
ConnectionImpl conn, ResultSetImpl rs) throws SQLException;
/**
* Could the column value at the given index (which starts at 0) be
* interpreted as a floating-point number (has +/-/E/e in it)?
*
* @param index
* of the column value (starting at 0) to check.
*
* @return true if the column value at the given index looks like it might
* be a floating-point number, false if not.
*
* @throws SQLException
* if an error occurs
*/
public abstract boolean isFloatingPointNumber(int index)
throws SQLException;
/**
* Is the column value at the given index (which starts at 0) NULL?
*
* @param index
* of the column value (starting at 0) to check.
*
* @return true if the column value is NULL, false if not.
*
* @throws SQLException
* if an error occurs
*/
public abstract boolean isNull(int index) throws SQLException;
/**
* Returns the length of the column at the given index (which starts at 0).
*
* @param index
* of the column value (starting at 0) for which to return the
* length.
* @return the length of the requested column, 0 if null (clients of this
* interface should use isNull() beforehand to determine status of
* NULL values in the column).
*
* @throws SQLException
*/
public abstract long length(int index) throws SQLException;
/**
* Sets the given column value (only works currently with
* ByteArrayRowHolder).
*
* @param index
* index of the column value (starting at 0) to set.
* @param value
* the (raw) value to set
*
* @throws SQLException
* if an error occurs, or the concrete RowHolder doesn't support
* this operation.
*/
public abstract void setColumnValue(int index, byte[] value)
throws SQLException;
public ResultSetRow setMetadata(Field[] f) throws SQLException {
this.metadata = f;
return this;
}
public abstract int getBytesSize();
}
| gpl-2.0 |
ur0/hermes | TMessagesProj/src/main/java/org/hermes/ui/Components/ProgressView.java | 1427 | /*
* This is the source code of Hermes for Android v. 1.3.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.hermes.ui.Components;
import android.graphics.Canvas;
import android.graphics.Paint;
import org.hermes.android.AndroidUtilities;
public class ProgressView {
private Paint innerPaint;
private Paint outerPaint;
public float currentProgress = 0;
public int width;
public int height;
public float progressHeight = AndroidUtilities.dp(2.0f);
public ProgressView() {
innerPaint = new Paint();
outerPaint = new Paint();
}
public void setProgressColors(int innerColor, int outerColor) {
innerPaint.setColor(innerColor);
outerPaint.setColor(outerColor);
}
public void setProgress(float progress) {
currentProgress = progress;
if (currentProgress < 0) {
currentProgress = 0;
} else if (currentProgress > 1) {
currentProgress = 1;
}
}
public void draw(Canvas canvas) {
canvas.drawRect(0, height / 2 - progressHeight / 2.0f, width, height / 2 + progressHeight / 2.0f, innerPaint);
canvas.drawRect(0, height / 2 - progressHeight / 2.0f, width * currentProgress, height / 2 + progressHeight / 2.0f, outerPaint);
}
}
| gpl-2.0 |
liTTleSiG/Algorithmique | src/s03/AmStramGram.java | 1360 | package s03;
public class AmStramGram {
public static void main(String[] args) {
int n=7, k=5;
if (args.length == 2) {
n = Integer.parseInt(args[0]);
k = Integer.parseInt(args[1]);
}
System.out.println("Winner is " + winnerAmStramGram(n, k));
}
// ----------------------------------------------------------
// "Josephus problem" with persons numbered 1..n
// Removes every k-th persons (ie skip k-1 persons)
// PRE: n>=1, k>=1
// RETURNS: the survivor
// Example: n=4, k=2:
// '1234 => 1'234 => 1'(2)34 => 1'34
// 1'34 => 13'4 => 13'(4) => 13'
// '13 => 1'3 => 1'(3) => 1' ===> survivor: 1
public static int winnerAmStramGram(int n, int k) {
List l = new List();
ListItr li = new ListItr(l);
for(int i=1;i<=n;i++)
{
li.insertAfter(i);
li.goToNext();
}
li.goToFirst();
int saveValue=0;
while(l.isEmpty()==false)
{
int i=k;
while(i>1)
{
li.goToNext();
if(li.isLast())
{
li.goToFirst();
}
i--;
}
li.removeAfter();
if(li.isLast())
{
li.goToFirst();
}
if (li.succ!=null)
saveValue=li.consultAfter();
}
return saveValue;
}
// ----------------------------------------------------------
}
| gpl-2.0 |
actiontech/dble | src/main/java/com/actiontech/dble/services/manager/response/ShowLoadDataErrorFile.java | 2876 | /*
* Copyright (C) 2016-2022 ActionTech.
* License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher.
*/
package com.actiontech.dble.services.manager.response;
import com.actiontech.dble.config.Fields;
import com.actiontech.dble.config.model.SystemConfig;
import com.actiontech.dble.net.mysql.*;
import com.actiontech.dble.services.manager.ManagerService;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import static com.actiontech.dble.backend.mysql.PacketUtil.getField;
import static com.actiontech.dble.backend.mysql.PacketUtil.getHeader;
public final class ShowLoadDataErrorFile {
private ShowLoadDataErrorFile() {
}
private static final int FIELD_COUNT = 1;
private static final ResultSetHeaderPacket HEADER = getHeader(FIELD_COUNT);
private static final FieldPacket[] FIELDS = new FieldPacket[FIELD_COUNT];
private static final EOFPacket EOF = new EOFPacket();
public static void execute(ManagerService service) {
int i = 0;
byte packetId = 0;
HEADER.setPacketId(++packetId);
FIELDS[i] = getField("error_load_data_file", Fields.FIELD_TYPE_VAR_STRING);
FIELDS[i].setPacketId(++packetId);
EOF.setPacketId(++packetId);
ByteBuffer buffer = service.allocate();
// write header
buffer = HEADER.write(buffer, service, true);
// write fields
for (FieldPacket field : FIELDS) {
buffer = field.write(buffer, service, true);
}
// write eof
buffer = EOF.write(buffer, service, true);
// write rows
String filePath = SystemConfig.getInstance().getHomePath() + File.separator + "temp" + File.separator + "error";
List<String> errorFileList = new ArrayList<>();
getErrorFile(filePath, errorFileList);
for (String errorFilePath : errorFileList) {
RowDataPacket row = new RowDataPacket(FIELD_COUNT);
row.add(errorFilePath.getBytes());
row.setPacketId(++packetId);
buffer = row.write(buffer, service, true);
}
// write last eof
EOFRowPacket lastEof = new EOFRowPacket();
lastEof.setPacketId(++packetId);
lastEof.write(buffer, service);
}
private static void getErrorFile(String filePath, List<String> errorFileList) {
File dirFile = new File(filePath);
if (!dirFile.exists()) {
return;
}
File[] fileList = dirFile.listFiles();
if (fileList != null) {
for (File file : fileList) {
if (file.isFile() && file.exists()) {
errorFileList.add(file.getPath());
} else if (file.isDirectory()) {
getErrorFile(file.getPath(), errorFileList);
}
}
}
}
}
| gpl-2.0 |
algoCraftDeveloperTeam/algosIII_tpFinal | src/fiuba/algo3/model/map/Earth.java | 864 | package fiuba.algo3.model.map;
import fiuba.algo3.model.exceptions.CannotOccupyTileException;
import fiuba.algo3.model.exceptions.NotEnoughRoomException;
import fiuba.algo3.model.occupant.Occupant;
import fiuba.algo3.model.occupant.units.TerranTransportVessel;
import fiuba.algo3.model.occupant.units.Unit;
public class Earth extends Tile{
public Earth(Coordinates coordinates){
super(coordinates);
info = "Earth. . ";
}
public void put(Occupant newOccupant) throws CannotOccupyTileException, NotEnoughRoomException {
if(occupied && occupant.canTransport()){
TerranTransportVessel occAsTransport = (TerranTransportVessel) occupant;
occAsTransport.addUnit((Unit) newOccupant);
}
else if (!occupied && newOccupant.canOccupyEarth()){
occupied = true;
occupant = newOccupant;
} else {
throw new CannotOccupyTileException();
}
}
} | gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest13497.java | 2294 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest13497")
public class BenchmarkTest13497 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getQueryString();
String bar = new Test().doSomething(param);
javax.xml.xpath.XPathFactory xpf = javax.xml.xpath.XPathFactory.newInstance();
javax.xml.xpath.XPath xp = xpf.newXPath();
try {
xp.compile(bar);
} catch (javax.xml.xpath.XPathExpressionException e) {
// OK to swallow
System.out.println("XPath expression exception caught and swallowed: " + e.getMessage());
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = new String( new sun.misc.BASE64Decoder().decodeBuffer(
new sun.misc.BASE64Encoder().encode( param.getBytes() ) ));
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
mahaotian/LeetCode | src/edu/neu/leetcode/array/BestTimeToBuyAndSellStockII.java | 630 | package edu.neu.leetcode.array;
public class BestTimeToBuyAndSellStockII {
public static int maxProfit(int[] prices) {
int res = 0, high = prices.length - 1;
for (int i = prices.length - 1; i > 0; i--) {
if (prices[i - 1] < prices[i]) {
if (i - 1 == 0) {
res += prices[high] - prices[i - 1];
break;
} else {
continue;
}
}
if (high > i) {
res += prices[high] - prices[i];
}
high = i - 1;
}
return res;
}
}
| gpl-2.0 |
WonderBeat/vasilich | alice-src/bitoflife/chatterbean/text/Sentence.java | 4272 | /*
Copyleft (C) 2005 Hio Perroni Filho
xperroni@yahoo.com
ICQ: 2490863
This file is part of ChatterBean.
ChatterBean 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.
ChatterBean 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 ChatterBean (look at the Documents/ directory); if not, either write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA, or visit (http://www.gnu.org/licenses/gpl.txt).
*/
package bitoflife.chatterbean.text;
import java.util.Arrays;
/**
*/
public class Sentence
{
/*
Attributes
*/
private String original;
private Integer[] mappings; // The index mappings of normalized elements to original elements.
private String normalized;
private String[] splitted; // The normalized entry, splitted in an array of words.
public static final Sentence ASTERISK = new Sentence(" * ", new Integer[] {0, 2}, " * ");
/*
Constructors
*/
public Sentence(String original, Integer[] mappings, String normalized)
{
setOriginal(original);
setMappings(mappings);
setNormalized(normalized);
}
/**
Constructs a Sentence out of a non-normalized input string.
*/
public Sentence(String original)
{
this(original, null, null);
}
/*
Methods
*/
public boolean equals(Object obj)
{
if (obj == null || !(obj instanceof Sentence)) return false;
Sentence compared = (Sentence) obj;
return (original.equals(compared.original) &&
Arrays.equals(mappings, compared.mappings) &&
normalized.equals(compared.normalized));
}
/**
Gets the number of individual words contained by the Sentence.
*/
public int length()
{
return splitted.length;
}
/**
Returns the normalized as an array of String words.
*/
public String[] normalized()
{
return splitted;
}
/**
Gets the (index)th word of the Sentence, in its normalized form.
*/
public String normalized(int index)
{
return splitted[index];
}
public String original(int beginIndex, int endIndex)
{
if (beginIndex < 0)
throw new ArrayIndexOutOfBoundsException(beginIndex);
while (beginIndex >= 0 && mappings[beginIndex] == null)
beginIndex--;
int n = mappings.length;
while (endIndex < n && mappings[endIndex] == null)
endIndex++;
if (endIndex >= n)
endIndex = n - 1;
String value = original.substring(mappings[beginIndex], mappings[endIndex] + 1);
value = value.replaceAll("^[^A-Za-z0-9]+|[^A-Za-z0-9]+$", " ");
return value;
}
/**
Returns a string representation of the Sentence. This is useful for printing the state of Sentence objects during tests.
@return A string formed of three bracket-separated sections: the original sentence string, the normalized-to-original word mapping array, and the normalized string.
*/
public String toString()
{
return "[" + original + "]" + Arrays.toString(mappings) + "[" + normalized + "]";
}
/**
Returns a trimmed version of the original Sentence string.
@return A trimmed version of the original Sentence string.
*/
public String trimOriginal()
{
return original.trim();
}
/*
Properties
*/
public Integer[] getMappings()
{
return mappings;
}
public void setMappings(Integer[] mappings)
{
this.mappings = mappings;
}
/**
Gets the Sentence in its normalized form.
*/
public String getNormalized()
{
return normalized;
}
public void setNormalized(String normalized)
{
this.normalized = normalized;
if (normalized != null)
splitted = normalized.trim().split(" ");
}
/**
Gets the Sentence, in its original, unformatted form.
*/
public String getOriginal()
{
return original;
}
public void setOriginal(String original)
{
this.original = original;
}
}
| gpl-2.0 |
Norkart/NK-VirtualGlobe | Xj3D/src/java/org/web3d/vrml/renderer/ogl/nodes/OGLAreaListener.java | 2694 | /*****************************************************************************
* Web3d.org Copyright (c) 2001
* Java Source
*
* This source is licensed under the GNU LGPL v2.1
* Please read http://www.gnu.org/copyleft/lgpl.html for more information
*
* This software comes with the standard NO WARRANTY disclaimer for any
* purpose. Use it at your own risk. If there's a problem you get to fix it.
*
****************************************************************************/
package org.web3d.vrml.renderer.ogl.nodes;
// External imports
import javax.vecmath.*;
// Local imports
import org.web3d.vrml.renderer.common.nodes.AreaListener;
/**
* The listener interface for receiving notice of the viewpoint on entry or
* exit from an area.
* <p>
* Each method receives both the user's current position and orientation in
* V-world coordinates but also the transform of the object that was picked
* and representing this interface. The idea of this is to save internal calls
* to getLocalToVWorld() and the extra capability bits required for this. The
* transform is available from the initial pick SceneGraphPath anyway, so this
* comes for free and leads to better performance. In addition, it saves
* needing to pass in a scene graph path for dealing with the
* getLocalToVWorld() case when we are under a SharedGroup.
*
* @author Alan Hudson, Justin Couch
* @version $Revision: 1.3 $
*/
public interface OGLAreaListener extends AreaListener {
/**
* Invoked when the user enters an area.
*
* @param position The new position of the user
* @param orientation The orientation of the user there
* @param localPosition The vworld transform object for the class
* that implemented this listener
*/
public void areaEntry(Point3f position,
Vector3f orientation,
Matrix4f vpMatrix,
Matrix4f localPosition);
/**
* Notification that the user is still in the area, but that the
* viewer reference point has changed.
*
* @param position The new position of the user
* @param orientation The orientation of the user there
* @param localPosition The vworld transform object for the class
* that implemented this listener
*/
public void userPositionChanged(Point3f position,
Vector3f orientation,
Matrix4f vpMatrix,
Matrix4f localPosition);
/**
* Invoked when the tracked object exits on area.
*/
public void areaExit();
}
| gpl-2.0 |
trombipeti/gerverbtester | src/verbtester/RootCheckBox.java | 1867 | package verbtester;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JCheckBox;
public class RootCheckBox extends JCheckBox {
public RootCheckBox(Action a) {
super(a);
init();
}
public RootCheckBox(Icon icon, boolean selected) {
super(icon, selected);
init();
}
public RootCheckBox(Icon icon) {
super(icon);
init();
}
public RootCheckBox(String text, boolean selected) {
super(text, selected);
init();
}
public RootCheckBox(String text, Icon icon, boolean selected) {
super(text, icon, selected);
init();
}
public RootCheckBox(String text, Icon icon) {
super(text, icon);
init();
}
public RootCheckBox(String text) {
super(text);
init();
}
private static final long serialVersionUID = 7420502854359388037L;
private List<SlaveCheckBox> slaves;
boolean stateChangedFromSlave;
public RootCheckBox() {
super();
init();
}
private void init() {
stateChangedFromSlave = false;
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(!stateChangedFromSlave && slaves != null) {
for(SlaveCheckBox s: slaves) {
s.changeStateFromRoot(isSelected());
}
}
}
});
}
public void setSlaves(SlaveCheckBox[] theSlaves) {
this.slaves = new ArrayList<SlaveCheckBox>();
for(SlaveCheckBox s: theSlaves) {
slaves.add(s);
}
}
public void addSlave(SlaveCheckBox s) {
slaves.add(s);
}
public void changeStateFromSlave(boolean isChecked) {
stateChangedFromSlave = true;
boolean allChecked = true;
for(JCheckBox s : slaves) {
if(!s.isSelected()) {
allChecked = false;
}
}
if(!allChecked) {
setSelected(false);
}
stateChangedFromSlave = false;
}
}
| gpl-2.0 |
arwheelock/chess | src/ai/TranspositionPlayer.java | 3005 | package ai;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;
public class TranspositionPlayer<M extends Move<N>, N extends Node<M, N>>
extends Player<M, N> {
private M bestFirstMove;
private int millis;
private TranspositionTable<M, N> table;
public TranspositionPlayer(int color, int millis) {
super(color);
this.millis = millis;
table = new TranspositionTable<>(1000000);
}
@Override
public M getMove(N node) {
return iterativeDeepening(node);
}
private M iterativeDeepening(N node) {
bestFirstMove = null;
int depth = 1;
long end = System.currentTimeMillis() + millis;
do {
negamax(node, depth++);
} while (System.currentTimeMillis() < end);
System.out.println("Transposition: " + depth);
return bestFirstMove;
}
private void negamax(N node, int depth) {
negamax(node, color, depth, Double.NEGATIVE_INFINITY,
Double.POSITIVE_INFINITY, true);
}
private double negamax(N node, int color, int depth, double alpha,
double beta, boolean isRoot) {
double alphaOrig = alpha;
TranspositionEntry<M> entry = table.get(node);
M bestMove = null;
if (entry != null && entry.getDepth() >= depth) {
switch (entry.getFlag()) {
case TranspositionEntry.EXACT:
return entry.getValue();
case TranspositionEntry.LOWER_BOUND:
alpha = Math.max(alpha, entry.getValue());
break;
case TranspositionEntry.UPPER_BOUND:
beta = Math.min(beta, entry.getValue());
break;
}
bestMove = entry.getBestMove();
}
if (depth == 0 || node.gameOver()) {
return color * node.getValue(color);
}
double bestValue = Double.NEGATIVE_INFINITY;
List<Pair<N, M>> pairs = getSortedMoves(node, color);
if (bestMove != null && bestMove.isLegal(node)) {
pairs.add(0, new Pair<>(node.apply(bestMove), bestMove));
}
for (Pair<N, M> pair : pairs) {
double val = -negamax(pair.getKey(), -color, depth - 1, -beta,
-alpha, false);
if (val > bestValue) {
bestValue = val;
bestMove = pair.getValue();
}
if (val > alpha) {
alpha = val;
if (isRoot) {
bestFirstMove = pair.getValue();
}
}
if (alpha >= beta) {
break;
}
}
int flag;
if (bestValue <= alphaOrig) {
flag = TranspositionEntry.UPPER_BOUND;
} else if (bestValue >= beta) {
flag = TranspositionEntry.LOWER_BOUND;
} else {
flag = TranspositionEntry.EXACT;
}
table.put(node, new TranspositionEntry<>(node.getZobristHash(),
bestMove, bestValue, depth, flag));
return bestValue;
}
private List<Pair<N, M>> getSortedMoves(N node, final int color) {
List<Pair<N, M>> pairs = new Vector<>();
for (M move : node.getLegalMoves()) {
pairs.add(new Pair<>(node.apply(move), move));
}
Collections.sort(pairs, new Comparator<Pair<N, M>>() {
@Override
public int compare(Pair<N, M> o1, Pair<N, M> o2) {
return color
* (o2.getKey().getEstimate() - o1.getKey()
.getEstimate());
}
});
return pairs;
}
}
| gpl-2.0 |
tingken/Evaluation-new | src/com/evaluation/service/HomeService.java | 4291 | package com.evaluation.service;
import com.evaluation.control.AccountManager;
import com.evaluation.dao.DatabaseAdapter;
import com.evaluation.util.TcpConnect;
import com.evaluation.view.*;
import android.os.BatteryManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class HomeService extends Service{
/**
*
*/
private static final String TAG = "effort";
private TcpConnect iTCPConnect = null;
//public DatabaseAdapter mDataAdapter;
private final IBinder mBinder = new LocalBinder();
public boolean serviceOver = false;
private int value;
// private TcpConnect iTCPConnect = null;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.e(TAG, "============>HomeService.onBind");
return mBinder;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public class LocalBinder extends Binder{
public HomeService getService(){
return HomeService.this;
}
}
public boolean onUnbind(Intent i){
Log.e(TAG, "===========>HomeService.onUnbind");
return false;
}
public void onRebind(Intent i){
Log.e(TAG, "===========>HomeService.onRebind");
}
public void onCreate(){
IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(homePressReceiver, homeFilter);
registerReceiver(homePressReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
iTCPConnect = new TcpConnect((MyApplication)this.getApplication());
iTCPConnect.start();
// Thread thread = new UnConnectThread();
// thread.start();
}
public int onStartCommand(Intent intent,int flags, int startId){
Log.e(TAG, "============>HomeService.onStartCommand");
//iTCPConnect = new TcpConnect(this);
//iTCPConnect.start();
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy(){
if (homePressReceiver != null) {
try {
unregisterReceiver(homePressReceiver);
} catch (Exception e) {
Log.e(TAG,
"unregisterReceiver homePressReceiver failure :"
+ e.getCause());
}
}
Log.e(TAG, "onStop");
serviceOver = true;
iTCPConnect.Close();
//Intent i = new Intent("RESTART_ACTIVITY");
//i.addFlags(Intent.flag);
//sendBroadcast(i);//传递过去
super.onDestroy();
}
private final BroadcastReceiver homePressReceiver = new BroadcastReceiver() {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
// if (reason != null
// && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
// // 自己随意控制程序,写自己想要的结果
// Log.i(TAG, "home_press");
// Intent i = new Intent("RESTART_ACTIVITY");
// sendBroadcast(i);//传递过去
// }
}
if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
Intent i = new Intent("TIMEOUT");
int status = intent.getIntExtra("status", 0);
switch (status) {
case BatteryManager.BATTERY_STATUS_UNKNOWN:
break;
case BatteryManager.BATTERY_STATUS_CHARGING:
break;
case BatteryManager.BATTERY_STATUS_DISCHARGING:
HomeService.this.sendBroadcast(i);
break;
case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
HomeService.this.sendBroadcast(i);
break;
case BatteryManager.BATTERY_STATUS_FULL:
break;
}
}
}
};
private class UnConnectThread extends Thread {
public void run() {
while(!serviceOver){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count = iTCPConnect.getCurrentLinkedSocketThreadNum();
Log.e(TAG, "定时检测socket连接数: " + count);
if(count < 1) {
Intent intent = new Intent("TIMEOUT");
HomeService.this.sendBroadcast(intent);
}
}
}
}
} | gpl-2.0 |
icybits/ts3-sq-api | de.icybits.ts3.sq.api/src/de/icybits/ts3/sq/api/commands/ServersnapshotcreateCommand.java | 401 | package de.icybits.ts3.sq.api.commands;
import de.icybits.ts3.sq.api.basic.Command;
import de.icybits.ts3.sq.api.interfaces.ITS3CommandNames;
/**
* create snapshot of a virtual server
*
* @author Alias: Iceac Sarutobi
*/
public class ServersnapshotcreateCommand extends Command
implements
ITS3CommandNames {
public ServersnapshotcreateCommand() {
super(COMMAND_SERVERSNAPSHOTCREATE);
}
} | gpl-2.0 |
emanoelopes/android | CaelumJS11/src/TestaReferencia.java | 287 |
public class TestaReferencia {
public static void main(String[] args) {
// TODO Auto-generated method stub
Conta c1 = new Conta();
c1.deposita(100);
Conta c2 = c1;
c2.deposita(200);
System.out.println(c1.saldo);
System.out.println(c2.saldo);
}
}
| gpl-2.0 |
bugcy013/opennms-tmp-tools | opennms-model/src/main/java/org/opennms/netmgt/model/MockServiceDaemonMBean.java | 1294 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.model;
public interface MockServiceDaemonMBean extends ServiceDaemonMBean {
}
| gpl-2.0 |
GoldenGnu/jeveassets | src/main/java/net/nikr/eve/jeveasset/i18n/BundleServiceFactory.java | 1439 | /*
* Copyright 2009-2022 Contributors (see credits.txt)
*
* This file is part of jEveAssets.
*
* jEveAssets 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.
*
* jEveAssets 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 jEveAssets; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package net.nikr.eve.jeveasset.i18n;
import java.util.Locale;
import uk.me.candle.translations.conf.DefaultBundleConfiguration;
import uk.me.candle.translations.service.BasicBundleService;
import uk.me.candle.translations.service.BundleService;
public class BundleServiceFactory {
private static BundleService bundleService;
public static BundleService getBundleService() {
//XXX - Workaround for default language
if (bundleService == null) {
bundleService = new BasicBundleService(new DefaultBundleConfiguration(), Locale.ENGLISH);
}
return bundleService;
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | mediatek/packages/apps/EngineerMode/src/com/mediatek/engineermode/hqanfc/PeerToPeerMode.java | 14964 | package com.mediatek.engineermode.hqanfc;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import com.mediatek.engineermode.Elog;
import com.mediatek.engineermode.R;
import com.mediatek.engineermode.hqanfc.NfcCommand.BitMapValue;
import com.mediatek.engineermode.hqanfc.NfcCommand.CommandType;
import com.mediatek.engineermode.hqanfc.NfcCommand.EmAction;
import com.mediatek.engineermode.hqanfc.NfcCommand.P2pDisableCardM;
import com.mediatek.engineermode.hqanfc.NfcCommand.RspResult;
import com.mediatek.engineermode.hqanfc.NfcEmReqRsp.NfcEmAlsP2pNtf;
import com.mediatek.engineermode.hqanfc.NfcEmReqRsp.NfcEmAlsP2pReq;
import com.mediatek.engineermode.hqanfc.NfcEmReqRsp.NfcEmAlsP2pRsp;
import java.nio.ByteBuffer;
public class PeerToPeerMode extends Activity {
protected static final String KEY_P2P_RSP_ARRAY = "p2p_rsp_array";
private static final int HANDLER_MSG_GET_RSP = 200;
private static final int HANDLER_MSG_GET_NTF = 201;
private static final int DIALOG_ID_RESULT = 0;
private static final int DIALOG_ID_WAIT = 1;
private static final int CHECKBOX_TYPEA = 0;
private static final int CHECKBOX_TYPEA_106 = 1;
private static final int CHECKBOX_TYPEA_212 = 2;
private static final int CHECKBOX_TYPEA_424 = 3;
private static final int CHECKBOX_TYPEA_848 = 4;
private static final int CHECKBOX_TYPEF = 5;
private static final int CHECKBOX_TYPEF_212 = 6;
private static final int CHECKBOX_TYPEF_424 = 7;
private static final int CHECKBOX_PASSIVE_MODE = 8;
private static final int CHECKBOX_ACTIVE_MODE = 9;
private static final int CHECKBOX_INITIATOR = 10;
private static final int CHECKBOX_TARGET = 11;
private static final int CHECKBOX_DISABLE_CARD = 12;
private static final int CHECKBOX_NUMBER = 13;
private CheckBox[] mSettingsCkBoxs = new CheckBox[CHECKBOX_NUMBER];
private Button mBtnSelectAll;
private Button mBtnClearAll;
private Button mBtnStart;
private Button mBtnReturn;
private Button mBtnRunInBack;
private NfcEmAlsP2pNtf mP2pNtf;
private NfcEmAlsP2pRsp mP2pRsp;
private byte[] mRspArray;
private String mNtfContent;
private boolean mEnableBackKey = true;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]mReceiver onReceive: " + action);
mRspArray = intent.getExtras().getByteArray(NfcCommand.MESSAGE_CONTENT_KEY);
if ((NfcCommand.ACTION_PRE + CommandType.MTK_NFC_EM_ALS_P2P_MODE_NTF).equals(action)) {
if (null != mRspArray) {
ByteBuffer buffer = ByteBuffer.wrap(mRspArray);
mP2pNtf = new NfcEmAlsP2pNtf();
mP2pNtf.readRaw(buffer);
mHandler.sendEmptyMessage(HANDLER_MSG_GET_NTF);
}
} else if ((NfcCommand.ACTION_PRE + CommandType.MTK_NFC_EM_ALS_P2P_MODE_RSP).equals(action)) {
if (null != mRspArray) {
ByteBuffer buffer = ByteBuffer.wrap(mRspArray);
mP2pRsp = new NfcEmAlsP2pRsp();
mP2pRsp.readRaw(buffer);
mHandler.sendEmptyMessage(HANDLER_MSG_GET_RSP);
}
} else {
Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]Other response");
}
}
};
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
String toastMsg = null;
if (HANDLER_MSG_GET_NTF == msg.what) {
switch (mP2pNtf.mResult) {
case RspResult.SUCCESS:
toastMsg = "P2P Data Exchange is terminated";
// mNtfContent = new String(mP2pNtf.mData);
// showDialog(DIALOG_ID_RESULT);
break;
case RspResult.FAIL:
toastMsg = "P2P Data Exchange is On-going";
break;
default:
toastMsg = "P2P Data Exchange is ERROR";
break;
}
} else if (HANDLER_MSG_GET_RSP == msg.what) {
dismissDialog(DIALOG_ID_WAIT);
switch (mP2pRsp.mResult) {
case RspResult.SUCCESS:
toastMsg = "P2P Mode Rsp Result: SUCCESS";
if (mBtnStart.getText().equals(PeerToPeerMode.this.getString(R.string.hqa_nfc_start))) {
setButtonsStatus(false);
} else {
setButtonsStatus(true);
}
break;
case RspResult.FAIL:
toastMsg = "P2P Mode Rsp Result: FAIL";
break;
default:
toastMsg = "P2P Mode Rsp Result: ERROR";
break;
}
}
Toast.makeText(PeerToPeerMode.this, toastMsg, Toast.LENGTH_SHORT).show();
}
};
private final CheckBox.OnCheckedChangeListener mCheckedListener = new CheckBox.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean checked) {
Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]onCheckedChanged view is " + buttonView.getText() + " value is "
+ checked);
if (buttonView.equals(mSettingsCkBoxs[CHECKBOX_TYPEA])) {
for (int i = CHECKBOX_TYPEA_106; i < CHECKBOX_TYPEF; i++) {
mSettingsCkBoxs[i].setChecked(checked);
}
} else if (buttonView.equals(mSettingsCkBoxs[CHECKBOX_TYPEF])) {
for (int i = CHECKBOX_TYPEF_212; i < CHECKBOX_PASSIVE_MODE; i++) {
mSettingsCkBoxs[i].setChecked(checked);
}
}
}
};
private final Button.OnClickListener mClickListener = new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]onClick button view is " + ((Button) arg0).getText());
if (arg0.equals(mBtnStart)) {
if (!checkRoleSelect()) {
Toast.makeText(PeerToPeerMode.this, R.string.hqa_nfc_p2p_role_tip, Toast.LENGTH_LONG).show();
} else {
showDialog(DIALOG_ID_WAIT);
doTestAction(mBtnStart.getText().equals(PeerToPeerMode.this.getString(R.string.hqa_nfc_start)));
}
} else if (arg0.equals(mBtnSelectAll)) {
changeAllSelect(true);
} else if (arg0.equals(mBtnClearAll)) {
changeAllSelect(false);
} else if (arg0.equals(mBtnReturn)) {
PeerToPeerMode.this.onBackPressed();
} else if (arg0.equals(mBtnRunInBack)) {
doTestAction(null);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hqa_nfc_p2p_mode);
initComponents();
changeAllSelect(true);
IntentFilter filter = new IntentFilter();
filter.addAction(NfcCommand.ACTION_PRE + CommandType.MTK_NFC_EM_ALS_P2P_MODE_RSP);
filter.addAction(NfcCommand.ACTION_PRE + CommandType.MTK_NFC_EM_ALS_P2P_MODE_NTF);
registerReceiver(mReceiver, filter);
}
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
@Override
public void onBackPressed() {
if (!mEnableBackKey) {
return;
}
super.onBackPressed();
}
private void initComponents() {
Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]initComponents");
mSettingsCkBoxs[CHECKBOX_TYPEA] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typea);
mSettingsCkBoxs[CHECKBOX_TYPEA].setOnCheckedChangeListener(mCheckedListener);
mSettingsCkBoxs[CHECKBOX_TYPEA_106] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typea_106);
mSettingsCkBoxs[CHECKBOX_TYPEA_212] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typea_212);
mSettingsCkBoxs[CHECKBOX_TYPEA_424] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typea_424);
mSettingsCkBoxs[CHECKBOX_TYPEA_848] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typea_848);
mSettingsCkBoxs[CHECKBOX_TYPEF] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typef);
mSettingsCkBoxs[CHECKBOX_TYPEF].setOnCheckedChangeListener(mCheckedListener);
mSettingsCkBoxs[CHECKBOX_TYPEF_212] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typef_212);
mSettingsCkBoxs[CHECKBOX_TYPEF_424] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typef_424);
mSettingsCkBoxs[CHECKBOX_PASSIVE_MODE] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_passive_mode);
mSettingsCkBoxs[CHECKBOX_ACTIVE_MODE] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_active_mode);
mSettingsCkBoxs[CHECKBOX_INITIATOR] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_initiator);
mSettingsCkBoxs[CHECKBOX_TARGET] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_target);
mSettingsCkBoxs[CHECKBOX_DISABLE_CARD] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_disable_card_emul);
mBtnSelectAll = (Button) findViewById(R.id.hqa_p2pmode_btn_select_all);
mBtnSelectAll.setOnClickListener(mClickListener);
mBtnClearAll = (Button) findViewById(R.id.hqa_p2pmode_btn_clear_all);
mBtnClearAll.setOnClickListener(mClickListener);
mBtnStart = (Button) findViewById(R.id.hqa_p2pmode_btn_start_stop);
mBtnStart.setOnClickListener(mClickListener);
mBtnReturn = (Button) findViewById(R.id.hqa_p2pmode_btn_return);
mBtnReturn.setOnClickListener(mClickListener);
mBtnRunInBack = (Button) findViewById(R.id.hqa_p2pmode_btn_run_back);
mBtnRunInBack.setOnClickListener(mClickListener);
mBtnRunInBack.setEnabled(false);
}
private void setButtonsStatus(boolean b) {
if (b) {
mBtnStart.setText(R.string.hqa_nfc_start);
} else {
mBtnStart.setText(R.string.hqa_nfc_stop);
}
mBtnRunInBack.setEnabled(!b);
mEnableBackKey = b;
mBtnReturn.setEnabled(b);
mBtnSelectAll.setEnabled(b);
mBtnClearAll.setEnabled(b);
}
private void changeAllSelect(boolean checked) {
Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]changeAllSelect status is " + checked);
for (int i = CHECKBOX_TYPEA; i < mSettingsCkBoxs.length; i++) {
mSettingsCkBoxs[i].setChecked(checked);
}
}
private void doTestAction(Boolean bStart) {
sendCommand(bStart);
}
private void sendCommand(Boolean bStart) {
NfcEmAlsP2pReq requestCmd = new NfcEmAlsP2pReq();
fillRequest(bStart, requestCmd);
NfcClient.getInstance().sendCommand(CommandType.MTK_NFC_EM_ALS_P2P_MODE_REQ, requestCmd);
}
private void fillRequest(Boolean bStart, NfcEmAlsP2pReq requestCmd) {
if (null == bStart) {
requestCmd.mAction = EmAction.ACTION_RUNINBG;
} else if (bStart.booleanValue()) {
requestCmd.mAction = EmAction.ACTION_START;
} else {
requestCmd.mAction = EmAction.ACTION_STOP;
}
int temp = 0;
temp |= mSettingsCkBoxs[CHECKBOX_TYPEA].isChecked() ? NfcCommand.EM_ALS_READER_M_TYPE_A : 0;
temp |= mSettingsCkBoxs[CHECKBOX_TYPEF].isChecked() ? NfcCommand.EM_ALS_READER_M_TYPE_F : 0;
requestCmd.mSupportType = temp;
CheckBox[] typeADateRateBoxs = { mSettingsCkBoxs[CHECKBOX_TYPEA_106], mSettingsCkBoxs[CHECKBOX_TYPEA_212],
mSettingsCkBoxs[CHECKBOX_TYPEA_424], mSettingsCkBoxs[CHECKBOX_TYPEA_848] };
requestCmd.mTypeADataRate = BitMapValue.getTypeAbDataRateValue(typeADateRateBoxs);
CheckBox[] typeFDateRateBoxs = { mSettingsCkBoxs[CHECKBOX_TYPEF_212], mSettingsCkBoxs[CHECKBOX_TYPEF_424] };
requestCmd.mTypeFDataRate = BitMapValue.getTypeFDataRateValue(typeFDateRateBoxs);
requestCmd.mIsDisableCardM = mSettingsCkBoxs[CHECKBOX_DISABLE_CARD].isChecked() ? P2pDisableCardM.DISABLE
: P2pDisableCardM.NOT_DISABLE;
temp = 0;
temp |= mSettingsCkBoxs[CHECKBOX_INITIATOR].isChecked() ? NfcCommand.EM_P2P_ROLE_INITIATOR_MODE : 0;
temp |= mSettingsCkBoxs[CHECKBOX_TARGET].isChecked() ? NfcCommand.EM_P2P_ROLE_TARGET_MODE : 0;
requestCmd.mRole = temp;
temp = 0;
temp |= mSettingsCkBoxs[CHECKBOX_PASSIVE_MODE].isChecked() ? NfcCommand.EM_P2P_MODE_PASSIVE_MODE : 0;
temp |= mSettingsCkBoxs[CHECKBOX_ACTIVE_MODE].isChecked() ? NfcCommand.EM_P2P_MODE_ACTIVE_MODE : 0;
requestCmd.mMode = temp;
}
@Override
protected Dialog onCreateDialog(int id) {
if (DIALOG_ID_WAIT == id) {
ProgressDialog dialog = null;
dialog = new ProgressDialog(this);
dialog.setMessage(getString(R.string.hqa_nfc_dialog_wait_message));
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
return dialog;
} else if (DIALOG_ID_RESULT == id) {
AlertDialog alertDialog = null;
alertDialog = new AlertDialog.Builder(PeerToPeerMode.this).setTitle(R.string.hqa_nfc_p2p_mode_ntf_title)
.setMessage(mNtfContent).setPositiveButton(android.R.string.ok, null).create();
return alertDialog;
}
return null;
}
private boolean checkRoleSelect() {
boolean result = true;
if (!mSettingsCkBoxs[CHECKBOX_INITIATOR].isChecked() && !mSettingsCkBoxs[CHECKBOX_TARGET].isChecked()) {
result = false;
}
if (!mSettingsCkBoxs[CHECKBOX_PASSIVE_MODE].isChecked() && !mSettingsCkBoxs[CHECKBOX_ACTIVE_MODE].isChecked()) {
result = false;
}
return result;
}
}
| gpl-2.0 |
MagiciansArtificeTeam/MEEP | src/com/meep/core/libs/configs/BiomeConfigHandler.java | 485 | package com.meep.core.libs.configs;
import net.minecraftforge.common.config.Configuration;
/**
* Created by poppypoppop on 22/12/2014.
*/
public class BiomeConfigHandler {
//Catagories
public static String general = "General";
public static String ids = "Biome IDs";
//Options
public static int oasisID;
public static void configOptions(Configuration config) {
oasisID = config.getInt("Oasis Biome ID", ids, 40, 40, 128, "Oasis Biome ID");
}
}
| gpl-2.0 |
classicwuhao/maxuse | src/gui/org/tzi/use/gui/views/diagrams/elements/DiamondNode.java | 8728 | /*
* USE - UML based specification environment
* Copyright (C) 1999-2004 Mark Richters, University of Bremen
*
* 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.
*/
// $Id: DiamondNode.java 5953 2016-05-11 14:00:02Z fhilken $
package org.tzi.use.gui.views.diagrams.elements;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.tzi.use.gui.util.PersistHelper;
import org.tzi.use.gui.views.diagrams.DiagramOptions;
import org.tzi.use.gui.views.diagrams.elements.edges.AssociationOrLinkPartEdge;
import org.tzi.use.gui.views.diagrams.elements.edges.EdgeBase;
import org.tzi.use.gui.views.diagrams.elements.positioning.StrategyFixed;
import org.tzi.use.gui.views.diagrams.elements.positioning.StrategyInBetween;
import org.tzi.use.gui.xmlparser.LayoutTags;
import org.tzi.use.uml.mm.MAssociation;
import org.tzi.use.uml.mm.MAssociationClass;
import org.tzi.use.uml.mm.MClass;
import org.tzi.use.uml.sys.MLink;
import org.tzi.use.uml.sys.MObject;
import org.w3c.dom.Element;
import com.ximpleware.AutoPilot;
import com.ximpleware.NavException;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
/**
* A pseude-node representing a diamond in an n-ary association.
*
* @version $ProjectVersion: 0.393 $
* @author Fabian Gutsche
*/
public class DiamondNode extends PlaceableNode {
private final DiagramOptions fOpt;
private final MAssociation fAssoc;
private MLink fLink;
private AssociationName fAssocName;
private final List<String> fConnectedNodes;
private final String fName;
private List<EdgeBase> fHalfEdges; // participating edges
public DiamondNode( MAssociation assoc, DiagramOptions opt ) {
fAssoc = assoc;
fName = assoc.name();
fOpt = opt;
fConnectedNodes = new ArrayList<String>();
Set<MClass> classes = fAssoc.associatedClasses();
for (MClass cls : classes) {
fConnectedNodes.add( cls.name() );
}
if (!(assoc instanceof MAssociationClass)) {
instanciateAssocName(false);
}
}
public DiamondNode( MLink link, DiagramOptions opt ) {
fAssoc = link.association();
fLink = link;
fName = fAssoc.name();
fOpt = opt;
fConnectedNodes = new ArrayList<String>();
List<MObject> objects = link.linkedObjects();
for (MObject obj : objects) {
fConnectedNodes.add( obj.name() );
}
if (!(fAssoc instanceof MAssociationClass)) {
instanciateAssocName(true);
}
}
private void instanciateAssocName(boolean isLink) {
fAssocName = new AssociationName( getId() + "::AssociationName", fName, fOpt, this, fAssoc, fLink );
}
public MAssociation association() {
return fAssoc;
}
public MLink link() {
return fLink;
}
@Override
public String getId() {
return fAssoc.name() + "::DiamondNode";
}
@Override
public String name() {
return fAssoc.name();
}
public void setHalfEdges( List<EdgeBase> edges, List<String> edgeIds) {
fHalfEdges = edges;
Set<PlaceableNode> related = new HashSet<PlaceableNode>();
for (int i = 0; i < edges.size(); ++i) {
EdgeBase e = edges.get(i);
related.add(e.target());
e.setIdSuffix("::" + edgeIds.get(i));
}
if (related.size() > 1)
this.setStrategy(new StrategyInBetween(this, related.toArray(new PlaceableNode[0]), 0, 0));
}
/**
* Draws a diamond with an underlined label in the object diagram.
*/
@Override
public void onDraw( Graphics2D g ) {
if ( isSelected() ) {
g.setColor( fOpt.getNODE_SELECTED_COLOR() );
} else {
g.setColor( fOpt.getDIAMONDNODE_COLOR() );
}
Shape ourShape = getShape();
g.fill( ourShape );
g.setColor( fOpt.getDIAMONDNODE_FRAME_COLOR() );
g.draw( ourShape );
if ( isSelected() ) {
g.setColor( fOpt.getEDGE_SELECTED_COLOR() );
} else {
g.setColor( fOpt.getEDGE_LABEL_COLOR() );
}
if ( fAssocName != null && fOpt.isShowAssocNames() ) {
g.setColor( fOpt.getEDGE_LABEL_COLOR() );
fAssocName.draw( g );
}
g.setColor( fOpt.getDIAMONDNODE_COLOR() );
}
@Override
public Shape getShape() {
Path2D.Double path = new Path2D.Double();
Rectangle2D bounds = getBounds();
path.moveTo(bounds.getX(), bounds.getCenterY());
path.lineTo(bounds.getCenterX(), bounds.getMinY());
path.lineTo(bounds.getMaxX(), bounds.getCenterY());
path.lineTo(bounds.getCenterX(), bounds.getMaxY());
path.closePath();
return path;
}
@Override
public void setDraggedPosition(double deltaX, double deltaY) {
// The first dragging of a diamond node switches its
// positioning strategy to "fixed".
if (this.getStrategy() instanceof StrategyInBetween)
this.setStrategy(StrategyFixed.instance);
super.setDraggedPosition(deltaX, deltaY);
}
public void resetPositionStrategy(){
Set<PlaceableNode> related = new HashSet<PlaceableNode>();
for (EdgeBase edgeBase : fHalfEdges) {
related.add(edgeBase.target());
}
if(related.size() > 1){
this.setStrategy(new StrategyInBetween(this, related.toArray(new PlaceableNode[0]), 0, 0));
}
}
@Override
public PlaceableNode getRelatedNode(double x, double y) {
if (fAssocName != null && fAssocName.occupies(x, y))
return fAssocName;
return super.getRelatedNode(x, y);
}
@Override
public void doCalculateSize( Graphics2D g ) {
setExactWidth(40);
setExactHeight(20);
if (fAssocName != null) fAssocName.calculateSize(g);
}
@Override
public String getStoreType() {
return "DiamondNode";
}
@Override
public String getStoreKind() {
return (fLink != null ? "link" : "association");
}
@Override
public void storeAdditionalInfo( PersistHelper helper, Element nodeElement, boolean hidden ) {
for(String nodeName : fConnectedNodes ) {
helper.appendChild( nodeElement, LayoutTags.CON_NODE, nodeName);
}
if (fAssocName != null) {
fAssocName.storePlacementInfo( helper, nodeElement, hidden );
}
if ( fHalfEdges != null ) {
for (EdgeBase e : fHalfEdges) {
e.storePlacementInfo( helper, nodeElement, hidden);
}
}
}
@Override
public void restoreAdditionalInfo( PersistHelper helper, int version ) {
// Restore association name
if (fAssocName != null) {
helper.toFirstChild(LayoutTags.EDGEPROPERTY);
fAssocName.restorePlacementInfo(helper, version);
helper.toParent();
}
if ( fHalfEdges != null ) {
for (EdgeBase e : fHalfEdges) {
if (e instanceof AssociationOrLinkPartEdge) {
AssociationOrLinkPartEdge partEdge = (AssociationOrLinkPartEdge)e;
String xpathExpr = "./edge[@type='" + LayoutTags.HALFEDGE + "' and name='" + partEdge.getName() + "']";
helper.getNav().push();
AutoPilot ap = new AutoPilot(helper.getNav());
try {
ap.selectXPath(xpathExpr);
try {
if (ap.evalXPath() != -1)
e.restorePlacementInfo(helper, version);
} catch (XPathEvalException ex) {
helper.getLog().append(ex.getMessage());
} catch (NavException ex) {
helper.getLog().append(ex.getMessage());
}
} catch (XPathParseException ex) {
helper.getLog().append(ex.getMessage());
} finally {
helper.getNav().pop();
}
}
}
}
}
} | gpl-2.0 |
rex-xxx/mt6572_x201 | mediatek/frameworks-ext/base/core/java/android/os/MessageLogger.java | 10671 | package android.os;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.util.Printer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Date;
import java.text.SimpleDateFormat;
/**
* @hide
*/
public class MessageLogger implements Printer {
private static final String TAG = "MessageLogger";
private static boolean mEnableLooperLog;
private static LinkedList mMessageHistoryRecord = new LinkedList();
private static LinkedList mLongTimeMessageHistoryRecord = new LinkedList();
private static LinkedList mMessageTimeRecord = new LinkedList();
private static LinkedList mNonSleepMessageTimeRecord = new LinkedList();
private static LinkedList mNonSleepLongTimeRecord = new LinkedList();
private static LinkedList mElapsedLongTimeRecord = new LinkedList();
final static int MESSAGE_SIZE = 20 * 2;// One for dispatching, one for
// finished
final static int LONGER_TIME_MESSAGE_SIZE = 40 * 2;// One for dispatching, one for
// finished
final static int LONGER_TIME = 200; //ms
final static int FLUSHOUT_SIZE = 1024*2; //ms
private static String mLastRecord = null;
private static long mLastRecordKernelTime; //Unir: Milli
private static long mNonSleepLastRecordKernelTime; //Unit: Milli
private static long mLastRecordDateTime; //Unir: Micro
private static int mState = 0;
private static long mMsgCnt = 0;
private static String messageInfo = "";
public MessageLogger() {
}
public long wallStart; //Unit:Micro
public long wallTime; //Unit:Micro
public long nonSleepWallStart; //Unit:Milli
public long nonSleepWallTime; //Unit:Milli
public static void addTimeToList(LinkedList mList, long startTime, long durationTime) {
mList.add(startTime);
mList.add(durationTime);
return;
}
public void println(String s) {
synchronized (mMessageHistoryRecord) {
mState++;
int size = mMessageHistoryRecord.size();
if (size > MESSAGE_SIZE) {
mMessageHistoryRecord.removeFirst();
mMessageTimeRecord.removeFirst();
mNonSleepMessageTimeRecord.removeFirst();
}
s = "Msg#:" + mMsgCnt + " " + s;
mMsgCnt++;
mMessageHistoryRecord.add(s);
mLastRecordKernelTime = SystemClock.elapsedRealtime();
mNonSleepLastRecordKernelTime = SystemClock.uptimeMillis();
mLastRecordDateTime = SystemClock.currentTimeMicro();
if( mState%2 == 0) {
mState = 0;
wallTime = SystemClock.currentTimeMicro() - wallStart;
nonSleepWallTime = SystemClock.uptimeMillis() - nonSleepWallStart;
addTimeToList(mMessageTimeRecord, wallStart, wallTime);
addTimeToList(mNonSleepMessageTimeRecord, nonSleepWallStart, nonSleepWallTime);
if(nonSleepWallTime >= LONGER_TIME) {
if(mLongTimeMessageHistoryRecord.size() >= LONGER_TIME_MESSAGE_SIZE)
{
mLongTimeMessageHistoryRecord.removeFirst();
for(int i = 0; i < 2 ;i++)
{
mNonSleepLongTimeRecord.removeFirst();
mElapsedLongTimeRecord.removeFirst();
}
}
mLongTimeMessageHistoryRecord.add(s);
addTimeToList(mNonSleepLongTimeRecord,wallStart,nonSleepWallTime);
addTimeToList(mElapsedLongTimeRecord,wallStart,wallTime);
}
} else {
wallStart = SystemClock.currentTimeMicro();
nonSleepWallStart = SystemClock.uptimeMillis();
/*
Test Longer History Code.
*/
/*
if(mMsgCnt%3 == 0 && nonSleepWallStart > 2*LONGER_TIME) {
nonSleepWallStart -= 2*LONGER_TIME;
}
*/
/*
Test Longer History Code
================================.
*/
}
if (mEnableLooperLog) {
if (s.contains(">")) {
Log.d(TAG,"Debugging_MessageLogger: " + s + " start");
} else {
Log.d(TAG,"Debugging_MessageLogger: " + s + " spent " + wallTime / 1000 + "ms");
}
}
}
}
private static int sizeToIndex( int size) {
return --size;
}
private static void flushedOrNot(StringBuilder sb, boolean bl ) {
if(sb.length() > FLUSHOUT_SIZE && !bl) {
//Log.d(TAG, "After Flushed, Current Size Is:" + sb.length() + ",bool" + bl);
sb.append("***Flushing, Current Size Is:" + sb.length() + ",bool" + bl +"***TAIL\n");
bl = true;
/// M: Add message history/queue to _exp_main.txt
messageInfo = messageInfo + sb.toString();
Log.d(TAG, sb.toString());
//Why New the one, not Clear the one? -> http://stackoverflow.com/questions/5192512/how-to-clear-empty-java-stringbuilder
//Performance is better for new object allocation.
//sb = new StringBuilder(1024);
sb.delete(0,sb.length());
}
else if(bl) {
bl = false;
}
/*
Test Longer History Code.
*/
/*
sb.append("***Current Size Is:" + sb.length() + "***\n");
*/
/*
Test Longer History Code.
================
*/
}
/*
Test Longer History Code.
*/
/*
private static int DumpRound = 0;
*/
/*
Test Longer History Code.
================
*/
public static String dump() {
synchronized (mMessageHistoryRecord) {
StringBuilder history = new StringBuilder(1024);
/*
Test Longer History Code.
*/
/*
history.append("=== DumpRound:" + DumpRound + " ===\n");
DumpRound++;
*/
/*
Test Longer History Code.
================
*/
history.append("MSG HISTORY IN MAIN THREAD:\n");
history.append("Current kernel time : " + SystemClock.elapsedRealtime() + "ms\n");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
//State = 1 means the current dispatching message has not been finished
int sizeForMsgRecord = mMessageHistoryRecord == null ? 0 : mMessageHistoryRecord.size();
if (mState == 1) {
Date date = new Date((long)mLastRecordDateTime/1000);
long spent = SystemClock.elapsedRealtime() - mLastRecordKernelTime;
long nonSleepSpent = SystemClock.uptimeMillis()- mNonSleepLastRecordKernelTime;
history.append("Last record : " + mMessageHistoryRecord.getLast());
history.append("\n");
history.append("Last record dispatching elapsedTime:" + spent + " ms/upTime:"+ nonSleepSpent +" ms\n");
history.append("Last record dispatching time : " + simpleDateFormat.format(date));
history.append("\n");
sizeForMsgRecord --;
}
String msg = null;
Long time = null;
Long nonSleepTime = null;
StringBuilder longerHistory = new StringBuilder(1024);
boolean flushed = false;
for (;sizeForMsgRecord > 0; sizeForMsgRecord--) {
msg = (String)mMessageHistoryRecord.get(sizeToIndex(sizeForMsgRecord));
time = (Long)mMessageTimeRecord.get(sizeToIndex(sizeForMsgRecord));
nonSleepTime = (Long)mNonSleepMessageTimeRecord.get(sizeToIndex(sizeForMsgRecord));
if (msg.contains(">")) {
Date date = new Date((long)time.longValue()/1000);
history.append(msg + " from " + simpleDateFormat.format(date));
history.append("\n");
} else {
history.append(msg + " elapsedTime:" + time/1000 + " ms/upTime:" + nonSleepTime +" ms");
history.append("\n");
}
flushedOrNot(history, flushed);
}
if(!flushed) {
/// M: Add message history/queue to _exp_main.txt
messageInfo = messageInfo + history.toString();
Log.d(TAG, history.toString());
}
/*Dump for LongerTimeMessageRecord*/
flushed = false;
longerHistory.append("=== LONGER MSG HISTORY IN MAIN THREAD ===\n");
sizeForMsgRecord = mLongTimeMessageHistoryRecord.size();
int indexForTimeRecord = mNonSleepLongTimeRecord.size() - 1;
for ( ;sizeForMsgRecord > 0; sizeForMsgRecord--, indexForTimeRecord-=2) {
msg = (String)mLongTimeMessageHistoryRecord.get(sizeToIndex(sizeForMsgRecord));
nonSleepTime = (Long) mNonSleepLongTimeRecord.get(indexForTimeRecord);
time = (Long) mNonSleepLongTimeRecord.get(indexForTimeRecord-1);
Date date = new Date((long)time.longValue()/1000);
longerHistory.append(msg + " from " + simpleDateFormat.format(date) + " elapsedTime:"+ (((Long)(mElapsedLongTimeRecord.get(indexForTimeRecord))).longValue()/1000)+" ms/upTime:" + nonSleepTime +"ms");
longerHistory.append("\n");
flushedOrNot(longerHistory, flushed);
}
if(!flushed) {
/// M: Add message history/queue to _exp_main.txt
messageInfo = messageInfo + longerHistory.toString();
Log.d(TAG, longerHistory.toString());
}
// Dump message queue
}
/// M: Add message history/queue to _exp_main.txt
String retMessageInfo = messageInfo + Looper.getMainLooper().getQueue().dumpMessageQueue();
messageInfo = "";
return retMessageInfo;
}
}
| gpl-2.0 |
calaveraInfo/hospis | core/mock/src/main/java/cz/cestadomu/hospis/mock/BackendMockResponse.java | 1197 | package cz.cestadomu.hospis.mock;
import static cz.cestadomu.hospis.mock.Mock.BACKEND_GET_VIEW_X_EMPLOYEES_RESPONSE_MOCK;
import static cz.cestadomu.hospis.mock.Mock.BACKEND_LOGIN_RESPONSE_MOCK;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component("backendMockResponse")
public class BackendMockResponse {
private static final Logger LOG = LoggerFactory.getLogger(BackendMockResponse.class);
public String mock(Mock mockResponseResource, String request) {
LOG.info("Recieved request to backend mock component:\n{}", request);
String response;
try {
response = IOUtils.toString(mockResponseResource.resourceUrl());
LOG.info("Returning mock response from backend component:\n{}", response);
return response;
} catch (IOException e) {
throw new RuntimeException("Unable to return mock response from backend component.", e);
}
}
public String login(String request) {
return mock(BACKEND_LOGIN_RESPONSE_MOCK, request);
}
public String getViewX(String request) {
return mock(BACKEND_GET_VIEW_X_EMPLOYEES_RESPONSE_MOCK, request);
}
}
| gpl-2.0 |
bedatadriven/renjin | core/src/main/java/org/renjin/primitives/sequence/RepStringVector.java | 2266 | /*
* Renjin : JVM-based interpreter for the R language for the statistical analysis
* Copyright © 2010-2019 BeDataDriven Groep B.V. and contributors
*
* 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, a copy is available at
* https://www.gnu.org/licenses/gpl-2.0.txt
*/
package org.renjin.primitives.sequence;
import org.renjin.sexp.AttributeMap;
import org.renjin.sexp.StringVector;
import org.renjin.sexp.Vector;
public class RepStringVector extends StringVector {
public Vector source;
private int sourceLength;
private int length;
private int each;
public RepStringVector(Vector source, int length, int each, AttributeMap attributes) {
super(attributes);
this.source = source;
this.sourceLength = source.length();
this.length = length;
this.each = each;
}
private RepStringVector(String constant, int length) {
super(AttributeMap.EMPTY);
this.source = StringVector.valueOf(constant);
this.sourceLength = source.length();
this.length = length;
this.each = 1;
}
@Override
public int length() {
return length;
}
@Override
protected StringVector cloneWithNewAttributes(AttributeMap attributes) {
return new RepStringVector(source, length, each, attributes);
}
@Override
public String getElementAsString(int index) {
sourceLength = source.length();
return source.getElementAsString( (index / each) % sourceLength);
}
@Override
public boolean isConstantAccessTime() {
return true;
}
public static StringVector createConstantVector(String constant,
int length) {
if (length <= 0) {
return StringVector.EMPTY;
}
return new RepStringVector(constant, length);
}
}
| gpl-2.0 |
tturbs/pattern | src/com/yongk/pattern/chainOfResponsibility/LimitSupport.java | 375 | package com.yongk.pattern.chainOfResponsibility;
public class LimitSupport extends Support {
private int limit;
public LimitSupport(String name, int limit) {
super(name);
this.limit = limit;
}
public LimitSupport(String name) {
super(name);
}
@Override
public boolean resolve(Trouble t) {
if (t.getNumber() < limit)
return true;
return false;
}
}
| gpl-2.0 |
rac021/blazegraph_1_5_3_cluster_2_nodes | bigdata-rdf/src/java/com/bigdata/rdf/sparql/ast/optimizers/ASTQueryHintOptimizer.java | 28914 | /**
Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved.
Contact:
SYSTAP, LLC
2501 Calvert ST NW #106
Washington, DC 20008
licenses@systap.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 Oct 26, 2011
*/
package com.bigdata.rdf.sparql.ast.optimizers;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.openrdf.model.Literal;
import org.openrdf.model.URI;
import com.bigdata.bop.BOp;
import com.bigdata.bop.BOpUtility;
import com.bigdata.bop.IBindingSet;
import com.bigdata.bop.IValueExpression;
import com.bigdata.rdf.model.BigdataURI;
import com.bigdata.rdf.model.BigdataValue;
import com.bigdata.rdf.sparql.ast.ASTBase;
import com.bigdata.rdf.sparql.ast.ConstantNode;
import com.bigdata.rdf.sparql.ast.FilterNode;
import com.bigdata.rdf.sparql.ast.GraphPatternGroup;
import com.bigdata.rdf.sparql.ast.IGroupMemberNode;
import com.bigdata.rdf.sparql.ast.IQueryNode;
import com.bigdata.rdf.sparql.ast.IValueExpressionNode;
import com.bigdata.rdf.sparql.ast.NamedSubqueriesNode;
import com.bigdata.rdf.sparql.ast.NamedSubqueryRoot;
import com.bigdata.rdf.sparql.ast.QueryBase;
import com.bigdata.rdf.sparql.ast.QueryHints;
import com.bigdata.rdf.sparql.ast.QueryNodeWithBindingSet;
import com.bigdata.rdf.sparql.ast.QueryRoot;
import com.bigdata.rdf.sparql.ast.StatementPatternNode;
import com.bigdata.rdf.sparql.ast.SubqueryFunctionNodeBase;
import com.bigdata.rdf.sparql.ast.SubqueryRoot;
import com.bigdata.rdf.sparql.ast.TermNode;
import com.bigdata.rdf.sparql.ast.VarNode;
import com.bigdata.rdf.sparql.ast.eval.AST2BOpContext;
import com.bigdata.rdf.sparql.ast.hints.IQueryHint;
import com.bigdata.rdf.sparql.ast.hints.QueryHintException;
import com.bigdata.rdf.sparql.ast.hints.QueryHintRegistry;
import com.bigdata.rdf.sparql.ast.hints.QueryHintScope;
import com.bigdata.rdf.sparql.ast.service.ServiceNode;
/**
* Query hints are identified applied to AST nodes based on the specified scope
* and the location within the AST in which they are found. Query hints
* recognized by this optimizer have the form:
*
* <pre>
* scopeURL propertyURL value
* </pre>
*
* Where <i>scope</i> is any of the {@link QueryHintScope}s; and <br/>
* Where <i>propertyURL</i> identifies the query hint;<br/>
* Where <i>value</i> is a literal.
* <p>
* Once recognized, query hints are removed from the AST. All query hints are
* declared internally using interfaces. It is an error if the specified query
* hint has not been registered with the {@link QueryHintRegistry}, if the
* {@link IQueryHint} can not validate the value, if the {@link QueryHintScope}
* is not legal for the {@link IQueryHint}, etc.
* <p>
* For example:
*
* <pre>
* ...
* {
* # query hint binds for this join group.
* hint:Group hint:com.bigdata.bop.PipelineOp.maxParallel 10
*
* ...
*
* # query hint binds for the next basic graph pattern in this join group.
* hint:Prior hint:com.bigdata.relation.accesspath.IBuffer.chunkCapacity 100
*
* ?x rdf:type foaf:Person .
* }
* </pre>
*
* @see QueryHints
* @see QueryHintScope
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
*/
public class ASTQueryHintOptimizer implements IASTOptimizer {
private static final Logger log = Logger
.getLogger(ASTQueryHintOptimizer.class);
@SuppressWarnings("unchecked")
@Override
public QueryNodeWithBindingSet optimize(
final AST2BOpContext context, final QueryNodeWithBindingSet input) {
final IQueryNode queryNode = input.getQueryNode();
final IBindingSet[] bindingSets = input.getBindingSets();
final QueryRoot queryRoot = (QueryRoot) queryNode;
if (context.queryHints != null && !context.queryHints.isEmpty()) {
// Apply any given query hints globally.
applyGlobalQueryHints(context, queryRoot, context.queryHints);
}
// First, process any pre-existing named subqueries.
{
final NamedSubqueriesNode namedSubqueries = queryRoot
.getNamedSubqueries();
if (namedSubqueries != null) {
for (NamedSubqueryRoot namedSubquery : namedSubqueries) {
processGroup(context, queryRoot, namedSubquery,
namedSubquery.getWhereClause());
}
}
}
// Now process the main where clause.
processGroup(context, queryRoot, queryRoot, queryRoot.getWhereClause());
return new QueryNodeWithBindingSet(queryNode, bindingSets);
}
/**
* Tnis is used to avoid descent into parts of the AST which can not have
* query hints, such as value expressions.
*/
private boolean isNodeAcceptingQueryHints(final BOp op) {
/**
* Note: Historically, only visited QueryNodeBase, but that does not let
* query hints be applied to a variety of relevant AST nodes, including
* the SliceOp. The new pattern is to exclude those parts of the AST
* interface heirarchy that should not have query hints applied, which
* is basically the value expressions.
*
* @see <a href="http://sourceforge.net/apps/trac/bigdata/ticket/791" >
* Clean up query hints </a>
*/
if (op instanceof IValueExpressionNode) {
// Skip value expressions.
return false;
}
if (op instanceof IValueExpression) {
// Skip value expressions.
return false;
}
// Visit anything else.
return true;
}
/**
* Applies the global query hints to each node in the query.
*
* @param queryRoot
* @param queryHints
*/
private void applyGlobalQueryHints(final AST2BOpContext context,
final QueryRoot queryRoot, final Properties queryHints) {
if (queryHints == null || queryHints.isEmpty())
return;
// validateQueryHints(context, queryHints);
final Iterator<BOp> itr = BOpUtility
.preOrderIteratorWithAnnotations(queryRoot);
// Note: working around a ConcurrentModificationException.
final List<ASTBase> list = new LinkedList<ASTBase>();
while (itr.hasNext()) {
final BOp op = itr.next();
if (!isNodeAcceptingQueryHints(op))
continue;
final ASTBase t = (ASTBase) op;
list.add(t);
}
for (ASTBase t : list) {
applyQueryHints(context, queryRoot, QueryHintScope.Query, t,
queryHints);
}
}
/**
* Apply each query hint in turn to the AST node.
*
* @param t
* The AST node.
* @param queryHints
* The query hints.
*/
private void applyQueryHints(final AST2BOpContext context,
final QueryRoot queryRoot,
final QueryHintScope scope, final ASTBase t,
final Properties queryHints) {
/*
* Apply the query hints to the node.
*/
@SuppressWarnings("rawtypes")
final Enumeration e = queryHints.propertyNames();
while (e.hasMoreElements()) {
final String name = (String) e.nextElement();
final String value = queryHints.getProperty(name);
_applyQueryHint(context, queryRoot, scope, t, name, value);
}
}
/**
* Apply the query hint to the AST node.
*
* @param t
* The AST node to which the query hint will be bound.
* @param name
* The name of the query hint.
* @param value
* The value.
*/
@SuppressWarnings("unchecked")
private void _applyQueryHint(final AST2BOpContext context, final QueryRoot queryRoot,
final QueryHintScope scope, final ASTBase t, final String name,
final String value) {
@SuppressWarnings("rawtypes")
final IQueryHint queryHint = QueryHintRegistry.get(name);
if (queryHint == null) {
// Unknown query hint.
throw new QueryHintException(scope, t, name, value);
}
// Parse/validate and handle type conversion for the query hint value.
final Object value2 = queryHint.validate(value);
if (log.isTraceEnabled())
log.trace("Applying hint: hint=" + queryHint.getName() + ", value="
+ value2 + ", node=" + t.getClass().getName());
// Apply the query hint.
queryHint.handle(context, queryRoot, scope, t, value2);
// if (scope == QueryHintScope.Query) {
// /*
// * All of these hints either are only permitted in the Query scope
// * or effect the default settings for the evaluation of this query
// * when they appear in the Query scope. For the latter category, the
// * hints may also appear in other scopes. For example, you can
// * override the access path sampling behavior either for the entire
// * query, for all BGPs in some scope, or for just a single BGP.
// */
// if (name.equals(QueryHints.ANALYTIC)) {
// context.nativeHashJoins = Boolean.valueOf(value);
// context.nativeDistinctSolutions = Boolean.valueOf(value);
// context.nativeDistinctSPO = Boolean.valueOf(value);
// } else if (name.equals(QueryHints.MERGE_JOIN)) {
// context.mergeJoin = Boolean.valueOf(value);
// } else if (name.equals(QueryHints.NATIVE_HASH_JOINS)) {
// context.nativeHashJoins = Boolean.valueOf(value);
// } else if (name.equals(QueryHints.NATIVE_DISTINCT_SOLUTIONS)) {
// context.nativeDistinctSolutions = Boolean.valueOf(value);
// } else if (name.equals(QueryHints.NATIVE_DISTINCT_SPO)) {
// context.nativeDistinctSPO = Boolean.valueOf(value);
// } else if (name.equals(QueryHints.REMOTE_APS)) {
// context.remoteAPs = Boolean.valueOf(value);
// } else if (name.equals(QueryHints.ACCESS_PATH_SAMPLE_LIMIT)) {
// context.accessPathSampleLimit = Integer.valueOf(value);
// } else if (name.equals(QueryHints.ACCESS_PATH_SCAN_AND_FILTER)) {
// context.accessPathScanAndFilter = Boolean.valueOf(value);
// } else {
// t.setQueryHint(name, value);
// }
// } else {
// t.setQueryHint(name, value);
// }
}
// /**
// * Validate the global query hints.
// *
// * @param queryHints
// */
// private void validateQueryHints(final AST2BOpContext context,
// final Properties queryHints) {
//
// final Enumeration<?> e = queryHints.propertyNames();
//
// while (e.hasMoreElements()) {
//
// final String name = (String) e.nextElement();
//
// final String value = queryHints.getProperty(name);
//
// validateQueryHint(context, name, value);
//
// }
//
// }
/**
* Recursively process a join group, applying any query hints found and
* removing them from the join group.
*
* @param context
* @param queryRoot
* The {@link QueryRoot}.
* @param group
* The join group.
*/
@SuppressWarnings("unchecked")
private void processGroup(final AST2BOpContext context,
final QueryRoot queryRoot, final QueryBase queryBase,
final GraphPatternGroup<IGroupMemberNode> group) {
if (group == null)
return;
/*
* Note: The loop needs to be carefully written as query hints will be
* removed after they are processed. This can either be done on a hint
* by hint basis or after we have processed all hints in the group. It
* is easier to make the latter robust, so this uses a second pass over
* each group in which a query hint was identified to remove the query
* hints once they have been interpreted.
*/
/*
* Identify and interpret query hints.
*/
// #of query hints found in this group.
int nfound = 0;
{
final int arity = group.arity();
// The previous AST node which was not a query hint.
ASTBase prior = null;
for (int i = 0; i < arity; i++) {
final IGroupMemberNode child = (IGroupMemberNode) group.get(i);
if (child instanceof StatementPatternNode) {
// Look for a query hint.
final StatementPatternNode sp = (StatementPatternNode) child;
if (!isQueryHint(sp)) {
// Not a query hint.
prior = sp;
continue;
}
// Apply query hint.
applyQueryHint(context, queryRoot, queryBase, group, prior,
sp);
nfound++;
continue;
}
/*
* Recursion (looking for query hints to be applied).
*/
if(child instanceof GraphPatternGroup<?>) {
processGroup(context, queryRoot, queryBase,
(GraphPatternGroup<IGroupMemberNode>) child);
} else if (child instanceof SubqueryRoot) {
processGroup(context, queryRoot, (SubqueryRoot)child,
((SubqueryRoot) child).getWhereClause());
} else if (child instanceof ServiceNode) {
processGroup(context, queryRoot, queryBase,
((ServiceNode) child).getGraphPattern());
} else if (child instanceof FilterNode
&& ((FilterNode) child).getValueExpressionNode() instanceof SubqueryFunctionNodeBase) {
/**
* @see <a href="http://trac.blazegraph.com/ticket/990"> Query hint not recognized in FILTER</a>
*/
final GraphPatternGroup<IGroupMemberNode> filterGraphPattern = ((SubqueryFunctionNodeBase) ((FilterNode) child)
.getValueExpressionNode()).getGraphPattern();
processGroup(context, queryRoot, queryBase,
filterGraphPattern);
}
prior = (ASTBase) child;
}
}
/*
* Remove the query hints from this group.
*/
if (nfound > 0) {
for (int i = 0; i < group.arity(); ) {
final IGroupMemberNode child = (IGroupMemberNode) group.get(i);
if (!(child instanceof StatementPatternNode)) {
i++;
continue;
}
final StatementPatternNode sp = (StatementPatternNode) child;
if (isQueryHint(sp)) {
// Remove and redo the loop.
group.removeArg(sp);
continue;
}
// Next child.
i++;
}
}
}
/**
* Return <code>true</code> iff this {@link StatementPatternNode} is a query
* hint. This method checks the namespace of the predicate. All query hints
* MUST start with the <code>hint:</code> namespace, which is given by
* {@link QueryHints#NAMESPACE}.
* <p>
* Within that namespace we have public query hints whose localName is
* declared in the {@link QueryHints} interface, e.g.,
* {@link QueryHints#CHUNK_SIZE} which appears as follows in a query:
*
* <pre>
* hint:chunkSize
* </pre>
*
* We also have non-public, fully qualified, query hints, e.g.,
*
* <pre>
* hint:com.bigdata.relation.accesspath.IBuffer.chunkCapacity
* </pre>
*
* In both cases, an {@link IQueryHint} is registered with the
* {@link QueryHintRegistry}. The "non-public" query hints are simply not
* declared by the {@link QueryHints} interface and are intended more for
* internal development and performance testing rather than as generally
* useful query hints.
*
* @param sp
* The {@link StatementPatternNode}.
*
* @return <code>true</code> if the SP is a query hint.
*
* @see <a href="http://sourceforge.net/apps/trac/bigdata/ticket/791" >
* Clean up query hints </a>
*/
private boolean isQueryHint(final StatementPatternNode sp) {
if(!(sp.p() instanceof ConstantNode))
return false;
final BigdataValue p = ((ConstantNode) sp.p()).getValue();
if(!(p instanceof URI))
return false;
final BigdataURI u = (BigdataURI) p;
final String str = u.stringValue();
if (str.startsWith(QueryHints.NAMESPACE)) {
// A possible query hint.
return true;
}
return false;
}
/**
* Extract and return the {@link QueryHintScope}.
*
* @param t
* The subject position of the query hint
* {@link StatementPatternNode}.
*
* @return The {@link QueryHintScope}.
*
* @throws RuntimeException
* if something goes wrong.
* @throws IllegalArgumentException
* if something goes wrong.
*/
private QueryHintScope getScope(final TermNode t) {
if(!(t instanceof ConstantNode))
throw new RuntimeException(
"Subject position of query hint must be a constant.");
final BigdataValue v = ((ConstantNode) t).getValue();
if (!(v instanceof BigdataURI))
throw new RuntimeException("Query hint scope is not a URI.");
final BigdataURI u = (BigdataURI) v;
return QueryHintScope.valueOf(u);
}
/**
* Extract, validate, and return the name of the query hint property.
*
* @param t
* The predicate position of the query hint
* {@link StatementPatternNode}.
*
* @return The name of the query hint property.
*/
private String getName(final TermNode t) {
if (!(t instanceof ConstantNode)) {
throw new RuntimeException(
"Predicate position of query hint must be a constant.");
}
final BigdataValue v = ((ConstantNode) t).getValue();
if (!(v instanceof BigdataURI))
throw new RuntimeException("Predicate position of query hint is not a URI.");
final BigdataURI u = (BigdataURI) v;
final String name = u.getLocalName();
return name;
}
/**
* Return the value for the query hint.
*
* @param t
* @return
*/
private String getValue(final TermNode t) {
// if (!(t instanceof ConstantNode)) {
// throw new RuntimeException(
// "Object position of query hint must be a constant.");
// }
/*
* Let the variable through as a string.
*/
if (t instanceof VarNode) {
return '?'+((VarNode) t).getValueExpression().getName();
}
final BigdataValue v = ((ConstantNode) t).getValue();
if (!(v instanceof Literal))
throw new RuntimeException(
"Object position of query hint is not a Literal.");
final Literal lit = (Literal) v;
return lit.stringValue();
}
/**
* @param context
* @param queryRoot
* @param group
* @param prior
* @param s The subject position of the query hint.
* @param o The object position of the query hint.
*/
private void applyQueryHint(//
final AST2BOpContext context,//
final QueryRoot queryRoot,// top-level query
final QueryBase queryBase,// either top-level query or subquery.
final GraphPatternGroup<IGroupMemberNode> group,//
final ASTBase prior, // MAY be null IFF scope != Prior
final StatementPatternNode hint //
) {
if(context == null)
throw new IllegalArgumentException();
if(queryRoot == null)
throw new IllegalArgumentException();
if(group == null)
throw new IllegalArgumentException();
if(hint == null)
throw new IllegalArgumentException();
final QueryHintScope scope = getScope(hint.s());
final String name = getName(hint.p());
final String value = getValue(hint.o());
if (log.isInfoEnabled())
log.info("name=" + name + ", scope=" + scope + ", value=" + value);
// validateQueryHint(context, name, value);
switch (scope) {
case Query: {
applyToQuery(context, queryRoot, scope, name, value);
break;
}
case SubQuery: {
applyToSubQuery(context, queryRoot, scope, queryBase, group, name, value);
break;
}
case Group: {
applyToGroup(context, queryRoot, scope, group, name, value);
break;
}
case GroupAndSubGroups: {
applyToGroupAndSubGroups(context, queryRoot, scope, group, name, value);
break;
}
case Prior: {
if (scope == QueryHintScope.Prior && prior == null) {
throw new RuntimeException(
"Query hint with Prior scope must follow the AST node to which it will bind.");
}
// Apply to just the last SP.
_applyQueryHint(context, queryRoot, scope, prior, name, value);
break;
}
default:
throw new UnsupportedOperationException("Unknown scope: " + scope);
}
}
/**
* @param group
* @param name
* @param value
*/
private void applyToSubQuery(final AST2BOpContext context,
final QueryRoot queryRoot,
final QueryHintScope scope,
final QueryBase queryBase,
GraphPatternGroup<IGroupMemberNode> group, final String name,
final String value) {
/*
* Find the top-level parent group for the given group.
*/
GraphPatternGroup<IGroupMemberNode> parent = group;
while (parent != null) {
group = parent;
parent = parent.getParentGraphPatternGroup();
}
// Apply to all child groups of that top-level group.
applyToGroupAndSubGroups(context, queryRoot, scope, group, name, value);
// if (isNodeAcceptingQueryHints(queryBase)) {
_applyQueryHint(context, queryRoot, scope, (ASTBase) queryBase, name, value);
// }
}
/**
* Applies the query hint to the entire query.
*
* @param queryRoot
* @param name
* @param value
*/
private void applyToQuery(final AST2BOpContext context,
final QueryRoot queryRoot,
final QueryHintScope scope,
final String name, final String value) {
if (false && context.queryHints != null) {
/**
* Also stuff the query hint on the global context for things which
* look there.
*
* Note: HINTS: This was putting the literal given name and value of
* the query hint. This is basically backwards. The query hints in
* the global scope provide a default. Explicitly given query hints
* in the query are delegated to IQueryHint implementations and then
* applied to the appropriate AST nodes.
*
* @see <a
* href="http://sourceforge.net/apps/trac/bigdata/ticket/791" >
* Clean up query hints </a>
*/
context.queryHints.setProperty(name, value);
}
final Iterator<BOp> itr = BOpUtility
.preOrderIteratorWithAnnotations(queryRoot);
// Note: working around a ConcurrentModificationException.
final List<ASTBase> list = new LinkedList<ASTBase>();
while (itr.hasNext()) {
final BOp op = itr.next();
if (!isNodeAcceptingQueryHints(op))
continue;
/*
* Set a properties object on each AST node. The properties object
* for each AST node will use the global query hints for its
* defaults so it can be overridden selectively.
*/
final ASTBase t = (ASTBase) op;
list.add(t);
}
for(ASTBase t : list) {
_applyQueryHint(context, queryRoot, scope, t, name, value);
}
}
/**
* Apply the query hint to the group and, recursively, to any sub-groups.
*
* @param group
* @param name
* @param value
*/
@SuppressWarnings("unchecked")
private void applyToGroupAndSubGroups(final AST2BOpContext context,
final QueryRoot queryRoot,
final QueryHintScope scope,
final GraphPatternGroup<IGroupMemberNode> group, final String name,
final String value) {
for (IGroupMemberNode child : group) {
_applyQueryHint(context, queryRoot, scope, (ASTBase) child, name, value);
if (child instanceof GraphPatternGroup<?>) {
applyToGroupAndSubGroups(context, queryRoot, scope,
(GraphPatternGroup<IGroupMemberNode>) child, name,
value);
}
}
// if(isNodeAcceptingQueryHints(group)) {
_applyQueryHint(context, queryRoot, scope, (ASTBase) group, name, value);
// }
}
/**
* Apply the query hint to the group.
*
* @param group
* @param name
* @param value
*/
private void applyToGroup(final AST2BOpContext context,
final QueryRoot queryRoot,
final QueryHintScope scope,
final GraphPatternGroup<IGroupMemberNode> group, final String name,
final String value) {
for (IGroupMemberNode child : group) {
_applyQueryHint(context, queryRoot, scope, (ASTBase) child, name, value);
}
// if (isNodeAcceptingQueryHints(group)) {
_applyQueryHint(context, queryRoot, scope, (ASTBase) group, name, value);
// }
}
}
| gpl-2.0 |
SCADA-LTS/Scada-LTS | src/com/serotonin/mango/util/SendMsgUtils.java | 11593 | package com.serotonin.mango.util;
import com.serotonin.mango.Common;
import com.serotonin.mango.rt.dataImage.DataPointRT;
import com.serotonin.mango.rt.event.EventInstance;
import com.serotonin.mango.rt.event.handlers.EmailHandlerRT;
import com.serotonin.mango.rt.event.handlers.EmailToSmsHandlerRT;
import com.serotonin.mango.rt.event.handlers.NotificationType;
import com.serotonin.mango.rt.event.type.SystemEventType;
import com.serotonin.mango.rt.maint.work.AfterWork;
import com.serotonin.mango.rt.maint.work.EmailWorkItem;
import com.serotonin.mango.rt.maint.work.EmailNotificationWorkItem;
import com.serotonin.mango.view.event.NoneEventRenderer;
import com.serotonin.mango.vo.DataPointVO;
import com.serotonin.mango.web.email.MangoEmailContent;
import com.serotonin.util.StringUtils;
import com.serotonin.web.i18n.LocalizableMessage;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
public final class SendMsgUtils {
private static final Log LOG = LogFactory.getLog(SendMsgUtils.class);
private SendMsgUtils() {}
public static boolean sendEmail(EventInstance evt, EmailHandlerRT.EmailNotificationType notificationType,
Set<String> addresses, String alias, AfterWork afterWork) {
try {
SendEmailConfig sendEmailConfig = SendEmailConfig.newConfigFromSystemSettings();
validateEmail(evt, notificationType, addresses, alias);
if (evt.getEventType().isSystemMessage()) {
if (((SystemEventType) evt.getEventType()).getSystemEventTypeId() == SystemEventType.TYPE_EMAIL_SEND_FAILURE) {
// Don't send email notifications about email send failures.
LOG.info("Not sending email for event raised due to email failure");
return false;
}
}
MangoEmailContent content = EmailContentUtils.createContent(evt, notificationType, alias);
String[] toAddrs = addresses.toArray(new String[0]);
InternetAddress[] internetAddresses = SendMsgUtils.convertToInternetAddresses(toAddrs);
validateAddresses(evt, notificationType, internetAddresses, alias);
// Send the email.
EmailNotificationWorkItem.queueMsg(internetAddresses, content, afterWork, sendEmailConfig);
return true;
} catch (Exception e) {
LOG.error(MessageFormat.format("Info about email: {0}, StackTrace: {1}",
getInfoEmail(evt,notificationType,alias),
ExceptionUtils.getStackTrace(e)));
return false;
}
}
public static boolean sendSms(EventInstance evt, EmailToSmsHandlerRT.SmsNotificationType notificationType,
Set<String> addresses, String alias, AfterWork afterWork) {
try {
SendEmailConfig sendEmailConfig = SendEmailConfig.newConfigFromSystemSettings();
validateEmail(evt, notificationType, addresses, alias);
if (evt.getEventType().isSystemMessage()) {
if (((SystemEventType) evt.getEventType()).getSystemEventTypeId() == SystemEventType.TYPE_EMAIL_SEND_FAILURE) {
// Don't send email notifications about email send failures.
LOG.info("Not sending email for event raised due to email failure");
return false;
}
}
MangoEmailContent content = EmailContentUtils.createSmsContent(evt, notificationType, alias);
String[] toAddrs = addresses.toArray(new String[0]);
InternetAddress[] internetAddresses = SendMsgUtils.convertToInternetAddresses(toAddrs);
validateAddresses(evt, notificationType, internetAddresses, alias);
// Send the email.
EmailNotificationWorkItem.queueMsg(internetAddresses, content, afterWork, sendEmailConfig);
return true;
} catch (Exception e) {
LOG.error(MessageFormat.format("Info about email: {0}, StackTrace: {1}",
getInfoEmail(evt,notificationType,alias),
ExceptionUtils.getStackTrace(e)));
return false;
}
}
public static boolean sendEmail(EventInstance evt, NotificationType notificationType, Set<String> addresses,
String alias) {
try {
SendEmailConfig.validateSystemSettings();
validateEmail(evt, notificationType, addresses, alias);
if (evt.getEventType().isSystemMessage()) {
if (((SystemEventType) evt.getEventType()).getSystemEventTypeId() == SystemEventType.TYPE_EMAIL_SEND_FAILURE) {
// Don't send email notifications about email send failures.
LOG.info("Not sending email for event raised due to email failure");
return false;
}
}
String[] toAddrs = addresses.toArray(new String[0]);
MangoEmailContent content = EmailContentUtils.createContent(evt, notificationType, alias);
validateAddresses(evt, notificationType, convertToInternetAddresses(toAddrs), alias);
// Send the email.
EmailWorkItem.queueEmail(toAddrs, content);
return true;
} catch (Exception e) {
LOG.error(MessageFormat.format("Info about email: {0}, StackTrace: {1}",
getInfoEmail(evt,notificationType,alias),
ExceptionUtils.getStackTrace(e)));
return false;
}
}
public static boolean sendSms(EventInstance evt, NotificationType notificationType, Set<String> addresses,
String alias) {
try {
SendEmailConfig.validateSystemSettings();
validateEmail(evt, notificationType, addresses, alias);
if (evt.getEventType().isSystemMessage()) {
if (((SystemEventType) evt.getEventType()).getSystemEventTypeId() == SystemEventType.TYPE_EMAIL_SEND_FAILURE) {
// Don't send email notifications about email send failures.
LOG.info("Not sending email for event raised due to email failure");
return false;
}
}
MangoEmailContent content = EmailContentUtils.createSmsContent(evt, notificationType, alias);
String[] toAddrs = addresses.toArray(new String[0]);
validateAddresses(evt, notificationType, convertToInternetAddresses(toAddrs), alias);
EmailWorkItem.queueEmail(toAddrs, content);
return true;
} catch (Exception e) {
LOG.error(MessageFormat.format("Info about email: {0}, StackTrace: {1}",
getInfoEmail(evt,notificationType,alias),
ExceptionUtils.getStackTrace(e)));
return false;
}
}
private static String getInfoEmail(EventInstance evt, NotificationType notificationType, String alias) {
String messageInfoAlias = MessageFormat.format("Alias: {0} \n", alias);
String messageInfoEmail = MessageFormat.format("Event: {0} \n", evt.getId());
String messageInfoNotification = MessageFormat.format("Notification: {0} \n", notificationType.getKey());
String subject = "";
String messageExceptionWhenGetSubjectEmail = "";
try {
LocalizableMessage subjectMsg;
LocalizableMessage notifTypeMsg = new LocalizableMessage(notificationType.getKey());
if (StringUtils.isEmpty(alias)) {
if (evt.getId() == Common.NEW_ID)
subjectMsg = new LocalizableMessage("ftl.subject.default.log", notifTypeMsg);
else
subjectMsg = new LocalizableMessage("ftl.subject.default.id", notifTypeMsg, evt.getId());
} else {
if (evt.getId() == Common.NEW_ID)
subjectMsg = new LocalizableMessage("ftl.subject.alias", alias, notifTypeMsg);
else
subjectMsg = new LocalizableMessage("ftl.subject.alias.id", alias, notifTypeMsg, evt.getId());
}
ResourceBundle bundle = Common.getBundle();
subject = subjectMsg.getLocalizedMessage(bundle);
} catch (Exception e) {
messageExceptionWhenGetSubjectEmail = MessageFormat.format("StackTrace for subjectMsg {0}",ExceptionUtils.getStackTrace(e));
}
String messages = new StringBuilder()
.append(messageInfoEmail)
.append(messageInfoNotification)
.append(messageInfoAlias)
.append(subject)
.append(messageExceptionWhenGetSubjectEmail).toString();
return messages;
}
private static void validateEmail(EventInstance evt, NotificationType notificationType, Set<String> addresses, String alias) throws Exception {
String messageErrorEventInstance = "Event Instance null \n";
String messageErrorNotyficationType = "Notification type is null \n";
String messageErrorEmails = " Don't have e-mail \n";
String messageErrorAlias = " Don't have alias\n";
String messages = "";
if (evt == null || evt.getEventType() == null) messages += messageErrorEventInstance;
if (notificationType == null) messages += messageErrorNotyficationType;
if (addresses == null || addresses.size() == 0) messages += messageErrorEmails;
if (alias == null) messages += messageErrorAlias;
if (messages.length() > 0) {
throw new Exception(getInfoEmail(evt, notificationType, alias) + messages );
}
}
private static void validateAddresses(EventInstance evt, NotificationType notificationType,
InternetAddress[] internetAddresses, String alias) throws Exception {
String messageErrorEmails = " Don't have e-mail \n";
String messages = "";
if (internetAddresses == null || internetAddresses.length == 0) messages += messageErrorEmails;
if (!messages.isEmpty()) {
throw new Exception(getInfoEmail(evt, notificationType, alias) + messages );
}
}
public static InternetAddress[] convertToInternetAddresses(String[] toAddresses) {
Set<InternetAddress> addresses = new HashSet<>();
for (int i = 0; i < toAddresses.length; i++) {
try {
InternetAddress internetAddress = new InternetAddress(toAddresses[i]);
addresses.add(internetAddress);
} catch (AddressException e) {
LOG.error(e.getMessage(), e);
}
}
return addresses.toArray(new InternetAddress[]{});
}
public static String getDataPointMessage(DataPointVO dataPoint, LocalizableMessage shortMsg) {
if (shortMsg.getKey().equals("event.detector.shortMessage") && shortMsg.getArgs().length == 2) {
return " " + shortMsg.getArgs()[1];
} else if (dataPoint.getDescription() != null && !dataPoint.getDescription().equals(""))
return " " + dataPoint.getDescription();
else
return " " + dataPoint.getName();
}
}
| gpl-2.0 |
quhfus/DoSeR | doser-core/src/main/java/doser/webclassify/dpo/WebSite.java | 1245 | package doser.webclassify.dpo;
import java.util.Set;
import doser.entitydisambiguation.table.logic.Type;
import doser.webclassify.algorithm.PageSimilarity;
public class WebSite implements Cloneable, Comparable<WebSite> {
private String name;
private String text;
private int objectId;
private Set<Type> types;
private PageSimilarity similarity;
public WebSite() {
super();
this.name = "";
this.text = "";
}
public String getName() {
return name;
}
public PageSimilarity getSimilarity() {
return similarity;
}
public void setSimilarity(PageSimilarity similarity) {
this.similarity = similarity;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Set<Type> getTypes() {
return types;
}
public void setTypes(Set<Type> types) {
this.types = types;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
@Override
public int compareTo(WebSite o) {
// System.out.println(this.name + " "+o.getName());
if (this.name.equalsIgnoreCase(o.getName())
&& this.getText().hashCode() == o.getText().hashCode()) {
return 0;
} else {
return -1;
}
}
} | gpl-2.0 |
tspauld98/white-mercury-dg | src/main/java/generator/misc/DataFileDefinition.java | 1890 | /*
* dgMaster: A versatile, open source data generator.
*(c) 2007 M. Michalakopoulos, mmichalak@gmail.com
*/
package generator.misc;
import java.util.Vector;
/**
*
* Represents the information used to create a new text output file.
* It also holds a vector of DataFileItem which define what to output in the
* text file.
*/
public class DataFileDefinition
{
private String name;
private String description;
private Vector outDataItems; //a place holder for DataFileItem
private String outFilename;
private String delimiter;
private long numOfRecs;
/** Creates a new instance of FileDefinition */
public DataFileDefinition()
{
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Vector getOutDataItems()
{
return outDataItems;
}
public void setOutDataItems(Vector vOutData)
{
this.outDataItems = vOutData;
}
public String getOutFilename()
{
return outFilename;
}
public void setOutFilename(String outFilename)
{
this.outFilename = outFilename;
}
public String getDescription()
{
return this.description;
}
public String getDelimiter()
{
return delimiter;
}
public void setDelimiter(String delimiter)
{
this.delimiter = delimiter;
}
public long getNumOfRecs()
{
return numOfRecs;
}
public void setNumOfRecs(long numOfRecs)
{
this.numOfRecs = numOfRecs;
}
public void setDescription(String description)
{
this.description = description;
}
public String toString()
{
return name;
}
}
| gpl-2.0 |
mutars/java_libav | wrapper/src/main/java/com/mutar/libav/bridge/avformat/AVIODirEntry.java | 4355 | package com.mutar.libav.bridge.avformat;
import org.bridj.BridJ;
import org.bridj.Pointer;
import org.bridj.StructObject;
import org.bridj.ann.Field;
import org.bridj.ann.Library;
/**
* <i>native declaration : ffmpeg_build/include/libavformat/avio.h:49</i><br>
* This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
* For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> or <a href="http://bridj.googlecode.com/">BridJ</a> .
*/
@Library("avformat")
public class AVIODirEntry extends StructObject {
static {
BridJ.register();
}
/**
* < Filename<br>
* C type : char*
*/
@Field(0)
public Pointer<Byte > name() {
return this.io.getPointerField(this, 0);
}
/**
* < Filename<br>
* C type : char*
*/
@Field(0)
public AVIODirEntry name(Pointer<Byte > name) {
this.io.setPointerField(this, 0, name);
return this;
}
/** < Type of the entry */
@Field(1)
public int type() {
return this.io.getIntField(this, 1);
}
/** < Type of the entry */
@Field(1)
public AVIODirEntry type(int type) {
this.io.setIntField(this, 1, type);
return this;
}
/**
* < Set to 1 when name is encoded with UTF-8, 0 otherwise.<br>
* Name can be encoded with UTF-8 even though 0 is set.
*/
@Field(2)
public int utf8() {
return this.io.getIntField(this, 2);
}
/**
* < Set to 1 when name is encoded with UTF-8, 0 otherwise.<br>
* Name can be encoded with UTF-8 even though 0 is set.
*/
@Field(2)
public AVIODirEntry utf8(int utf8) {
this.io.setIntField(this, 2, utf8);
return this;
}
/** < File size in bytes, -1 if unknown. */
@Field(3)
public long size() {
return this.io.getLongField(this, 3);
}
/** < File size in bytes, -1 if unknown. */
@Field(3)
public AVIODirEntry size(long size) {
this.io.setLongField(this, 3, size);
return this;
}
/**
* < Time of last modification in microseconds since unix<br>
* epoch, -1 if unknown.
*/
@Field(4)
public long modification_timestamp() {
return this.io.getLongField(this, 4);
}
/**
* < Time of last modification in microseconds since unix<br>
* epoch, -1 if unknown.
*/
@Field(4)
public AVIODirEntry modification_timestamp(long modification_timestamp) {
this.io.setLongField(this, 4, modification_timestamp);
return this;
}
/**
* < Time of last access in microseconds since unix epoch,<br>
* -1 if unknown.
*/
@Field(5)
public long access_timestamp() {
return this.io.getLongField(this, 5);
}
/**
* < Time of last access in microseconds since unix epoch,<br>
* -1 if unknown.
*/
@Field(5)
public AVIODirEntry access_timestamp(long access_timestamp) {
this.io.setLongField(this, 5, access_timestamp);
return this;
}
/**
* < Time of last status change in microseconds since unix<br>
* epoch, -1 if unknown.
*/
@Field(6)
public long status_change_timestamp() {
return this.io.getLongField(this, 6);
}
/**
* < Time of last status change in microseconds since unix<br>
* epoch, -1 if unknown.
*/
@Field(6)
public AVIODirEntry status_change_timestamp(long status_change_timestamp) {
this.io.setLongField(this, 6, status_change_timestamp);
return this;
}
/** < User ID of owner, -1 if unknown. */
@Field(7)
public long user_id() {
return this.io.getLongField(this, 7);
}
/** < User ID of owner, -1 if unknown. */
@Field(7)
public AVIODirEntry user_id(long user_id) {
this.io.setLongField(this, 7, user_id);
return this;
}
/** < Group ID of owner, -1 if unknown. */
@Field(8)
public long group_id() {
return this.io.getLongField(this, 8);
}
/** < Group ID of owner, -1 if unknown. */
@Field(8)
public AVIODirEntry group_id(long group_id) {
this.io.setLongField(this, 8, group_id);
return this;
}
/** < Unix file mode, -1 if unknown. */
@Field(9)
public long filemode() {
return this.io.getLongField(this, 9);
}
/** < Unix file mode, -1 if unknown. */
@Field(9)
public AVIODirEntry filemode(long filemode) {
this.io.setLongField(this, 9, filemode);
return this;
}
public AVIODirEntry() {
super();
}
public AVIODirEntry(Pointer pointer) {
super(pointer);
}
}
| gpl-2.0 |
sunknife/GoJavaOnline | EE Module 7 Part1/src/main/java/daos/EmployeeDao.java | 291 | package daos;
import objects.Employee;
import java.util.List;
public interface EmployeeDao {
void createEmployee(Employee employee);
void deleteEmployee(String surname, String name);
Employee searchForEmployee(String surname, String name);
List<Employee> findAll();
}
| gpl-2.0 |
mulesoft/mule-tooling-incubator | org.mule.tooling.incubator.editor.model/src/org/mule/tooling/editor/model/Connector.java | 1265 | package org.mule.tooling.editor.model;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Connector extends AbstractPaletteComponent {
private ConnectivityTesting connectivityTesting;
@XmlAttribute
public ConnectivityTesting getConnectivityTesting() {
return connectivityTesting;
}
public void setConnectivityTesting(ConnectivityTesting connectivityTesting) {
this.connectivityTesting = connectivityTesting;
}
@Override
public void accept(IElementVisitor visitor) {
visitor.visit(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((connectivityTesting == null) ? 0 : connectivityTesting.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Connector other = (Connector) obj;
if (connectivityTesting != other.connectivityTesting)
return false;
return true;
}
}
| gpl-2.0 |
lostdj/Jaklin-OpenJFX | modules/graphics/src/main/java/com/sun/glass/events/MouseEvent.java | 2312 | /*
* 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 com.sun.glass.events;
import java.lang.annotation.Native;
public class MouseEvent {
//mymod
@Native
final static public int BUTTON_NONE = 211;
@Native
final static public int BUTTON_LEFT = 212;
@Native
final static public int BUTTON_RIGHT = 213;
@Native
final static public int BUTTON_OTHER = 214;
@Native
final static public int DOWN = 221;
@Native
final static public int UP = 222;
@Native
final static public int DRAG = 223;
@Native
final static public int MOVE = 224;
@Native
final static public int ENTER = 225;
@Native
final static public int EXIT = 226;
@Native
final static public int CLICK = 227; // synthetic
/**
* Artificial WHEEL event type.
* This kind of mouse event is NEVER sent to an app.
* The app must listen to Scroll events instead.
* This identifier is required for internal purposes.
*/
@Native
final static public int WHEEL = 228;
}
| gpl-2.0 |
egyptscholarsinc/momken-text2phoneme | src/main/java/org/egyptscholars/momken/text2phoneme/App.java | 4240 | package org.egyptscholars.momken.text2phoneme;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import edu.stanford.nlp.international.arabic.Buckwalter;
/**
* Text2Phonem
*
* @author Amgad Madkour <amgad.madkour@egyptscholars.org>
*
*/
public class App
{
private static ArrayList<String> createPhonemes(HashMap<String,String> lookupTable,String text){
ArrayList<String> phonemeEntries=new ArrayList<String>();
System.out.println(text);
//String lastChar = "";
for(int i=0 ; i < text.length()-1; i++){
String currentChar = lookupTable.get(Character.toString(text.charAt(i)));
if (currentChar != null){
//Add the current character
phonemeEntries.add(currentChar);
String nextCh = lookupTable.get(Character.toString(text.charAt(i+1)));
//Handle Special Case of aa
if(nextCh != null && (currentChar.startsWith("d.") ||
currentChar.startsWith("t.")||
currentChar.startsWith("z.")||
currentChar.startsWith("s."))){
if(nextCh.charAt(0) == 'a'){
phonemeEntries.add("a. 70 28 109 71 104");
i++;
}else if(nextCh.charAt(0) == 'i'){
phonemeEntries.add("i. 70 28 109 71 104");
i++;
}else if(nextCh.charAt(0) == 'u'){
phonemeEntries.add("u. 61 35 101 83 102");
i++;
}
}
//lastChar = currentChar;
}
}
System.out.println("---"+text);
if(lookupTable.get(Character.toString(text.charAt(text.length()-1)))!=null)
phonemeEntries.add(lookupTable.get(Character.toString(text.charAt(text.length()-1))));
//Cleanup redundant entries due to Tashkeel (i.e. i. followed by i etc.)
int sz = phonemeEntries.size();
for(int i = 0 ; i < sz-1; i++){
if(phonemeEntries.get(i).charAt(0) == phonemeEntries.get(i+1).charAt(0)){
phonemeEntries.remove(i+1);
sz -= 1;
}
if(phonemeEntries.get(i).startsWith("u.") && phonemeEntries.get(i+1).startsWith("a")){
phonemeEntries.remove(i+1);
sz -= 1;
}
}
System.out.println(phonemeEntries);
return phonemeEntries;
}
public static String cleanBuckwalter(String buck){
System.out.println("Before: "+buck);
StringBuffer buff=new StringBuffer();
String lst = "A'btvjHxd*rzs$SDTZEgfqklmnhwyaiu}p><O";
for(int i = 0 ; i < buck.length() ; i++){
if(lst.contains(String.valueOf(buck.charAt(i)))){
buff.append(String.valueOf(buck.charAt(i)));
}
}
return buff.toString();
}
public static void main( String[] args ){
String temp;
BufferedReader lookupRdr;
BufferedReader txtRdr;
PrintWriter phonemeWrt;
HashMap<String,String> lookupTable;
String[] parts;
ArrayList<String> phonemeEntries= new ArrayList<String>();
try {
//TODO Replace with Apache command Line handling later (cleaner)
lookupRdr = new BufferedReader(new FileReader(args[0]));
txtRdr = new BufferedReader(new FileReader(args[1]));
phonemeWrt = new PrintWriter(new FileWriter(args[2]));
lookupTable = new HashMap<String,String>();
//Load lookup table
while((temp = lookupRdr.readLine())!= null){
parts = temp.split("\t");
lookupTable.put(parts[0], parts[1]);
}
//Load text
Buckwalter b = new Buckwalter();
String words;
while((temp = txtRdr.readLine())!= null){
temp = temp.replace(".", "");
words = b.unicodeToBuckwalter(temp);
parts = words.split(" ");
for (int i=0 ; i<parts.length; i++){
String cleaned = cleanBuckwalter(parts[i]);
if(cleaned.length()>0){
ArrayList<String> ph = createPhonemes(lookupTable, cleaned);
phonemeEntries.addAll(ph);
phonemeEntries.add("_ 5");
}
}
}
//Output the results to file
for(String entry:phonemeEntries){
phonemeWrt.println(entry);
}
System.out.println("Phoneme File Created");
phonemeWrt.close();
lookupRdr.close();
txtRdr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| gpl-2.0 |
Joniras/Tatue-Organiser | Code/Android-Project/Tatue-Rater2/app/src/main/java/com/htl_villach/tatue_rater/Classes/Rechteck.java | 273 | package com.htl_villach.tatue_rater.Classes;
/**
* Created by simon on 10.03.2016.
*/
public class Rechteck {
public Punkt a;
public Punkt b;
public Rechteck() {
}
public Rechteck(Punkt a, Punkt b) {
this.a = a;
this.b = b;
}
}
| gpl-2.0 |