repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest20802.java
2533
/** * 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 Nick Sanidas <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("/BenchmarkTest20802") public class BenchmarkTest20802 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 { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request ); String param = scr.getTheValue("foo"); String bar = doSomething(param); String a1 = ""; String a2 = ""; String osName = System.getProperty("os.name"); if (osName.indexOf("Windows") != -1) { a1 = "cmd.exe"; a2 = "/c"; } else { a1 = "sh"; a2 = "-c"; } String[] args = {a1, a2, "echo"}; String[] argsEnv = { bar }; Runtime r = Runtime.getRuntime(); try { Process p = r.exec(args, argsEnv); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p); } catch (IOException e) { System.out.println("Problem executing cmdi - TestCase"); throw new ServletException(e); } } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param); return bar; } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest19342.java
2112
/** * 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 Nick Sanidas <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("/BenchmarkTest19342") public class BenchmarkTest19342 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[] values = request.getParameterValues("foo"); String param; if (values.length != 0) param = request.getParameterValues("foo")[0]; else param = null; String bar = doSomething(param); Object[] obj = { "a", bar }; response.getWriter().format("notfoo",obj); } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar; // Simple if statement that assigns param to bar on true condition int i = 196; if ( (500/42) + i > 200 ) bar = param; else bar = "This should never happen"; return bar; } }
gpl-2.0
santanche/java2learn
src/java/src/pt/c02oo/s05encapsulamento/s11bastiao/Bastiao.java
1630
package pt.c02oo.s05encapsulamento.s11bastiao; public class Bastiao { private int idade; private String estado; private String nome; public Bastiao(int idade, String estado, String nome) { this.idade = idade; this.estado = estado; this.nome = nome; } public void aparece() { // cabeleira if (idade >= 2) System.out.println(" *"); // corpo com olhos if (estado.equalsIgnoreCase("acordado")) System.out.println(" o*o"); else System.out.println(" -*-"); // barba if (idade >= 3) System.out.println("*****"); System.out.println(nome); System.out.println(); } public void cresce() { if (idade < 3) idade++; aparece(); } public void acorda() { estado = "acordado"; aparece(); } public void dorme() { estado = "dormindo"; aparece(); } public int getIdade() { return idade; } public void setIdade(int idade) { if (idade <= 3) this.idade = idade; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } }
gpl-2.0
mviitanen/marsmod
mcp/src/minecraft/net/minecraft/item/ItemPotion.java
15598
package net.minecraft.item; import com.google.common.collect.HashMultimap; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.IAttribute; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityPotion; import net.minecraft.init.Items; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.potion.PotionHelper; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IIcon; import net.minecraft.util.StatCollector; import net.minecraft.world.World; public class ItemPotion extends Item { /** * Contains a map from integers to the list of potion effects that potions with that damage value confer (to prevent * recalculating it). */ private HashMap effectCache = new HashMap(); private static final Map field_77835_b = new LinkedHashMap(); private IIcon field_94591_c; private IIcon field_94590_d; private IIcon field_94592_ct; private static final String __OBFID = "CL_00000055"; public ItemPotion() { this.setMaxStackSize(1); this.setHasSubtypes(true); this.setMaxDamage(0); this.setCreativeTab(CreativeTabs.tabBrewing); } /** * Returns a list of potion effects for the specified itemstack. */ public List getEffects(ItemStack p_77832_1_) { if (p_77832_1_.hasTagCompound() && p_77832_1_.getTagCompound().func_150297_b("CustomPotionEffects", 9)) { ArrayList var7 = new ArrayList(); NBTTagList var3 = p_77832_1_.getTagCompound().getTagList("CustomPotionEffects", 10); for (int var4 = 0; var4 < var3.tagCount(); ++var4) { NBTTagCompound var5 = var3.getCompoundTagAt(var4); PotionEffect var6 = PotionEffect.readCustomPotionEffectFromNBT(var5); if (var6 != null) { var7.add(var6); } } return var7; } else { List var2 = (List)this.effectCache.get(Integer.valueOf(p_77832_1_.getItemDamage())); if (var2 == null) { var2 = PotionHelper.getPotionEffects(p_77832_1_.getItemDamage(), false); this.effectCache.put(Integer.valueOf(p_77832_1_.getItemDamage()), var2); } return var2; } } /** * Returns a list of effects for the specified potion damage value. */ public List getEffects(int p_77834_1_) { List var2 = (List)this.effectCache.get(Integer.valueOf(p_77834_1_)); if (var2 == null) { var2 = PotionHelper.getPotionEffects(p_77834_1_, false); this.effectCache.put(Integer.valueOf(p_77834_1_), var2); } return var2; } public ItemStack onEaten(ItemStack p_77654_1_, World p_77654_2_, EntityPlayer p_77654_3_) { if (!p_77654_3_.capabilities.isCreativeMode) { --p_77654_1_.stackSize; } if (!p_77654_2_.isClient) { List var4 = this.getEffects(p_77654_1_); if (var4 != null) { Iterator var5 = var4.iterator(); while (var5.hasNext()) { PotionEffect var6 = (PotionEffect)var5.next(); p_77654_3_.addPotionEffect(new PotionEffect(var6)); } } } if (!p_77654_3_.capabilities.isCreativeMode) { if (p_77654_1_.stackSize <= 0) { return new ItemStack(Items.glass_bottle); } p_77654_3_.inventory.addItemStackToInventory(new ItemStack(Items.glass_bottle)); } return p_77654_1_; } /** * How long it takes to use or consume an item */ public int getMaxItemUseDuration(ItemStack p_77626_1_) { return 32; } /** * returns the action that specifies what animation to play when the items is being used */ public EnumAction getItemUseAction(ItemStack p_77661_1_) { return EnumAction.drink; } /** * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack p_77659_1_, World p_77659_2_, EntityPlayer p_77659_3_) { if (isSplash(p_77659_1_.getItemDamage())) { if (!p_77659_3_.capabilities.isCreativeMode) { --p_77659_1_.stackSize; } p_77659_2_.playSoundAtEntity(p_77659_3_, "random.bow", 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F)); if (!p_77659_2_.isClient) { p_77659_2_.spawnEntityInWorld(new EntityPotion(p_77659_2_, p_77659_3_, p_77659_1_)); } return p_77659_1_; } else { p_77659_3_.setItemInUse(p_77659_1_, this.getMaxItemUseDuration(p_77659_1_)); return p_77659_1_; } } /** * Callback for item usage. If the item does something special on right clicking, he will have one of those. Return * True if something happen and false if it don't. This is for ITEMS, not BLOCKS */ public boolean onItemUse(ItemStack p_77648_1_, EntityPlayer p_77648_2_, World p_77648_3_, int p_77648_4_, int p_77648_5_, int p_77648_6_, int p_77648_7_, float p_77648_8_, float p_77648_9_, float p_77648_10_) { return false; } /** * Gets an icon index based on an item's damage value */ public IIcon getIconFromDamage(int p_77617_1_) { return isSplash(p_77617_1_) ? this.field_94591_c : this.field_94590_d; } /** * Gets an icon index based on an item's damage value and the given render pass */ public IIcon getIconFromDamageForRenderPass(int p_77618_1_, int p_77618_2_) { return p_77618_2_ == 0 ? this.field_94592_ct : super.getIconFromDamageForRenderPass(p_77618_1_, p_77618_2_); } /** * returns wether or not a potion is a throwable splash potion based on damage value */ public static boolean isSplash(int p_77831_0_) { return (p_77831_0_ & 16384) != 0; } public int getColorFromDamage(int p_77620_1_) { return PotionHelper.func_77915_a(p_77620_1_, false); } public int getColorFromItemStack(ItemStack p_82790_1_, int p_82790_2_) { return p_82790_2_ > 0 ? 16777215 : this.getColorFromDamage(p_82790_1_.getItemDamage()); } public boolean requiresMultipleRenderPasses() { return true; } public boolean isEffectInstant(int p_77833_1_) { List var2 = this.getEffects(p_77833_1_); if (var2 != null && !var2.isEmpty()) { Iterator var3 = var2.iterator(); PotionEffect var4; do { if (!var3.hasNext()) { return false; } var4 = (PotionEffect)var3.next(); } while (!Potion.potionTypes[var4.getPotionID()].isInstant()); return true; } else { return false; } } public String getItemStackDisplayName(ItemStack p_77653_1_) { if (p_77653_1_.getItemDamage() == 0) { return StatCollector.translateToLocal("item.emptyPotion.name").trim(); } else { String var2 = ""; if (isSplash(p_77653_1_.getItemDamage())) { var2 = StatCollector.translateToLocal("potion.prefix.grenade").trim() + " "; } List var3 = Items.potionitem.getEffects(p_77653_1_); String var4; if (var3 != null && !var3.isEmpty()) { var4 = ((PotionEffect)var3.get(0)).getEffectName(); var4 = var4 + ".postfix"; return var2 + StatCollector.translateToLocal(var4).trim(); } else { var4 = PotionHelper.func_77905_c(p_77653_1_.getItemDamage()); return StatCollector.translateToLocal(var4).trim() + " " + super.getItemStackDisplayName(p_77653_1_); } } } /** * allows items to add custom lines of information to the mouseover description */ public void addInformation(ItemStack p_77624_1_, EntityPlayer p_77624_2_, List p_77624_3_, boolean p_77624_4_) { if (p_77624_1_.getItemDamage() != 0) { List var5 = Items.potionitem.getEffects(p_77624_1_); HashMultimap var6 = HashMultimap.create(); Iterator var16; if (var5 != null && !var5.isEmpty()) { var16 = var5.iterator(); while (var16.hasNext()) { PotionEffect var8 = (PotionEffect)var16.next(); String var9 = StatCollector.translateToLocal(var8.getEffectName()).trim(); Potion var10 = Potion.potionTypes[var8.getPotionID()]; Map var11 = var10.func_111186_k(); if (var11 != null && var11.size() > 0) { Iterator var12 = var11.entrySet().iterator(); while (var12.hasNext()) { Entry var13 = (Entry)var12.next(); AttributeModifier var14 = (AttributeModifier)var13.getValue(); AttributeModifier var15 = new AttributeModifier(var14.getName(), var10.func_111183_a(var8.getAmplifier(), var14), var14.getOperation()); var6.put(((IAttribute)var13.getKey()).getAttributeUnlocalizedName(), var15); } } if (var8.getAmplifier() > 0) { var9 = var9 + " " + StatCollector.translateToLocal("potion.potency." + var8.getAmplifier()).trim(); } if (var8.getDuration() > 20) { var9 = var9 + " (" + Potion.getDurationString(var8) + ")"; } if (var10.isBadEffect()) { p_77624_3_.add(EnumChatFormatting.RED + var9); } else { p_77624_3_.add(EnumChatFormatting.GRAY + var9); } } } else { String var7 = StatCollector.translateToLocal("potion.empty").trim(); p_77624_3_.add(EnumChatFormatting.GRAY + var7); } if (!var6.isEmpty()) { p_77624_3_.add(""); p_77624_3_.add(EnumChatFormatting.DARK_PURPLE + StatCollector.translateToLocal("potion.effects.whenDrank")); var16 = var6.entries().iterator(); while (var16.hasNext()) { Entry var17 = (Entry)var16.next(); AttributeModifier var18 = (AttributeModifier)var17.getValue(); double var19 = var18.getAmount(); double var20; if (var18.getOperation() != 1 && var18.getOperation() != 2) { var20 = var18.getAmount(); } else { var20 = var18.getAmount() * 100.0D; } if (var19 > 0.0D) { p_77624_3_.add(EnumChatFormatting.BLUE + StatCollector.translateToLocalFormatted("attribute.modifier.plus." + var18.getOperation(), new Object[] {ItemStack.field_111284_a.format(var20), StatCollector.translateToLocal("attribute.name." + (String)var17.getKey())})); } else if (var19 < 0.0D) { var20 *= -1.0D; p_77624_3_.add(EnumChatFormatting.RED + StatCollector.translateToLocalFormatted("attribute.modifier.take." + var18.getOperation(), new Object[] {ItemStack.field_111284_a.format(var20), StatCollector.translateToLocal("attribute.name." + (String)var17.getKey())})); } } } } } public boolean hasEffect(ItemStack p_77636_1_) { List var2 = this.getEffects(p_77636_1_); return var2 != null && !var2.isEmpty(); } /** * This returns the sub items */ public void getSubItems(Item p_150895_1_, CreativeTabs p_150895_2_, List p_150895_3_) { super.getSubItems(p_150895_1_, p_150895_2_, p_150895_3_); int var5; if (field_77835_b.isEmpty()) { for (int var4 = 0; var4 <= 15; ++var4) { for (var5 = 0; var5 <= 1; ++var5) { int var6; if (var5 == 0) { var6 = var4 | 8192; } else { var6 = var4 | 16384; } for (int var7 = 0; var7 <= 2; ++var7) { int var8 = var6; if (var7 != 0) { if (var7 == 1) { var8 = var6 | 32; } else if (var7 == 2) { var8 = var6 | 64; } } List var9 = PotionHelper.getPotionEffects(var8, false); if (var9 != null && !var9.isEmpty()) { field_77835_b.put(var9, Integer.valueOf(var8)); } } } } } Iterator var10 = field_77835_b.values().iterator(); while (var10.hasNext()) { var5 = ((Integer)var10.next()).intValue(); p_150895_3_.add(new ItemStack(p_150895_1_, 1, var5)); } } public void registerIcons(IIconRegister p_94581_1_) { this.field_94590_d = p_94581_1_.registerIcon(this.getIconString() + "_" + "bottle_drinkable"); this.field_94591_c = p_94581_1_.registerIcon(this.getIconString() + "_" + "bottle_splash"); this.field_94592_ct = p_94581_1_.registerIcon(this.getIconString() + "_" + "overlay"); } public static IIcon func_94589_d(String p_94589_0_) { return p_94589_0_.equals("bottle_drinkable") ? Items.potionitem.field_94590_d : (p_94589_0_.equals("bottle_splash") ? Items.potionitem.field_94591_c : (p_94589_0_.equals("overlay") ? Items.potionitem.field_94592_ct : null)); } }
gpl-2.0
DigDream/Ta-s-book-Android
src/com/digdream/tasbook/ui/RegisterActivity.java
9917
package com.digdream.tasbook.ui; import org.apache.http.Header; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.digdream.tasbook.R; import com.digdream.tasbook.data.UserPreferences; import com.digdream.tasbook.util.URLProtocol; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class RegisterActivity extends Activity { // Ìîд´Ó¶ÌÐÅSDKÓ¦Óúǫ́ע²áµÃµ½µÄAPPKEY private static String APPKEY = "32d36d1083b0"; // Ìîд´Ó¶ÌÐÅSDKÓ¦Óúǫ́ע²áµÃµ½µÄAPPSECRET private static String APPSECRET = "c886be90f4d031c4d21bdc796fd458a1"; // ¶ÌÐÅ×¢²á£¬Ëæ»ú²úÉúÍ·Ïñ private static final String[] AVATARS = { "http://tupian.qqjay.com/u/2011/0729/e755c434c91fed9f6f73152731788cb3.jpg", "http://99touxiang.com/public/upload/nvsheng/125/27-011820_433.jpg", "http://img1.touxiang.cn/uploads/allimg/111029/2330264224-36.png", "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339485237265.jpg", "http://diy.qqjay.com/u/files/2012/0523/f466c38e1c6c99ee2d6cd7746207a97a.jpg", "http://img1.touxiang.cn/uploads/20121224/24-054837_708.jpg", "http://img1.touxiang.cn/uploads/20121212/12-060125_658.jpg", "http://img1.touxiang.cn/uploads/20130608/08-054059_703.jpg", "http://diy.qqjay.com/u2/2013/0422/fadc08459b1ef5fc1ea6b5b8d22e44b4.jpg", "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339510584349.jpg", "http://img1.touxiang.cn/uploads/20130515/15-080722_514.jpg", "http://diy.qqjay.com/u2/2013/0401/4355c29b30d295b26da6f242a65bcaad.jpg" }; private boolean ready; private Dialog pd; private TextView tvNum; private TextView mTitle; private EditText mFullName; private EditText mPhone; private EditText mPassword; private EditText mConfirmPwd; private ImageView mBtnBack; private String sName; private String sPassword; private String sPhone; private Button mBtnRegister; public static Handler mhandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_register); findViewsById(); initView(); } /** * Toast * * @param resId */ public void ShowToast(final int resId) { runOnUiThread(new Runnable() { private Toast mToast; @Override public void run() { if (mToast == null) { mToast = Toast.makeText( RegisterActivity.this.getApplicationContext(), resId, Toast.LENGTH_LONG); } else { mToast.setText(resId); } mToast.show(); } }); } private void register() { sName = mFullName.getText().toString(); sPassword = mPassword.getText().toString(); String sConfirmPassword = mConfirmPwd.getText().toString(); sPhone = mPhone.getText().toString(); if (TextUtils.isEmpty(sName)) { ShowToast(R.string.toast_error_username_null); return; } if (TextUtils.isEmpty(sPassword)) { ShowToast(R.string.toast_error_password_null); return; } if (TextUtils.isEmpty(sPhone)) { ShowToast(R.string.toast_error_phone_null); return; } if (TextUtils.isEmpty(sConfirmPassword)) { ShowToast(R.string.toast_error_password_error); return; } if (TextUtils.equals(sPassword.trim(), sConfirmPassword.trim()) == false) { ShowToast(R.string.toast_error_password_error); return; } /* * mhandler = new Handler() { * * * (non-Javadoc) * * @see android.os.Handler#handleMessage(android.os.Message) * * @Override public void handleMessage(Message msg) { if (msg.what == * URLProtocol.CMD_REGISTER) { Bundle bundle = msg.getData(); int code = * bundle.getInt("code"); switch (code) { // ´¦Àí·µ»Ø×¢²á³É¹¦µÄÐÅÏ¢¡£×¢²á³É¹¦toast£¬Ìø×ª¡£ * case URLProtocol.ERROR_SIGNUP_SUCCESS: * ShowToast(R.string.toast_success_sign_up); Intent intent = new * Intent(); * * intent.setClass(RegisterActivity.this, MainTabActivity.class); * * startActivity(intent); finish(); break; case * URLProtocol.ERROR_SIGNUP_NAME_REPEAT: new * AlertDialog.Builder(RegisterActivity.this) .setTitle("×¢²áʧ°Ü") * .setMessage("Óû§ÃûÒÑ´æÔÚ£¬Çë¸ü»»Óû§Ãû") .setPositiveButton("È·¶¨", null) .show(); * break; case URLProtocol.ERROR_SIGNUP_PHONE_REPEAT: new * AlertDialog.Builder(RegisterActivity.this) .setTitle("×¢²áʧ°Ü") * .setMessage("ÊÖ»úºÅÒÑ´æÔÚ£¬Çë¸ü»»ÊÖ»úºÅ") .setPositiveButton("È·¶¨", null) .show(); * break; case URLProtocol.ERROR_SIGNUP_DATABASE_FALSE: new * AlertDialog.Builder(RegisterActivity.this) .setTitle("×¢²áʧ°Ü") * .setMessage("Êý¾Ý¿â²Ù×÷ʧ°Ü") .setPositiveButton("È·¶¨", null) .show(); break; * default: * * } } } }; */ RegisterByAsyncHttpClientPost(sName, sPassword, sPhone); } private void initView() { mTitle.setText("×¢²á"); mBtnBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); mBtnRegister.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { register(); } }); } private void findViewsById() { mTitle = (TextView) findViewById(R.id.title); mFullName = (EditText) findViewById(R.id.signup_fullname_edittext); mPhone = (EditText) findViewById(R.id.signup_phone_edittext); mConfirmPwd = (EditText) findViewById(R.id.signup_password_confirm_edittext); mPassword = (EditText) findViewById(R.id.signup_password_edittext); mBtnBack = (ImageView) findViewById(R.id.btn_action_bar_left); mBtnRegister = (Button) findViewById(R.id.signup_signup_button); } /** * ²ÉÓÃAsyncHttpClientµÄPost·½Ê½½øÐÐʵÏÖ * * @param userName * @param userPass * @param phone */ public void RegisterByAsyncHttpClientPost(String userName, String userPass, String phone) { AsyncHttpClient client = new AsyncHttpClient(); // ´´½¨Òì²½ÇëÇóµÄ¿Í»§¶Ë¶ÔÏó // ´´½¨ÇëÇó²ÎÊýµÄ·â×°µÄ¶ÔÏó RequestParams params = new RequestParams(); params.put("user_name", userName); // ÉèÖÃÇëÇóµÄ²ÎÊýÃûºÍ²ÎÊýÖµ params.put("user_pass", userPass);// ÉèÖÃÇëÇóµÄ²ÎÊýÃûºÍ²ÎÊý params.put("phone", phone); // Ö´ÐÐpost·½·¨ client.post(URLProtocol.ROOT, params, new AsyncHttpResponseHandler() { private String json; /** * ³É¹¦´¦ÀíµÄ·½·¨ statusCode:ÏìÓ¦µÄ״̬Âë; headers:ÏàÓ¦µÄÍ·ÐÅÏ¢ ±ÈÈç ÏìÓ¦µÄʱ¼ä£¬ÏìÓ¦µÄ·þÎñÆ÷ ; * responseBody:ÏìÓ¦ÄÚÈݵÄ×Ö½Ú */ @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { if (statusCode == 200) { /* * UserPreferences preferences = new UserPreferences(); * preferences.init(LoginActivity.this); * preferences.saveName(name); * preferences.savePWD(password); // preferencesÉèÖÃ×Ô¶¯µÇ¼¡£¡£ * preferences.setAutoLogin(true); * * ShowToast(R.string.login_success); Intent intent = new * Intent(); intent.setClass(LoginActivity.this, * ListViewActivity.class); startActivity(intent); finish(); */ json = new String(responseBody); Log.i("tasbook", json); json.replaceAll("(\r\n|\r|\n|\n\r)", " "); try { JSONObject jsonobject = new JSONObject(json); int code = jsonobject.getInt("code"); switch (code) { case URLProtocol.SUCCESS: ShowToast(R.string.toast_success_sign_up); Intent intent = new Intent(); // JSONArray addrArrays = jsonobject // .getJSONArray("result"); /* * for (int i = 0; i < addrArrays.length(); i++) { * JSONObject addrJsonObj = addrArrays * .getJSONObject(i); */ JSONObject jsonresult = jsonobject.getJSONObject("result"); String uid = jsonresult.getString("uid"); String username = jsonresult.getString("username"); UserPreferences preferences = new UserPreferences(); preferences.init(RegisterActivity.this); preferences.saveName(username); preferences.saveUID(uid); intent.setClass(RegisterActivity.this, MainTabActivity.class); startActivity(intent); finish(); break; case URLProtocol.FALSE: int errorcode = jsonobject.getInt("errorcode"); switch (errorcode) { case URLProtocol.ERROR_SIGNUP_NAME_REPEAT: new AlertDialog.Builder(RegisterActivity.this) .setTitle("×¢²áʧ°Ü") .setMessage("Óû§ÃûÒÑ´æÔÚ£¬Çë¸ü»»Óû§Ãû") .setPositiveButton("È·¶¨", null).show(); case URLProtocol.ERROR_SIGNUP_PHONE_REPEAT: new AlertDialog.Builder(RegisterActivity.this) .setTitle("×¢²áʧ°Ü") .setMessage("ÊÖ»úºÅÒÑ´æÔÚ£¬Çë¸ü»»ÊÖ»úºÅ") .setPositiveButton("È·¶¨", null).show(); break; case URLProtocol.ERROR_SIGNUP_DATABASE_FALSE: new AlertDialog.Builder(RegisterActivity.this) .setTitle("×¢²áʧ°Ü").setMessage("Êý¾Ý¿â²Ù×÷ʧ°Ü") .setPositiveButton("È·¶¨", null).show(); break; } break; default: } } catch (JSONException e) { e.printStackTrace(); } } else { ShowToast(R.string.toast_error_signup); } } /** * ʧ°Ü´¦ÀíµÄ·½·¨ error£ºÏìӦʧ°ÜµÄ´íÎóÐÅÏ¢·â×°µ½Õâ¸öÒì³£¶ÔÏóÖÐ */ @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { ShowToast(R.string.network_not_connected); error.printStackTrace();// °Ñ´íÎóÐÅÏ¢´òÓ¡³ö¹ì¼£À´ } }); } }
gpl-2.0
teabo/wholly-framework
wholly-commons/src/main/java/com/whollyframework/authentications/IUserExtend.java
105
package com.whollyframework.authentications; public interface IUserExtend extends IValueObject{ }
gpl-2.0
lumag/JBookReader
src/org/jbookreader/formatengine/IRenderingObject.java
1737
/* * JBookReader - Java FictionBook Reader * Copyright (C) 2006 Dmitry Baryshkov * * 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 org.jbookreader.formatengine; import org.jbookreader.book.bom.INode; /** * This interface represents a rendering object. * * @author Dmitry Baryshkov (dbaryshkov@gmail.com) * */ public interface IRenderingObject { /** * Returns the total height of the object. * @return the total height of the object. */ double getHeight(); /** * Returns the width of the object. * @return the width of the object. */ double getWidth(); /** * Renders the object to assigned * {@link org.jbookreader.formatengine.IBookPainter}. * */ void render(); /** * Returns the node which this rendering object represents. * @return the node which this rendering object represents. */ INode getNode(); void setMarginTop(double margin); void setMarginRight(double margin); void setMarginBottom(double margin); void setMarginLeft(double margin); boolean isSplittable(); }
gpl-2.0
Bradfromthepiggery/feedulator
server/src/Http.java
3286
public final class Http { public static final String CRLF = "\r\n"; public static final String HTTP = "HTTP"; public static final String PROTOCOL_DELIMITER = "/"; public static final String ACCEPT_RANGES = "Accept-Ranges"; public static final String AGE = "Age"; public static final String ALLOW = "Allow"; public static final String CACHE_CONTROL = "Cache-Control"; public static final String CONTENT_ENCODING = "Content-Encoding"; public static final String CONTENT_LANGUAGE = "Content-Language"; public static final String CONTENT_LENGTH = "Content-Length"; public static final String CONTENT_LOCATION = "Content-Location"; public static final String CONTENT_DISPOSITION = "Content-Disposition"; public static final String CONTENT_MD5 = "Content-MD5"; public static final String CONTENT_RANGE = "Content-Range"; public static final String CONTENT_TYPE = "Content-Type"; public static final String DATE = "Date"; public static final String ETAG = "ETag"; public static final String EXPIRES = "Expires"; public static final String LAST_MODIFIED = "Last-Modified"; public static final String LOCATION = "Location"; public static final String PRAGMA = "Pragma"; public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; public static final String REFRESH = "Refresh"; public static final String RETRY_AFTER = "Retry-After"; public static final String SERVER = "Server"; public static final String SET_COOKIE = "Set-Cookie"; public static final String TRAILER = "Trailer"; public static final String TRANSFER_ENCODING = "Transfer-Encoding"; public static final String VARY = "Vary"; public static final String VIA = "Via"; public static final String WARNING = "Warning"; public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; public static final String ACCEPT = "Accept"; public static final String ACCEPT_CHARSET = "Accept-Charset"; public static final String ACCEPT_ENCODING = "Accept-Encoding"; public static final String ACCEPT_LANGUAGE = "Accept-Language"; public static final String AUTHORIZATION = "Authorization"; public static final String CONNECTION = "Connection"; public static final String COOKIE = "Cookie"; public static final String EXPECT = "Expect"; public static final String FROM = "From"; public static final String HOST = "Host"; public static final String IF_MATCH = "If-Match"; public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; public static final String IF_NONE_MATCH = "If-None-Match"; public static final String IF_RANGE = "If-Range"; public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; public static final String MAX_FORWARDS = "Max-Forwards"; public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; public static final String RANGE = "Range"; public static final String REFERER = "Referer"; public static final String TE = "TE"; public static final String UPGRADE = "Upgrade"; public static final String USER_AGENT = "User-Agent"; public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; public static final String ACCESS_CONTROL_REQUEST_HEADER = "Access-Control-Request-Headers"; private Http() { // no instances... } }
gpl-2.0
biblelamp/JavaExercises
JavaRushTasks/1.JavaSyntax/src/com/javarush/task/task08/task0822/Solution.java
986
package com.javarush.task.task08.task0822; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; /* Минимальное из N чисел */ public class Solution { public static void main(String[] args) throws Exception { List<Integer> integerList = getIntegerList(); System.out.println(getMinimum(integerList)); } public static int getMinimum(List<Integer> array) { return Collections.min(array); } public static List<Integer> getIntegerList() throws IOException { List<Integer> list = new ArrayList<Integer>(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); for (int i = 0; i < n; i++) list.add(Integer.parseInt(reader.readLine())); return list; } }
gpl-2.0
klst-com/metasfresh
de.metas.dlm/base/src/main/java/de/metas/dlm/exception/DLMReferenceExceptionWrapper.java
6218
package de.metas.dlm.exception; import java.sql.SQLException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.adempiere.ad.table.api.IADTableDAO; import org.adempiere.exceptions.DBException; import org.adempiere.util.Check; import org.adempiere.util.Services; import org.adempiere.util.exceptions.IExceptionWrapper; import org.compiere.model.I_AD_Column; import org.compiere.model.I_AD_Table; import org.postgresql.util.PSQLException; import org.postgresql.util.ServerErrorMessage; import com.google.common.annotations.VisibleForTesting; import de.metas.dlm.partitioner.config.TableReferenceDescriptor; /* * #%L * metasfresh-dlm * %% * Copyright (C) 2016 metas GmbH * %% * 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, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ /** * Augments {@link DBException}. With this instance being registered, {@link DBException} can wrap an {@link SQLException} into a {@link DLMReferenceException}<br> * Registered via {@link DBException#registerExceptionWrapper(IExceptionWrapper)} * * the "DETAIL" from an error message from the database looks like this: * * * DLM_Referenced_Table_Name = c_payment_tbl; DLM_Referencing_Table_Name = c_bankstatementline_ref; DLM_Referencig_Column_Name = c_payment_id; * * * @author metas-dev <dev@metasfresh.com> * */ public class DLMReferenceExceptionWrapper implements IExceptionWrapper<DBException> { /** * metasfresh-custom error code. */ @VisibleForTesting static final String PG_SQLSTATE_Referencing_Record_Has_Wrong_DLM_Level = "235D3"; /** * metasfresh-custom error code. */ @VisibleForTesting static final String PG_SQLSTATE_Referencing_Table_Has_No_DLM_LEvel = "235N3"; /** * This pattern is used to parse the postgresql error message. some notes: * <li>we try to be tolerant with minor variations in the string, as long as the important parts are still correct. * <li>for the two groups of <code>([a-zA-Z0-9_]+?)(_tbl)?</code>, and an input of either <code>c_payment</code> or <code>c_payment_tbl</code>, the first group always matches <code>c_payment</code>.<br> * This is what we want, because we are not interested in the <code>_tbl</code> prefix.<br> * It works because the first group is "reluctant" and the second one is "greedy". */ private static final Pattern DETAIL_REGEXP = Pattern.compile("[;, ]*DLM_Referenced_Table_Name *= *([a-zA-Z0-9_]+?)(_tbl)?[;, ]+DLM_Referenced_Record_ID *= *([0-9]+?)[;, ]+DLM_Referencing_Table_Name *= *([a-zA-Z0-9_]+?)(_tbl)?[;, ]+DLM_Referencig_Column_Name *= *([a-zA-Z0-9_]+?)(_tbl)?[;, ]*", Pattern.CASE_INSENSITIVE); public static DLMReferenceExceptionWrapper INSTANCE = new DLMReferenceExceptionWrapper(); private DLMReferenceExceptionWrapper() { } @Override public DBException wrapIfNeededOrReturnNull(final Throwable t) { final Boolean referencingTableHasDLMLevel; if (DBException.isSQLState(t, PG_SQLSTATE_Referencing_Record_Has_Wrong_DLM_Level)) { referencingTableHasDLMLevel = true; } else if (DBException.isSQLState(t, PG_SQLSTATE_Referencing_Table_Has_No_DLM_LEvel)) { referencingTableHasDLMLevel = false; } else { return null; } // // parse the exception detail and extract the infos final SQLException sqlException = DBException.extractSQLExceptionOrNull(t); Check.errorUnless(sqlException instanceof PSQLException, "exception={} needs to be a PSQLExcetion", sqlException); final PSQLException psqlException = (PSQLException)sqlException; final ServerErrorMessage serverErrorMessage = psqlException.getServerErrorMessage(); Check.errorIf(serverErrorMessage == null, "ServerErrorMessage of PSQLException={} may not be null", psqlException); final String detail = serverErrorMessage.getDetail(); Check.errorIf(Check.isEmpty(detail, true), "DETAIL ServerErrorMessage={} from of PSQLException={} may not be null", serverErrorMessage, psqlException); final String[] infos = extractInfos(detail); // // the the "real" tables and column from the extracted lowercase infos final IADTableDAO adTableDAO = Services.get(IADTableDAO.class); final I_AD_Table referencedTable = adTableDAO.retrieveTable(infos[0]); Check.errorIf(referencedTable == null, "Unable to retrieve an AD_Table for referencedTable name={}", infos[0]); final I_AD_Table referencingTable = adTableDAO.retrieveTable(infos[2]); Check.errorIf(referencingTable == null, "Unable to retrieve an AD_Table for referencingTable name={}", infos[2]); final I_AD_Column referencingColumn = adTableDAO.retrieveColumn(referencingTable.getTableName(), infos[3]); Check.errorIf(referencingTable == null, "Unable to retrieve an AD_Column for referencingTable name={} and referencingColumn name={}", infos[2], infos[3]); return new DLMReferenceException(t, TableReferenceDescriptor.of( referencingTable.getTableName(), referencingColumn.getColumnName(), referencedTable.getTableName(), Integer.parseInt(infos[1])), referencingTableHasDLMLevel); } @VisibleForTesting static String[] extractInfos(final String detail) { final Matcher matcher = DETAIL_REGEXP.matcher(detail); final boolean matches = matcher.matches(); Check.errorUnless(matches, "given string={} does not match our regexp={}", detail, DETAIL_REGEXP); final String referencedTableName = matcher.group(1); final String referencedRecordId = matcher.group(3); final String referencingTableName = matcher.group(4); final String referencingColumnName = matcher.group(6); return new String[] { referencedTableName, referencedRecordId, referencingTableName, referencingColumnName }; } }
gpl-2.0
camposer/curso_xp
calculadora/src/main/java/com/example/calculadora/exception/NaturalInvalidoException.java
392
package com.example.calculadora.exception; public class NaturalInvalidoException extends RuntimeException { private static final long serialVersionUID = -1579518490246527848L; private Object valor; public NaturalInvalidoException(Object valor) { this.valor = valor; } public Object getValor() { return valor; } public void setValor(Object valor) { this.valor = valor; } }
gpl-2.0
markosa/hydromon
src/main/java/net/hydromon/core/dto/util/DTOUtils.java
845
package net.hydromon.core.dto.util; import net.hydromon.core.dto.AddSensor; import net.hydromon.core.dto.SensorDTO; import net.hydromon.core.model.Sensor; import org.springframework.stereotype.Component; @Component public class DTOUtils { public Sensor convert(AddSensor addSensor) { Sensor sensor = new Sensor(); sensor.setDescription(addSensor.getDescription()); sensor.setName(addSensor.getName()); return sensor; } public SensorDTO convert(Sensor sensor) { SensorDTO sensorDTO = new SensorDTO(); sensorDTO.setDescription(sensor.getDescription()); sensorDTO.setName(sensor.getName()); sensorDTO.setLocation(sensor.getLocation()); sensorDTO.setType(sensor.getType()); sensorDTO.setChart(sensor.getChart()); sensorDTO.setId(sensor.getId()); sensorDTO.setUnit(sensor.getUnit()); return sensorDTO; } }
gpl-2.0
jensnerche/plantuml
src/net/sourceforge/plantuml/svek/image/EntityImageGroup.java
2453
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2014, Arnaud Roques * * Project Info: http://plantuml.sourceforge.net * * This file is part of PlantUML. * * PlantUML 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. * * PlantUML 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * Original Author: Arnaud Roques * * Revision $Revision: 5183 $ * */ package net.sourceforge.plantuml.svek.image; import java.awt.geom.Dimension2D; import net.sourceforge.plantuml.Dimension2DDouble; import net.sourceforge.plantuml.ISkinParam; import net.sourceforge.plantuml.cucadiagram.ILeaf; import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.svek.AbstractEntityImage; import net.sourceforge.plantuml.svek.ShapeType; import net.sourceforge.plantuml.ugraphic.UGraphic; public class EntityImageGroup extends AbstractEntityImage { // final private TextBlock desc; // final private static int MARGIN = 10; public EntityImageGroup(ILeaf entity, ISkinParam skinParam) { super(entity, skinParam); // this.desc = Display.create(StringUtils.getWithNewlines(entity.getDisplay()), new FontConfiguration( // getFont(FontParam.ACTIVITY), HtmlColorUtils.BLACK), HorizontalAlignment.CENTER); } public Dimension2D calculateDimension(StringBounder stringBounder) { return new Dimension2DDouble(30, 30); } final public void drawU(UGraphic ug) { } public ShapeType getShapeType() { return ShapeType.RECTANGLE; } public int getShield() { return 0; } }
gpl-2.0
lepakko683/CelestialWizardry
src/main/java/celestibytes/celestialwizardry/item/ItemSeasonRing.java
4323
package celestibytes.celestialwizardry.item; import celestibytes.celestialwizardry.reference.Names; import celestibytes.celestialwizardry.reference.Reference; import celestibytes.celestialwizardry.reference.Settings; import celestibytes.core.util.HolidayHelper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import cpw.mods.fml.common.Optional; import baubles.api.BaubleType; import baubles.api.IBauble; import baubles.common.container.InventoryBaubles; import baubles.common.lib.PlayerHandler; @Optional.Interface(modid = Reference.BAUBLES_ID, iface = Reference.BAUBLES_IFACE) public class ItemSeasonRing extends ItemSingle implements IBauble { private int count = 0; public ItemSeasonRing() { super(); this.setMaxStackSize(1); this.setUnlocalizedName(Names.Items.SEASON_RING); } @Override @Optional.Method(modid = Reference.BAUBLES_ID) public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { if (!world.isRemote) { InventoryBaubles baubles = PlayerHandler.getPlayerBaubles(player); for (int i = 0; i < baubles.getSizeInventory(); i++) { if (baubles.getStackInSlot(i) == null && baubles.isItemValidForSlot(i, stack)) { baubles.setInventorySlotContents(i, stack.copy()); if (!player.capabilities.isCreativeMode) { player.inventory .setInventorySlotContents(player.inventory.currentItem, null); } onEquipped(stack, player); break; } } } return stack; } /** * This method return the type of bauble this is. Type is used to determine the slots it can go into. * * @param itemstack */ @Override @Optional.Method(modid = Reference.BAUBLES_ID) public BaubleType getBaubleType(ItemStack itemstack) { return BaubleType.RING; } /** * This method is called once per tick if the bauble is being worn by a player * * @param itemstack * @param player */ @Override @Optional.Method(modid = Reference.BAUBLES_ID) public void onWornTick(ItemStack itemstack, EntityLivingBase player) { if (Settings.enableSeasonal && HolidayHelper.isBirthday()) { if (count >= 100) { player.worldObj.spawnEntityInWorld( new EntityItem(player.worldObj, player.posX, player.posY + 2, player.posZ, new ItemStack(Items.cake)) ); } count++; if (count >= 140) { count = 0; } } } /** * This method is called when the bauble is equipped by a player * * @param itemstack * @param player */ @Override @Optional.Method(modid = Reference.BAUBLES_ID) public void onEquipped(ItemStack itemstack, EntityLivingBase player) { } /** * This method is called when the bauble is unequipped by a player * * @param itemstack * @param player */ @Override @Optional.Method(modid = Reference.BAUBLES_ID) public void onUnequipped(ItemStack itemstack, EntityLivingBase player) { } /** * can this bauble be placed in a bauble slot * * @param itemstack * @param player */ @Override @Optional.Method(modid = Reference.BAUBLES_ID) public boolean canEquip(ItemStack itemstack, EntityLivingBase player) { return true; } /** * Can this bauble be removed from a bauble slot * * @param itemstack * @param player */ @Override @Optional.Method(modid = Reference.BAUBLES_ID) public boolean canUnequip(ItemStack itemstack, EntityLivingBase player) { return !(Settings.enableSeasonal && HolidayHelper.isBirthday()); } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00514.java
2122
/** * 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 Nick Sanidas <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("/BenchmarkTest00514") public class BenchmarkTest00514 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 { javax.servlet.http.Cookie[] cookies = request.getCookies(); String param = null; boolean foundit = false; if (cookies != null) { for (javax.servlet.http.Cookie cookie : cookies) { if (cookie.getName().equals("foo")) { param = cookie.getValue(); foundit = true; } } if (!foundit) { // no cookie found in collection param = ""; } } else { // no cookies param = ""; } String bar = org.apache.commons.lang.StringEscapeUtils.escapeHtml(param); Object[] obj = { "a", bar }; response.getWriter().format(java.util.Locale.US,"notfoo",obj); } }
gpl-2.0
DanielliUrbieta/ProjetoHidraWS
src/org/eclipse/jgit/internal/storage/dfs/BeforeDfsPackIndexLoadedEvent.java
3033
/* * Copyright (C) 2012, 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.eclipse.jgit.internal.storage.dfs; import org.eclipse.jgit.events.RepositoryEvent; /** * Describes the {@link DfsPackFile} just before its index is loaded. Currently, * DfsPackFile directly dispatches the event on * {@link org.eclipse.jgit.lib.Repository#getGlobalListenerList}. Which means * the call to {@link #getRepository} will always return null. */ public class BeforeDfsPackIndexLoadedEvent extends RepositoryEvent<BeforeDfsPackIndexLoadedListener> { private final DfsPackFile pack; /** * A new event triggered before a PackFile index is loaded. * * @param pack * the pack */ public BeforeDfsPackIndexLoadedEvent(DfsPackFile pack) { this.pack = pack; } /** @return the PackFile containing the index that will be loaded. */ public DfsPackFile getPackFile() { return pack; } @Override public Class<BeforeDfsPackIndexLoadedListener> getListenerType() { return BeforeDfsPackIndexLoadedListener.class; } @Override public void dispatch(BeforeDfsPackIndexLoadedListener listener) { listener.onBeforeDfsPackIndexLoaded(this); } }
gpl-2.0
smarr/GraalCompiler
graal/com.oracle.graal.compiler.test/src/com/oracle/graal/compiler/test/IntegerEqualsCanonicalizerTest.java
4773
/* * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.compiler.test; import org.junit.Test; import com.oracle.graal.nodes.FrameState; import com.oracle.graal.nodes.StructuredGraph; import com.oracle.graal.nodes.StructuredGraph.AllowAssumptions; import com.oracle.graal.phases.common.CanonicalizerPhase; import com.oracle.graal.phases.tiers.PhaseContext; public class IntegerEqualsCanonicalizerTest extends GraalCompilerTest { @Test public void testShiftEquals() { /* * tests the canonicalization of (x >>> const) == 0 to x |test| (-1 << const) */ test("testShiftEqualsSnippet", "testShiftEqualsReference"); } @SuppressWarnings("unused") private static int field; public static void testShiftEqualsSnippet(int x, int[] array, int y) { // optimize field = (x >>> 10) == 0 ? 1 : 0; field = (array.length >> 10) == 0 ? 1 : 0; field = (x << 10) == 0 ? 1 : 0; // don't optimize field = (x >> 10) == 0 ? 1 : 0; field = (x >>> y) == 0 ? 1 : 0; field = (x >> y) == 0 ? 1 : 0; field = (x << y) == 0 ? 1 : 0; field = (x >>> y) == 1 ? 1 : 0; field = (x >> y) == 1 ? 1 : 0; field = (x << y) == 1 ? 1 : 0; } public static void testShiftEqualsReference(int x, int[] array, int y) { field = (x & 0xfffffc00) == 0 ? 1 : 0; field = (array.length & 0xfffffc00) == 0 ? 1 : 0; field = (x & 0x3fffff) == 0 ? 1 : 0; // don't optimize signed right shifts field = (x >> 10) == 0 ? 1 : 0; // don't optimize no-constant shift amounts field = (x >>> y) == 0 ? 1 : 0; field = (x >> y) == 0 ? 1 : 0; field = (x << y) == 0 ? 1 : 0; // don't optimize non-zero comparisons field = (x >>> y) == 1 ? 1 : 0; field = (x >> y) == 1 ? 1 : 0; field = (x << y) == 1 ? 1 : 0; } @Test public void testCompare() { test("testCompareSnippet", "testCompareReference"); } public static void testCompareSnippet(int x, int y, int[] array1, int[] array2) { int tempX = x; int array1Length = array1.length; int array2Length = array2.length; // optimize field = x == tempX ? 1 : 0; field = x != tempX ? 1 : 0; field = array1Length != (-1 - array2Length) ? 1 : 0; field = array1Length == (-1 - array2Length) ? 1 : 0; // don't optimize field = x == y ? 1 : 0; field = array1Length == array2Length ? 1 : 0; field = array1Length == (-array2Length) ? 1 : 0; } public static void testCompareReference(int x, int y, int[] array1, int[] array2) { int array1Length = array1.length; int array2Length = array2.length; // optimize field = 1; field = 0; field = 1; field = 0; // don't optimize (overlapping value ranges) field = x == y ? 1 : 0; field = array1Length == array2Length ? 1 : 0; field = array1Length == (-array2Length) ? 1 : 0; } private void test(String snippet, String referenceSnippet) { StructuredGraph graph = getCanonicalizedGraph(snippet); StructuredGraph referenceGraph = getCanonicalizedGraph(referenceSnippet); assertEquals(referenceGraph, graph); } private StructuredGraph getCanonicalizedGraph(String snippet) { StructuredGraph graph = parseEager(snippet, AllowAssumptions.YES); new CanonicalizerPhase().apply(graph, new PhaseContext(getProviders())); for (FrameState state : graph.getNodes(FrameState.TYPE).snapshot()) { state.replaceAtUsages(null); state.safeDelete(); } return graph; } }
gpl-2.0
jesus997/Simple-SignEdit
src/es/hol/iberians/MrJesus997/SE/Updater.java
29838
package es.hol.iberians.MrJesus997.SE; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.logging.Level; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; /** * Check for updates on BukkitDev for a given plugin, and download the updates if needed. * <p/> * <b>VERY, VERY IMPORTANT</b>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating. * <br> * It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config that prevents the auto-updater from running <b>AT ALL</b>. * <br> * If you fail to include this option in your config, your plugin will be <b>REJECTED</b> when you attempt to submit it to dev.bukkit.org. * <p/> * An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater. * <br> * If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l * * @author Gravity * @version 2.2 */ public class Updater { /* Constants */ // Remote file's title private static final String TITLE_VALUE = "name"; // Remote file's download link private static final String LINK_VALUE = "downloadUrl"; // Remote file's release type private static final String TYPE_VALUE = "releaseType"; // Remote file's build version private static final String VERSION_VALUE = "gameVersion"; // Path to GET private static final String QUERY = "/servermods/files?projectIds="; // Slugs will be appended to this to get to the project's RSS feed private static final String HOST = "https://api.curseforge.com"; // User-agent when querying Curse private static final String USER_AGENT = "Updater (by Gravity)"; // Used for locating version numbers in file names private static final String DELIMETER = "^v|[\\s_-]v"; // If the version number contains one of these, don't update. private static final String[] NO_UPDATE_TAG = { "-DEV", "-PRE", "-SNAPSHOT" }; // Used for downloading files private static final int BYTE_SIZE = 1024; // Config key for api key private static final String API_KEY_CONFIG_KEY = "api-key"; // Config key for disabling Updater private static final String DISABLE_CONFIG_KEY = "disable"; // Default api key value in config private static final String API_KEY_DEFAULT = "PUT_API_KEY_HERE"; // Default disable value in config private static final boolean DISABLE_DEFAULT = false; /* User-provided variables */ // Plugin running Updater private final Plugin plugin; // Type of update check to run private final UpdateType type; // Whether to announce file downloads private final boolean announce; // The plugin file (jar) private final File file; // The folder that downloads will be placed in private final File updateFolder; // The provided callback (if any) private final UpdateCallback callback; // Project's Curse ID private int id = -1; // BukkitDev ServerMods API key private String apiKey = null; /* Collected from Curse API */ private String versionName; private String versionLink; private String versionType; private String versionGameVersion; /* Update process variables */ // Connection to RSS private URL url; // Updater thread private Thread thread; // Used for determining the outcome of the update process private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; /** * Gives the developer the result of the update process. Can be obtained by called {@link #getResult()} */ public enum UpdateResult { /** * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. */ SUCCESS, /** * The updater did not find an update, and nothing was downloaded. */ NO_UPDATE, /** * The server administrator has disabled the updating system. */ DISABLED, /** * The updater found an update, but was unable to download it. */ FAIL_DOWNLOAD, /** * For some reason, the updater was unable to contact dev.bukkit.org to download the file. */ FAIL_DBO, /** * When running the version check, the file on DBO did not contain a recognizable version. */ FAIL_NOVERSION, /** * The id provided by the plugin running the updater was invalid and doesn't exist on DBO. */ FAIL_BADID, /** * The server administrator has improperly configured their API key in the configuration. */ FAIL_APIKEY, /** * The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded. */ UPDATE_AVAILABLE } /** * Allows the developer to specify the type of update that will be run. */ public enum UpdateType { /** * Run a version check, and then if the file is out of date, download the newest version. */ DEFAULT, /** * Don't run a version check, just find the latest update and download it. */ NO_VERSION_CHECK, /** * Get information about the version and the download size, but don't actually download anything. */ NO_DOWNLOAD } /** * Represents the various release types of a file on BukkitDev. */ public enum ReleaseType { /** * An "alpha" file. */ ALPHA, /** * A "beta" file. */ BETA, /** * A "release" file. */ RELEASE } /** * Initialize the updater. * * @param plugin The plugin that is checking for an update. * @param id The dev.bukkit.org id of the project. * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. * @param type Specify the type of update this will be. See {@link UpdateType} * @param announce True if the program should announce the progress of new updates in console. */ public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { this(plugin, id, file, type, null, announce); } /** * Initialize the updater with the provided callback. * * @param plugin The plugin that is checking for an update. * @param id The dev.bukkit.org id of the project. * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. * @param type Specify the type of update this will be. See {@link UpdateType} * @param callback The callback instance to notify when the Updater has finished */ public Updater(Plugin plugin, int id, File file, UpdateType type, UpdateCallback callback) { this(plugin, id, file, type, callback, false); } /** * Initialize the updater with the provided callback. * * @param plugin The plugin that is checking for an update. * @param id The dev.bukkit.org id of the project. * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class. * @param type Specify the type of update this will be. See {@link UpdateType} * @param callback The callback instance to notify when the Updater has finished * @param announce True if the program should announce the progress of new updates in console. */ public Updater(Plugin plugin, int id, File file, UpdateType type, UpdateCallback callback, boolean announce) { this.plugin = plugin; this.type = type; this.announce = announce; this.file = file; this.id = id; this.updateFolder = this.plugin.getServer().getUpdateFolderFile(); this.callback = callback; final File pluginFile = this.plugin.getDataFolder().getParentFile(); final File updaterFile = new File(pluginFile, "Updater"); final File updaterConfigFile = new File(updaterFile, "config.yml"); YamlConfiguration config = new YamlConfiguration(); config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); config.addDefault(API_KEY_CONFIG_KEY, API_KEY_DEFAULT); config.addDefault(DISABLE_CONFIG_KEY, DISABLE_DEFAULT); if (!updaterFile.exists()) { this.fileIOOrError(updaterFile, updaterFile.mkdir(), true); } boolean createFile = !updaterConfigFile.exists(); try { if (createFile) { this.fileIOOrError(updaterConfigFile, updaterConfigFile.mkdir(), true); config.options().copyDefaults(true); config.save(updaterConfigFile); } else { config.load(updaterConfigFile); } } catch (final Exception e) { final String message; if (createFile) { message = "The updater could not create configuration at " + updaterFile.getAbsolutePath(); } else { message = "The updater could not load configuration at " + updaterFile.getAbsolutePath(); } this.plugin.getLogger().log(Level.SEVERE, message, e); } if (config.getBoolean(DISABLE_CONFIG_KEY)) { this.result = UpdateResult.DISABLED; return; } String key = config.getString(API_KEY_CONFIG_KEY); if (API_KEY_DEFAULT.equalsIgnoreCase(key) || "".equals(key)) { key = null; } this.apiKey = key; try { this.url = new URL(Updater.HOST + Updater.QUERY + this.id); } catch (final MalformedURLException e) { this.plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + this.id + " is invalid.", e); this.result = UpdateResult.FAIL_BADID; } if (this.result != UpdateResult.FAIL_BADID) { this.thread = new Thread(new UpdateRunnable()); this.thread.start(); } else { runUpdater(); } } /** * Get the result of the update process. * * @return result of the update process. * @see UpdateResult */ public Updater.UpdateResult getResult() { this.waitForThread(); return this.result; } /** * Get the latest version's release type. * * @return latest version's release type. * @see ReleaseType */ public ReleaseType getLatestType() { this.waitForThread(); if (this.versionType != null) { for (ReleaseType type : ReleaseType.values()) { if (this.versionType.equalsIgnoreCase(type.name())) { return type; } } } return null; } /** * Get the latest version's game version (such as "CB 1.2.5-R1.0"). * * @return latest version's game version. */ public String getLatestGameVersion() { this.waitForThread(); return this.versionGameVersion; } /** * Get the latest version's name (such as "Project v1.0"). * * @return latest version's name. */ public String getLatestName() { this.waitForThread(); return this.versionName; } /** * Get the latest version's direct file link. * * @return latest version's file link. */ public String getLatestFileLink() { this.waitForThread(); return this.versionLink; } /** * As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish * before allowing anyone to check the result. */ private void waitForThread() { if ((this.thread != null) && this.thread.isAlive()) { try { this.thread.join(); } catch (final InterruptedException e) { this.plugin.getLogger().log(Level.SEVERE, null, e); } } } /** * Save an update from dev.bukkit.org into the server's update folder. * * @param folder the updates folder location. * @param file the name of the file to save it as. * @param link the url of the file. */ private void saveFile(String file) { final File folder = this.updateFolder; deleteOldFiles(); if (!folder.exists()) { this.fileIOOrError(folder, folder.mkdir(), true); } downloadFile(); // Check to see if it's a zip file, if it is, unzip it. final File dFile = new File(folder.getAbsolutePath(), file); if (dFile.getName().endsWith(".zip")) { // Unzip this.unzip(dFile.getAbsolutePath()); } if (this.announce) { this.plugin.getLogger().info("Finished updating."); } } /** * Download a file and save it to the specified folder. * @param link link to file. * @param folder folder to save file to. */ private void downloadFile() { BufferedInputStream in = null; FileOutputStream fout = null; try { URL fileUrl = new URL(this.versionLink); final int fileLength = fileUrl.openConnection().getContentLength(); in = new BufferedInputStream(fileUrl.openStream()); fout = new FileOutputStream(new File(this.updateFolder, file.getName())); final byte[] data = new byte[Updater.BYTE_SIZE]; int count; if (this.announce) { this.plugin.getLogger().info("About to download a new update: " + this.versionName); } long downloaded = 0; while ((count = in.read(data, 0, Updater.BYTE_SIZE)) != -1) { downloaded += count; fout.write(data, 0, count); final int percent = (int) ((downloaded * 100) / fileLength); if (this.announce && ((percent % 10) == 0)) { this.plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); } } } catch (Exception ex) { this.plugin.getLogger().log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful.", ex); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; } finally { try { if (in != null) { in.close(); } } catch (final IOException ex) { this.plugin.getLogger().log(Level.SEVERE, null, ex); } try { if (fout != null) { fout.close(); } } catch (final IOException ex) { this.plugin.getLogger().log(Level.SEVERE, null, ex); } } } /** * Remove possibly leftover files from the update folder. */ private void deleteOldFiles() { //Just a quick check to make sure we didn't leave any files from last time... File[] list = listFilesOrError(this.updateFolder); for (final File xFile : list) { if (xFile.getName().endsWith(".zip")) { this.fileIOOrError(xFile, xFile.mkdir(), true); } } } /** * Part of Zip-File-Extractor, modified by Gravity for use with Updater. * * @param file the location of the file to extract. */ private void unzip(String file) { final File fSourceZip = new File(file); try { final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); this.fileIOOrError(destinationFilePath.getParentFile(), destinationFilePath.getParentFile().mkdirs(), true); if (!entry.isDirectory()) { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; final byte[] buffer = new byte[Updater.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginExists(name)) { File output = new File(this.updateFolder, name); this.fileIOOrError(output, destinationFilePath.renameTo(output), true); } } } zipFile.close(); // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. moveNewZipFiles(zipPath); } catch (final IOException e) { this.plugin.getLogger().log(Level.SEVERE, "The auto-updater tried to unzip a new update file, but was unsuccessful.", e); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; } finally { this.fileIOOrError(fSourceZip, fSourceZip.delete(), false); } } /** * Find any new files extracted from an update into the plugin's data directory. * @param zipPath path of extracted files. */ private void moveNewZipFiles(String zipPath) { File[] list = listFilesOrError(new File(zipPath)); for (final File dFile : list) { if (dFile.isDirectory() && this.pluginExists(dFile.getName())) { // Current dir final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // List of existing files in the new dir final File[] dList = listFilesOrError(dFile); // List of existing files in the current dir final File[] oList = listFilesOrError(oFile); for (File cFile : dList) { // Loop through all the files in the new dir boolean found = false; for (final File xFile : oList) { // Loop through all the contents in the current dir to see if it exists if (xFile.getName().equals(cFile.getName())) { found = true; break; } } if (!found) { // Move the new file into the current dir File output = new File(oFile, cFile.getName()); this.fileIOOrError(output, cFile.renameTo(output), true); } else { // This file already exists, so we don't need it anymore. this.fileIOOrError(cFile, cFile.delete(), false); } } } this.fileIOOrError(dFile, dFile.delete(), false); } File zip = new File(zipPath); this.fileIOOrError(zip, zip.delete(), false); } /** * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. * * @param name a name to check for inside the plugins folder. * @return true if a file inside the plugins folder is named this. */ private boolean pluginExists(String name) { File[] plugins = listFilesOrError(new File("plugins")); for (final File file : plugins) { if (file.getName().equals(name)) { return true; } } return false; } /** * Check to see if the program should continue by evaluating whether the plugin is already updated, or shouldn't be updated. * * @return true if the version was located and is not the same as the remote's newest. */ private boolean versionCheck() { final String title = this.versionName; if (this.type != UpdateType.NO_VERSION_CHECK) { final String localVersion = this.plugin.getDescription().getVersion(); if (title.split(DELIMETER).length == 2) { // Get the newest file's version number final String remoteVersion = title.split(DELIMETER)[1].split(" ")[0]; if (this.hasTag(localVersion) || !this.shouldUpdate(localVersion, remoteVersion)) { // We already have the latest version, or this build is tagged for no-update this.result = Updater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' final String authorInfo = this.plugin.getDescription().getAuthors().isEmpty() ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); this.plugin.getLogger().warning("Please notify the author of this error."); this.result = Updater.UpdateResult.FAIL_NOVERSION; return false; } } return true; } /** * <b>If you wish to run mathematical versioning checks, edit this method.</b> * <p> * With default behavior, Updater will NOT verify that a remote version available on BukkitDev * which is not this version is indeed an "update". * If a version is present on BukkitDev that is not the version that is currently running, * Updater will assume that it is a newer version. * This is because there is no standard versioning scheme, and creating a calculation that can * determine whether a new update is actually an update is sometimes extremely complicated. * </p> * <p> * Updater will call this method from {@link #versionCheck(String)} before deciding whether * the remote version is actually an update. * If you have a specific versioning scheme with which a mathematical determination can * be reliably made to decide whether one version is higher than another, you may * revise this method, using the local and remote version parameters, to execute the * appropriate check. * </p> * <p> * Returning a value of <b>false</b> will tell the update process that this is NOT a new version. * Without revision, this method will always consider a remote version at all different from * that of the local version a new update. * </p> * @param localVersion the current version * @param remoteVersion the remote version * @return true if Updater should consider the remote version an update, false if not. */ public boolean shouldUpdate(String localVersion, String remoteVersion) { return !localVersion.equalsIgnoreCase(remoteVersion); } /** * Evaluate whether the version number is marked showing that it should not be updated by this program. * * @param version a version number to check for tags in. * @return true if updating should be disabled. */ private boolean hasTag(String version) { for (final String string : Updater.NO_UPDATE_TAG) { if (version.contains(string)) { return true; } } return false; } /** * Make a connection to the BukkitDev API and request the newest file's details. * * @return true if successful. */ private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", Updater.USER_AGENT); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.isEmpty()) { this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1); this.versionName = (String) latestUpdate.get(Updater.TITLE_VALUE); this.versionLink = (String) latestUpdate.get(Updater.LINK_VALUE); this.versionType = (String) latestUpdate.get(Updater.TYPE_VALUE); this.versionGameVersion = (String) latestUpdate.get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } this.plugin.getLogger().log(Level.SEVERE, null, e); return false; } } /** * Perform a file operation and log any errors if it fails. * @param file file operation is performed on. * @param result result of file operation. * @param create true if a file is being created, false if deleted. */ private void fileIOOrError(File file, boolean result, boolean create) { if (!result) { this.plugin.getLogger().severe("The updater could not " + (create ? "create" : "delete") + " file at: " + file.getAbsolutePath()); } } private File[] listFilesOrError(File folder) { File[] contents = folder.listFiles(); if (contents == null) { this.plugin.getLogger().severe("The updater could not access files at: " + this.updateFolder.getAbsolutePath()); return new File[0]; } else { return contents; } } /** * Called on main thread when the Updater has finished working, regardless * of result. */ public interface UpdateCallback { /** * Called when the updater has finished working. * @param updater The updater instance */ void onFinish(Updater updater); } private class UpdateRunnable implements Runnable { @Override public void run() { runUpdater(); } } private void runUpdater() { if (this.url != null && (this.read() && this.versionCheck())) { // Obtain the results of the project's file feed if ((this.versionLink != null) && (this.type != UpdateType.NO_DOWNLOAD)) { String name = this.file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name if (this.versionLink.endsWith(".zip")) { name = this.versionLink.substring(this.versionLink.lastIndexOf("/") + 1); } this.saveFile(name); } else { this.result = UpdateResult.UPDATE_AVAILABLE; } } if (this.callback != null) { new BukkitRunnable() { @Override public void run() { runCallback(); } }.runTask(this.plugin); } } private void runCallback() { this.callback.onFinish(this); } }
gpl-2.0
HAW-BAI4-SE2/UniKit-DatabaseInternal
project/src/net/unikit/database/internal/interfaces/managers/TeamRegistrationModelManager.java
409
package net.unikit.database.internal.interfaces.managers; import net.unikit.database.interfaces.managers.AbstractModelManager; import net.unikit.database.internal.interfaces.entities.TeamRegistrationModel; /** * A manager for the team registrations. * @author Andreas Berks * @since 1.2.1 */ public interface TeamRegistrationModelManager extends AbstractModelManager<TeamRegistrationModel, Integer> { }
gpl-2.0
biblelamp/JavaExercises
Stepic.org/Stepic_4_3_8.java
1331
import java.util.logging.*; class Stepic_4_3_8 { static Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) { } /* * Implement a method of tuning the parameters of logging * 1. Logger named "org.stepic.java.logging.ClassA" receives messages of all levels * 2. Logger named "org.stepic.java.logging.Class B" receives messages WARNING level and higher * 3. Messages that come from the lower to the level of loggers "org.stepic.java", * regardless of the severity of the messages are printed to the console in XML format (*) * and are not passed on to higher levels handlers "org.stepic", "org" and "." */ static void configureLogging() { Logger loggerA = Logger.getLogger("org.stepic.java.logging.ClassA"); Logger loggerB = Logger.getLogger("org.stepic.java.logging.ClassB"); Logger logger = Logger.getLogger("org.stepic.java"); loggerA.setLevel(Level.ALL); loggerB.setLevel(Level.WARNING); Handler consoleHandler = new ConsoleHandler(); Formatter xmlFormatter = new XMLFormatter(); consoleHandler.setLevel(Level.ALL); consoleHandler.setFormatter(xmlFormatter); logger.addHandler(consoleHandler); logger.setUseParentHandlers(false); } }
gpl-2.0
jakub-chatrny/sheep_heep
sheep_heap/sheep_heap-core/src/main/java/game/render/RenderMap.java
5343
package game.render; import static kryten.engine.Draw.rect; import static kryten.engine.Draw.rectRepTex; import static game.render.Render.getWindowHeight; import static game.render.Render.getWindowWidth; import java.awt.Font; import java.awt.Point; import org.newdawn.slick.Color; import org.newdawn.slick.TrueTypeFont; import org.newdawn.slick.opengl.Texture; import game.GMap; import game.object.Field; import static game.Global.*; public class RenderMap { /** * Improved map rendering. Render ground as one rectangle with scaled texture. and everything else over it. * @param map * @param render */ public static void mapOptimal(GMap map, Render render) { ground(map, render); mountainAndLakes(map, render); } /** * Render ground. Should be fully optimal. * @param map * @param render */ private static void ground(GMap map, Render render) { int renderFieldSize = render.getRenderFieldSize(); Point renderPosition = render.getRenderPosition(); int windowWidth = (int) getWindowWidth(); int windowHeight = (int) getWindowHeight(); int maxCols = windowWidth / renderFieldSize; int maxRows = windowHeight / renderFieldSize; // shift object right if render position is greater then zero int startX = (-renderPosition.x) * renderFieldSize; startX = startX >= 0 ? startX : 0; // shift object bottom if render position is greater then zero int startY = (-renderPosition.y) * renderFieldSize; startY = startY >= 0 ? startY : 0; // count object width int width = (map.getCols() - renderPosition.x) * renderFieldSize; width = width > windowWidth ? windowWidth : width - startX; // count object height int height = (map.getRows() - renderPosition.y) * renderFieldSize; height = height > windowHeight ? windowHeight : height - startY; // count texture scaling int textureScaleX = width == windowWidth ? maxCols : (renderPosition.x > 0 ? map.getCols() - renderPosition.x : maxCols + renderPosition.x); int textureScaleY = height == windowHeight ? maxRows : (renderPosition.y > 0 ? map.getRows() - renderPosition.y : maxRows + renderPosition.y); // check if is object on screen if ((0 < width && 0 < height)) { rectRepTex(startX, startY, width, height, new Color(95, 186, 48), Field.getFieldTexture(0), textureScaleX, textureScaleY); /*System.out.println(renderPosition.x + ", " + renderPosition.y); System.out.println(startX + ", " + startY + ", " + width + ", " + height + ", ");*/ } } /** * Render on screen mountains and lakes. Not Optimal * @param map * @param render */ private static void mountainAndLakes(GMap map, Render render) { //TODO make optimal //int vertexCounter = 0; int startX, startY; int renderFieldSize = render.getRenderFieldSize(); Point renderPosition = render.getRenderPosition(); int maxCols = (int) getWindowWidth() / renderFieldSize; int maxRows = (int) getWindowHeight() / renderFieldSize; if (maxRows % renderFieldSize != 0) maxRows++; int col, row; for (col = 0; (col - renderPosition.x) < maxCols && col < map.getCols(); col++) { if ((col - renderPosition.x) < 0) //out of screen continue; for (row = 0; (row - renderPosition.y) < maxRows && row < map.getRows(); row++) { if ((row - renderPosition.y) < 0) //out of screen continue; startX = (col - renderPosition.x) * renderFieldSize; startY = (row - renderPosition.y) * renderFieldSize; // set color Field field = map.getField(col, row); if (field.getAltitude() == 0) continue; // this method doesn't render ground Color color = field.getColor();//getFieldColor(field); //vertexCounter++; // set texture Texture texture = field.getTexture();//getFieldTexture(field, render.getSprites()); // if (field.getAltitude() != 255) rect(startX, startY, renderFieldSize, renderFieldSize, color, texture); } } //System.out.println(vertexCounter); } /** * Render coordinates of map to screen when is @game.renderCoordsFlag set * * @param flag * @param render * @param sprites */ public static void coords(Render render) { int renderFieldSize = render.getRenderFieldSize(); Point renderPosition = render.getRenderPosition(); for (int col = 0; col < getWindowWidth() / renderFieldSize; col++) for (int row = 0; row < getWindowHeight() / renderFieldSize; row++) if (render.isRenderCoordsFlag() && renderFieldSize > 20) { TrueTypeFont ttf = getFont("Times New Roman", Font.PLAIN, renderFieldSize == 80 ? 12 : 6); ttf.drawString(col * renderFieldSize + 1, row * renderFieldSize + 1, (col + renderPosition.x) + "," + (row + renderPosition.y), Color.white); } } /** * Render grid to screen when is @game.renderGridFlag set * * @param game */ public static void grid(Render render) { if (render.isRenderGridFlag()) { // local variables Texture texture = getTexture("blank"); int renderFieldSize = render.getRenderFieldSize(); for (int i = 1; i < getWindowWidth() / renderFieldSize; i++) rect(i * renderFieldSize, 0, (int) 1, getWindowHeight(), Color.black, texture); for (int j = 1; j < getWindowHeight() / renderFieldSize; j++) rect(0, j * renderFieldSize, getWindowWidth(), 0.6f, Color.black, texture); } } }
gpl-2.0
mbeier1406/jm
src/test/java/de/gmxhome/golkonda/ja/SDKFormatterTest.java
661
package de.gmxhome.golkonda.ja; import java.util.logging.Logger; import org.junit.Test; import junit.framework.Assert; public class SDKFormatterTest { Logger logger = Logger.getLogger(SDKFormatterTest.class.getCanonicalName()); @Test public void stringTest() { String str = String.format("%2$6s%1$6s", "hallo", "x"); logger.info("str="+str); Assert.assertEquals(str, " x hallo"); str = String.format("%2$-6s%1$6s", "hallo", "x"); logger.info("str="+str); Assert.assertEquals(str, "x hallo"); str = String.format("%2$08.3f %1$.3f", 1.23456, 2.34567); logger.info("str="+str); Assert.assertEquals(str, "0002.346 1.235"); } }
gpl-2.0
tinfinite/dove-android
TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java
25564
/* * This is the source code of Telegram for Android v. 1.3.2. * 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. */ package org.telegram.ui; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.TextWatcher; import android.text.style.ImageSpan; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import org.telegram.android.AndroidUtilities; import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.android.LocaleController; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.TLRPC; import org.telegram.android.ContactsController; import org.telegram.messenger.FileLog; import org.telegram.android.MessagesController; import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.ui.Adapters.ContactsAdapter; import org.telegram.ui.Adapters.SearchAdapter; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.Cells.UserCell; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LetterSectionsListView; import java.util.ArrayList; import java.util.HashMap; public class GroupCreateActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { public interface GroupCreateActivityDelegate { void didSelectUsers(ArrayList<Integer> ids); } private class XImageSpan extends ImageSpan { public int uid; public XImageSpan(Drawable d, int verticalAlignment) { super(d, verticalAlignment); } @Override public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { if (fm == null) { fm = new Paint.FontMetricsInt(); } int sz = super.getSize(paint, text, start, end, fm); int offset = AndroidUtilities.dp(6); int w = (fm.bottom - fm.top) / 2; fm.top = -w - offset; fm.bottom = w - offset; fm.ascent = -w - offset; fm.leading = 0; fm.descent = w - offset; return sz; } } private ContactsAdapter listViewAdapter; private TextView emptyTextView; private EditText userSelectEditText; private LetterSectionsListView listView; private SearchAdapter searchListViewAdapter; private GroupCreateActivityDelegate delegate; private int beforeChangeIndex; private int maxCount = 199; private boolean ignoreChange = false; private boolean isBroadcast = false; private boolean isAlwaysShare = false; private boolean isNeverShare = false; private boolean searchWas; private boolean searching; private CharSequence changeString; private HashMap<Integer, XImageSpan> selectedContacts = new HashMap<>(); private ArrayList<XImageSpan> allSpans = new ArrayList<>(); private final static int done_button = 1; public GroupCreateActivity() { super(); } public GroupCreateActivity(Bundle args) { super(args); isBroadcast = args.getBoolean("broadcast", false); isAlwaysShare = args.getBoolean("isAlwaysShare", false); isNeverShare = args.getBoolean("isNeverShare", false); maxCount = !isBroadcast ? (MessagesController.getInstance().maxGroupCount - 1) : MessagesController.getInstance().maxBroadcastCount; } @Override public boolean onFragmentCreate() { NotificationCenter.getInstance().addObserver(this, NotificationCenter.contactsDidLoaded); NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatDidCreated); return super.onFragmentCreate(); } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.contactsDidLoaded); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.chatDidCreated); } @Override public View createView(Context context, LayoutInflater inflater) { //代码监测 Tracker t = ApplicationLoader.getInstance().getTracker(ApplicationLoader.TrackerName.APP_TRACKER); t.setScreenName("new_group"); t.send(new HitBuilders.AppViewBuilder().build()); searching = false; searchWas = false; actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(true); if (isAlwaysShare) { actionBar.setTitle(LocaleController.getString("AlwaysShareWithTitle", R.string.AlwaysShareWithTitle)); } else if (isNeverShare) { actionBar.setTitle(LocaleController.getString("NeverShareWithTitle", R.string.NeverShareWithTitle)); } else { actionBar.setTitle(isBroadcast ? LocaleController.getString("NewBroadcastList", R.string.NewBroadcastList) : LocaleController.getString("NewGroup", R.string.NewGroup)); actionBar.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount)); } actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == done_button) { if (selectedContacts.isEmpty()) { return; } ArrayList<Integer> result = new ArrayList<>(); result.addAll(selectedContacts.keySet()); if (isAlwaysShare || isNeverShare) { if (delegate != null) { delegate.didSelectUsers(result); } finishFragment(); } else { Bundle args = new Bundle(); args.putIntegerArrayList("result", result); args.putBoolean("broadcast", isBroadcast); presentFragment(new GroupCreateFinalActivity(args)); } } } }); ActionBarMenu menu = actionBar.createMenu(); menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); searchListViewAdapter = new SearchAdapter(context, null, false); searchListViewAdapter.setCheckedMap(selectedContacts); searchListViewAdapter.setUseUserCell(true); listViewAdapter = new ContactsAdapter(context, true, false, null, false); listViewAdapter.setCheckedMap(selectedContacts); fragmentView = new LinearLayout(context); LinearLayout linearLayout = (LinearLayout) fragmentView; linearLayout.setOrientation(LinearLayout.VERTICAL); FrameLayout frameLayout = new FrameLayout(context); linearLayout.addView(frameLayout); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); layoutParams.width = LayoutHelper.MATCH_PARENT; layoutParams.height = LayoutHelper.WRAP_CONTENT; layoutParams.gravity = Gravity.TOP; frameLayout.setLayoutParams(layoutParams); userSelectEditText = new EditText(context); userSelectEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); userSelectEditText.setHintTextColor(0xff979797); userSelectEditText.setTextColor(0xff212121); userSelectEditText.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_MULTI_LINE); userSelectEditText.setMinimumHeight(AndroidUtilities.dp(54)); userSelectEditText.setSingleLine(false); userSelectEditText.setLines(2); userSelectEditText.setMaxLines(2); userSelectEditText.setVerticalScrollBarEnabled(true); userSelectEditText.setHorizontalScrollBarEnabled(false); userSelectEditText.setPadding(0, 0, 0, 0); userSelectEditText.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI); userSelectEditText.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); AndroidUtilities.clearCursorDrawable(userSelectEditText); frameLayout.addView(userSelectEditText); FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) userSelectEditText.getLayoutParams(); layoutParams1.width = LayoutHelper.MATCH_PARENT; layoutParams1.height = LayoutHelper.WRAP_CONTENT; layoutParams1.leftMargin = AndroidUtilities.dp(10); layoutParams1.rightMargin = AndroidUtilities.dp(10); layoutParams1.gravity = Gravity.TOP; userSelectEditText.setLayoutParams(layoutParams1); if (isAlwaysShare) { userSelectEditText.setHint(LocaleController.getString("AlwaysShareWithPlaceholder", R.string.AlwaysShareWithPlaceholder)); } else if (isNeverShare) { userSelectEditText.setHint(LocaleController.getString("NeverShareWithPlaceholder", R.string.NeverShareWithPlaceholder)); } else { userSelectEditText.setHint(LocaleController.getString("SendMessageTo", R.string.SendMessageTo)); } if (Build.VERSION.SDK_INT >= 11) { userSelectEditText.setTextIsSelectable(false); } userSelectEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { if (!ignoreChange) { beforeChangeIndex = userSelectEditText.getSelectionStart(); changeString = new SpannableString(charSequence); } } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { if (!ignoreChange) { boolean search = false; int afterChangeIndex = userSelectEditText.getSelectionEnd(); if (editable.toString().length() < changeString.toString().length()) { String deletedString = ""; try { deletedString = changeString.toString().substring(afterChangeIndex, beforeChangeIndex); } catch (Exception e) { FileLog.e("tmessages", e); } if (deletedString.length() > 0) { if (searching && searchWas) { search = true; } Spannable span = userSelectEditText.getText(); for (int a = 0; a < allSpans.size(); a++) { XImageSpan sp = allSpans.get(a); if (span.getSpanStart(sp) == -1) { allSpans.remove(sp); selectedContacts.remove(sp.uid); } } if (!isAlwaysShare && !isNeverShare) { actionBar.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount)); } listView.invalidateViews(); } else { search = true; } } else { search = true; } if (search) { String text = userSelectEditText.getText().toString().replace("<", ""); if (text.length() != 0) { searching = true; searchWas = true; if (listView != null) { listView.setAdapter(searchListViewAdapter); searchListViewAdapter.notifyDataSetChanged(); if (android.os.Build.VERSION.SDK_INT >= 11) { listView.setFastScrollAlwaysVisible(false); } listView.setFastScrollEnabled(false); listView.setVerticalScrollBarEnabled(true); } if (emptyTextView != null) { emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult)); } searchListViewAdapter.searchDialogs(text); } else { searchListViewAdapter.searchDialogs(null); searching = false; searchWas = false; listView.setAdapter(listViewAdapter); listViewAdapter.notifyDataSetChanged(); if (android.os.Build.VERSION.SDK_INT >= 11) { listView.setFastScrollAlwaysVisible(true); } listView.setFastScrollEnabled(true); listView.setVerticalScrollBarEnabled(false); emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); } } } } }); LinearLayout emptyTextLayout = new LinearLayout(context); emptyTextLayout.setVisibility(View.INVISIBLE); emptyTextLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.addView(emptyTextLayout); layoutParams = (LinearLayout.LayoutParams) emptyTextLayout.getLayoutParams(); layoutParams.width = LayoutHelper.MATCH_PARENT; layoutParams.height = LayoutHelper.MATCH_PARENT; emptyTextLayout.setLayoutParams(layoutParams); emptyTextLayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); emptyTextView = new TextView(context); emptyTextView.setTextColor(0xff808080); emptyTextView.setTextSize(20); emptyTextView.setGravity(Gravity.CENTER); emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); emptyTextLayout.addView(emptyTextView); layoutParams = (LinearLayout.LayoutParams) emptyTextView.getLayoutParams(); layoutParams.width = LayoutHelper.MATCH_PARENT; layoutParams.height = LayoutHelper.MATCH_PARENT; layoutParams.weight = 0.5f; emptyTextView.setLayoutParams(layoutParams); FrameLayout frameLayout2 = new FrameLayout(context); emptyTextLayout.addView(frameLayout2); layoutParams = (LinearLayout.LayoutParams) frameLayout2.getLayoutParams(); layoutParams.width = LayoutHelper.MATCH_PARENT; layoutParams.height = LayoutHelper.MATCH_PARENT; layoutParams.weight = 0.5f; frameLayout2.setLayoutParams(layoutParams); listView = new LetterSectionsListView(context); listView.setEmptyView(emptyTextLayout); listView.setVerticalScrollBarEnabled(false); listView.setDivider(null); listView.setDividerHeight(0); listView.setFastScrollEnabled(true); listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); listView.setAdapter(listViewAdapter); if (Build.VERSION.SDK_INT >= 11) { listView.setFastScrollAlwaysVisible(true); listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); } linearLayout.addView(listView); layoutParams = (LinearLayout.LayoutParams) listView.getLayoutParams(); layoutParams.width = LayoutHelper.MATCH_PARENT; layoutParams.height = LayoutHelper.MATCH_PARENT; listView.setLayoutParams(layoutParams); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { TLRPC.User user = null; if (searching && searchWas) { user = searchListViewAdapter.getItem(i); } else { int section = listViewAdapter.getSectionForPosition(i); int row = listViewAdapter.getPositionInSectionForPosition(i); if (row < 0 || section < 0) { return; } user = (TLRPC.User) listViewAdapter.getItem(section, row); } if (user == null) { return; } boolean check = true; if (selectedContacts.containsKey(user.id)) { check = false; try { XImageSpan span = selectedContacts.get(user.id); selectedContacts.remove(user.id); SpannableStringBuilder text = new SpannableStringBuilder(userSelectEditText.getText()); text.delete(text.getSpanStart(span), text.getSpanEnd(span)); allSpans.remove(span); ignoreChange = true; userSelectEditText.setText(text); userSelectEditText.setSelection(text.length()); ignoreChange = false; } catch (Exception e) { FileLog.e("tmessages", e); } } else { if (selectedContacts.size() == maxCount) { return; } ignoreChange = true; XImageSpan span = createAndPutChipForUser(user); span.uid = user.id; ignoreChange = false; } if (!isAlwaysShare && !isNeverShare) { actionBar.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount)); } if (searching || searchWas) { ignoreChange = true; SpannableStringBuilder ssb = new SpannableStringBuilder(""); for (ImageSpan sp : allSpans) { ssb.append("<<"); ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE); } userSelectEditText.setText(ssb); userSelectEditText.setSelection(ssb.length()); ignoreChange = false; searchListViewAdapter.searchDialogs(null); searching = false; searchWas = false; listView.setAdapter(listViewAdapter); listViewAdapter.notifyDataSetChanged(); if (android.os.Build.VERSION.SDK_INT >= 11) { listView.setFastScrollAlwaysVisible(true); } listView.setFastScrollEnabled(true); listView.setVerticalScrollBarEnabled(false); emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); } else { if (view instanceof UserCell) { ((UserCell) view).setChecked(check, true); } } } }); listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int i) { if (i == SCROLL_STATE_TOUCH_SCROLL) { AndroidUtilities.hideKeyboard(userSelectEditText); } if (listViewAdapter != null) { listViewAdapter.setIsScrolling(i != SCROLL_STATE_IDLE); } } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (absListView.isFastScrollEnabled()) { AndroidUtilities.clearDrawableAnimation(absListView); } } }); return fragmentView; } @Override public void didReceivedNotification(int id, Object... args) { if (id == NotificationCenter.contactsDidLoaded) { if (listViewAdapter != null) { listViewAdapter.notifyDataSetChanged(); } } else if (id == NotificationCenter.updateInterfaces) { int mask = (Integer)args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { updateVisibleRows(mask); } } else if (id == NotificationCenter.chatDidCreated) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { removeSelfFromStack(); } }); } } private void updateVisibleRows(int mask) { if (listView != null) { int count = listView.getChildCount(); for (int a = 0; a < count; a++) { View child = listView.getChildAt(a); if (child instanceof UserCell) { ((UserCell) child).update(mask); } } } } public void setDelegate(GroupCreateActivityDelegate delegate) { this.delegate = delegate; } private XImageSpan createAndPutChipForUser(TLRPC.User user) { LayoutInflater lf = (LayoutInflater) ApplicationLoader.applicationContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View textView = lf.inflate(R.layout.group_create_bubble, null); TextView text = (TextView)textView.findViewById(R.id.bubble_text_view); String name = ContactsController.formatName(user.first_name, user.last_name); if (name.length() == 0 && user.phone != null && user.phone.length() != 0) { name = PhoneFormat.getInstance().format("+" + user.phone); } text.setText(name + ", "); int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); textView.measure(spec, spec); textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight()); Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(b); canvas.translate(-textView.getScrollX(), -textView.getScrollY()); textView.draw(canvas); textView.setDrawingCacheEnabled(true); Bitmap cacheBmp = textView.getDrawingCache(); Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true); textView.destroyDrawingCache(); final BitmapDrawable bmpDrawable = new BitmapDrawable(b); bmpDrawable.setBounds(0, 0, b.getWidth(), b.getHeight()); SpannableStringBuilder ssb = new SpannableStringBuilder(""); XImageSpan span = new XImageSpan(bmpDrawable, ImageSpan.ALIGN_BASELINE); allSpans.add(span); selectedContacts.put(user.id, span); for (ImageSpan sp : allSpans) { ssb.append("<<"); ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE); } userSelectEditText.setText(ssb); userSelectEditText.setSelection(ssb.length()); return span; } }
gpl-2.0
karianna/jdk8_tl
jdk/src/solaris/classes/sun/nio/ch/EventPortWrapper.java
8628
/* * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.nio.ch; import sun.misc.Unsafe; import java.io.IOException; import java.util.*; import static sun.nio.ch.SolarisEventPort.*; /** * Manages a Solaris event port and manipulates a native array of pollfd structs * on Solaris. */ class EventPortWrapper { private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final int addressSize = unsafe.addressSize(); // Maximum number of open file descriptors static final int OPEN_MAX = IOUtil.fdLimit(); // Maximum number of events to retrive in one call to port_getn static final int POLL_MAX = Math.min(OPEN_MAX-1, 1024); // initial size of the array to hold pending updates private final int INITIAL_PENDING_UPDATE_SIZE = 256; // maximum size of updateArray private final int MAX_UPDATE_ARRAY_SIZE = Math.min(OPEN_MAX, 64*1024); // special update status to indicate that it should be ignored private static final byte IGNORE = -1; // port file descriptor private final int pfd; // the poll array (populated by port_getn) private final long pollArrayAddress; private final AllocatedNativeObject pollArray; // required when accessing the update* fields private final Object updateLock = new Object(); // the number of pending updates private int updateCount; // queue of file descriptors with updates pending private int[] updateDescriptors = new int[INITIAL_PENDING_UPDATE_SIZE]; // events for file descriptors with registration changes pending, indexed // by file descriptor and stored as bytes for efficiency reasons. For // file descriptors higher than MAX_UPDATE_ARRAY_SIZE (unlimited case at // least then the update is stored in a map. private final byte[] eventsLow = new byte[MAX_UPDATE_ARRAY_SIZE]; private Map<Integer,Byte> eventsHigh; // Used by release and updateRegistrations to track whether a file // descriptor is registered with /dev/poll. private final BitSet registered = new BitSet(); // bit set to indicate if a file descriptor has been visited when // processing updates (used to avoid duplicates calls to port_associate) private BitSet visited = new BitSet(); EventPortWrapper() throws IOException { int allocationSize = POLL_MAX * SIZEOF_PORT_EVENT; pollArray = new AllocatedNativeObject(allocationSize, true); pollArrayAddress = pollArray.address(); this.pfd = port_create(); if (OPEN_MAX > MAX_UPDATE_ARRAY_SIZE) eventsHigh = new HashMap<>(); } void close() throws IOException { port_close(pfd); pollArray.free(); } private short getSource(int i) { int offset = SIZEOF_PORT_EVENT * i + OFFSETOF_SOURCE; return pollArray.getShort(offset); } int getEventOps(int i) { int offset = SIZEOF_PORT_EVENT * i + OFFSETOF_EVENTS; return pollArray.getInt(offset); } int getDescriptor(int i) { int offset = SIZEOF_PORT_EVENT * i + OFFSETOF_OBJECT; if (addressSize == 4) { return pollArray.getInt(offset); } else { return (int) pollArray.getLong(offset); } } private void setDescriptor(int i, int fd) { int offset = SIZEOF_PORT_EVENT * i + OFFSETOF_OBJECT; if (addressSize == 4) { pollArray.putInt(offset, fd); } else { pollArray.putLong(offset, fd); } } private void setUpdate(int fd, byte events) { if (fd < MAX_UPDATE_ARRAY_SIZE) { eventsLow[fd] = events; } else { eventsHigh.put(Integer.valueOf(fd), Byte.valueOf(events)); } } private byte getUpdate(int fd) { if (fd < MAX_UPDATE_ARRAY_SIZE) { return eventsLow[fd]; } else { Byte result = eventsHigh.get(Integer.valueOf(fd)); // result should never be null return result.byteValue(); } } int poll(long timeout) throws IOException { // update registrations prior to poll synchronized (updateLock) { // process newest updates first int i = updateCount - 1; while (i >= 0) { int fd = updateDescriptors[i]; if (!visited.get(fd)) { short ev = getUpdate(fd); if (ev != IGNORE) { if (ev == 0) { if (registered.get(fd)) { port_dissociate(pfd, PORT_SOURCE_FD, (long)fd); registered.clear(fd); } } else { if (port_associate(pfd, PORT_SOURCE_FD, (long)fd, ev)) { registered.set(fd); } } } visited.set(fd); } i--; } updateCount = 0; } // poll for events int updated = port_getn(pfd, pollArrayAddress, POLL_MAX, timeout); // after polling we need to queue all polled file descriptors as they // are candidates to register for the next poll. synchronized (updateLock) { for (int i=0; i<updated; i++) { if (getSource(i) == PORT_SOURCE_USER) { interrupted = true; setDescriptor(i, -1); } else { // the default is to re-associate for the next poll int fd = getDescriptor(i); registered.clear(fd); setInterest(fd); } } } return updated; } private void setInterest(int fd) { assert Thread.holdsLock(updateLock); // record the file descriptor and events, expanding the // respective arrays first if necessary. int oldCapacity = updateDescriptors.length; if (updateCount >= oldCapacity) { int newCapacity = oldCapacity + INITIAL_PENDING_UPDATE_SIZE; int[] newDescriptors = new int[newCapacity]; System.arraycopy(updateDescriptors, 0, newDescriptors, 0, oldCapacity); updateDescriptors = newDescriptors; } updateDescriptors[updateCount++] = fd; visited.clear(fd); } void setInterest(int fd, int mask) { synchronized (updateLock) { setInterest(fd); setUpdate(fd, (byte)mask); assert getUpdate(fd) == mask; } } void release(int fd) { synchronized (updateLock) { if (registered.get(fd)) { try { port_dissociate(pfd, PORT_SOURCE_FD, (long)fd); } catch (IOException ioe) { throw new InternalError(ioe); } registered.clear(fd); } setUpdate(fd, IGNORE); } } // -- wakeup support -- private boolean interrupted; public void interrupt() { try { port_send(pfd, 0); } catch (IOException ioe) { throw new InternalError(ioe); } } boolean interrupted() { return interrupted; } void clearInterrupted() { interrupted = false; } }
gpl-2.0
hyattgra/leetcode
BulbSwitcher/Solution.java
166
package BulbSwitcher; /** * Created by Alan on 1/30/2016. */ public class Solution { public int bulbSwitch(int n) { return (int) Math.sqrt(n); } }
gpl-2.0
VicCebedo/SeabedOHM
src/com/seabed/ohm/DataType.java
2177
package com.seabed.ohm; import java.lang.reflect.Field; import java.sql.Timestamp; import java.util.List; import org.json.JSONObject; public abstract class DataType { public static final int DATA_TYPE_LONG = 1; public static final int DATA_TYPE_FLOAT = 2; public static final int DATA_TYPE_BOOLEAN = 3; public static final int DATA_TYPE_STRING = 4; public static final int DATA_TYPE_TIMESTAMP = 5; public static final int DATA_TYPE_LIST = 6; public static final int DATA_TYPE_JSON = 7; public static final int DATA_TYPE_INT = 7; public static boolean isNumber(int dType) { return dType == DATA_TYPE_LONG || dType == DATA_TYPE_INT; } /** * Get the data type associated with this field in the passed object. * * @param obj * @param field * @return */ public static int getDataType(Object obj, Field field) { int dataType = 0; Class<?> dataTypeClazz = null; try { Object value = field.get(obj); if (value == null) { return DataType.DATA_TYPE_STRING; } dataTypeClazz = field.get(obj).getClass(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (dataTypeClazz == List.class) { dataType = DataType.DATA_TYPE_LIST; } else if (dataTypeClazz == JSONObject.class) { dataType = DataType.DATA_TYPE_JSON; } else if (dataTypeClazz == Timestamp.class) { dataType = DataType.DATA_TYPE_TIMESTAMP; } else if (dataTypeClazz == String.class) { dataType = DataType.DATA_TYPE_STRING; } else if (dataTypeClazz == Boolean.class || dataTypeClazz == Boolean.TYPE) { dataType = DataType.DATA_TYPE_BOOLEAN; } else if (dataTypeClazz == Float.class || dataTypeClazz == Float.TYPE) { dataType = DataType.DATA_TYPE_FLOAT; } else if (dataTypeClazz == Long.class || dataTypeClazz == Long.TYPE || dataTypeClazz == Double.class || dataTypeClazz == Double.TYPE || dataTypeClazz == Short.class || dataTypeClazz == Short.TYPE) { dataType = DataType.DATA_TYPE_LONG; } else if (dataTypeClazz == Integer.class || dataTypeClazz == Integer.TYPE) { dataType = DataType.DATA_TYPE_INT; } return dataType; } }
gpl-2.0
vikto9494/Lobo_Browser
XAMJ_Project/HTML_Renderer/org/lobobrowser/html/AbstractHtmlRendererContext.java
4329
/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html; import java.awt.event.MouseEvent; import java.net.URL; import org.w3c.dom.html2.HTMLCollection; import org.w3c.dom.html2.HTMLElement; import org.w3c.dom.html2.HTMLLinkElement; /** * Abstract implementation of the {@link HtmlRendererContext} interface with * blank methods, provided for developer convenience. */ public abstract class AbstractHtmlRendererContext implements HtmlRendererContext { public void alert(String message) { } public void back() { } public void blur() { } public void close() { } public boolean confirm(String message) { return false; } public BrowserFrame createBrowserFrame() { return null; } public void focus() { } public String getDefaultStatus() { return null; } public HTMLCollection getFrames() { return null; } public HtmlObject getHtmlObject(HTMLElement element) { return null; } public String getName() { return null; } public HtmlRendererContext getOpener() { return null; } public HtmlRendererContext getParent() { return null; } public String getStatus() { return null; } public HtmlRendererContext getTop() { return null; } public UserAgentContext getUserAgentContext() { return null; } /** * Returns false unless overridden. */ public boolean isClosed() { return false; } /** * Returns true unless overridden. */ public boolean isImageLoadingEnabled() { return true; } /** * Returns false unless overridden. */ public boolean isVisitedLink(HTMLLinkElement link) { return false; } public void linkClicked(HTMLElement linkNode, URL url, String target) { } public void navigate(URL url, String target) { } /** * Returns true unless overridden. */ public boolean onContextMenu(HTMLElement element, MouseEvent event) { return true; } public void onMouseOut(HTMLElement element, MouseEvent event) { } public void onMouseOver(HTMLElement element, MouseEvent event) { } public HtmlRendererContext open(String absoluteUrl, String windowName, String windowFeatures, boolean replace) { return null; } public HtmlRendererContext open(URL url, String windowName, String windowFeatures, boolean replace) { return null; } public String prompt(String message, String inputDefault) { return null; } public void reload() { } public void scroll(int x, int y) { } public void setDefaultStatus(String value) { } public void setOpener(HtmlRendererContext opener) { } public void setStatus(String message) { } public void submitForm(String method, URL action, String target, String enctype, FormInput[] formInputs) { } /** * Returns true unless overridden. */ public boolean onDoubleClick(HTMLElement element, MouseEvent event) { return true; } /** * Returns true unless overridden. */ public boolean onMouseClick(HTMLElement element, MouseEvent event) { return true; } public void scrollBy(int x, int y) { } public void resizeBy(int byWidth, int byHeight) { } public void resizeTo(int width, int height) { } public void forward() { } public String getCurrentURL() { return null; } public int getHistoryLength() { return 0; } public String getNextURL() { return null; } public String getPreviousURL() { return null; } public void goToHistoryURL(String url) { } public void moveInHistory(int offset) { } }
gpl-2.0
JamoBox/CrazyFeet
src/tk/acronus/CrazyFeet/CrazyFeetListener.java
2556
package tk.acronus.CrazyFeet; import org.bukkit.ChatColor; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; public class CrazyFeetListener implements Listener { ChatColor green = ChatColor.GREEN; @EventHandler public void onCrazyFireMove(PlayerMoveEvent pME) { Player player = pME.getPlayer(); if(CrazyFeet.CrazyFire.contains(player)) { Location to = pME.getTo(); Location from = pME.getFrom(); Location loc = player.getLocation(); if(to.getX() != from.getBlockX() || to.getY() != from.getY() || to.getZ() != from.getZ()) { loc.setY(loc.getY()-1); player.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1, 100); } else { pME.setCancelled(false); } } else { pME.setCancelled(false); } } @EventHandler public void onCrazySmokeMove(PlayerMoveEvent pME) { Player player = pME.getPlayer(); if(CrazyFeet.CrazySmoke.contains(player)) { Location to = pME.getTo(); Location from = pME.getFrom(); Location loc = player.getLocation(); if(to.getX() != from.getBlockX() || to.getY() != from.getY() || to.getZ() != from.getZ()) { loc.setY(loc.getY()); player.getWorld().playEffect(loc, Effect.SMOKE, 1, 100); } else { pME.setCancelled(false); } } else { pME.setCancelled(false); } } @EventHandler public void onCrazyMagicMove(PlayerMoveEvent pME) { Player player = pME.getPlayer(); if(CrazyFeet.CrazyMagic.contains(player)) { Location to = pME.getTo(); Location from = pME.getFrom(); Location loc = player.getLocation(); if(to.getX() != from.getBlockX() || to.getY() != from.getY() || to.getZ() != from.getZ()) { loc.setY(loc.getY()-1); player.getWorld().playEffect(loc, Effect.POTION_BREAK, 1, 100); } else { pME.setCancelled(false); } } else { pME.setCancelled(false); } } @EventHandler public void onCrazyPearlMove(PlayerMoveEvent pME) { Player player = pME.getPlayer(); if(CrazyFeet.CrazyPearl.contains(player)) { Location to = pME.getTo(); Location from = pME.getFrom(); Location loc = player.getLocation(); if(to.getX() != from.getBlockX() || to.getY() != from.getY() || to.getZ() != from.getZ()) { loc.setY(loc.getY()); player.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1, 100); } else { pME.setCancelled(false); } } else { pME.setCancelled(false); } } }
gpl-2.0
meijmOrg/Repo-test
freelance-hr-info/src/java/com/yh/hr/info/ver/unit/comm/dto/VerPbOwnAllowanceDTO.java
3082
package com.yh.hr.info.ver.unit.comm.dto; public class VerPbOwnAllowanceDTO{ /** *主键 **/ private java.lang.Long ownAllowanceOid; /** *PersonOid **/ private java.lang.Long personOid; /** *津贴类别编码 **/ private java.lang.String allowanceCategoryCode; /** *津贴类别名称 **/ private java.lang.String allowanceCategoryName; /** *津贴编码 **/ private java.lang.String allowanceCode; /** *津贴名称 **/ private java.lang.String allowanceName; /** *金额 **/ private java.lang.Double allowanceAmount; /** *开始享受时间 **/ private java.util.Date startDate; private java.lang.String startDateStr; /** *截止享受时间 **/ private java.util.Date endDate; private java.lang.String endDateStr; /** *备注 **/ private java.lang.String remark; public VerPbOwnAllowanceDTO() { } public java.lang.String getStartDateStr() { return startDateStr; } public void setStartDateStr(java.lang.String startDateStr) { this.startDateStr = startDateStr; } public java.lang.String getEndDateStr() { return endDateStr; } public void setEndDateStr(java.lang.String endDateStr) { this.endDateStr = endDateStr; } public java.lang.Long getOwnAllowanceOid() { return ownAllowanceOid; } public void setOwnAllowanceOid(java.lang.Long ownAllowanceOid) { this.ownAllowanceOid = ownAllowanceOid; } public java.lang.String getAllowanceCategoryCode() { return allowanceCategoryCode; } public void setAllowanceCategoryCode(java.lang.String allowanceCategoryCode) { this.allowanceCategoryCode = allowanceCategoryCode; } public java.lang.String getAllowanceCategoryName() { return allowanceCategoryName; } public void setAllowanceCategoryName(java.lang.String allowanceCategoryName) { this.allowanceCategoryName = allowanceCategoryName; } public java.lang.String getAllowanceCode() { return allowanceCode; } public void setAllowanceCode(java.lang.String allowanceCode) { this.allowanceCode = allowanceCode; } public java.lang.String getAllowanceName() { return allowanceName; } public void setAllowanceName(java.lang.String allowanceName) { this.allowanceName = allowanceName; } public java.lang.Double getAllowanceAmount() { return allowanceAmount; } public void setAllowanceAmount(java.lang.Double allowanceAmount) { this.allowanceAmount = allowanceAmount; } public java.util.Date getStartDate() { return startDate; } public void setStartDate(java.util.Date startDate) { this.startDate = startDate; } public java.util.Date getEndDate() { return endDate; } public void setEndDate(java.util.Date endDate) { this.endDate = endDate; } public java.lang.String getRemark() { return remark; } public void setRemark(java.lang.String remark) { this.remark = remark; } public void setPersonOid(java.lang.Long personOid){ this.personOid = personOid; } public java.lang.Long getPersonOid(){ return this.personOid; } }
gpl-2.0
truhanen/JSana
JSana/src_others/org/crosswire/jsword/passage/ReadOnlyKeyList.java
6476
/** * Distribution License: * JSword is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License, version 2.1 as published by * the Free Software Foundation. This program is distributed in the hope * that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The License is available on the internet at: * http://www.gnu.org/copyleft/lgpl.html * or by writing to: * Free Software Foundation, Inc. * 59 Temple Place - Suite 330 * Boston, MA 02111-1307, USA * * Copyright: 2005 * The copyright to this program is held by it's authors. * * ID: $Id: ReadOnlyKeyList.java 2110 2011-03-08 13:55:32Z dmsmith $ */ package org.crosswire.jsword.passage; import java.util.Iterator; import org.crosswire.jsword.JSOtherMsg; /** * A read-only wrapper around any writable implementation of Key. * * @see gnu.lgpl.License for license details.<br> * The copyright to this program is held by it's authors. * @author Joe Walker [joe at eireneh dot com] */ public class ReadOnlyKeyList implements Key { /** * Simple ctor */ public ReadOnlyKeyList(Key keys, boolean ignore) { this.keys = keys; this.ignore = ignore; } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#getCardinality() */ public int getCardinality() { return keys.getCardinality(); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#canHaveChildren() */ public boolean canHaveChildren() { return keys.canHaveChildren(); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#getChildCount() */ public int getChildCount() { return keys.getChildCount(); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#isEmpty() */ public boolean isEmpty() { return keys.isEmpty(); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#contains(org.crosswire.jsword.passage.Key) */ public boolean contains(Key key) { return keys.contains(key); } /* (non-Javadoc) * @see java.lang.Iterable#iterator() */ public Iterator<Key> iterator() { return keys.iterator(); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#addAll(org.crosswire.jsword.passage.Key) */ public void addAll(Key key) { if (ignore) { return; } throw new IllegalStateException(JSOtherMsg.lookupText("Cannot alter a read-only key list")); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#removeAll(org.crosswire.jsword.passage.Key) */ public void removeAll(Key key) { if (ignore) { return; } throw new IllegalStateException(JSOtherMsg.lookupText("Cannot alter a read-only key list")); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#retainAll(org.crosswire.jsword.passage.Key) */ public void retainAll(Key key) { if (ignore) { return; } throw new IllegalStateException(JSOtherMsg.lookupText("Cannot alter a read-only key list")); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#clear() */ public void clear() { if (ignore) { return; } throw new IllegalStateException(JSOtherMsg.lookupText("Cannot alter a read-only key list")); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#getName() */ public String getName() { return keys.getName(); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#getRootName() */ public String getRootName() { return keys.getRootName(); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#getName(org.crosswire.jsword.passage.Key) */ public String getName(Key base) { return keys.getName(base); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#getOsisRef() */ public String getOsisRef() { return keys.getOsisRef(); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#getOsisID() */ public String getOsisID() { return keys.getOsisID(); } @Override public int hashCode() { return keys.hashCode(); } @Override public boolean equals(Object obj) { return keys.equals(obj); } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Key o) { return keys.compareTo(o); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#get(int) */ public Key get(int index) { return keys.get(index); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#indexOf(org.crosswire.jsword.passage.Key) */ public int indexOf(Key that) { return keys.indexOf(that); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#getParent() */ public Key getParent() { return keys.getParent(); } /* (non-Javadoc) * @see org.crosswire.jsword.passage.Key#blur(int, org.crosswire.jsword.passage.RestrictionType) */ public void blur(int by, RestrictionType restrict) { if (ignore) { return; } throw new IllegalStateException(JSOtherMsg.lookupText("Cannot alter a read-only key list")); } @Override public ReadOnlyKeyList clone() { ReadOnlyKeyList clone = null; try { clone = (ReadOnlyKeyList) super.clone(); clone.keys = keys.clone(); } catch (CloneNotSupportedException e) { assert false : e; } return clone; } /** * Do we ignore write requests or throw? */ private boolean ignore; /** * The Key to which we proxy */ private Key keys; /** * Serialization ID */ private static final long serialVersionUID = -7947159638198641657L; }
gpl-2.0
PrincetonUniversity/NVJVM
build/linux-amd64/jaxws/drop/jaxws_src/src/com/sun/xml/internal/xsom/impl/parser/state/group.java
16167
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. 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. */ /* this file is generated by RelaxNGCC */ package com.sun.xml.internal.xsom.impl.parser.state; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.Attributes; import com.sun.xml.internal.xsom.impl.parser.NGCCRuntimeEx; import com.sun.xml.internal.xsom.*; import com.sun.xml.internal.xsom.parser.*; import com.sun.xml.internal.xsom.impl.*; import com.sun.xml.internal.xsom.impl.parser.*; import org.xml.sax.Locator; import org.xml.sax.ContentHandler; import org.xml.sax.helpers.*; import java.util.*; import java.math.BigInteger; class group extends NGCCHandler { private AnnotationImpl annotation; private String name; private ModelGroupImpl term; private ForeignAttributesImpl fa; protected final NGCCRuntimeEx $runtime; private int $_ngcc_current_state; protected String $uri; protected String $localName; protected String $qname; public final NGCCRuntime getRuntime() { return($runtime); } public group(NGCCHandler parent, NGCCEventSource source, NGCCRuntimeEx runtime, int cookie) { super(source, parent, cookie); $runtime = runtime; $_ngcc_current_state = 15; } public group(NGCCRuntimeEx runtime) { this(null, runtime, runtime, -1); } private void action0()throws SAXException { result = new ModelGroupDeclImpl( $runtime.document, annotation, loc, fa, $runtime.currentSchema.getTargetNamespace(), name, term ); } private void action1()throws SAXException { mloc = $runtime.copyLocator(); compositorName = $localName; } private void action2()throws SAXException { loc = $runtime.copyLocator(); } public void enterElement(String $__uri, String $__local, String $__qname, Attributes $attrs) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 3: { if((((($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("all")) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("choice"))) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("sequence"))) || (($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("element")) || (($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("any")) || (($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("group")) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("annotation"))))))) { NGCCHandler h = new modelGroupBody(this, super._source, $runtime, 113, mloc,compositorName); spawnChildFromEnterElement(h, $__uri, $__local, $__qname, $attrs); } else { unexpectedEnterElement($__qname); } } break; case 15: { if(($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("group"))) { $runtime.onEnterElementConsumed($__uri, $__local, $__qname, $attrs); action2(); $_ngcc_current_state = 11; } else { unexpectedEnterElement($__qname); } } break; case 6: { if(($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("annotation"))) { NGCCHandler h = new annotation(this, super._source, $runtime, 117, null,AnnotationContext.MODELGROUP_DECL); spawnChildFromEnterElement(h, $__uri, $__local, $__qname, $attrs); } else { $_ngcc_current_state = 5; $runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs); } } break; case 10: { if(($ai = $runtime.getAttributeIndex("","name"))>=0) { $runtime.consumeAttribute($ai); $runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs); } else { unexpectedEnterElement($__qname); } } break; case 5: { if(((($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("all")) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("choice"))) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("sequence")))) { NGCCHandler h = new foreignAttributes(this, super._source, $runtime, 115, null); spawnChildFromEnterElement(h, $__uri, $__local, $__qname, $attrs); } else { unexpectedEnterElement($__qname); } } break; case 0: { revertToParentFromEnterElement(result, super._cookie, $__uri, $__local, $__qname, $attrs); } break; case 11: { if(($ai = $runtime.getAttributeIndex("","ID"))>=0) { $runtime.consumeAttribute($ai); $runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs); } else { $_ngcc_current_state = 10; $runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs); } } break; case 4: { if(((($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("all")) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("choice"))) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("sequence")))) { $runtime.onEnterElementConsumed($__uri, $__local, $__qname, $attrs); $_ngcc_current_state = 3; } else { unexpectedEnterElement($__qname); } } break; default: { unexpectedEnterElement($__qname); } break; } } public void leaveElement(String $__uri, String $__local, String $__qname) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 3: { if(((($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("all")) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("choice"))) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("sequence")))) { NGCCHandler h = new modelGroupBody(this, super._source, $runtime, 113, mloc,compositorName); spawnChildFromLeaveElement(h, $__uri, $__local, $__qname); } else { unexpectedLeaveElement($__qname); } } break; case 1: { if(($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("group"))) { $runtime.onLeaveElementConsumed($__uri, $__local, $__qname); $_ngcc_current_state = 0; action0(); } else { unexpectedLeaveElement($__qname); } } break; case 6: { $_ngcc_current_state = 5; $runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname); } break; case 2: { if(((($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("all")) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("choice"))) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("sequence")))) { $runtime.onLeaveElementConsumed($__uri, $__local, $__qname); $_ngcc_current_state = 1; } else { unexpectedLeaveElement($__qname); } } break; case 10: { if(($ai = $runtime.getAttributeIndex("","name"))>=0) { $runtime.consumeAttribute($ai); $runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname); } else { unexpectedLeaveElement($__qname); } } break; case 0: { revertToParentFromLeaveElement(result, super._cookie, $__uri, $__local, $__qname); } break; case 11: { if(($ai = $runtime.getAttributeIndex("","ID"))>=0) { $runtime.consumeAttribute($ai); $runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname); } else { $_ngcc_current_state = 10; $runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname); } } break; default: { unexpectedLeaveElement($__qname); } break; } } public void enterAttribute(String $__uri, String $__local, String $__qname) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 6: { $_ngcc_current_state = 5; $runtime.sendEnterAttribute(super._cookie, $__uri, $__local, $__qname); } break; case 10: { if(($__uri.equals("") && $__local.equals("name"))) { $_ngcc_current_state = 9; } else { unexpectedEnterAttribute($__qname); } } break; case 0: { revertToParentFromEnterAttribute(result, super._cookie, $__uri, $__local, $__qname); } break; case 11: { if(($__uri.equals("") && $__local.equals("ID"))) { $_ngcc_current_state = 13; } else { $_ngcc_current_state = 10; $runtime.sendEnterAttribute(super._cookie, $__uri, $__local, $__qname); } } break; default: { unexpectedEnterAttribute($__qname); } break; } } public void leaveAttribute(String $__uri, String $__local, String $__qname) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 6: { $_ngcc_current_state = 5; $runtime.sendLeaveAttribute(super._cookie, $__uri, $__local, $__qname); } break; case 8: { if(($__uri.equals("") && $__local.equals("name"))) { $_ngcc_current_state = 6; } else { unexpectedLeaveAttribute($__qname); } } break; case 0: { revertToParentFromLeaveAttribute(result, super._cookie, $__uri, $__local, $__qname); } break; case 11: { $_ngcc_current_state = 10; $runtime.sendLeaveAttribute(super._cookie, $__uri, $__local, $__qname); } break; case 12: { if(($__uri.equals("") && $__local.equals("ID"))) { $_ngcc_current_state = 10; } else { unexpectedLeaveAttribute($__qname); } } break; default: { unexpectedLeaveAttribute($__qname); } break; } } public void text(String $value) throws SAXException { int $ai; switch($_ngcc_current_state) { case 6: { $_ngcc_current_state = 5; $runtime.sendText(super._cookie, $value); } break; case 10: { if(($ai = $runtime.getAttributeIndex("","name"))>=0) { $runtime.consumeAttribute($ai); $runtime.sendText(super._cookie, $value); } } break; case 0: { revertToParentFromText(result, super._cookie, $value); } break; case 9: { name = $value; $_ngcc_current_state = 8; } break; case 11: { if(($ai = $runtime.getAttributeIndex("","ID"))>=0) { $runtime.consumeAttribute($ai); $runtime.sendText(super._cookie, $value); } else { $_ngcc_current_state = 10; $runtime.sendText(super._cookie, $value); } } break; case 13: { $_ngcc_current_state = 12; } break; } } public void onChildCompleted(Object $__result__, int $__cookie__, boolean $__needAttCheck__)throws SAXException { switch($__cookie__) { case 113: { term = ((ModelGroupImpl)$__result__); $_ngcc_current_state = 2; } break; case 115: { fa = ((ForeignAttributesImpl)$__result__); action1(); $_ngcc_current_state = 4; } break; case 117: { annotation = ((AnnotationImpl)$__result__); $_ngcc_current_state = 5; } break; } } public boolean accepted() { return(($_ngcc_current_state == 0)); } private ModelGroupDeclImpl result; private Locator loc,mloc; private String compositorName; }
gpl-2.0
moriyoshi/quercus-gae
src/main/java/com/caucho/quercus/expr/BitXorExpr.java
1909
/* * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.quercus.expr; import com.caucho.quercus.Location; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.Value; /** * Represents a PHP bitwise xor expression. */ public class BitXorExpr extends BinaryExpr { public BitXorExpr(Location location, Expr left, Expr right) { super(location, left, right); } public BitXorExpr(Expr left, Expr right) { super(left, right); } /** * Returns true for a long. */ public boolean isLong() { return true; } /** * Evaluates the expression. * * @param env the calling environment. * * @return the expression value. */ public Value eval(Env env) { Value lValue = _left.eval(env); Value rValue = _right.eval(env); return lValue.bitXor(rValue); } public String toString() { return "(" + _left + " ^ " + _right + ")"; } }
gpl-2.0
swatkatz/problem-solving
src/main/java/org/uber/JsonCreator.java
2676
package org.uber; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Description * * @author swkumar (swkumar@groupon.com) * @since 1.0.0 */ public class JsonCreator { private static void addValueToJson(Object value, StringBuffer sb) { if (value == null) { sb.append(createValue("null")); } else if (value instanceof Map) { Map<String, Object> castMap = (Map<String, Object>) value; sb.append("{"); for (Map.Entry<String, Object> entry : castMap.entrySet()) { String key = entry.getKey(); Object mapVal = entry.getValue(); sb.append(createKey(key)); addValueToJson(mapVal, sb); } sb.append("}"); } else if (value instanceof Boolean) { Boolean castVal = (Boolean) value; if (Boolean.TRUE.equals(castVal)) { sb.append(createValue("true")); } else { sb.append(createValue("false")); } } else if (value instanceof String) { String castVal = (String) value; sb.append(createValue(castVal)); } else if (value instanceof Integer) { Integer castVal = (Integer) value; sb.append(createValue(castVal.toString())); } else if (value instanceof List) { List<Object> castList = (List<Object>) value; sb.append(" ["); for (int i = 0; i < castList.size(); i++) { addValueToJson(castList.get(i), sb); } sb.replace(sb.length() - 1, sb.length(), ""); sb.append("]"); } else { throw new IllegalArgumentException("no definition found"); } } private static String createKey(String key) { return "\"" + key + "\" : "; } private static String createValue(String val) { return val + " ,"; } public static void main(String args[]) { Map<String, Object> jsonMem = new HashMap<String, Object>(); jsonMem.put("k1", 3); jsonMem.put("k2", "ser"); Map<String, Object> subMap = new HashMap<String, Object>(); List<Object> value = new ArrayList<Object>(); Map<String, Object> testMap = new HashMap<String, Object>(); testMap.put("k6", "str6"); value.addAll(Arrays.asList(true, 4, testMap)); subMap.put("k4", value); jsonMem.put("k3", subMap); StringBuffer sb = new StringBuffer(); addValueToJson(jsonMem, sb); System.out.println(sb); } }
gpl-2.0
SMLaursen/ShareLatex-Buddy-Android
ShareLaTeXBuddy/app/src/main/java/dk/smlaursen/sharelatexbuddy/ShareLaTeXFacade.java
7647
package dk.smlaursen.sharelatexbuddy; import android.os.Environment; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import javax.security.auth.login.LoginException; /** * Created by Sune on 18-02-2015. */ public class ShareLaTeXFacade { private static final int TIMEOUT = 3000; private static final String baseUrl = "http://192.168.1.76:3000"; //// PRIVATE HELPER METHODS //// /**This method validates the responsecode from a http-request and throws suitable errors if any*/ private static void validateResponseCode(int responseCode, String function) throws LoginException, UnsupportedOperationException{ int responseCategory = responseCode / 100; String msg; switch (responseCategory){ case 1: case 2: case 3: Log.d("validateResponseCode", "validated OK"); return; case 4: msg = responseCode+" during "+function+ " i.e. User Not Authenticated"; Log.e("validateResponseCode",msg); throw new LoginException(msg); case 5: msg = responseCode+" during "+function+ " i.e. ShareLaTeX-server unable to perform request"; Log.e("validateResponseCode",msg); throw new UnsupportedOperationException(msg); } } //// SHARELATEX API METHODS //// /** This method retrieves the projects visible to the logged in user which has to be stored using the CookieManager * @throws java.io.IOException When ShareLaTeX is unreachable * @throws javax.security.auth.login.LoginException if the user is not logged in * @throws java.lang.UnsupportedOperationException if ShareLaTeX could not execute our request for some reason. * @return HashMap<String,String> mapping between project names and ids*/ public static synchronized HashMap<String, String> getMapOfProjects() throws IOException,LoginException,UnsupportedOperationException{ String url = baseUrl+"/api/project"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); con.setRequestMethod("GET"); int responseCode = con.getResponseCode(); validateResponseCode(responseCode, "getMapOfProjects"); //If validated ok, read response BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = in.readLine()) != null) { response.append(line); } in.close(); con.disconnect(); //A map for holding the mappings between name and id of the projects HashMap<String, String> projectsMap = new HashMap<String,String>(); //Parse each project name/id pair try{ //Parse JSON into projects JSONObject jObject = new JSONObject(response.toString()); JSONArray jArray = jObject.getJSONArray("projects"); for(int i=0;i < jArray.length(); i++){ JSONObject oneObject = jArray.getJSONObject(i); //Skip deleted projects if(oneObject.has("archived") && oneObject.getString("archived").equals("true")){ continue; } String name = oneObject.getString("name"); String id = oneObject.getString("_id"); projectsMap.put(name, id); } //IF a JSON exception is catched, we received HTML instead of JSON indicating were not properly authenticated. } catch (JSONException e){ Log.e("getMapOfProjects","Received JSONException "+e.getMessage()+" while parsing response : "+response.toString()); throw new LoginException(); } return projectsMap; } /**This method instructs ShareLaTeX to compile the project with the given id. * @throws java.io.IOException When ShareLaTeX is unreachable * @throws javax.security.auth.login.LoginException if the user is not logged in properly * @throws java.lang.UnsupportedOperationException if ShareLaTeX could not execute our request for some reason.*/ public static synchronized void compilePDF(String id) throws IOException, LoginException, UnsupportedOperationException{ String url = baseUrl+"/api/project/"+id+"/compile"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); //Validate response-code int responseCode = con.getResponseCode(); validateResponseCode(responseCode, "compilePDF"); //If validated ok, read response BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = in.readLine()) != null) { response.append(line); } in.close(); con.disconnect(); try{ JSONObject jObject = new JSONObject(response.toString()); //Check that it could compile correctly and return here if that is the case if(jObject.has("status") && jObject.get("status").equals("success")) { return; } } catch(JSONException e){ Log.e("compilePDF","Unexpectedly received JSONException "+e); } //If did not compile properly throw exception throw new UnsupportedOperationException("ShareLaTeX was unable to compile project. /n The project may contain fatal syntax-errors. "); } /**This method fetches the pdf of the project with the given id. * @throws java.io.IOException When ShareLaTeX is unreachable * @throws javax.security.auth.login.LoginException if the user is not logged in properly * @throws java.lang.UnsupportedOperationException if ShareLaTeX could not execute our request for some reason. * @return the retrieved PDF-File*/ public static synchronized File retrievePDF(String id) throws IOException, LoginException, UnsupportedOperationException{ String url = baseUrl+"/api/project/"+id+"/output/output.pdf"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); //Validate response-code int responseCode = con.getResponseCode(); validateResponseCode(responseCode, "retrievePDF"); //If validated ok, create output file and start writing its contents File file = new File(Environment.getExternalStorageDirectory()+"/out.pdf"); OutputStream outStream = new FileOutputStream(file); int read = 0; byte[] bytes = new byte[1024]; InputStream in = con.getInputStream(); while ((read = in.read(bytes)) != -1) { outStream.write(bytes, 0, read); } outStream.flush(); outStream.close(); con.disconnect(); return file; } }
gpl-2.0
BuddhaLabs/DeD-OSX
soot/soot-2.3.0/generated/jastadd/soot/JastAddJ/AssignExpr.java
10322
package soot.JastAddJ; import java.util.HashSet;import java.util.LinkedHashSet;import java.io.File;import java.util.*;import beaver.*;import java.util.ArrayList;import java.util.zip.*;import java.io.*;import java.io.FileNotFoundException;import java.util.Collection;import soot.*;import soot.util.*;import soot.jimple.*;import soot.coffi.ClassFile;import soot.coffi.method_info;import soot.coffi.CONSTANT_Utf8_info;import soot.coffi.CoffiMethodSource; public abstract class AssignExpr extends Expr implements Cloneable { public void flushCache() { super.flushCache(); type_computed = false; type_value = null; } @SuppressWarnings({"unchecked", "cast"}) public AssignExpr clone() throws CloneNotSupportedException { AssignExpr node = (AssignExpr)super.clone(); node.type_computed = false; node.type_value = null; node.in$Circle(false); node.is$Final(false); return node; } // Declared in DefiniteAssignment.jrag at line 464 // 16.2.2 9th bullet protected boolean checkDUeverywhere(Variable v) { if(getDest().isVariable() && getDest().varDecl() == v) if(!getSource().isDAafter(v)) return false; return super.checkDUeverywhere(v); } // Declared in NodeConstructors.jrag at line 94 public static Stmt asStmt(Expr left, Expr right) { return new ExprStmt(new AssignSimpleExpr(left, right)); } // Declared in PrettyPrint.jadd at line 259 // Assign Expression public void toString(StringBuffer s) { getDest().toString(s); s.append(printOp()); getSource().toString(s); } // Declared in TypeCheck.jrag at line 52 public void typeCheck() { if(!getDest().isVariable()) error("left hand side is not a variable"); else { TypeDecl source = sourceType(); TypeDecl dest = getDest().type(); if(getSource().type().isPrimitive() && getDest().type().isPrimitive()) return; error("can not assign " + getDest() + " of type " + getDest().type().typeName() + " a value of type " + sourceType().typeName()); } } // Declared in Expressions.jrag at line 62 // compound assign expression public soot.Value eval(Body b) { TypeDecl dest = getDest().type(); TypeDecl source = getSource().type(); TypeDecl type; if(dest.isNumericType() && source.isNumericType()) type = dest.binaryNumericPromotion(source); else type = dest; Value lvalue = getDest().eval(b); Value v = lvalue instanceof Local ? lvalue : (Value)lvalue.clone(); Value value = b.newTemp(dest.emitCastTo(b, v, type)); Value rvalue = source.emitCastTo(b, getSource(), type); Value result = asImmediate(b, type.emitCastTo(b, createAssignOp(b, value, rvalue), dest )); getDest().emitStore(b, lvalue, result); return result; } // Declared in Expressions.jrag at line 125 // shift assign expression public soot.Value emitShiftExpr(Body b) { TypeDecl dest = getDest().type(); TypeDecl source = getSource().type(); TypeDecl type = dest.unaryNumericPromotion(); Value lvalue = getDest().eval(b); Value v = lvalue instanceof Local ? lvalue : (Value)lvalue.clone(); Value value = b.newTemp(dest.emitCastTo(b, v, type)); Value rvalue = source.emitCastTo(b, getSource(), typeInt()); Value result = asImmediate(b, type.emitCastTo(b, createAssignOp(b, value, rvalue), dest )); getDest().emitStore(b, lvalue, result); return result; } // Declared in Expressions.jrag at line 148 // create the operation for a compound assign expression public soot.Value createAssignOp(Body b, soot.Value fst, soot.Value snd) { throw new Error("Operation createAssignOp is not implemented for " + getClass().getName()); } // Declared in java.ast at line 3 // Declared in java.ast line 99 public AssignExpr() { super(); } // Declared in java.ast at line 10 // Declared in java.ast line 99 public AssignExpr(Expr p0, Expr p1) { setChild(p0, 0); setChild(p1, 1); } // Declared in java.ast at line 15 protected int numChildren() { return 2; } // Declared in java.ast at line 18 public boolean mayHaveRewrite() { return false; } // Declared in java.ast at line 2 // Declared in java.ast line 99 public void setDest(Expr node) { setChild(node, 0); } // Declared in java.ast at line 5 public Expr getDest() { return (Expr)getChild(0); } // Declared in java.ast at line 9 public Expr getDestNoTransform() { return (Expr)getChildNoTransform(0); } // Declared in java.ast at line 2 // Declared in java.ast line 99 public void setSource(Expr node) { setChild(node, 1); } // Declared in java.ast at line 5 public Expr getSource() { return (Expr)getChild(1); } // Declared in java.ast at line 9 public Expr getSourceNoTransform() { return (Expr)getChildNoTransform(1); } // Declared in DefiniteAssignment.jrag at line 394 @SuppressWarnings({"unchecked", "cast"}) public boolean isDAafter(Variable v) { boolean isDAafter_Variable_value = isDAafter_compute(v); return isDAafter_Variable_value; } private boolean isDAafter_compute(Variable v) { return getSource().isDAafter(v); } // Declared in DefiniteAssignment.jrag at line 398 @SuppressWarnings({"unchecked", "cast"}) public boolean isDAafterTrue(Variable v) { boolean isDAafterTrue_Variable_value = isDAafterTrue_compute(v); return isDAafterTrue_Variable_value; } private boolean isDAafterTrue_compute(Variable v) { return isDAafter(v) || isFalse(); } // Declared in DefiniteAssignment.jrag at line 399 @SuppressWarnings({"unchecked", "cast"}) public boolean isDAafterFalse(Variable v) { boolean isDAafterFalse_Variable_value = isDAafterFalse_compute(v); return isDAafterFalse_Variable_value; } private boolean isDAafterFalse_compute(Variable v) { return isDAafter(v) || isTrue(); } // Declared in DefiniteAssignment.jrag at line 827 @SuppressWarnings({"unchecked", "cast"}) public boolean isDUafter(Variable v) { boolean isDUafter_Variable_value = isDUafter_compute(v); return isDUafter_Variable_value; } private boolean isDUafter_compute(Variable v) { return getSource().isDUafter(v); } // Declared in DefiniteAssignment.jrag at line 830 @SuppressWarnings({"unchecked", "cast"}) public boolean isDUafterTrue(Variable v) { boolean isDUafterTrue_Variable_value = isDUafterTrue_compute(v); return isDUafterTrue_Variable_value; } private boolean isDUafterTrue_compute(Variable v) { return isDUafter(v); } // Declared in DefiniteAssignment.jrag at line 831 @SuppressWarnings({"unchecked", "cast"}) public boolean isDUafterFalse(Variable v) { boolean isDUafterFalse_Variable_value = isDUafterFalse_compute(v); return isDUafterFalse_Variable_value; } private boolean isDUafterFalse_compute(Variable v) { return isDUafter(v); } // Declared in PrettyPrint.jadd at line 265 @SuppressWarnings({"unchecked", "cast"}) public String printOp() { String printOp_value = printOp_compute(); return printOp_value; } private String printOp_compute() { return " = "; } protected boolean type_computed = false; protected TypeDecl type_value; // Declared in TypeAnalysis.jrag at line 298 @SuppressWarnings({"unchecked", "cast"}) public TypeDecl type() { if(type_computed) return type_value; int num = boundariesCrossed; boolean isFinal = this.is$Final(); type_value = type_compute(); if(isFinal && num == boundariesCrossed) type_computed = true; return type_value; } private TypeDecl type_compute() { return getDest().type(); } // Declared in TypeCheck.jrag at line 109 @SuppressWarnings({"unchecked", "cast"}) public TypeDecl sourceType() { TypeDecl sourceType_value = sourceType_compute(); return sourceType_value; } private TypeDecl sourceType_compute() { return getSource().type().isPrimitive() ? getSource().type() : unknownType(); } // Declared in DefiniteAssignment.jrag at line 29 public boolean Define_boolean_isSource(ASTNode caller, ASTNode child) { if(caller == getSourceNoTransform()) { return true; } if(caller == getDestNoTransform()) { return true; } return getParent().Define_boolean_isSource(this, caller); } // Declared in DefiniteAssignment.jrag at line 19 public boolean Define_boolean_isDest(ASTNode caller, ASTNode child) { if(caller == getSourceNoTransform()) { return false; } if(caller == getDestNoTransform()) { return true; } return getParent().Define_boolean_isDest(this, caller); } // Declared in SyntacticClassification.jrag at line 99 public NameType Define_NameType_nameType(ASTNode caller, ASTNode child) { if(caller == getDestNoTransform()) { return NameType.EXPRESSION_NAME; } return getParent().Define_NameType_nameType(this, caller); } // Declared in DefiniteAssignment.jrag at line 396 public boolean Define_boolean_isDAbefore(ASTNode caller, ASTNode child, Variable v) { if(caller == getDestNoTransform()) { return isDAbefore(v); } if(caller == getSourceNoTransform()) { return getDest().isDAafter(v); } return getParent().Define_boolean_isDAbefore(this, caller, v); } // Declared in DefiniteAssignment.jrag at line 829 public boolean Define_boolean_isDUbefore(ASTNode caller, ASTNode child, Variable v) { if(caller == getDestNoTransform()) { return isDUbefore(v); } if(caller == getSourceNoTransform()) { return getDest().isDUafter(v); } return getParent().Define_boolean_isDUbefore(this, caller, v); } public ASTNode rewriteTo() { return super.rewriteTo(); } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/test/java/rmi/reliability/benchmark/bench/serial/CharArrays.java
2988
/* * 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. */ /* * */ package bench.serial; import bench.Benchmark; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Benchmark for testing speed of char array reads/writes. */ public class CharArrays implements Benchmark { /** * Write and read char arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write * cycles. The ObjectOutputStream is reset after each batch of cycles has * completed. * Arguments: <array size> <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { int size = Integer.parseInt(args[0]); int nbatches = Integer.parseInt(args[1]); int ncycles = Integer.parseInt(args[2]); char[][] arrays = new char[ncycles][size]; StreamBuffer sbuf = new StreamBuffer(); ObjectOutputStream oout = new ObjectOutputStream(sbuf.getOutputStream()); ObjectInputStream oin = new ObjectInputStream(sbuf.getInputStream()); doReps(oout, oin, sbuf, arrays, 1); // warmup long start = System.currentTimeMillis(); doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; } /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, StreamBuffer sbuf, char[][] arrays, int nbatches) throws Exception { int ncycles = arrays.length; for (int i = 0; i < nbatches; i++) { sbuf.reset(); oout.reset(); for (int j = 0; j < ncycles; j++) { oout.writeObject(arrays[j]); } oout.flush(); for (int j = 0; j < ncycles; j++) { oin.readObject(); } } } }
gpl-2.0
vuze/vuze-remote-for-android
vuzeAndroidRemote/src/main/java/com/vuze/android/remote/session/Session_Tag.java
7493
/* * 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. * 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.vuze.android.remote.session; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import com.vuze.android.remote.*; import com.vuze.android.remote.rpc.*; import com.vuze.util.MapUtils; import com.vuze.util.Thunk; import android.support.annotation.Nullable; import android.support.v4.util.LongSparseArray; /** * Tag methods for a {@link Session} * * Created by TuxPaper on 12/13/16. */ public class Session_Tag { @Thunk final Session session; private final List<TagListReceivedListener> tagListReceivedListeners = new CopyOnWriteArrayList<>(); @Thunk LongSparseArray<Map<?, ?>> mapTags; @Thunk boolean needsTagRefresh = false; private Long tagAllUID = null; Session_Tag(Session session) { this.session = session; } public void addTagListReceivedListener(TagListReceivedListener l) { session.ensureNotDestroyed(); synchronized (tagListReceivedListeners) { if (!tagListReceivedListeners.contains(l)) { tagListReceivedListeners.add(l); if (mapTags != null) { l.tagListReceived(getTags()); } } } } public void destroy() { tagListReceivedListeners.clear(); } @SuppressWarnings("unchecked") @Nullable public Map<?, ?> getTag(Long uid) { session.ensureNotDestroyed(); if (uid < 10) { AndroidUtils.ValueStringArray basicTags = AndroidUtils.getValueStringArray( VuzeRemoteApp.getContext().getResources(), R.array.filterby_list); for (int i = 0; i < basicTags.size; i++) { if (uid == basicTags.values[i]) { Map map = new HashMap(); map.put("uid", uid); String name = basicTags.strings[i].replaceAll("Download State: ", ""); map.put("name", name); return map; } } } if (mapTags == null) { return null; } Map<?, ?> map = mapTags.get(uid); if (map == null) { needsTagRefresh = true; } return map; } public Long getTagAllUID() { session.ensureNotDestroyed(); return tagAllUID; } @Nullable public List<Map<?, ?>> getTags() { session.ensureNotDestroyed(); if (mapTags == null) { return null; } ArrayList<Map<?, ?>> list = new ArrayList<>(); synchronized (session.mLock) { for (int i = 0, num = mapTags.size(); i < num; i++) { list.add(mapTags.valueAt(i)); } } Collections.sort(list, new Comparator<Map<?, ?>>() { @Override public int compare(Map<?, ?> lhs, Map<?, ?> rhs) { int lType = MapUtils.getMapInt(lhs, "type", 0); int rType = MapUtils.getMapInt(rhs, "type", 0); if (lType < rType) { return -1; } if (lType > rType) { return 1; } String lhGroup = MapUtils.getMapString(lhs, TransmissionVars.FIELD_TAG_GROUP, ""); String rhGroup = MapUtils.getMapString(rhs, TransmissionVars.FIELD_TAG_GROUP, ""); int i = lhGroup.compareToIgnoreCase(rhGroup); if (i != 0) { return i; } String lhName = MapUtils.getMapString(lhs, "name", ""); String rhName = MapUtils.getMapString(rhs, "name", ""); return lhName.compareToIgnoreCase(rhName); } }); return list; } @SuppressWarnings("unchecked") @Thunk void placeTagListIntoMap(List<?> tagList) { // put new list of tags into mapTags. Update the existing tag Map in case // some other part of the app stored a reference to it. synchronized (session.mLock) { int numUserCategories = 0; long uidUncat = -1; LongSparseArray mapNewTags = new LongSparseArray<>(tagList.size()); for (Object tag : tagList) { if (tag instanceof Map) { Map<?, ?> mapNewTag = (Map<?, ?>) tag; Long uid = MapUtils.getMapLong(mapNewTag, "uid", 0); Map mapOldTag = mapTags == null ? null : mapTags.get(uid); if (mapNewTag.containsKey("name")) { if (mapOldTag == null) { mapNewTags.put(uid, mapNewTag); } else { mapOldTag.clear(); mapOldTag.putAll(mapNewTag); mapNewTags.put(uid, mapOldTag); } } else { long count = MapUtils.getMapLong(mapNewTag, TransmissionVars.FIELD_TAG_COUNT, -1); if (count >= 0 && mapOldTag != null) { mapOldTag.put(TransmissionVars.FIELD_TAG_COUNT, count); } mapNewTags.put(uid, mapOldTag); } int type = MapUtils.getMapInt(mapNewTag, "type", 0); //category if (type == 1) { // USER=0,ALL=1,UNCAT=2 int catType = MapUtils.getMapInt(mapNewTag, TransmissionVars.FIELD_TAG_CATEGORY_TYPE, -1); if (catType == 0) { numUserCategories++; } else if (catType == 1) { tagAllUID = uid; } else if (catType == 2) { uidUncat = uid; } } } } if (numUserCategories == 0 && uidUncat >= 0) { mapNewTags.remove(uidUncat); } mapTags = mapNewTags; } if (tagListReceivedListeners.size() > 0) { List<Map<?, ?>> tags = session.tag.getTags(); for (TagListReceivedListener l : tagListReceivedListeners) { l.tagListReceived(tags); } } } public void refreshTags(boolean onlyRefreshCount) { if (!session.getSupports(RPCSupports.SUPPORTS_TAGS)) { return; } if (mapTags == null || mapTags.size() == 0) { onlyRefreshCount = false; } Map args = null; if (onlyRefreshCount) { args = new HashMap(1); //noinspection unchecked args.put("fields", Arrays.asList("uid", TransmissionVars.FIELD_TAG_COUNT)); } session.transmissionRPC.simpleRpcCall("tags-get-list", args, new ReplyMapReceivedListener() { @Override public void rpcError(String id, Exception e) { needsTagRefresh = false; } @Override public void rpcFailure(String id, String message) { needsTagRefresh = false; } @Override public void rpcSuccess(String id, Map<?, ?> optionalMap) { needsTagRefresh = false; List<?> tagList = MapUtils.getMapList(optionalMap, "tags", null); if (tagList == null) { synchronized (session.mLock) { mapTags = null; } return; } placeTagListIntoMap(tagList); } }); } public void removeTagListReceivedListener(TagListReceivedListener l) { synchronized (tagListReceivedListeners) { tagListReceivedListeners.remove(l); } } public void removeTagFromTorrents(final String callID, final long[] torrentIDs, final Object[] tags) { session._executeRpc(new Session.RpcExecuter() { @Override public void executeRpc(TransmissionRPC rpc) { rpc.removeTagFromTorrents(callID, torrentIDs, tags); } }); } public void addTagToTorrents(final String callID, final long[] torrentIDs, final Object[] tags) { session._executeRpc(new Session.RpcExecuter() { @Override public void executeRpc(TransmissionRPC rpc) { rpc.addTagToTorrents(callID, torrentIDs, tags); } }); } }
gpl-2.0
nrgaway/qubes-tools
experimental/tomcat/apache-tomcat-8.0.15-src/test/org/apache/tomcat/util/net/jsse/openssl/TesterOpenSSL.java
7795
/* * 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.net.jsse.openssl; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.catalina.util.IOTools; import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream; public class TesterOpenSSL { public static final String EXPECTED_VERSION = "1.0.1j"; public static final boolean IS_EXPECTED_VERSION; public static final Set<Cipher> OPENSSL_UNIMPLEMENTED_CIPHERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( Cipher.TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, Cipher.TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, Cipher.TLS_DH_DSS_WITH_AES_256_GCM_SHA384, Cipher.TLS_DH_RSA_WITH_AES_256_GCM_SHA384, Cipher.TLS_DH_DSS_WITH_AES_256_CBC_SHA256, Cipher.TLS_DH_RSA_WITH_AES_256_CBC_SHA256, Cipher.TLS_DH_RSA_WITH_AES_256_CBC_SHA, Cipher.TLS_DH_DSS_WITH_AES_256_CBC_SHA, Cipher.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA, Cipher.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA, Cipher.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA, Cipher.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA, Cipher.TLS_DH_DSS_WITH_AES_128_GCM_SHA256, Cipher.TLS_DH_RSA_WITH_AES_128_CBC_SHA256, Cipher.TLS_DH_DSS_WITH_AES_128_CBC_SHA256, Cipher.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA, Cipher.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA, Cipher.TLS_DH_RSA_WITH_AES_128_GCM_SHA256, Cipher.TLS_DH_RSA_WITH_AES_128_CBC_SHA, Cipher.TLS_DH_DSS_WITH_AES_128_CBC_SHA, Cipher.TLS_DH_RSA_WITH_DES_CBC_SHA, Cipher.TLS_DH_DSS_WITH_DES_CBC_SHA, Cipher.TLS_DH_RSA_WITH_SEED_CBC_SHA, Cipher.TLS_DH_DSS_WITH_SEED_CBC_SHA, Cipher.TLS_DHE_DSS_WITH_RC4_128_SHA, Cipher.SSL_CK_RC2_128_CBC_WITH_MD5, Cipher.SSL_FORTEZZA_DMS_WITH_NULL_SHA, Cipher.SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA, Cipher.SSL_FORTEZZA_DMS_WITH_RC4_128_SHA, Cipher.TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA, Cipher.TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, Cipher.TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5, Cipher.TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA, Cipher.TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, Cipher.TLS_RSA_EXPORT1024_WITH_RC4_56_MD5))); static { String versionString = null; try { versionString = executeOpenSSLCommand("version"); } catch (IOException e) { versionString = ""; } IS_EXPECTED_VERSION = versionString.contains(EXPECTED_VERSION); } private TesterOpenSSL() { // Utility class. Hide default constructor. } public static Set<String> getOpenSSLCiphersAsSet(String specification) throws Exception { String[] ciphers = getOpenSSLCiphersAsExpression(specification).trim().split(":"); Set<String> result = new HashSet<>(ciphers.length); for (String cipher : ciphers) { result.add(cipher); } return result; } public static String getOpenSSLCiphersAsExpression(String specification) throws Exception { String stdout; if (specification == null) { stdout = executeOpenSSLCommand("ciphers", "-v"); } else { stdout = executeOpenSSLCommand("ciphers", "-v", specification); } if (stdout.length() == 0) { return stdout; } StringBuilder output = new StringBuilder(); boolean first = true; // OpenSSL should have returned one cipher per line String ciphers[] = stdout.split("\n"); for (String cipher : ciphers) { if (first) { first = false; } else { output.append(':'); } // Name is first part int i = cipher.indexOf(' '); output.append(cipher.substring(0, i)); // Advance i past the space while (Character.isWhitespace(cipher.charAt(i))) { i++; } // Protocol is the second int j = cipher.indexOf(' ', i); output.append('+'); output.append(cipher.substring(i, j)); } return output.toString(); } /* * Use this method to filter parser results when comparing them to OpenSSL * results to take account of unimplemented cipher suites. */ public static void removeUnimplementedCiphersJsse(List<String> list) { for (Cipher cipher : OPENSSL_UNIMPLEMENTED_CIPHERS) { for (String jsseName : cipher.getJsseNames()) { list.remove(jsseName); } } } private static String executeOpenSSLCommand(String... args) throws IOException { String openSSLPath = System.getProperty("tomcat.test.openssl.path"); if (openSSLPath == null || openSSLPath.length() == 0) { openSSLPath = "openssl"; } List<String> cmd = new ArrayList<>(); cmd.add(openSSLPath); for (String arg : args) { cmd.add(arg); } ProcessBuilder pb = new ProcessBuilder(cmd.toArray(new String[cmd.size()])); Process p = pb.start(); InputStreamToText stdout = new InputStreamToText(p.getInputStream()); InputStreamToText stderr = new InputStreamToText(p.getErrorStream()); Thread t1 = new Thread(stdout); t1.setName("OpenSSL stdout reader"); t1.start(); Thread t2 = new Thread(stderr); t2.setName("OpenSSL stderr reader"); t2.start(); try { p.waitFor(); } catch (InterruptedException e) { throw new IOException(e); } String errorText = stderr.getText(); if (errorText.length() > 0) { System.err.println(errorText); } return stdout.getText().trim(); } private static class InputStreamToText implements Runnable { private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); private final InputStream is; InputStreamToText(InputStream is) { this.is = is; } @Override public void run() { try { IOTools.flow(is, baos); } catch (IOException e) { // Ignore } } public String getText() { return baos.toString(); } } }
gpl-2.0
jensnerche/plantuml
src/net/sourceforge/plantuml/sequencediagram/puma/SegmentPosition.java
1708
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2014, Arnaud Roques * * Project Info: http://plantuml.sourceforge.net * * This file is part of PlantUML. * * PlantUML 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. * * PlantUML 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * Original Author: Arnaud Roques * * Revision $Revision: 4636 $ * */ package net.sourceforge.plantuml.sequencediagram.puma; public class SegmentPosition { final private PSegment segment; final private double position; public SegmentPosition(PSegment segment, double position) { this.segment = segment; this.position = position; } public double getPosition() { return segment.getPosition(position); } public PSegment getSegment() { return segment; } }
gpl-2.0
setjmp2013/WowLogParser
src/wowlogparser/gui/AuraInfoFrame.java
1517
/* This file is part of Wow Log Parser, a program to parse World of Warcraft combat log files. Copyright (C) Gustav Haapalahti 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package wowlogparser.gui; import java.awt.Frame; import java.util.List; import javax.swing.JFrame; import wowlogparserbase.events.BasicEvent; /** * * @author racy */ public class AuraInfoFrame extends JFrame { public AuraInfoFrame(List<BasicEvent> events, double startTime, double stopTime, Frame owner, String title, boolean modal) { super(title); setDefaultCloseOperation(DISPOSE_ON_CLOSE); initComponents(events, startTime, stopTime); pack(); } public void initComponents(List<BasicEvent> events, double startTime, double stopTime) { AuraInfoPanel p = new AuraInfoPanel(events, startTime, stopTime); getContentPane().add(p); } }
gpl-2.0
kumait/HXFj
src/main/java/hxf/persistence/descriptors/Parameter.java
108
package hxf.persistence.descriptors; /** * Created by kumait on 8/25/2015. */ public class Parameter { }
gpl-2.0
PimvanGurp/advanced-java
src/nl/HAN/ASD/APP/tree/BSTree.java
11485
package nl.HAN.ASD.APP.tree; import java.security.InvalidParameterException; /** * Created by Pim van Gurp, 9/21/2015. */ public class BSTree<T extends Comparable<? super T>, E> { /** * Key of the object stored in the current node */ private T key; /** * Value of the object stored in the current node */ private E value; /** * Tree connected to the left */ private BSTree<T, E> left; /** * Tree connected to the right */ private BSTree<T, E> right; /** * Sum of all the subtrees underneath the current node */ private int subTreeValue; /** * Empty constructor */ public BSTree() {} /** * Constructor that immediately * sets the current object stored * @param key identifier of object * @param value contents of object */ public BSTree(T key, E value) { this.key = key; this.value = value; subTreeValue = 0; } /** * Check if current node has children * @return 1 node has no children * 0 node has children */ public Boolean isLeaf() { return left == null && right == null; } /** * Get the contents of the stored object * @return contents */ public E getValue() { return value; } /** * Add a new node to the tree by comparing it * to the current node and hanging it left or right * @param other node to compare and add * @param value content of the new node */ public void add(T other, E value) { if(key == null) { key = other; this.value = value; } if(key.compareTo( other ) > 0) { addLeft( other, value ); } else if(key.compareTo( other ) < 0) { addRight( other, value ); } } /** * Add the new node to the left of the current node * @param other key of node to add * @param value content of new node */ public void addLeft(T other, E value) { if(left == null) { left = new BSTree<>( other, value ); } else { left.add(other, value); } } /** * Add the new node to the right of the current node * @param other key of node to add * @param value content of new node */ public void addRight(T other, E value) { if(right == null) { right = new BSTree<>( other, value ); } else { right.add(other, value); } } /** * find a value in the tree by recursively comparing it * @param k key of object that should be in the tree * @return null if item not found or value if found */ public E find(T k) { if(isLeaf()) return null; int factor = k.compareTo(key); if(factor == 0) return value; return (factor > 0) ? right.find(k) : left.find(k); } /** * Same as find but returns the subtree instead of only the value * @param k key of the object to find * @return tree with object as root */ public BSTree<T, E> findTree(T k) { if(isLeaf()) return null; int factor = key.compareTo(k); if(factor == 0) return this; return (factor < 0) ? right.findTree(k) : left.findTree(k); } /** * Find the maximum value in the current tree * @return max value */ public E max() { return right == null ? value : right.max(); } /** * Same as max but returns a tree * @return max subtree in current tree */ public BSTree<T, E> maxTree() { return right == null ? this : right.maxTree(); } /** * Find minimum value in current tree * @return minimum value */ public E min() { return left == null ? value : left.min(); } /** * Same as min but returns a tree * @return minimum tree */ public BSTree<T, E> minTree() { return left == null ? this : left.minTree(); } /** * Recursively remove a value inside the tree * @param k key of the object to remove from the tree * @return the removed tree */ public BSTree<T, E> remove(T k) { int factor = k.compareTo( key ); if(isLeaf()) return null; if(factor == 0) { //0 children if(isLeaf()) return null; //2 children if(left != null && right != null) { BSTree<T, E> max = left.maxTree(); remove( max.key ); max.right = right; max.left = left; return max; } //1 child if(left != null) return left; if(right != null) return right; } if(factor < 0) left = left.remove( k ); if(factor > 0) right = right.remove( k ); return this; } /** * Calculate the amount of trees underneath the current node * and updat this amount * @return subTreeValue */ @SuppressWarnings("ConstantConditions") private int calculateSubTreeValues() { resetSubTreeValues(); if(isLeaf()) { subTreeValue = 0; return 1 + subTreeValue; } if(right != null && left == null) { subTreeValue += right.calculateSubTreeValues(); return 1 + subTreeValue; } if(left != null && right == null) { subTreeValue += left.calculateSubTreeValues(); return 1 + subTreeValue; } subTreeValue += right.calculateSubTreeValues() + left.calculateSubTreeValues(); return 1 + subTreeValue; } /** * Reset the values of subTrees back to Zero. */ private void resetSubTreeValues() { subTreeValue = 0; if(right != null) right.resetSubTreeValues(); if(left != null) left.resetSubTreeValues(); } /** * Give the number of leaves hanging in current tree * @return number of leaves */ @SuppressWarnings("ConstantConditions") public int nLeaves() { if(isLeaf()) return 1; if(right == null && left != null) return left.nLeaves(); if(right != null && left == null) return right.nLeaves(); return right.nLeaves() + left.nLeaves(); } /** * Give number of node below the current that contain 1 child * with a null value * @return number of 1 nulls children */ @SuppressWarnings("ConstantConditions") public int n1Nulls() { if(isLeaf()) return 0; if(right == null && left != null) return 1 + left.n1Nulls(); if(right != null && left == null) return 1 + right.n1Nulls(); return right.n1Nulls() + left.n1Nulls(); } /** * Returns the amount of nodes that have 2 children * @return nodes with 2 children */ @SuppressWarnings("ConstantConditions") public int n2NonNulls() { if(isLeaf()) return 0; if(right != null && left != null) { return 1 + left.n2NonNulls() + right.n2NonNulls(); } else { if(left != null) return left.n2NonNulls(); else return right.n2NonNulls(); } } /** * Return a string of the entire tree. * used for printing * @param depth used for alignment, use -1 for no alignment * @param order PRE, POST and IN indicate how to print the String * @return String representation of Tree */ public String toString(int depth, Order order) { calculateSubTreeValues(); String result = ""; String tab = ""; if(depth != -1) { depth++; for (int i = 0; i < depth; i++) { tab += "\t"; } } switch (order) { case IN: result = getInOrder(depth, result, tab); break; case POST: result = getPostOrder(depth, result, tab); break; case PRE: result = getPreOrder(depth, result, tab); break; default: throw new InvalidParameterException("Order must be PRE, IN or ORDER, found: " + order); } return result; } /** * Get the string result for InOrder * @param depth how far to align the printed elements * @param result the string to concatenate the result on * @param tab calculate spacing using depth * @return Result with added String */ private String getInOrder(int depth, String result, String tab) { result = left(depth, result, tab, Order.IN); result = current(depth, result, tab); result = right(depth, result, tab, Order.IN); return result; } /** * Get the string result for PreOrder * @param depth how far to align the printed elements * @param result the string to concatenate the result on * @param tab calculate spacing using depth * @return Result with added String */ private String getPreOrder(int depth, String result, String tab) { result = left(depth, result, tab, Order.PRE); result = current(depth, result, tab); result = right(depth, result, tab, Order.PRE); return result; } /** * Get the string result for PostOrder * @param depth how far to align the printed elements * @param result the string to concatenate the result on * @param tab calculate spacing using depth * @return Result with added String */ private String getPostOrder(int depth, String result, String tab) { result = left(depth, result, tab, Order.POST); result = current(depth, result, tab); result = right(depth, result, tab, Order.POST); return result; } /** * Print the current node * @param depth how far to align the printed elements * @param result the string to concatenate the result on * @param tab calculate spacing using depth * @return Result with added String */ private String current(int depth, String result, String tab) { result += key; result += (depth == -1) ? " " : "\n" + tab; return result; } /** * Print the left node and the left side * @param depth how far to align the printed elements * @param result the string to concatenate the result on * @param tab calculate spacing using depth * @return Result with added String */ private String left(int depth, String result, String tab, Order order) { result += (left == null) ? "" : tab + left.toString(depth, order); result += (depth == -1) ? " " : "\n" + tab; return result; } /** * Print the right node and the right side * @param depth how far to align the printed elements * @param result the string to concatenate the result on * @param tab calculate spacing using depth * @return Result with added String */ private String right(int depth, String result, String tab, Order in) { result += (right == null) ? "" : tab + right.toString(depth, in); result += (depth == -1) ? " " : "\n" + tab; return result; } }
gpl-2.0
ryan-gyger/senior-web
src/main/java/org/nized/web/api/QuestionSerializer.java
598
package org.nized.web.api; import java.io.IOException; import org.nized.web.domain.Question; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; public class QuestionSerializer extends JsonSerializer<Question> { @Override public void serialize(Question value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { // TODO Auto-generated method stub } }
gpl-2.0
SpoonLabs/astor
src/main/java/fr/inria/main/AbstractMain.java
46474
package fr.inria.main; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.UnrecognizedOptionException; import org.apache.log4j.Level; import org.apache.log4j.Logger; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import fr.inria.astor.core.entities.ProgramVariant; import fr.inria.astor.core.output.ReportResults; import fr.inria.astor.core.setup.ConfigurationProperties; import fr.inria.astor.core.setup.ProjectConfiguration; import fr.inria.astor.core.setup.ProjectRepairFacade; import fr.inria.astor.core.setup.RandomManager; import fr.inria.astor.core.solutionsearch.AstorCoreEngine; import fr.inria.astor.core.solutionsearch.extension.SolutionVariantSortCriterion; import fr.inria.astor.core.solutionsearch.extension.VariantCompiler; import fr.inria.astor.core.solutionsearch.population.FitnessFunction; import fr.inria.astor.core.solutionsearch.population.PopulationConformation; import fr.inria.astor.core.solutionsearch.population.PopulationController; import fr.inria.astor.core.solutionsearch.spaces.ingredients.IngredientSearchStrategy; import fr.inria.astor.core.solutionsearch.spaces.ingredients.scopes.AstorCtIngredientPool; import fr.inria.astor.core.solutionsearch.spaces.operators.AstorOperator; import fr.inria.astor.core.solutionsearch.spaces.operators.OperatorSelectionStrategy; import fr.inria.astor.core.solutionsearch.spaces.operators.OperatorSpace; import fr.inria.astor.core.validation.ProgramVariantValidator; import fr.inria.astor.util.TimeUtil; import fr.inria.main.evolution.ExtensionPoints; import spoon.Launcher; import spoon.OutputType; import spoon.SpoonModelBuilder.InputType; /** * Abstract entry point of the framework. It defines and manages program * arguments. * * @author Matias Martinez * */ public abstract class AbstractMain { protected static Logger log = Logger.getLogger(Thread.currentThread().getName()); public static ProjectRepairFacade projectFacade; protected static Options options = new Options(); CommandLineParser parser = new BasicParser(); static { options.addOption("id", true, "(Optional) Name/identified of the project to evaluate (Default: folder name)"); options.addOption("mode", true, " (Optional) Mode (Default: jGenProg Mode)"); options.addOption("autoconfigure", true, " Auto-configure project. Must install https://github.com/tdurieux/project-info-maven-plugin"); options.addOption("location", true, "URL of the project to manipulate"); options.addOption("dependencies", true, "dependencies of the application, separated by char " + File.pathSeparator); options.addOption("package", true, "package to instrument e.g. org.commons.math"); options.addOption("failing", true, "failing test cases, separated by Path separator char (: in linux/mac and ; in windows)"); options.addOption("out", true, "(Optional) Out dir: place were solutions and intermediate program variants are stored. (Default: ./outputMutation/)"); options.addOption("help", false, "print help and usage"); options.addOption("bug280", false, "Run the bug 280 from Apache Commons Math"); options.addOption("bug288", false, "Run the bug 288 from Apache Commons Math"); options.addOption("bug309", false, "Run the bug 309 from Apache Commons Math"); options.addOption("bug428", false, "Run the bug 428 from Apache Commons Math"); options.addOption("bug340", false, "Run the bug 340 from Apache Commons Math"); // Optional parameters options.addOption("jvm4testexecution", true, "(Optional) location of JVM that executes the mutated version of a program (Folder that contains java script, such as /bin/ )."); options.addOption("jvm4evosuitetestexecution", true, "(Optional) location of JVM that executes the EvoSuite test cases. If it is not specified, Astor uses that one from property 'jvm4testexecution'"); options.addOption("maxgen", true, "(Optional) max number of generation a program variant is evolved"); options.addOption("population", true, "(Optional) number of population (program variants) that the approach evolves"); options.addOption("maxtime", true, "(Optional) maximum time (in minutes) to execute the whole experiment"); options.addOption("validation", true, "(Optional) type of validation: process|evosuite. Default:" + ConfigurationProperties.properties.getProperty("validation") + "It accepts custormize validation prodedures, which must extend from " + ProgramVariantValidator.class.getCanonicalName()); options.addOption("flthreshold", true, "(Optional) threshold for Fault locatication. Default:" + ConfigurationProperties.properties.getProperty("flthreshold")); options.addOption("maxsuspcandidates", true, "(Optional) Maximun number of suspicious statement considered. Default: " + ConfigurationProperties.properties.getProperty("maxsuspcandidates")); options.addOption("reintroduce", true, "(Optional) indicates whether it reintroduces the original program in each generation (value: " + PopulationConformation.ORIGINAL.toString() + "), " + " reintroduces parent variant in next generation (value: " + PopulationConformation.PARENTS.toString() + "), " + " reintroduce the solution in the next generation (value: " + PopulationConformation.SOLUTIONS.toString() + ") " + " reintroduces origina and parents (value: original-parents) " + "or do not reintroduce nothing (value: none). More than one option can be written, separated by: " + File.pathSeparator + "Default: " + ConfigurationProperties.properties.getProperty("reintroduce")); options.addOption("tmax1", true, "(Optional) maximum time (in miliseconds) for validating the failing test case "); options.addOption("tmax2", true, "(Optional) maximum time (in miliseconds) for validating the regression test cases "); options.addOption("stopfirst", true, "(Optional) Indicates whether it stops when it finds the first solution (default: true)"); options.addOption("allpoints", true, "(Optional) True if analyze all points of a program validation during a generation. False for analyzing only one gen per generation."); options.addOption("savesolution", false, "(Optional) Save on disk intermediate program variants (even those that do not compile)"); options.addOption("saveall", false, "(Optional) Save on disk all program variants generated"); options.addOption("testbystep", false, "(Optional) Executes each test cases in a separate process."); options.addOption("modificationpointnavigation", true, "(Optional) Method to navigate the modification point space of a variant: inorder, random, weight random (according to the gen's suspicous value)"); options.addOption("mutationrate", true, "(Optional) Value between 0 and 1 that indicates the probability of modify one gen (default: 1)"); options.addOption("probagenmutation", false, "(Optional) Mutates a gen according to its suspicious value. Default: always mutates gen."); options.addOption("srcjavafolder", true, "(Optional) folder with the application source code files (default: /src/java/main/)"); options.addOption("srctestfolder", true, "(Optional) folder with the test cases source code files (default: /src/test/main/)"); options.addOption("binjavafolder", true, "(Optional) folder with the application binaries (default: /target/classes/)"); options.addOption("bintestfolder", true, "(Optional) folder with the test cases binaries (default: /target/test-classes/)"); options.addOption("multipointmodification", false, "(Optional) An element of a program variant (i.e., gen) can be modified several times in different generation"); options.addOption("uniqueoptogen", true, "(Optional) An operation can be applied only once to a gen, even this operation is in other variant."); options.addOption("resetoperations", false, "(Optional) The program variants do not pass the operators throughs the generations"); options.addOption("regressionforfaultlocalization", true, "(Optional) Use the regression for fault localization.Otherwise, failing test cases. Default: " + ConfigurationProperties.properties.getProperty("regressionforfaultlocalization")); options.addOption("javacompliancelevel", true, "(Optional) Compliance level (e.g., 7 for java 1.7, 6 for java 1.6). Default Java 1.7"); options.addOption("alternativecompliancelevel", true, "(Optional) Alternative compliance level. Default Java 1.4. Used after Astor tries to compile to the complicance level and fails."); options.addOption("seed", true, "(Optional) Random seed, for reproducible runs. Default is whatever java.util.Random uses when not explicitly initialized."); options.addOption("scope", true, "(Optional) Scope of the ingredient seach space: Local (same class), package (classes from the same package) or global (all classes from the application under analysis). Default: local." + " It accepts customize scopes, which must implement from " + AstorCtIngredientPool.class.getCanonicalName()); options.addOption("skipfaultlocalization", false, "The fault localization is skipped and all statements are considered"); options.addOption("maxdate", true, "(Optional) Indicates the hour Astor has to stop processing. it must have the format: HH:mm"); options.addOption(ExtensionPoints.REPAIR_OPERATORS.identifier, true, "(Optional) Indicates the class name of the operators used by the selected execution mode. They must extend from " + AstorOperator.class.getName() + ". Operator names must be separated by char " + File.pathSeparator + ". The classes must be included in the classpath."); options.addOption("ingredientstrategy", true, "(Optional) Indicates the name of the class that astor calls for retrieving ingredients. They must extend from " + IngredientSearchStrategy.class.getName() + " The classes must be included in the classpath."); options.addOption("opselectionstrategy", true, "(Optional) Indicates the name of the class that astor calls for selecting an operator from the operator space. They must extend from " + OperatorSelectionStrategy.class.getName() + " The classes must be included in the classpath."); options.addOption("customengine", true, "(Optional) Indicates the class name of the execution mode. It must extend from " + AstorCoreEngine.class.getName()); options.addOption(ExtensionPoints.TARGET_CODE_PROCESSOR.identifier, true, "(Optional) Indicates the class name of the process that selects target elements. They must extend from " + ExtensionPoints.TARGET_CODE_PROCESSOR._class.getName() + " The classes must be included in the classpath."); for (ExtensionPoints epoint : ExtensionPoints.values()) { if (!options.hasOption(epoint.identifier)) { options.addOption(epoint.identifier, true, String .format("Extension point %s. It must extend/implement from %s", epoint.name(), epoint._class)); } } options.addOption("excludeRegression", false, "Exclude test regression execution"); options.addOption("ignoredtestcases", true, "Test cases to ignore"); options.addOption("dse", false, "Apply DSE into Evosuite"); options.addOption("esoverpatched", false, "Apply ES over the patched version. By default it applies over the buggy version."); options.addOption("evosuitetimeout", true, "ES global timeout (in seconds)"); options.addOption("ESParameters", true, "(Optional) Parameters to pass to ES. Separe parameters name and values using " + File.pathSeparator); options.addOption("learningdir", true, "Learning Dir"); options.addOption("clonegranularity", true, "Clone granularity"); options.addOption("patchprioritization", true, "(Optional) Indicates the class name of the class that orders patches. It must extend from " + SolutionVariantSortCriterion.class.getName()); options.addOption("transformingredient", false, "indicates if Astor transforms ingredients."); options.addOption("loglevel", true, "Indicates the log level. Values: " + Arrays.toString(Level.getAllPossiblePriorities())); options.addOption("timezone", true, "Timezone to be used in the process that Astor creates. Default: " + ConfigurationProperties.getProperty("timezone")); options.addOption("faultlocalization", true, "Class name of Fault locatication Strategy. Default:" + ConfigurationProperties.properties.getProperty("faultlocalization")); options.addOption("fitnessfunction", true, "(Optional) Class name of Fitness function for evaluating a variant. It must extend from " + FitnessFunction.class.getCanonicalName() + " The classes must be included in the classpath."); options.addOption("outputresult", true, "(Optional) Class name for manipulating the output. It must extend from " + ReportResults.class.getCanonicalName() + " The classes must be included in the classpath."); options.addOption("populationcontroller", true, "(Optional) class name that controls the population evolution. It must extend from " + PopulationController.class.getCanonicalName() + " The classes must be included in the classpath."); options.addOption("filterfaultlocalization", true, "Indicates whether Astor filters the FL output. Default:" + ConfigurationProperties.properties.getProperty("filterfaultlocalization")); options.addOption("operatorspace", true, "Operator Space contains the operators. It must extends from " + OperatorSpace.class.getName()); options.addOption("compiler", true, "Class used for compile a Program variant. It must extends from " + VariantCompiler.class.getName()); options.addOption("regressiontestcases4fl", true, "Classes names of test cases used in the regression, separated by '" + File.pathSeparator + "' . If the argument it is not specified, Astor automatically calculates them."); options.addOption("manipulatesuper", false, "Allows to manipulate 'super' statements. Disable by default."); options.addOption("classestoinstrument", true, "List of classes names that Astor instrument, separated by '" + File.pathSeparator + "' . If the argument it is not specified, Astor uses all classes from the program under repair."); options.addOption("maxVarCombination", true, "Max number of combinations per variable out-of-scope. Default: " + ConfigurationProperties.getPropertyInt("maxVarCombination")); options.addOption("parameters", true, "Parameters, divided by " + File.pathSeparator); options.addOption("autocompile", true, "wheteher auto compile"); options.addOption("runjava7code", false, "Validates on Java 7"); options.addOption("antipattern", true, "(Optional) Indicates whether to apply anti-patterns when running jGenProg2 (default: false)"); } public abstract void run(String location, String projectName, String dependencies, String packageToInstrument, double thfl, String failing) throws Exception; // CLG notes that this slightly modifies the semantics of example execution, // such that it now will execute examples for non-GenProg tools as well. // This may not be desired, but it was easier to implement this way, for // several reasons, and she can't see a reason that the examples *wouldn't* // work for the other tools. private boolean isExample(CommandLine cmd) { String[] examples = { "bug280", "bug288", "bug340", "bug428" }; for (String example : examples) { if (cmd.hasOption(example)) { return true; } } return false; } public boolean isExample(String[] args) { CommandLine cmd = null; try { cmd = parser.parse(options, args); return isExample(cmd); } catch (Exception e) { // generic exceptions are bad practice, but Java // is also the worst. log.error("Error: " + e.getMessage()); help(); return false; } } public boolean processArguments(String[] args) throws Exception { ConfigurationProperties.clear(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (UnrecognizedOptionException e) { log.error("Error: " + e.getMessage()); help(); return false; } if (cmd.hasOption("help")) { help(); return false; } if (cmd.hasOption("jvm4testexecution")) { ConfigurationProperties.properties.setProperty("jvm4testexecution", cmd.getOptionValue("jvm4testexecution")); } else { String javahome = System.getProperty("java.home"); File location = new File(javahome); javahome = location + File.separator + "bin"; File javalocationbin = new File(javahome); if (!javalocationbin.exists()) { System.err.println("Problems to generate java jdk path"); return false; } ConfigurationProperties.properties.setProperty("jvm4testexecution", javahome); } if (cmd.hasOption("jvm4evosuitetestexecution")) { ConfigurationProperties.properties.setProperty("jvm4evosuitetestexecution", cmd.getOptionValue("jvm4evosuitetestexecution")); } else { // We need a JDK as we compile the test cases from Evosuite String javahome = System.getProperty("java.home"); File location = new File(javahome); if (location.getName().equals("jre")) { javahome = location.getParent() + File.separator + "bin"; File javalocationbin = new File(javahome); if (!javalocationbin.exists()) { System.err.println("Problems to generate java jdk path"); return false; } } else { javahome = location + File.separator + "bin"; File javalocationbin = new File(javahome); if (!javalocationbin.exists()) { System.err.println("Problems to generate java jdk path"); return false; } } ConfigurationProperties.properties.setProperty("jvm4evosuitetestexecution", javahome); } if (!this.isExample(cmd)) { String dependenciespath = cmd.getOptionValue("dependencies"); String location = cmd.getOptionValue("location"); // Process mandatory parameters. if (location == null) { help(); return false; } ConfigurationProperties.properties.setProperty("location", location); if (dependenciespath != null) { ConfigurationProperties.properties.setProperty("dependenciespath", dependenciespath); } String failing = cmd.getOptionValue("failing"); if ((failing != null)) ConfigurationProperties.properties.setProperty("failing", failing); } if (!ProjectConfiguration.validJDK()) { System.err.println("Error: invalid jdk folder"); return false; } else { String jvmhome = ConfigurationProperties.properties.getProperty("jvm4testexecution"); String jdkVersion = ProjectConfiguration.getVersionJDK(jvmhome); if (jdkVersion != null) { ConfigurationProperties.properties.setProperty("jvmversion", jdkVersion); log.info("Java version of the JDK used to run tests: " + jdkVersion); log.info("The compliance of the JVM is: " + ProjectConfiguration.getJavaVersionOfJVM4Validation()); } else log.equals("Error: problems to determine the version of the JDK located at path: " + jvmhome); } if (cmd.hasOption("package")) ConfigurationProperties.properties.setProperty("packageToInstrument", cmd.getOptionValue("package")); if (cmd.hasOption("id")) ConfigurationProperties.properties.setProperty("projectIdentifier", cmd.getOptionValue("id")); if (cmd.hasOption("mode")) ConfigurationProperties.properties.setProperty("mode", cmd.getOptionValue("mode")); String outputPath = ""; if (cmd.hasOption("out")) { outputPath = cmd.getOptionValue("out"); } else { outputPath = ConfigurationProperties.properties.getProperty("workingDirectory"); } ConfigurationProperties.properties.setProperty("workingDirectory", (new File(outputPath)).getAbsolutePath()); // Process optional values. if (cmd.hasOption("maxgen")) ConfigurationProperties.properties.setProperty("maxGeneration", cmd.getOptionValue("maxgen")); if (cmd.hasOption("population")) ConfigurationProperties.properties.setProperty("population", cmd.getOptionValue("population")); if (cmd.hasOption("validation")) ConfigurationProperties.properties.setProperty("validation", cmd.getOptionValue("validation")); if (cmd.hasOption("maxsuspcandidates")) ConfigurationProperties.properties.setProperty("maxsuspcandidates", cmd.getOptionValue("maxsuspcandidates")); if (cmd.hasOption("flthreshold")) { try { ConfigurationProperties.properties.setProperty("flthreshold", cmd.getOptionValue("flthreshold")); } catch (Exception e) { log.error("Error: threshold not valid"); help(); return false; } } if (cmd.hasOption("reintroduce")) ConfigurationProperties.properties.setProperty("reintroduce", cmd.getOptionValue("reintroduce")); if (cmd.hasOption("tmax1")) ConfigurationProperties.properties.setProperty("tmax1", cmd.getOptionValue("tmax1")); if (cmd.hasOption("tmax2")) ConfigurationProperties.properties.setProperty("tmax2", cmd.getOptionValue("tmax2")); if (cmd.hasOption("stopfirst")) ConfigurationProperties.properties.setProperty("stopfirst", cmd.getOptionValue("stopfirst")); if (cmd.hasOption("allpoints")) ConfigurationProperties.properties.setProperty("allpoints", cmd.getOptionValue("allpoints")); if (cmd.hasOption("savesolution")) ConfigurationProperties.properties.setProperty("savesolution", "true"); if (cmd.hasOption("saveall")) ConfigurationProperties.properties.setProperty("saveall", "true"); if (cmd.hasOption("testbystep")) ConfigurationProperties.properties.setProperty("testbystep", "true"); if (cmd.hasOption("runjava7code")) ConfigurationProperties.properties.setProperty("runjava7code", "true"); if (cmd.hasOption("modificationpointnavigation")) ConfigurationProperties.properties.setProperty("modificationpointnavigation", cmd.getOptionValue("modificationpointnavigation")); if (cmd.hasOption("mutationrate")) ConfigurationProperties.properties.setProperty("mutationrate", cmd.getOptionValue("mutationrate")); if (cmd.hasOption("srcjavafolder")) ConfigurationProperties.properties.setProperty("srcjavafolder", cmd.getOptionValue("srcjavafolder")); if (cmd.hasOption("srctestfolder")) ConfigurationProperties.properties.setProperty("srctestfolder", cmd.getOptionValue("srctestfolder")); if (cmd.hasOption("binjavafolder")) ConfigurationProperties.properties.setProperty("binjavafolder", cmd.getOptionValue("binjavafolder")); if (cmd.hasOption("bintestfolder")) ConfigurationProperties.properties.setProperty("bintestfolder", cmd.getOptionValue("bintestfolder")); if (cmd.hasOption("maxtime")) ConfigurationProperties.properties.setProperty("maxtime", cmd.getOptionValue("maxtime")); if (cmd.hasOption("maxdate")) { String hour = cmd.getOptionValue("maxdate"); try { TimeUtil.tranformHours(hour); } catch (Exception e) { log.error("Problem when parser maxdate property, tip: HH:mm"); } ConfigurationProperties.properties.setProperty("maxdate", hour); } if (cmd.hasOption("multipointmodification")) ConfigurationProperties.properties.setProperty("multipointmodification", "true"); if (cmd.hasOption("javacompliancelevel")) ConfigurationProperties.properties.setProperty("javacompliancelevel", cmd.getOptionValue("javacompliancelevel")); if (cmd.hasOption("alternativecompliancelevel")) ConfigurationProperties.properties.setProperty("alternativecompliancelevel", cmd.getOptionValue("alternativecompliancelevel")); if (cmd.hasOption("resetoperations")) ConfigurationProperties.properties.setProperty("resetoperations", "true"); if (cmd.hasOption("regressionforfaultlocalization")) ConfigurationProperties.properties.setProperty("regressionforfaultlocalization", cmd.getOptionValue("regressionforfaultlocalization")); if (cmd.hasOption("probagenmutation")) ConfigurationProperties.properties.setProperty("probagenmutation", "true"); if (cmd.hasOption("skipfaultlocalization")) ConfigurationProperties.properties.setProperty("skipfaultlocalization", "true"); if (cmd.hasOption("uniqueoptogen")) ConfigurationProperties.properties.setProperty("uniqueoptogen", cmd.getOptionValue("uniqueoptogen")); if (cmd.hasOption("seed")) ConfigurationProperties.properties.setProperty("seed", cmd.getOptionValue("seed")); if (cmd.hasOption("scope")) ConfigurationProperties.properties.setProperty("scope", cmd.getOptionValue("scope")); if (cmd.hasOption(ExtensionPoints.REPAIR_OPERATORS.identifier)) ConfigurationProperties.properties.setProperty(ExtensionPoints.REPAIR_OPERATORS.identifier, cmd.getOptionValue(ExtensionPoints.REPAIR_OPERATORS.identifier)); if (cmd.hasOption("ingredientstrategy")) ConfigurationProperties.properties.setProperty("ingredientstrategy", cmd.getOptionValue("ingredientstrategy")); if (cmd.hasOption("opselectionstrategy")) ConfigurationProperties.properties.setProperty(ExtensionPoints.OPERATOR_SELECTION_STRATEGY.identifier, cmd.getOptionValue("opselectionstrategy")); for (ExtensionPoints epoint : ExtensionPoints.values()) { if (cmd.hasOption(epoint.identifier)) ConfigurationProperties.properties.setProperty(epoint.identifier, cmd.getOptionValue(epoint.identifier)); } if (cmd.hasOption("customengine")) ConfigurationProperties.properties.setProperty("customengine", cmd.getOptionValue("customengine")); if (cmd.hasOption("excludeRegression")) ConfigurationProperties.properties.setProperty("executeRegression", "false"); if (cmd.hasOption("ignoredtestcases")) ConfigurationProperties.properties.setProperty("ignoredTestCases", cmd.getOptionValue("ignoredtestcases")); if (cmd.hasOption("evosuitetimeout")) ConfigurationProperties.properties.setProperty("evosuitetimeout", cmd.getOptionValue("evosuitetimeout")); ConfigurationProperties.properties.setProperty("evoDSE", Boolean.toString(cmd.hasOption("dse"))); ConfigurationProperties.properties.setProperty("evoRunOnBuggyClass", Boolean.toString(!(cmd.hasOption("esoverpatched")))); if (cmd.hasOption("ESParameters")) ConfigurationProperties.properties.setProperty("ESParameters", cmd.getOptionValue("ESParameters")); if (cmd.hasOption("learningdir")) ConfigurationProperties.properties.setProperty("learningdir", cmd.getOptionValue("learningdir")); if (cmd.hasOption("clonegranularity")) ConfigurationProperties.properties.setProperty("clonegranularity", cmd.getOptionValue("clonegranularity")); if (cmd.hasOption("patchprioritization")) ConfigurationProperties.properties.setProperty("patchprioritization", cmd.getOptionValue("patchprioritization")); if (cmd.hasOption("transformingredient")) ConfigurationProperties.properties.setProperty("transformingredient", "true"); if (cmd.hasOption("timezone")) { ConfigurationProperties.properties.setProperty("timezone", cmd.getOptionValue("timezone")); } if (cmd.hasOption("faultlocalization")) { ConfigurationProperties.properties.setProperty("faultlocalization", cmd.getOptionValue("faultlocalization")); } if (cmd.hasOption("fitnessfunction")) { ConfigurationProperties.properties.setProperty("fitnessfunction", cmd.getOptionValue("fitnessfunction")); } if (cmd.hasOption("outputresult")) { ConfigurationProperties.properties.setProperty("outputresult", cmd.getOptionValue("outputresult")); } if (cmd.hasOption("populationcontroller")) { ConfigurationProperties.properties.setProperty("populationcontroller", cmd.getOptionValue("populationcontroller")); } if (cmd.hasOption("filterfaultlocalization")) ConfigurationProperties.properties.setProperty("filterfaultlocalization", cmd.getOptionValue("filterfaultlocalization")); if (cmd.hasOption("operatorspace")) ConfigurationProperties.properties.setProperty("operatorspace", cmd.getOptionValue("operatorspace")); if (cmd.hasOption("compiler")) ConfigurationProperties.properties.setProperty("compiler", cmd.getOptionValue("compiler")); if (cmd.hasOption("regressiontestcases4fl")) ConfigurationProperties.properties.setProperty("regressiontestcases4fl", cmd.getOptionValue("regressiontestcases4fl")); if (cmd.hasOption("manipulatesuper")) ConfigurationProperties.properties.setProperty("manipulatesuper", Boolean.TRUE.toString()); if (cmd.hasOption("classestoinstrument")) ConfigurationProperties.properties.setProperty("classestoinstrument", cmd.getOptionValue("classestoinstrument")); if (cmd.hasOption("maxVarCombination")) ConfigurationProperties.properties.setProperty("maxVarCombination", cmd.getOptionValue("maxVarCombination")); if (cmd.hasOption("antipattern")) ConfigurationProperties.properties.setProperty("antipattern", cmd.getOptionValue("antipattern")); if (cmd.hasOption("parameters")) { String[] pars = cmd.getOptionValue("parameters").split(File.pathSeparator); for (int i = 0; i < pars.length; i = i + 2) { String key = pars[i]; String value = pars[i + 1]; ConfigurationProperties.properties.setProperty(key, value); } } processOtherCommands(cmd); if (cmd.hasOption("autocompile")) ConfigurationProperties.properties.setProperty("autocompile", cmd.getOptionValue("autocompile")); boolean autoconfigure = cmd.hasOption("autoconfigure") // && Boolean.valueOf(cmd.getOptionValue("autoconfigure")); if (autoconfigure || ConfigurationProperties.getPropertyBool("autoconfigure")) { executeAutoConfigure(ConfigurationProperties.properties.getProperty("location")); } log.info("command line arguments: " + Arrays.toString(args).replace(",", " ")); // CLG believes, but is not totally confident in her belief, that this // is a reasonable place to initialize the random number generator. RandomManager.initialize(); return true; } public void processOtherCommands(CommandLine cmd) { // Subclass can override this method } private void executeAutoConfigure(String location) throws IOException { log.debug("Determining project properties from " + location); ProcessBuilder builder = new ProcessBuilder(); String mvnCommand = getMvnCommand(); if (mvnCommand == null || mvnCommand.trim().isEmpty()) { throw new IllegalArgumentException( "To execute autoconfigure please add the maven command in your path or add it to the property 'mvndir'"); } String projectInfoCommand = ConfigurationProperties.getProperty("projectinfocommand"); builder.command(mvnCommand, projectInfoCommand, "-q"); builder.directory(new File(location)); Process process = builder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String content = ""; String line; while ((line = reader.readLine()) != null) { content += line + "\n"; } log.debug(content); JsonElement jelement = new JsonParser().parse(content); JsonObject jobject = jelement.getAsJsonObject(); String basedir = jobject.get("baseDir").getAsString(); String compliance = jobject.get("complianceLevel").toString(); JsonArray sources = jobject.get("sources").getAsJsonArray(); JsonArray binSources = jobject.get("binSources").getAsJsonArray(); JsonArray binTests = jobject.get("binTests").getAsJsonArray(); JsonArray tests = jobject.get("tests").getAsJsonArray(); JsonArray classpath = jobject.get("classpath").getAsJsonArray(); String testProp = getJoin(tests).replace(basedir, ""); String sourcesP = getJoin(sources).replace(basedir, ""); String binSourcesP = getJoin(binSources).replace(basedir, ""); String binTestsP = getJoin(binTests).replace(basedir, ""); String classpathP = getJoin(classpath); log.debug("basedir: " + basedir); log.debug("test: " + testProp); log.debug("sources: " + sourcesP); log.debug("binSourceP: " + binSourcesP); log.debug("binTests: " + binTestsP); log.debug("classpath: " + classpathP); log.debug("compliance: " + compliance); if (sourcesP.isEmpty()) { throw new IllegalAccessError("Source folder could not be determined."); } ConfigurationProperties.properties.setProperty("javacompliancelevel", compliance); ConfigurationProperties.properties.setProperty("srcjavafolder", sourcesP); ConfigurationProperties.properties.setProperty("srctestfolder", testProp); ConfigurationProperties.properties.setProperty("binjavafolder", binSourcesP); ConfigurationProperties.properties.setProperty("bintestfolder", binTestsP); ConfigurationProperties.properties.setProperty("dependenciespath", classpathP); } private String getJoin(JsonArray array) { Iterator<JsonElement> it = array.iterator(); String result = ""; while (it.hasNext()) { String element = it.next().getAsString(); result += element + File.pathSeparator; } if (result.length() > 0) { // remove the last separator result = result.substring(0, result.length() - 1); } return result; } public static String getMvnCommand() { String mvnCommand = ConfigurationProperties.getProperty("mvndir"); if (mvnCommand == null) { mvnCommand = findExecutableOnPath("mvn"); } return mvnCommand; } public static String findExecutableOnPath(String name) { Map p = System.getenv(); for (String dirname : System.getenv("PATH").split(File.pathSeparator)) { File file = new File(dirname, name); log.info(file + " " + file.exists()); if (file.isFile() && file.canExecute()) { return file.getAbsolutePath(); } } return null; } /** * Finds an example to test in the command line * * @param args * @return * @throws Exception */ public boolean executeExample(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); ConfigurationProperties.properties.setProperty("stopfirst", "true"); String dependenciespath = null, folder = null, failing = null, location = null, packageToInstrument = null; double faultLocalizationThreshold = 0; if (cmd.hasOption("bug280")) { dependenciespath = new File("./examples/math_85/libs/junit-4.4.jar").getAbsolutePath(); folder = "Math-issue-280"; failing = "org.apache.commons.math.distribution.NormalDistributionTest"; location = new File("./examples/Math-issue-280/").getAbsolutePath(); packageToInstrument = "org.apache.commons"; faultLocalizationThreshold = 0.2; } if (cmd.hasOption("bug288")) { dependenciespath = "examples/Math-issue-288/lib/junit-4.4.jar"; folder = "Math-issue-288"; failing = "org.apache.commons.math.optimization.linear.SimplexSolverTest"; location = "examples/Math-issue-288/"; packageToInstrument = "org.apache.commons"; faultLocalizationThreshold = 0.2; } if (cmd.hasOption("bug309")) { dependenciespath = "examples/Math-issue-309/lib/junit-4.4.jar"; folder = "Math-issue-309"; failing = "org.apache.commons.math.random.RandomDataTest"; location = ("examples/Math-issue-309/"); packageToInstrument = "org.apache.commons"; faultLocalizationThreshold = 0.5; } if (cmd.hasOption("bug340")) { dependenciespath = "examples/Math-issue-340/lib/junit-4.4.jar"; folder = "Math-issue-340"; failing = "org.apache.commons.math.fraction.BigFractionTest"; location = ("examples/Math-issue-340/"); packageToInstrument = "org.apache.commons"; faultLocalizationThreshold = 0.5; } if (cmd.hasOption("bug428")) { dependenciespath = "examples/Lang-issue-428/lib/easymock-2.5.2.jar" + File.pathSeparator + "examples/Lang-issue-428/lib/junit-4.7.jar"; folder = "Lang-issue-428"; failing = "org.apache.commons.lang3.StringUtilsIsTest"; location = ("examples/Lang-issue-428/"); packageToInstrument = "org.apache.commons"; faultLocalizationThreshold = 0.5; } if (location != null) { ConfigurationProperties.properties.setProperty("flthreshold", new Double(faultLocalizationThreshold).toString()); this.run(location, folder, dependenciespath, packageToInstrument, faultLocalizationThreshold, failing); return true; } return false; } private static void help() { HelpFormatter formater = new HelpFormatter(); formater.printHelp("Main", options); log.info("More options and default values at 'configuration.properties' file"); System.exit(0); } /** * Compile the original code * * @param properties */ protected void compileProject(ProjectConfiguration properties) { final Launcher launcher = new Launcher(); for (String path_src : properties.getOriginalDirSrc()) { log.debug("Add folder to compile: " + path_src); launcher.addInputResource(path_src); } for (String path_test : properties.getTestDirSrc()) { log.debug("Add folder to compile: " + path_test); launcher.addInputResource(path_test); } String binoutput = properties.getWorkingDirForBytecode() + File.separator + (ProgramVariant.DEFAULT_ORIGINAL_VARIANT); launcher.setBinaryOutputDirectory(binoutput); log.info("Compiling original code from " + launcher.getModelBuilder().getInputSources() + "\n bytecode saved in " + launcher.getModelBuilder().getBinaryOutputDirectory()); launcher.getEnvironment() .setPreserveLineNumbers(ConfigurationProperties.getPropertyBool("preservelinenumbers")); launcher.getEnvironment().setComplianceLevel(ConfigurationProperties.getPropertyInt("javacompliancelevel")); launcher.getEnvironment().setShouldCompile(true); launcher.getEnvironment().setSourceClasspath(properties.getDependenciesString().split(File.pathSeparator)); launcher.buildModel(); launcher.getModelBuilder().generateProcessedSourceFiles(OutputType.COMPILATION_UNITS); launcher.getModelBuilder().compile(InputType.FILES); projectFacade.getProperties().setOriginalAppBinDir( Collections.singletonList(launcher.getModelBuilder().getBinaryOutputDirectory().getAbsolutePath())); projectFacade.getProperties().setOriginalTestBinDir( Collections.singletonList(launcher.getModelBuilder().getBinaryOutputDirectory().getAbsolutePath())); // launcher.getModelBuilder().generateProcessedSourceFiles(OutputType.CLASSES); } protected ProjectRepairFacade getProjectConfiguration(String location, String projectIdentifier, String method, List<String> failingTestCases, String dependencies, boolean srcWithMain) throws Exception { if (projectIdentifier == null || projectIdentifier.equals("")) { File locFile = new File(location); projectIdentifier = locFile.getName(); } String projectUnderRepairKeyFolder = File.separator + method + "-" + projectIdentifier + File.separator; String workingdir = ConfigurationProperties.getProperty("workingDirectory"); String workingDirForSource = workingdir + projectUnderRepairKeyFolder + "/src/"; String workingDirForBytecode = workingdir + projectUnderRepairKeyFolder + "/bin/"; String originalProjectRoot = location + File.separator; ProjectConfiguration properties = new ProjectConfiguration(); properties.setWorkingDirRoot(workingdir + projectUnderRepairKeyFolder); properties.setWorkingDirForSource(workingDirForSource); properties.setWorkingDirForBytecode(workingDirForBytecode); properties.setFixid(projectIdentifier); properties.setOriginalProjectRootDir(originalProjectRoot); determineSourceFolders(properties, srcWithMain, originalProjectRoot); if (dependencies != null) { properties.setDependencies(dependencies); } if (!ConfigurationProperties.getPropertyBool("autocompile")) { String paramBinFolder = ConfigurationProperties.getProperty("binjavafolder"); if (paramBinFolder == null || paramBinFolder.trim().isEmpty()) { throw new IllegalArgumentException("The bin folders for java src do not exist."); } else { String[] singleFolders = paramBinFolder.split(File.pathSeparator); List<String> originalBin = determineBinFolder(originalProjectRoot, singleFolders); properties.setOriginalAppBinDir(originalBin); } String paramBinTestFolder = ConfigurationProperties.getProperty("bintestfolder"); if (paramBinTestFolder == null || paramBinTestFolder.trim().isEmpty()) { throw new IllegalArgumentException("The bin folders for tests do not exist."); } else { String[] singleBinTestFolders = paramBinTestFolder.split(File.pathSeparator); List<String> originalBinTest = determineBinFolder(originalProjectRoot, singleBinTestFolders); properties.setOriginalTestBinDir(originalBinTest); } } properties.setFailingTestCases(failingTestCases); properties.setPackageToInstrument(ConfigurationProperties.getProperty("packageToInstrument")); properties.setDataFolder(ConfigurationProperties.getProperty("resourcesfolder")); ProjectRepairFacade ce = new ProjectRepairFacade(properties); return ce; } private List<String> determineBinFolder(String originalProjectRoot, String[] singleFolders) { List<String> bins = new ArrayList(); for (String folder : singleFolders) { if (folder.trim().isEmpty()) { throw new IllegalArgumentException("The bin folder is empty"); } File fBin = new File(originalProjectRoot + File.separator + folder).getAbsoluteFile(); if (Files.exists(fBin.toPath())) { bins.add(fBin.getAbsolutePath()); } else throw new IllegalArgumentException("The bin folder " + fBin + " does not exist."); } return bins; } private List<String> determineSourceFolders(ProjectConfiguration properties, boolean srcWithMain, String originalProjectRoot) throws IOException { final boolean onlyOneFolder = true; List<String> sourceFolders = new ArrayList<>(); String paramSrc = ConfigurationProperties.getProperty("srcjavafolder"); String[] srcs = paramSrc.split(File.pathSeparator); // adding src from parameter addToFolder(sourceFolders, srcs, originalProjectRoot, !onlyOneFolder); if (sourceFolders.isEmpty()) { // Adding src folders by guessing potential folders String[] possibleSrcFolders = new String[] { (originalProjectRoot + File.separator + "src/main/java"), (originalProjectRoot + File.separator + "src/java"), (originalProjectRoot + File.separator + "src"), }; addToFolder(sourceFolders, possibleSrcFolders, originalProjectRoot, onlyOneFolder); } log.info("Source folders: " + sourceFolders); properties.setOriginalDirSrc(sourceFolders); // Now test folder String paramTestSrc = ConfigurationProperties.getProperty("srctestfolder"); List<String> sourceTestFolders = new ArrayList<>(); // adding test folder from the argument String[] srcTs = paramTestSrc.split(File.pathSeparator); addToFolder(sourceTestFolders, srcTs, originalProjectRoot, !onlyOneFolder); if (sourceTestFolders.isEmpty()) { // Adding src test folders by guessing potential folders String[] possibleTestSrcFolders = new String[] { (originalProjectRoot + File.separator + "src/test/java"), (originalProjectRoot + File.separator + "src/test"), (originalProjectRoot + File.separator + "test"), }; addToFolder(sourceTestFolders, possibleTestSrcFolders, originalProjectRoot, onlyOneFolder); } log.info("Source Test folders: " + sourceTestFolders); properties.setTestDirSrc(sourceTestFolders); return sourceFolders; } private void addToFolder(List<String> pathResults, String[] possibleTestSrcFolders, String originalProjectRoot, boolean onlyOne) throws IOException { boolean added = false; for (String possibleSrc : possibleTestSrcFolders) { File fSrc = new File(File.separator + possibleSrc).getAbsoluteFile(); if (Files.exists(fSrc.toPath())) { if (!pathResults.contains(fSrc.getAbsolutePath())) { pathResults.add(fSrc.getAbsolutePath()); added = true; } } else { File fSrcRelative = new File(originalProjectRoot + File.separator + possibleSrc); if (Files.isDirectory(fSrcRelative.toPath())) { if (!pathResults.contains(fSrcRelative.getAbsolutePath())) { pathResults.add(fSrcRelative.getAbsolutePath()); added = true; } } } if (onlyOne && added) break; } } public void initProject(String location, String projectName, String dependencies, String packageToInstrument, double thfl, String failing) throws Exception { List<String> failingList = (failing != null) ? Arrays.asList(failing.split(File.pathSeparator)) : new ArrayList<>(); String method = this.getClass().getSimpleName(); projectFacade = getProjectConfiguration(location, projectName, method, failingList, dependencies, true); projectFacade.getProperties().setExperimentName(this.getClass().getSimpleName()); projectFacade.setupWorkingDirectories(ProgramVariant.DEFAULT_ORIGINAL_VARIANT); if (ConfigurationProperties.getPropertyBool("autocompile")) { compileProject(projectFacade.getProperties()); } } public void setupLogging() throws IOException { // done with log4j2.xml } public void execute(String[] args) throws Exception { boolean correct = processArguments(args); log.info("Running Astor on a JDK at " + System.getProperty("java.home")); if (!correct) { System.err.println("Problems with commands arguments"); return; } if (isExample(args)) { executeExample(args); return; } String dependencies = ConfigurationProperties.getProperty("dependenciespath"); dependencies += (ConfigurationProperties.hasProperty("extendeddependencies")) ? (File.pathSeparator + ConfigurationProperties.hasProperty("extendeddependencies")) : ""; String failing = ConfigurationProperties.getProperty("failing"); String location = ConfigurationProperties.getProperty("location"); String packageToInstrument = ConfigurationProperties.getProperty("packageToInstrument"); double thfl = ConfigurationProperties.getPropertyDouble("flthreshold"); String projectName = ConfigurationProperties.getProperty("projectIdentifier"); setupLogging(); run(location, projectName, dependencies, packageToInstrument, thfl, failing); } }
gpl-2.0
liip/liip-aem
pretty-jsp/src/main/java/ch/liip/aem/taglib/IsPageEqualOrChildOfTag.java
1233
package ch.liip.aem.taglib; import ch.liip.aem.request.RequestObjects; import ch.liip.aem.request.utils.PageUtils; import com.day.cq.wcm.api.Page; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; /** * @author Matthieu Cornut */ public class IsPageEqualOrChildOfTag extends ComponentTagSupport { private String var; private Page pageToTest; private Page targetPage; @Override public int doStartTag() throws JspException { RequestObjects requestObjects = createRequestObjects(); Page actualPageToTest = determinePageToTest(requestObjects); boolean result = PageUtils.isPageEqualOrChildOf(actualPageToTest, this.targetPage); this.pageContext.setAttribute(var, result, PageContext.PAGE_SCOPE); return SKIP_BODY; } private Page determinePageToTest(RequestObjects requestObjects) { return this.pageToTest!=null?this.pageToTest:requestObjects.getCurrentPage(); } public void setPageToTest(Page pageToTest) { this.pageToTest = pageToTest; } public void setTargetPage(Page targetPage) { this.targetPage = targetPage; } public void setVar(String var) { this.var = var; } }
gpl-2.0
Eggop92/DAS_BizkaiaTransportesApp
Android/src/eggop/DAS/bizkaiatransportesapp/RecibidorGCM.java
605
package eggop.DAS.bizkaiatransportesapp; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.support.v4.content.WakefulBroadcastReceiver; public class RecibidorGCM extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub ComponentName comp = new ComponentName(context.getPackageName(), ServicioGCM.class.getName()); startWakefulService(context, intent.setComponent(comp)); setResultCode(Activity.RESULT_OK); } }
gpl-2.0
ayld/Facade
src/main/java/net/ayld/facade/util/Components.java
697
package net.ayld.facade.util; import org.springframework.context.ApplicationContext; public enum Components { JAR_MAKER("jarMaker"), LIB_JAR_EXPLODER("jarExploder"), EXPLICIT_JAR_EXPLODER("explicitJarExploder"), CLASS_DEPENDENCY_RESOLVER("classDependencyResolver"), SOURCE_DEPENDENCY_RESOLVER("sourceDependencyResolver"), DEPENDENCY_MATCHER_STRATEGY("unanimousMatcher"), EVENT_BUS("statusUpdateEventBus"); private final ApplicationContext context; private final String name; private Components(String name) { this.context = Contexts.SPRING.instance(); this.name = name; } @SuppressWarnings("unchecked") public <T> T getInstance() { return (T) context.getBean(name); } }
gpl-2.0
fnatter/freeplane-debian-dev
freeplane/src/main/java/org/freeplane/features/link/ConnectorProperties.java
5344
/* * Freeplane - mind map editor * Copyright (C) 2014 Dimitry * * This file author is Dimitry * * 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, see <http://www.gnu.org/licenses/>. */ package org.freeplane.features.link; import java.awt.Color; import java.awt.Point; import org.freeplane.features.link.ConnectorModel.Shape; import org.freeplane.features.map.NodeModel; /** * @author Dimitry Polivaev * 23.03.2014 */ class ConnectorProperties{ private Color color; private int alpha; private ArrowType endArrow; private int[] dash; private Point endInclination; private String middleLabel; private String sourceLabel; private ArrowType startArrow; private Point startInclination; private String targetLabel; private int width; private Shape shape; private String labelFontFamily; private int labelFontSize; public ConnectorProperties(ConnectorArrows connectorEnds, int[] dash, final Color color, final int alpha, final Shape shape, final int width, final String labelFontFamily, final int labelFontSize) { assert color != null; assert shape != null; assert connectorEnds!=null; this.startArrow = connectorEnds.start; this.endArrow = connectorEnds.end; this.dash = dash; this.color = color; this.setAlpha(alpha); this.width = width; this.shape = shape; this.labelFontFamily = labelFontFamily; this.labelFontSize = labelFontSize; } public Shape getShape() { return shape; } public void setShape(final Shape shape) { assert shape != null; this.shape = shape; } public int[] getDash() { return dash; } public void setDash(int[] dash) { this.dash = dash; } public Color getColor() { return color; } public ArrowType getEndArrow() { return endArrow; } public Point getEndInclination() { if (endInclination == null) { return null; } return new Point(endInclination); } public String getMiddleLabel() { return middleLabel; } public String getSourceLabel() { return sourceLabel; } public ArrowType getStartArrow() { return startArrow; } public Point getStartInclination() { if (startInclination == null) { return null; } return new Point(startInclination); } public String getTargetLabel() { return targetLabel; } public int getWidth() { return width; } public void setColor(final Color color) { assert color != null; this.color = color; } public void setEndArrow(final ArrowType endArrow) { assert endArrow != null; this.endArrow = endArrow; } public void setEndInclination(final Point endInclination) { assert endInclination != null; this.endInclination = endInclination; } public void setMiddleLabel(final String middleLabel) { this.middleLabel = empty2null(middleLabel); } private boolean showControlPointsFlag; public boolean getShowControlPointsFlag() { return showControlPointsFlag; } public void setShowControlPoints(final boolean bShowControlPointsFlag) { showControlPointsFlag = bShowControlPointsFlag; } public void setSourceLabel(final String label) { sourceLabel = empty2null(label); } public void setStartArrow(final ArrowType startArrow) { assert startArrow != null; this.startArrow = startArrow; } public void setStartInclination(final Point startInclination) { this.startInclination = startInclination; } public void setTargetLabel(final String targetLabel) { this.targetLabel = empty2null(targetLabel); } public void setWidth(final int width) { this.width = width; } public void setAlpha(int alpha) { this.alpha = alpha; } public int getAlpha() { return alpha; } public String getLabelFontFamily() { return labelFontFamily; } public void setLabelFontFamily(String labelFontFamily) { this.labelFontFamily = labelFontFamily; } public int getLabelFontSize() { return labelFontSize; } public void setLabelFontSize(int labelFontSize) { this.labelFontSize = labelFontSize; } private String empty2null(final String label) { return "".equals(label) ? null : label; } public void changeInclination(int deltaX, final int deltaY, final NodeModel linkedNodeView, final Point changedInclination) { if (linkedNodeView.isLeft()) { deltaX = -deltaX; } changedInclination.translate(deltaX, deltaY); if (changedInclination.x != 0 && Math.abs((double) changedInclination.y / changedInclination.x) < 0.015) { changedInclination.y = 0; } final double k = changedInclination.distance(0, 0); if (k < 10) { if (k > 0) { changedInclination.x = (int) (changedInclination.x * 10 / k); changedInclination.y = (int) (changedInclination.y * 10 / k); } else { changedInclination.x = 10; } } } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01110.java
2546
/** * 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 Nick Sanidas <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("/BenchmarkTest01110") public class BenchmarkTest01110 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.getHeader("foo"); java.util.List<String> valuesList = new java.util.ArrayList<String>( ); valuesList.add("safe"); valuesList.add( param ); valuesList.add( "moresafe" ); valuesList.remove(0); // remove the 1st safe value String bar = valuesList.get(0); // get the param value try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-512", "SUN"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.lang.String)"); throw new ServletException(e); } catch (java.security.NoSuchProviderException e) { System.out.println("Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.lang.String)"); throw new ServletException(e); } response.getWriter().println("Hash Test java.security.MessageDigest.getInstance(java.lang.String,java.lang.String) executed"); } }
gpl-2.0
LeonardCohen/coding
IDDD_Samples-master/collaboration/src/main/java/com/saasovation/collaboration/application/forum/ForumQueryService.java
3569
// Copyright 2012,2013 Vaughn Vernon // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.saasovation.collaboration.application.forum; import java.util.Collection; import javax.sql.DataSource; import com.saasovation.collaboration.application.forum.data.ForumData; import com.saasovation.collaboration.application.forum.data.ForumDiscussionsData; import com.saasovation.common.port.adapter.persistence.AbstractQueryService; import com.saasovation.common.port.adapter.persistence.JoinOn; public class ForumQueryService extends AbstractQueryService { public ForumQueryService(DataSource aDataSource) { super(aDataSource); } public Collection<ForumData> allForumsDataOfTenant(String aTenantId) { return this.queryObjects( ForumData.class, "select * from tbl_vw_forum where tenant_id = ?", new JoinOn(), aTenantId); } public ForumData forumDataOfId(String aTenantId, String aForumId) { return this.queryObject( ForumData.class, "select * from tbl_vw_forum where tenant_id = ? and forum_id = ?", new JoinOn(), aTenantId, aForumId); } public ForumDiscussionsData forumDiscussionsDataOfId(String aTenantId, String aForumId) { return this.queryObject( ForumDiscussionsData.class, "select " + "forum.closed, forum.creator_email_address, forum.creator_identity, " + "forum.creator_name, forum.description, forum.exclusive_owner, forum.forum_id, " + "forum.moderator_email_address, forum.moderator_identity, forum.moderator_name, " + "forum.subject, forum.tenant_id, " + "disc.author_email_address as o_discussions_author_email_address, " + "disc.author_identity as o_discussions_author_identity, " + "disc.author_name as o_discussions_author_name, " + "disc.closed as o_discussions_closed, " + "disc.discussion_id as o_discussions_discussion_id, " + "disc.exclusive_owner as o_discussions_exclusive_owner, " + "disc.forum_id as o_discussions_forum_id, " + "disc.subject as o_discussions_subject, " + "disc.tenant_id as o_discussions_tenant_id " + "from tbl_vw_forum as forum left outer join tbl_vw_discussion as disc " + " on forum.forum_id = disc.forum_id " + "where (forum.tenant_id = ? and forum.forum_id = ?)", new JoinOn("forum_id", "o_discussions_forum_id"), aTenantId, aForumId); } public String forumIdOfExclusiveOwner(String aTenantId, String anExclusiveOwner) { return this.queryString( "select forum_id from tbl_vw_forum where tenant_id = ? and exclusive_owner = ?", aTenantId, anExclusiveOwner); } }
gpl-2.0
isa-group/ideas-studio
src/main/java/es/us/isa/ideas/app/services/labpack/LabpackResource.java
116
package es.us.isa.ideas.app.services.labpack; /** * * @author japarejo */ public class LabpackResource { }
gpl-2.0
ctrawick/daoism
daoism-spring-jdbc/src/main/java/net/cultured/daoism/spring/jdbc/SingleUpdateDAO.java
1829
package net.cultured.daoism.spring.jdbc; import java.util.function.BiFunction; import java.util.function.Function; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; public class SingleUpdateDAO<T> extends NamedParameterJdbcDaoSupport { private Function<T, SingleOperation> operationDelegate; private BiFunction<Integer, T, Boolean> updateCountValidator = new DefaultSingleUpdateValidator<>(); public Function<T, SingleOperation> getOperationDelegate() { return this.operationDelegate; } public void setOperationDelegate(final Function<T, SingleOperation> operationDelegate) { this.operationDelegate = operationDelegate; } public BiFunction<Integer, T, Boolean> getUpdateCountValidator() { return this.updateCountValidator; } public void setUpdateCountValidator(final BiFunction<Integer, T, Boolean> updateCountValidator) { this.updateCountValidator = updateCountValidator; } public void doUpdate(final T data) { // Get the update operation. final SingleOperation op = this.operationDelegate.apply(data); // Execute the update. final String sql = op.getSql(); final SqlParameterSource paramSource = op.getParameters(); final NamedParameterJdbcTemplate template = getNamedParameterJdbcTemplate(); final int count = template.update(sql, paramSource); // Validate update counts using the configured validator. if (this.updateCountValidator != null && !this.updateCountValidator.apply(count, data)) { throw new InvalidUpdateCountException("Update count validation failed"); } } }
gpl-2.0
delafer/j7project
commontools/thirddep-j7/src/main/java/org/eclipse/swt/custom/StyledTextDropTargetEffect.java
8538
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.custom; import org.eclipse.swt.*; import org.eclipse.swt.dnd.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; /** * This adapter class provides a default drag under effect (eg. select and scroll) * when a drag occurs over a <code>StyledText</code>. * * <p>Classes that wish to provide their own drag under effect for a <code>StyledText</code> * can extend this class, override the <code>StyledTextDropTargetEffect.dragOver</code> * method and override any other applicable methods in <code>StyledTextDropTargetEffect</code> to * display their own drag under effect.</p> * * Subclasses that override any methods of this class should call the corresponding * <code>super</code> method to get the default drag under effect implementation. * * <p>The feedback value is either one of the FEEDBACK constants defined in * class <code>DND</code> which is applicable to instances of this class, * or it must be built by <em>bitwise OR</em>'ing together * (that is, using the <code>int</code> "|" operator) two or more * of those <code>DND</code> effect constants. * </p> * <p> * <dl> * <dt><b>Feedback:</b></dt> * <dd>FEEDBACK_SELECT, FEEDBACK_SCROLL</dd> * </dl> * </p> * * @see DropTargetAdapter * @see DropTargetEvent * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> * * @since 3.3 */ public class StyledTextDropTargetEffect extends DropTargetEffect { static final int CARET_WIDTH = 2; static final int SCROLL_HYSTERESIS = 100; // milli seconds static final int SCROLL_TOLERANCE = 20; // pixels int currentOffset = -1; long scrollBeginTime; int scrollX = -1, scrollY = -1; Listener paintListener; /** * Creates a new <code>StyledTextDropTargetEffect</code> to handle the drag under effect on the specified * <code>StyledText</code>. * * @param styledText the <code>StyledText</code> over which the user positions the cursor to drop the data */ public StyledTextDropTargetEffect(StyledText styledText) { super(styledText); paintListener = new Listener () { public void handleEvent (Event event) { if (currentOffset != -1) { StyledText text = (StyledText) getControl(); Point position = text.getLocationAtOffset(currentOffset); int height = text.getLineHeight(currentOffset); event.gc.setBackground(event.display.getSystemColor (SWT.COLOR_BLACK)); event.gc.fillRectangle(position.x, position.y, CARET_WIDTH, height); } } }; } /** * This implementation of <code>dragEnter</code> provides a default drag under effect * for the feedback specified in <code>event.feedback</code>. * * For additional information see <code>DropTargetAdapter.dragEnter</code>. * * Subclasses that override this method should call <code>super.dragEnter(event)</code> * to get the default drag under effect implementation. * * @param event the information associated with the drag start event * * @see DropTargetAdapter * @see DropTargetEvent */ @Override public void dragEnter(DropTargetEvent event) { currentOffset = -1; scrollBeginTime = 0; scrollX = -1; scrollY = -1; getControl().removeListener(SWT.Paint, paintListener); getControl().addListener (SWT.Paint, paintListener); } /** * This implementation of <code>dragLeave</code> provides a default drag under effect * for the feedback specified in <code>event.feedback</code>. * * For additional information see <code>DropTargetAdapter.dragLeave</code>. * * Subclasses that override this method should call <code>super.dragLeave(event)</code> * to get the default drag under effect implementation. * * @param event the information associated with the drag leave event * * @see DropTargetAdapter * @see DropTargetEvent */ @Override public void dragLeave(DropTargetEvent event) { StyledText text = (StyledText) getControl(); if (currentOffset != -1) { refreshCaret(text, currentOffset, -1); } text.removeListener(SWT.Paint, paintListener); scrollBeginTime = 0; scrollX = -1; scrollY = -1; } /** * This implementation of <code>dragOver</code> provides a default drag under effect * for the feedback specified in <code>event.feedback</code>. * * For additional information see <code>DropTargetAdapter.dragOver</code>. * * Subclasses that override this method should call <code>super.dragOver(event)</code> * to get the default drag under effect implementation. * * @param event the information associated with the drag over event * * @see DropTargetAdapter * @see DropTargetEvent * @see DND#FEEDBACK_SELECT * @see DND#FEEDBACK_SCROLL */ @Override public void dragOver(DropTargetEvent event) { int effect = event.feedback; StyledText text = (StyledText) getControl(); Point pt = text.getDisplay().map(null, text, event.x, event.y); if ((effect & DND.FEEDBACK_SCROLL) == 0) { scrollBeginTime = 0; scrollX = scrollY = -1; } else { if (text.getCharCount() == 0) { scrollBeginTime = 0; scrollX = scrollY = -1; } else { if (scrollX != -1 && scrollY != -1 && scrollBeginTime != 0 && (pt.x >= scrollX && pt.x <= (scrollX + SCROLL_TOLERANCE) || pt.y >= scrollY && pt.y <= (scrollY + SCROLL_TOLERANCE))) { if (System.currentTimeMillis() >= scrollBeginTime) { Rectangle area = text.getClientArea(); GC gc = new GC(text); FontMetrics fm = gc.getFontMetrics(); gc.dispose(); int charWidth = fm.getAverageCharWidth(); int scrollAmount = 10*charWidth; if (pt.x < area.x + 3*charWidth) { int leftPixel = text.getHorizontalPixel(); text.setHorizontalPixel(leftPixel - scrollAmount); } if (pt.x > area.width - 3*charWidth) { int leftPixel = text.getHorizontalPixel(); text.setHorizontalPixel(leftPixel + scrollAmount); } int lineHeight = text.getLineHeight(); if (pt.y < area.y + lineHeight) { int topPixel = text.getTopPixel(); text.setTopPixel(topPixel - lineHeight); } if (pt.y > area.height - lineHeight) { int topPixel = text.getTopPixel(); text.setTopPixel(topPixel + lineHeight); } scrollBeginTime = 0; scrollX = scrollY = -1; } } else { scrollBeginTime = System.currentTimeMillis() + SCROLL_HYSTERESIS; scrollX = pt.x; scrollY = pt.y; } } } if ((effect & DND.FEEDBACK_SELECT) != 0) { int[] trailing = new int [1]; int newOffset = text.getOffsetAtPoint(pt.x, pt.y, trailing, false); newOffset += trailing [0]; if (newOffset != currentOffset) { refreshCaret(text, currentOffset, newOffset); currentOffset = newOffset; } } } void refreshCaret(StyledText text, int oldOffset, int newOffset) { if (oldOffset != newOffset) { if (oldOffset != -1) { Point oldPos = text.getLocationAtOffset(oldOffset); int oldHeight = text.getLineHeight(oldOffset); text.redraw (oldPos.x, oldPos.y, CARET_WIDTH, oldHeight, false); } if (newOffset != -1) { Point newPos = text.getLocationAtOffset(newOffset); int newHeight = text.getLineHeight(newOffset); text.redraw (newPos.x, newPos.y, CARET_WIDTH, newHeight, false); } } } /** * This implementation of <code>dropAccept</code> provides a default drag under effect * for the feedback specified in <code>event.feedback</code>. * * For additional information see <code>DropTargetAdapter.dropAccept</code>. * * Subclasses that override this method should call <code>super.dropAccept(event)</code> * to get the default drag under effect implementation. * * @param event the information associated with the drop accept event * * @see DropTargetAdapter * @see DropTargetEvent */ @Override public void dropAccept(DropTargetEvent event) { if (currentOffset != -1) { StyledText text = (StyledText) getControl(); text.setSelection(currentOffset); currentOffset = -1; } } }
gpl-2.0
rex-xxx/mt6572_x201
frameworks/base/services/java/com/android/server/AttributeCache.java
5029
/* ** ** Copyright 2007, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.android.server; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.os.UserHandle; import android.util.SparseArray; import java.util.HashMap; import java.util.WeakHashMap; /** * TODO: This should be better integrated into the system so it doesn't need * special calls from the activity manager to clear it. */ public final class AttributeCache { private static AttributeCache sInstance = null; private final Context mContext; private final SparseArray<WeakHashMap<String, Package>> mPackages = new SparseArray<WeakHashMap<String, Package>>(); private final Configuration mConfiguration = new Configuration(); public final static class Package { public final Context context; private final SparseArray<HashMap<int[], Entry>> mMap = new SparseArray<HashMap<int[], Entry>>(); public Package(Context c) { context = c; } } public final static class Entry { public final Context context; public final TypedArray array; public Entry(Context c, TypedArray ta) { context = c; array = ta; } } public static void init(Context context) { if (sInstance == null) { sInstance = new AttributeCache(context); } } public static AttributeCache instance() { return sInstance; } public AttributeCache(Context context) { mContext = context; } public void removePackage(String packageName) { synchronized (this) { for (int i=0; i<mPackages.size(); i++) { mPackages.valueAt(i).remove(packageName); } } } public void updateConfiguration(Configuration config) { synchronized (this) { int changes = mConfiguration.updateFrom(config); if ((changes & ~(ActivityInfo.CONFIG_FONT_SCALE | ActivityInfo.CONFIG_KEYBOARD_HIDDEN | ActivityInfo.CONFIG_ORIENTATION)) != 0) { // The configurations being masked out are ones that commonly // change so we don't want flushing the cache... all others // will flush the cache. mPackages.clear(); } } } public void removeUser(int userId) { synchronized (this) { mPackages.remove(userId); } } public Entry get(int userId, String packageName, int resId, int[] styleable) { synchronized (this) { WeakHashMap<String, Package> packages = mPackages.get(userId); if (packages == null) { packages = new WeakHashMap<String, Package>(); mPackages.put(userId, packages); } Package pkg = packages.get(packageName); HashMap<int[], Entry> map = null; Entry ent = null; if (pkg != null) { map = pkg.mMap.get(resId); if (map != null) { ent = map.get(styleable); if (ent != null) { return ent; } } } else { Context context; try { context = mContext.createPackageContextAsUser(packageName, 0, new UserHandle(userId)); if (context == null) { return null; } } catch (PackageManager.NameNotFoundException e) { return null; } pkg = new Package(context); packages.put(packageName, pkg); } if (map == null) { map = new HashMap<int[], Entry>(); pkg.mMap.put(resId, map); } try { ent = new Entry(pkg.context, pkg.context.obtainStyledAttributes(resId, styleable)); map.put(styleable, ent); } catch (Resources.NotFoundException e) { return null; } return ent; } } }
gpl-2.0
ruslanrf/wpps
wpps_plugins/tuwien.dbai.wpps.objident/src/tuwien/dbai/wpps/objident/model/transportSearchExperiment/TObjectExtended.java
2016
/** * */ package tuwien.dbai.wpps.objident.model.transportSearchExperiment; import tuwien.dbai.wpps.objident.model.TObject; /** * @author Ruslan (ruslanrf@gmail.com) * @created Nov 14, 2012 8:09:32 PM */ public class TObjectExtended { public TObjectExtended(TObject tObject , EScenario scenario , String webPageId , EWebFormAttributeType webFormElement) { this.tObject = tObject; this.scenario = scenario; this.webPageId = webPageId; this.webFormElement = webFormElement; } public TObject gettObject() { return tObject; } public void settObject(TObject tObject) { this.tObject = tObject; } public void setScenario(EScenario scenario) { this.scenario = scenario; } public void setWebPageId(String webPageId) { this.webPageId = webPageId; } public void setWebFormElement(EWebFormAttributeType webFormElement) { this.webFormElement = webFormElement; } public EScenario getScenario() { return scenario; } public String getWebPageId() { return webPageId; } public EWebFormAttributeType getWebFormElement() { return webFormElement; } private TObject tObject; private EScenario scenario; private String webPageId; private EWebFormAttributeType webFormElement; // TObjectExtended(BrowserRelatedModel browserRelatedModel, Rectangle2D area, // Set<IInstanceAdp> contained, IWebPageBlock webPage, EventBus eventBus // , EScenario scenario, String webPageId, EWebFormAttributeType webFormElement) { // super(browserRelatedModel, area, contained, webPage, eventBus); // this.scenario = scenario; // this.webPageId = webPageId; // this.webFormElement = webFormElement; // } // public static TObjectExtended createInstance(TObject o // , EScenario scenario, String webPageId, EWebFormAttributeType webFormElement) { // return new TObjectExtended(o.getBrowserRelatedModel() // , o.getArea() // , o.getContainedObjects() // , o.getWebPage() // , o.getEventBus() // , scenario // , webPageId // , webFormElement); // } }
gpl-2.0
joezxh/DATAX-UI
eshbase-proxy/src/main/java/com/github/esadmin/meta/dao/impl/ElasticSearchMetaReverseImpl.java
7204
package com.github.esadmin.meta.dao.impl; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.elasticsearch.action.admin.indices.get.GetIndexRequest; import org.elasticsearch.action.admin.indices.get.GetIndexRequestBuilder; import org.elasticsearch.action.admin.indices.get.GetIndexResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.shield.ShieldPlugin; import org.guess.sys.model.User; import org.guess.sys.util.UserUtil; import com.carrotsearch.hppc.cursors.ObjectObjectCursor; import com.github.esadmin.meta.dao.MetaReverseDao; import com.github.esadmin.meta.model.DBTable; import com.github.esadmin.meta.model.DataSource; import com.github.esadmin.meta.model.Database; import com.github.esadmin.meta.model.DbColumn; import com.github.esadmin.meta.model.MetaProperty; /** * elasticsearch元数据读取 * * @author admin * */ public class ElasticSearchMetaReverseImpl implements MetaReverseDao { private Map<String, Client> esclientMap = new ConcurrentHashMap<String, Client>(); @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public DataSource reverseMeta(DataSource ds, List<MetaProperty> mps) throws Exception { Client client = getEsClient(ds.getId() + "-" + ds.getDsName(), mps); // 访问获取index库集合 GetIndexRequestBuilder indexRequestBuilder = client.admin().indices().prepareGetIndex(); indexRequestBuilder.addFeatures(GetIndexRequest.Feature.MAPPINGS).addFeatures(GetIndexRequest.Feature.SETTINGS); GetIndexResponse getIndexResponse = client.admin().indices().getIndex(indexRequestBuilder.request()).actionGet(); GetIndexRequest.Feature[] features = indexRequestBuilder.request().features(); String[] indices = getIndexResponse.indices(); User cuser = UserUtil.getCurrentUser(); for(Database db:ds.getDatabases()){ db.setCheckLabel(0); db.setUpdater(cuser); db.setUpdateDate(new Date()); } for (String index : indices) { // 解析索引库为database Database db =ds.getDatabase(index); db.setDatasource(ds); db.setDbname(index); db.setCheckLabel(1); if (index.startsWith(".") ) continue; for (GetIndexRequest.Feature feature : features) { switch (feature) { case SETTINGS: Settings settings = getIndexResponse.settings().get(index); db.setSchemaName(settings.get("index.uuid")); break; case MAPPINGS: ImmutableOpenMap<String, MappingMetaData> mappings = getIndexResponse.mappings().get(index); if (mappings != null) { if (db.getTables()!=null){ for(DBTable table:db.getTables()){ table.setCheckLabel(0); table.setUpdatebyId(cuser.getId()); table.setUpdateDate(new Date()); } } for (ObjectObjectCursor<String, MappingMetaData> typeEntry : mappings) { DBTable table =db.getDBTable(typeEntry.key);// new DBTable(); table.setTableName(typeEntry.key); table.setCheckLabel(1); table.setTablePname(typeEntry.key); table.setTableType(1); table.setDatabase(db); table.setRemark(""); // table.set typeEntry.value.toString() Map<String, Object> fields = typeEntry.value.sourceAsMap(); if (fields.get("_all") != null) { table.setRemark(table.getRemark()+"|_all"+":"+((Map) fields.get("_all")).get("enabled")); } if (fields.get("_source") != null) { table.setRemark(table.getRemark()+"|_source"+":"+((Map) fields.get("_source")).get("enabled")); } if (fields.get("_parent") != null) { table.setRemark(table.getRemark()+"|_parent"+":"+((Map) fields.get("_parent")).get("type")); } table.setRemark(table.getRemark()+"|_routing"+":"+ typeEntry.value.routing().required()); Map mf=(Map)fields.get("properties"); Iterator iter=mf.entrySet().iterator(); while(iter.hasNext()){//字段 Map.Entry<String,Map> ob=(Map.Entry<String,Map>) iter.next(); DbColumn field=table.getNewDbColumn(ob.getKey()); field.setColumnName(ob.getKey()); field.setColumnPname(ob.getKey()); field.setRemark(ob.getKey()); field.setCheckLabel(1); field.setFieldCode(ob.getKey()); field.setType(getFieldValue("type",ob)); field.setFormat(getFieldValue("format",ob)); field.setIndex(getFieldValue("index",ob)); field.setDbtable(table); table.addColumn(field); } db.addTable(table); } } break; default: throw new IllegalStateException("feature [" + feature + "] is not valid"); } } ds.addDatabase(db); } return ds; } private String getFieldValue(String key,Map.Entry<String,Map> ob){ Object obj=ob.getValue().get(key); if (obj!=null){ return (String)obj; } return null; } /** * 从集合中获取参数设置对象 * * @param paramKey * @param mproes * @return */ private MetaProperty getMetaProperty(String paramKey, List<MetaProperty> mproes) { for (MetaProperty mp : mproes) { if (mp.getPropertyKey().equalsIgnoreCase(paramKey)) { return mp; } } return new MetaProperty(); } private Client getEsClient(String key, List<MetaProperty> mps) { Client cl = esclientMap.get(key); if (cl == null) { String[] hosts = StringUtils.split(getMetaProperty("transportNodes", mps).getPropertyValue(), ","); int id = 0; InetSocketTransportAddress[] transportAddress = new InetSocketTransportAddress[hosts.length]; for (String host : hosts) { String[] hp = StringUtils.split(host, ":"); try { transportAddress[id] = new InetSocketTransportAddress(InetAddress.getByName(hp[0]), NumberUtils.toInt(hp[1], 9300)); } catch (UnknownHostException e) { e.printStackTrace(); } id++; } Settings settings = null; if (StringUtils.isNotEmpty(getMetaProperty("shield_user", mps).getPropertyValue())) { settings = Settings.settingsBuilder().put("cluster.name", getMetaProperty("clustername", mps).getPropertyValue()) .put("shield.user", getMetaProperty("shield_user", mps).getPropertyValue() + ":" + getMetaProperty("shield_password", mps).getPropertyValue()) .put("client.transport.sniff", true).build(); cl = TransportClient.builder().addPlugin(ShieldPlugin.class).settings(settings).build().addTransportAddresses(transportAddress); } else { settings = Settings.settingsBuilder().put("cluster.name", getMetaProperty("clustername", mps).getPropertyValue()).put("client.transport.sniff", true).build(); cl = TransportClient.builder().settings(settings).build().addTransportAddresses(transportAddress); } esclientMap.put(key, cl); } return cl; } }
gpl-2.0
richmartin/detox
src/test/java/com/moozvine/detox/testtypes/complexhierarchies/Token.java
220
package com.moozvine.detox.testtypes.complexhierarchies; import com.moozvine.detox.GenerateDTO; import com.moozvine.detox.Serializable; @GenerateDTO public interface Token extends Serializable { String getValue(); }
gpl-2.0
hexbinary/landing
src/main/java/org/oscarehr/PMmodule/task/BedProgramDischargeTask.java
5323
/** * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. 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 * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada */ package org.oscarehr.PMmodule.task; import java.util.Date; import java.util.TimerTask; import org.apache.log4j.Logger; import org.oscarehr.PMmodule.exception.AdmissionException; import org.oscarehr.PMmodule.model.Program; import org.oscarehr.PMmodule.service.AdmissionManager; import org.oscarehr.PMmodule.service.ProgramManager; import org.oscarehr.PMmodule.utility.DateTimeFormatUtils; import org.oscarehr.common.model.Bed; import org.oscarehr.common.model.BedDemographic; import org.oscarehr.common.model.Provider; import org.oscarehr.managers.BedManager; import org.oscarehr.managers.BedDemographicManager; import org.oscarehr.util.DbConnectionFilter; import org.oscarehr.util.LoggedInInfo; import org.oscarehr.util.MiscUtils; import org.oscarehr.util.MiscUtilsOld; import org.oscarehr.util.ShutdownException; public class BedProgramDischargeTask extends TimerTask { private static final Logger log=MiscUtils.getLogger(); // TODO IC Bedlog bedProgram.getDischargeTime(); private static final String DISCHARGE_TIME = "8:00 AM"; private static final long PERIOD = 3600000; private ProgramManager programManager; private BedManager bedManager; private BedDemographicManager bedDemographicManager; private AdmissionManager admissionManager; public void setProgramManager(ProgramManager programManager) { this.programManager = programManager; } public void setBedManager(BedManager bedManager) { this.bedManager = bedManager; } public void setBedDemographicManager(BedDemographicManager bedDemographicManager) { this.bedDemographicManager = bedDemographicManager; } @Override public void run() { LoggedInInfo.setLoggedInInfoToCurrentClassAndMethod(); try { log.debug("start bed program discharge task"); Program[] bedPrograms = programManager.getBedPrograms(); if(bedPrograms == null) { log.error("getBedPrograms returned null"); return; } for (Program bedProgram : bedPrograms) { MiscUtilsOld.checkShutdownSignaled(); Date dischargeTime = DateTimeFormatUtils.getTimeFromString(DISCHARGE_TIME); Date previousExecutionTime = DateTimeFormatUtils.getTimeFromLong(scheduledExecutionTime() - PERIOD); Date currentExecutionTime = DateTimeFormatUtils.getTimeFromLong(scheduledExecutionTime()); // previousExecutionTime < dischargeTime <= currentExecutionTime if (previousExecutionTime.before(dischargeTime) && (dischargeTime.equals(currentExecutionTime) || dischargeTime.before(currentExecutionTime))) { Bed[] reservedBeds = bedManager.getBedsByProgram(bedProgram.getId(), true); if(reservedBeds == null) { log.error("getBedsByProgram returned null for bed program with id: " + bedProgram.getId()); continue; } for (Bed reservedBed : reservedBeds) { MiscUtilsOld.checkShutdownSignaled(); BedDemographic bedDemographic = bedDemographicManager.getBedDemographicByBed(reservedBed.getId()); if (bedDemographic != null && bedDemographic.getId() != null && bedDemographic.isExpired()) { try { admissionManager.processDischargeToCommunity(Program.DEFAULT_COMMUNITY_PROGRAM_ID, bedDemographic.getId().getDemographicNo(), Provider.SYSTEM_PROVIDER_NO, "bed reservation ended - automatically discharged", "0", null); } catch (AdmissionException e) { log.error("Error discharging to community", e); } } } } } log.debug("finish bed program discharge task"); } catch (ShutdownException e) { log.debug("BedProgramDischargeTask noticed shutdown signaled."); } finally { LoggedInInfo.loggedInInfo.remove(); DbConnectionFilter.releaseAllThreadDbResources(); } } }
gpl-2.0
cuongnd/test_pro
android_application/bho886/app/src/main/java/com/vantinviet/vtv/libraries/validator/validator/RangeValidator.java
1936
package com.vantinviet.vtv.libraries.validator.validator; import android.content.Context; import android.graphics.drawable.Drawable; import com.vantinviet.vtv.R; import com.vantinviet.vtv.libraries.validator.AbstractValidator; /** * Validates whether the given value is between a range of values * * @author Dixon D'Cunha (Exikle) */ public class RangeValidator extends AbstractValidator { /** * The start of the range */ final double START_RANGE; /** * The end of the range */ final double END_RANGE; /** * The error Id from the string resource */ private static int mErrorMessage; // Your custom error message /** * Default error message if none specified */ private static final int DEFAULT_ERROR_MESSAGE_RESOURCE = R.string.validator_range; public RangeValidator(Context c, double start, double end) { super(c, DEFAULT_ERROR_MESSAGE_RESOURCE); START_RANGE = start; END_RANGE = end; } public RangeValidator(Context c, int errorMessageRes, Drawable errorDrawable, double start, double end) { super(c, errorMessageRes, errorDrawable); START_RANGE = start; END_RANGE = end; } /** * @param context * @param start * of the range * @param end * of the range * @param errorMessageRes */ public RangeValidator(Context c, double start, double end, int errorMessageRes) { super(c, errorMessageRes); mErrorMessage = errorMessageRes; START_RANGE = start; END_RANGE = end; } @Override public String getMessage() { return getContext().getString(mErrorMessage); } /** * Checks is value is between given range * @return true if between range; false if outside of range */ @Override public boolean isValid(String value) { if (value != null && value.length() > 0) { double inputedSize = Double.parseDouble(value); return inputedSize >= START_RANGE && inputedSize <= END_RANGE; } else return false; } }
gpl-2.0
jyhong836/CellularAutomata3D
src/com/cellular3d/CellularAutomata3DClient.java
357
package com.cellular3d; public class CellularAutomata3DClient { /** * @param args */ public static void main(String[] args) { System.out.println("* start CellularAutomata3D in MainFrame *\n"); CellularAutomata3DApplet ca3d = new CellularAutomata3DApplet(); // Applet new CA3DClientJFrame(ca3d, ca3d.AppletWidth, ca3d.AppletHeight); } }
gpl-2.0
mrTsjolder/SWOP-KULAK
src/domain/Reservation.java
3580
package domain; import domain.task.Task; import domain.time.Timespan; import java.time.LocalDateTime; import java.util.Comparator; /** * This class represents a reservation of a resource for a task * over a certain timespan * * @author Mathias, Pieter-Jan, Frederic */ public class Reservation { private final Task task; private final Timespan timespan; /** * Initializes a new reservation for the given task over the given timespan. * * @param task The task to make the reservation for * @param period The period over which to make the reservation */ public Reservation(Task task, Timespan period) { this.task = task; this.timespan = period; } /**************************************************** * Getters & Setters * ****************************************************/ /** * @return The task this reservation is made for */ public Task getTask() { return task; } /** * @return The timespan over which this reservation is made */ public Timespan getTimespan() { return timespan; } /** * @return The starttime of this reservation */ public LocalDateTime getStartTime() { return timespan.getStartTime(); } /** * @return The end time of this reservation */ public LocalDateTime getEndTime() { return timespan.getEndTime(); } /**************************************************** * Static methods * ****************************************************/ /** * Get a comparator to sort reservations on their time spans. * NOTE that this comparator can return 0 if {@code !o1.equals(o2)}. * * @return a comparator that compares the time spans of reservations * in order to sort reservations. * @see Timespan#compareTo(Timespan) */ public static Comparator<Reservation> timespanComparator() { return (Reservation o1, Reservation o2) -> o1.getTimespan().compareTo(o2.getTimespan()); } /**************************************************** * Other methods * ****************************************************/ /** * Return whether or not this reservation causes a conflict with a given time span. * * @param span * The time span to check conflict with. * @return {@code true} if span overlaps with the time span of this reservation. */ public boolean conflictsWith(Timespan span) { return getTimespan().overlapsWith(span); } /** * Checks whether this reservation conflicts with another reservation * * @param reservation The reservation to compare with * @return True if and only if the time span of this reservation * overlaps with the time span of the given reservation. */ public boolean conflictsWith(Reservation reservation) { return conflictsWith(reservation.getTimespan()); } /** * Checks whether this reservation expires before the given time * * @param time The time to check * @return True if and only if the timespan of this reservation end * strictly before the given time. */ public boolean expiredBefore(LocalDateTime time) { return getEndTime().isBefore(time); } /** * Checks whether this reservation starts after the given time * * @param time The time to check * @return True if and only if the timespan of this reservation starts * strictly after the given time. */ public boolean startsAfter(LocalDateTime time) { return getTimespan().startsAfter(time); } }
gpl-2.0
fredizzimo/keyboardlayout
smac/src/aeatk/ca/ubc/cs/beta/aeatk/targetalgorithmevaluator/TargetAlgorithmEvaluatorRunObserver.java
371
package ca.ubc.cs.beta.aeatk.targetalgorithmevaluator; import java.util.List; import ca.ubc.cs.beta.aeatk.algorithmrunresult.AlgorithmRunResult; public interface TargetAlgorithmEvaluatorRunObserver { /** * Invoked on a best effort basis when new information is available * @param runs */ public void currentStatus(List<? extends AlgorithmRunResult> runs); }
gpl-2.0
diogodanielsoaresferreira/ProgrammingExercises-Java-
P2/Exame/E11/ExameProg2.java
3427
/** * Diogo Daniel Soares Ferreira * <diogodanielsoaresferreira@ua.pt> * Nº Mecanográfico: 76504 * Universidade de Aveiro, 2015 */ package p2; /** * Este programa serve para verificar se uma expressão aritmética (formada * por dígitos, operações elementares e parêntesis) é sintacticamente válida. * Crie o módulo StackX de forma que este programa funcione devidamente * respeitando o comportamento esperado de uma Pilha. */ import static java.lang.System.*; import java.util.Scanner; public class ExameProg2 { public static void main(String[] args) { Stack2 p = new Stack2(); String[] e = {"(e)","e+e","e-e","e*e","e/e","D"}; // formas alternativas para // definir uma expressão if (args.length != 1) { exit(1); // ERRO na chamada! } String expr = args[0]; for(int i = 0;i < expr.length();i++) { char c = expr.charAt(i); if (Character.isDigit(c)) p.push('D'); // coloca o carácter 'D' no stack, indicando presença de um dígito else p.push(c); // coloca o carácter armazenado em c no stack out.print(" PUSH: "); out.println(p.toStrings()); // escreve numa única linha o conteúdo da pilha (sem a alterar) boolean change; do { // tenta reduzir a expressão no topo do stack para outra mais simples change = false; for(int j = 0;!change && j < e.length;j++) { String pattern = e[j]; int n = pattern.length(); if (p.topMatches(pattern)) { // verifica se os n caracteres no topo da pilha são iguais a pattern p.popN(n); // retira n elementos do topo p.push('e'); // coloca 'e' no stack change = true; out.print("REDUCE: "); out.println(p.toStrings()); // escreve numa única linha o conteúdo da pilha (sem a alterar) } } } while(change); } if (p.size() == 1 && p.top() == 'e') out.println("Correct expression!"); else out.println("Bad expression!"); } } /* Exemplos de utilização e resultados esperados: > java -ea ProgX "2+2" PUSH: D REDUCE: e PUSH: e+ PUSH: e+D REDUCE: e+e REDUCE: e Correct expression! > java -ea ProgX "2+(2-3)" PUSH: D REDUCE: e PUSH: e+ PUSH: e+( PUSH: e+(D REDUCE: e+(e PUSH: e+(e- PUSH: e+(e-D REDUCE: e+(e-e REDUCE: e+(e PUSH: e+(e) REDUCE: e+e REDUCE: e Correct expression! > java -ea ProgX "3*(4/(3))" PUSH: D REDUCE: e PUSH: e* PUSH: e*( PUSH: e*(D REDUCE: e*(e PUSH: e*(e/ PUSH: e*(e/( PUSH: e*(e/(D REDUCE: e*(e/(e PUSH: e*(e/(e) REDUCE: e*(e/e REDUCE: e*(e PUSH: e*(e) REDUCE: e*e REDUCE: e Correct expression! > java -ea ProgX "2+" PUSH: D REDUCE: e PUSH: e+ Bad expression! > java -ea ProgX "(3*(2+4)+5))" PUSH: ( PUSH: (D REDUCE: (e PUSH: (e* PUSH: (e*( PUSH: (e*(D REDUCE: (e*(e PUSH: (e*(e+ PUSH: (e*(e+D REDUCE: (e*(e+e REDUCE: (e*(e PUSH: (e*(e) REDUCE: (e*e REDUCE: (e PUSH: (e+ PUSH: (e+D REDUCE: (e+e REDUCE: (e PUSH: (e) REDUCE: e PUSH: e) Bad expression! > java -ea ProgX "2+4*(4++5)" PUSH: D REDUCE: e PUSH: e+ PUSH: e+D REDUCE: e+e REDUCE: e PUSH: e* PUSH: e*( PUSH: e*(D REDUCE: e*(e PUSH: e*(e+ PUSH: e*(e++ PUSH: e*(e++D REDUCE: e*(e++e PUSH: e*(e++e) Bad expression! */
gpl-2.0
IceColdCode/JGameLib
image/SpriteSheetLoader.java
110
package image; import javax.imageio.ImageIO; import java.awt.*; public class SpriteSheetLoader { }
gpl-2.0
tharindum/opennms_dashboard
opennms-dao/src/test/java/org/opennms/netmgt/dao/support/DefaultRrdDaoTest.java
10268
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2007-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.dao.support; import static org.easymock.EasyMock.expect; import java.io.File; import java.io.IOException; import java.util.HashSet; import junit.framework.TestCase; import org.opennms.netmgt.model.OnmsAttribute; import org.opennms.netmgt.model.OnmsResource; import org.opennms.netmgt.model.RrdGraphAttribute; import org.opennms.netmgt.rrd.DefaultRrdGraphDetails; import org.opennms.netmgt.rrd.RrdException; import org.opennms.netmgt.rrd.RrdStrategy; import org.opennms.test.ThrowableAnticipator; import org.opennms.test.mock.EasyMockUtils; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.util.StringUtils; /** * @author <a href="mailto:dj@opennms.org">DJ Gregor</a> */ public class DefaultRrdDaoTest extends TestCase { private EasyMockUtils m_mocks = new EasyMockUtils(); private RrdStrategy<?,?> m_rrdStrategy = m_mocks.createMock(RrdStrategy.class); private DefaultRrdDao m_dao; @Override public void setUp() throws Exception { super.setUp(); RrdTestUtils.initialize(); m_dao = new DefaultRrdDao(); m_dao.setRrdStrategy(m_rrdStrategy); m_dao.setRrdBaseDirectory(new File(System.getProperty("java.io.tmpdir"))); m_dao.setRrdBinaryPath("/bin/true"); m_dao.afterPropertiesSet(); } public void testInit() { // Don't do anything... test that the setUp method works } public void testPrintValue() throws Exception { long end = System.currentTimeMillis(); long start = end - (24 * 60 * 60 * 1000); OnmsResource childResource = preparePrintValueTest(start, end, "1"); m_mocks.replayAll(); Double value = m_dao.getPrintValue(childResource.getAttributes().iterator().next(), "AVERAGE", start, end); m_mocks.verifyAll(); assertNotNull("value should not be null", value); assertEquals("value", 1.0, value); } public void testPrintValueWithNaN() throws Exception { long end = System.currentTimeMillis(); long start = end - (24 * 60 * 60 * 1000); OnmsResource childResource = preparePrintValueTest(start, end, "NaN"); m_mocks.replayAll(); Double value = m_dao.getPrintValue(childResource.getAttributes().iterator().next(), "AVERAGE", start, end); m_mocks.verifyAll(); assertNotNull("value should not be null", value); assertEquals("value", Double.NaN, value); } public void testPrintValueWithnan() throws Exception { long end = System.currentTimeMillis(); long start = end - (24 * 60 * 60 * 1000); OnmsResource childResource = preparePrintValueTest(start, end, "nan"); m_mocks.replayAll(); Double value = m_dao.getPrintValue(childResource.getAttributes().iterator().next(), "AVERAGE", start, end); m_mocks.verifyAll(); assertNotNull("value should not be null", value); assertEquals("value", Double.NaN, value); } // NMS-5275 public void testPrintValueWithNegativeNan() throws Exception { long end = System.currentTimeMillis(); long start = end - (24 * 60 * 60 * 1000); OnmsResource childResource = preparePrintValueTest(start, end, "-nan"); m_mocks.replayAll(); Double value = m_dao.getPrintValue(childResource.getAttributes().iterator().next(), "AVERAGE", start, end); m_mocks.verifyAll(); assertNotNull("value should not be null", value); assertEquals("value", Double.NaN, value); } public void testPrintValueWithBogusLine() throws Exception { long end = System.currentTimeMillis(); long start = end - (24 * 60 * 60 * 1000); String printLine = "blah blah blah this should be a floating point number blah blah blah"; OnmsResource childResource = preparePrintValueTest(start, end, printLine); m_mocks.replayAll(); ThrowableAnticipator ta = new ThrowableAnticipator(); ta.anticipate(new DataAccessResourceFailureException("Value of line 1 of output from RRD is not a valid floating point number: '" + printLine + "'")); try { m_dao.getPrintValue(childResource.getAttributes().iterator().next(), "AVERAGE", start, end); } catch (Throwable t) { ta.throwableReceived(t); } m_mocks.verifyAll(); ta.verifyAnticipated(); } private OnmsResource preparePrintValueTest(long start, long end, String printLine) throws IOException, RrdException { String rrdDir = "snmp" + File.separator + "1" + File.separator + "eth0"; String rrdFile = "ifInOctets.jrb"; String escapedFile = rrdDir + File.separator + rrdFile; if (File.separatorChar == '\\') { escapedFile = escapedFile.replace("\\", "\\\\"); } String[] command = new String[] { m_dao.getRrdBinaryPath(), "graph", "-", "--start=" + (start / 1000), "--end=" + (end / 1000), "DEF:ds=" + escapedFile + ":ifInOctets:AVERAGE", "PRINT:ds:AVERAGE:\"%le\"" }; String commandString = StringUtils.arrayToDelimitedString(command, " "); OnmsResource topResource = new OnmsResource("1", "Node One", new MockResourceType(), new HashSet<OnmsAttribute>(0)); OnmsAttribute attribute = new RrdGraphAttribute("ifInOctets", rrdDir, rrdFile); HashSet<OnmsAttribute> attributeSet = new HashSet<OnmsAttribute>(1); attributeSet.add(attribute); MockResourceType childResourceType = new MockResourceType(); OnmsResource childResource = new OnmsResource("eth0", "Interface One: eth0", childResourceType, attributeSet); childResource.setParent(topResource); DefaultRrdGraphDetails details = new DefaultRrdGraphDetails(); details.setPrintLines(new String[] { printLine }); expect(m_rrdStrategy.createGraphReturnDetails(commandString, m_dao.getRrdBaseDirectory())).andReturn(details); return childResource; } public void testFetchLastValue() throws Exception { String rrdDir = "snmp" + File.separator + "1" + File.separator + "eth0"; String rrdFile = "ifInOctets.jrb"; OnmsResource topResource = new OnmsResource("1", "Node One", new MockResourceType(), new HashSet<OnmsAttribute>(0)); OnmsAttribute attribute = new RrdGraphAttribute("ifInOctets", rrdDir, rrdFile); HashSet<OnmsAttribute> attributeSet = new HashSet<OnmsAttribute>(1); attributeSet.add(attribute); MockResourceType childResourceType = new MockResourceType(); OnmsResource childResource = new OnmsResource("eth0", "Interface One: eth0", childResourceType, attributeSet); childResource.setParent(topResource); int interval = 300000; Double expectedValue = new Double(1.0); String fullRrdFilePath = m_dao.getRrdBaseDirectory().getAbsolutePath() + File.separator + rrdDir + File.separator + rrdFile; expect(m_rrdStrategy.fetchLastValue(fullRrdFilePath, attribute.getName(), interval)).andReturn(expectedValue); m_mocks.replayAll(); Double value = m_dao.getLastFetchValue(attribute, interval); m_mocks.verifyAll(); assertNotNull("last fetched value must not be null, but was null", value); assertEquals("last fetched value", expectedValue, value); } public void testFetchLastValueInRange() throws Exception { String rrdDir = "snmp" + File.separator + "1" + File.separator + "eth0"; String rrdFile = "ifInOctets.jrb"; OnmsResource topResource = new OnmsResource("1", "Node One", new MockResourceType(), new HashSet<OnmsAttribute>(0)); OnmsAttribute attribute = new RrdGraphAttribute("ifInOctets", rrdDir, rrdFile); HashSet<OnmsAttribute> attributeSet = new HashSet<OnmsAttribute>(1); attributeSet.add(attribute); MockResourceType childResourceType = new MockResourceType(); OnmsResource childResource = new OnmsResource("eth0", "Interface One: eth0", childResourceType, attributeSet); childResource.setParent(topResource); int interval = 300000; int range = 300000; Double expectedValue = new Double(1.0); String fullRrdFilePath = m_dao.getRrdBaseDirectory().getAbsolutePath() + File.separator + rrdDir + File.separator + rrdFile; expect(m_rrdStrategy.fetchLastValueInRange(fullRrdFilePath, attribute.getName(), interval, range)).andReturn(expectedValue); m_mocks.replayAll(); Double value = m_dao.getLastFetchValue(attribute, interval, range); m_mocks.verifyAll(); assertNotNull("last fetched value must not be null, but was null", value); assertEquals("last fetched value", expectedValue, value); } }
gpl-2.0
landsurveyorsunited/reader
reader-android/app/src/main/java/com/sismics/reader/fragment/ArticlesDefaultFragment.java
1161
package com.sismics.reader.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.androidquery.AQuery; import com.sismics.reader.R; /** * Articles default fragment. * * @author bgamard */ public class ArticlesDefaultFragment extends NavigationFragment { /** * AQuery. */ private AQuery aq; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.articles_fragment, container, false); aq = new AQuery(view); aq.id(R.id.articleList).getListView().setEmptyView(aq.id(R.id.progressBar).getView()); aq.id(R.id.loadingText).text(R.string.loading_subscriptions); return view; } /** * Listen to subscription loading error. */ public void onSubscriptionError() { aq.id(R.id.emptyList).text(R.string.error_loading_subscriptions); aq.id(R.id.articleList).getListView().setEmptyView(aq.id(R.id.emptyList).getView()); aq.id(R.id.progressBar).gone(); } }
gpl-2.0
ForrestSu/CourseAssistant
CourseHelper/src/com/hunau/db/DBManager.java
6809
package com.hunau.db; import java.util.ArrayList; import java.util.List; import com.hunau.dao.Course; import com.hunau.dao.Rank; import com.hunau.dao.Score; import com.hunau.dao.StuInfo; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class DBManager { private DBHelper helper; private SQLiteDatabase db; public DBManager(Context context) { helper = new DBHelper(context, "hunau.db", 1); db = helper.getWritableDatabase(); } /************************************************************************/ /** 1.¿Î³Ì²Ù×÷ */ /************************************************************************/ // Ìí¼ÓËùÓпγÌÊý¾Ý public void addAllCourses(List<Course> courses) { db.beginTransaction(); // ¿ªÊ¼ÊÂÎñ try { for (Course c : courses) { db.execSQL( "INSERT INTO course VALUES(null,?,?, ?,?,?,?,?)", new Object[] { c.getCourseName(), c.getTeacher(), c.getType(), c.getPlace(), c.getCourseWeek(), c.getCourseJs(), c.getCourseZc() }); } db.setTransactionSuccessful(); // ÉèÖÃÊÂÎñ³É¹¦Íê³É } finally { db.endTransaction(); // ½áÊøÊÂÎñ } } // ²éѯËùÓпγÌÊý¾Ý public List<Course> queryAllCourses() { List<Course> courses = new ArrayList<Course>(); Course cou; Cursor c = db.query("course", null, null, null, null, null, "coursejs asc,courseweek asc"); while (c.moveToNext()) { cou = new Course(); cou.setId(c.getInt(c.getColumnIndex("id"))); cou.setCourseName(c.getString(c.getColumnIndex("coursename"))); cou.setTeacher(c.getString(c.getColumnIndex("teacher"))); cou.setType(c.getInt(c.getColumnIndex("type"))); cou.setCourseJs(c.getInt(c.getColumnIndex("coursejs"))); cou.setCourseWeek(c.getInt(c.getColumnIndex("courseweek"))); cou.setCourseZc(c.getString(c.getColumnIndex("coursezc"))); cou.setPlace(c.getString(c.getColumnIndex("place"))); courses.add(cou); } c.close(); return courses; } public boolean UpdateCourse(Course c) { db.execSQL( "UPDATE course set coursename=?,teacher=?,type=?,place=?," + "courseweek =?,coursejs=?,coursezc=? where id=?", new Object[] { c.getCourseName(), c.getTeacher(), c.getType(), c.getPlace(), c.getCourseWeek(), c.getCourseJs(), c.getCourseZc(),c.getId() }); return true; } public boolean addCourse(Course c) { db.execSQL( "INSERT INTO course VALUES(null,?,?, ?,?,?,?,?)", new Object[] { c.getCourseName(), c.getTeacher(), c.getType(), c.getPlace(), c.getCourseWeek(), c.getCourseJs(), c.getCourseZc() }); return true; } // ɾ³ýËùÓÐ¿Î³Ì public void deleteAllCourse() { db.delete("course", null, null); } /************************************************************************/ /** 2.³É¼¨ ²Ù×÷ */ /************************************************************************/ // Ìí¼ÓËùÓгɼ¨µÃ·Ö¼Ç¼ /************************************************************************/ public void addAllScores(List<Score> scores) { db.beginTransaction(); // ¿ªÊ¼ÊÂÎñ try { for (Score s : scores) { db.execSQL( "INSERT INTO score VALUES(null,?,?,?,?,?,?,?,?,?)", new Object[] { s.getCourseNo(), s.getCourseName(), s.getXlh(), s.getCredit(), s.getTim(), s.getUsualCredit(), s.getFinalGrade(), s.getGrade(), s.getExamType() }); } db.setTransactionSuccessful(); // ÉèÖÃÊÂÎñ³É¹¦Íê³É } finally { db.endTransaction(); // ½áÊøÊÂÎñ } } // ²éѯËùÓгɼ¨ public List<Score> queryAllScores() { List<Score> scos = new ArrayList<Score>(); Score sco = null; Cursor c = db.query("score", null, null, null, null, null, "id asc"); while (c.moveToNext()) { sco = new Score(); sco.setCourseNo(c.getString(c.getColumnIndex("courseNo"))); sco.setCourseName(c.getString(c.getColumnIndex("courseName"))); sco.setXlh(c.getString(c.getColumnIndex("xlh"))); sco.setTim(c.getString(c.getColumnIndex("tim"))); sco.setGrade(c.getString(c.getColumnIndex("grade"))); sco.setUsualCredit(c.getString(c.getColumnIndex("usualCredit"))); sco.setFinalGrade(c.getString(c.getColumnIndex("finalGrade"))); scos.add(sco); } c.close(); return scos; } // ɾ³ýËùÓгɼ¨ public void deleteAllScores() { db.delete("score", null, null); } /************************************************************************/ /** 3.³É¼¨ÅÅÃû */ /************************************************************************/ public void addAllRanks(List<Rank> ranks) { db.beginTransaction(); // ¿ªÊ¼ÊÂÎñ try { for (Rank s : ranks) { db.execSQL( "INSERT INTO ranks VALUES(null,?,?,?,?,?,?,?)", new Object[] { s.getCourseNo(), s.getCourseName(), s.getGrade(), s.getNum(), s.getHigh(), s.getLow(), s.getRank() }); } db.setTransactionSuccessful(); // ÉèÖÃÊÂÎñ³É¹¦Íê³É } finally { db.endTransaction(); // ½áÊøÊÂÎñ } } // ²éѯËùÓгɼ¨ public List<Rank> queryAllRanks() { List<Rank> scos = new ArrayList<Rank>(); Rank sco = null; Cursor c = db.query("ranks", null, null, null, null, null, "id asc"); while (c.moveToNext()) { sco = new Rank(); sco.setCourseNo(c.getString(c.getColumnIndex("courseNo"))); sco.setCourseName(c.getString(c.getColumnIndex("courseName"))); sco.setGrade(c.getString(c.getColumnIndex("grade"))); sco.setNum(c.getString(c.getColumnIndex("num"))); sco.setHigh(c.getString(c.getColumnIndex("high"))); sco.setLow(c.getString(c.getColumnIndex("low"))); sco.setRank(c.getString(c.getColumnIndex("rank"))); scos.add(sco); } c.close(); return scos; } // ɾ³ýËùÓÐÅÅÃû public void deleteAllRanks() { db.delete("ranks", null, null); } /*********************************************************/ /* ѧÉúÐÅÏ¢²Ù×÷ */ /*********************************************************/ /************************************************************************/ public void addStuInfo(StuInfo s) { db.execSQL("INSERT INTO stuinfo VALUES(null,?,?,?)", new Object[] { s.getStuname(), s.getStunumber(), s.getGrade() }); } // ·µ»ØÑ§ÉúµÄÐÅÏ¢ public StuInfo queryStuInfo() { if (!db.isOpen()) { db = helper.getReadableDatabase(); } StuInfo stu = null; Cursor c = db.query("stuinfo", null, null, null, null, null, "id asc"); if (c.moveToNext()) { stu = new StuInfo(); stu.setStuname(c.getString(c.getColumnIndex("stuname"))); stu.setStunumber(c.getString(c.getColumnIndex("stunumber"))); stu.setGrade(c.getDouble(c.getColumnIndex("grade"))); } c.close(); return stu; } public void deleteStuInfo() { db.delete("stuinfo", null, null); } /*********************************************************/ /*********************************************************/ // 5.¹Ø±ÕÊý¾Ý¿â public void closeDB() { if(db!=null)db.close(); } }
gpl-2.0
consulo/mssdw-java-client
src/main/java/mssdw/protocol/Type_GetPropertyCustomAttributes.java
1319
package mssdw.protocol; import mssdw.JDWPException; import mssdw.PacketStream; import mssdw.PropertyMirror; import mssdw.TypeMirror; import mssdw.VirtualMachineImpl; /** * @author VISTALL * @since 23.07.2015 */ public class Type_GetPropertyCustomAttributes implements Type { static final int COMMAND = 12; public static Type_GetPropertyCustomAttributes process(VirtualMachineImpl vm, TypeMirror typeMirror, PropertyMirror propertyMirror) throws JDWPException { PacketStream ps = enqueueCommand(vm, typeMirror, propertyMirror); return waitForReply(vm, ps, typeMirror); } static PacketStream enqueueCommand(VirtualMachineImpl vm, TypeMirror typeMirror, PropertyMirror propertyMirror) { PacketStream ps = new PacketStream(vm, COMMAND_SET, COMMAND); ps.writeTypeRef(typeMirror.getTypeRef()); ps.writeInt(propertyMirror.id()); ps.send(); return ps; } static Type_GetPropertyCustomAttributes waitForReply(VirtualMachineImpl vm, PacketStream ps, TypeMirror typeMirror) throws JDWPException { ps.waitForReply(); return new Type_GetPropertyCustomAttributes(vm, ps, typeMirror); } public final String[] customAttributeMirrors; private Type_GetPropertyCustomAttributes(VirtualMachineImpl vm, PacketStream ps, TypeMirror parent) { customAttributeMirrors = ps.readCustomAttributes(); } }
gpl-2.0
fingli/FreeDcam
app/src/main/java/freed/cam/apis/camera1/parameters/device/qcom/ZTE_ADV_IMX234.java
3530
/* * * Copyright (C) 2015 Ingo Fuchs * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * / */ package freed.cam.apis.camera1.parameters.device.qcom; import android.graphics.Rect; import android.hardware.Camera; import android.hardware.Camera.Parameters; import java.util.ArrayList; import freed.cam.apis.KEYS; import freed.cam.apis.basecamera.CameraWrapperInterface; import freed.cam.apis.basecamera.FocusRect; import freed.cam.apis.basecamera.parameters.manual.AbstractManualParameter; import freed.cam.apis.basecamera.parameters.modes.MatrixChooserParameter; import freed.cam.apis.basecamera.parameters.modes.ModeParameterInterface; import freed.cam.apis.camera1.parameters.manual.focus.BaseFocusManual; import freed.cam.apis.camera1.parameters.manual.whitebalance.BaseCCTManual; import freed.cam.apis.camera1.parameters.manual.zte.ShutterManualZTE; import freed.cam.apis.camera1.parameters.modes.NightModeZTE; import freed.dng.DngProfile; /** * Created by troop on 01.06.2016. */ public class ZTE_ADV_IMX234 extends ZTE_ADV { public ZTE_ADV_IMX234(Parameters parameters, CameraWrapperInterface cameraUiWrapper) { super(parameters, cameraUiWrapper); } //needs some more debug @Override public AbstractManualParameter getExposureTimeParameter() { return new ShutterManualZTE(parameters, cameraUiWrapper); } @Override public AbstractManualParameter getManualFocusParameter() { return new BaseFocusManual(parameters, KEYS.KEY_MANUAL_FOCUS_POSITION,0,79,KEYS.KEY_FOCUS_MODE_MANUAL, cameraUiWrapper,1,1); } @Override public AbstractManualParameter getCCTParameter() { return new BaseCCTManual(parameters,KEYS.WB_MANUAL_CCT,8000,2000, cameraUiWrapper,100, KEYS.WB_MODE_MANUAL_CCT); } @Override public ModeParameterInterface getNightMode() { return new NightModeZTE(parameters, cameraUiWrapper); } @Override public boolean IsDngSupported() { return true; } @Override public DngProfile getDngProfile(int filesize) { switch (filesize) { case 20041728: return new DngProfile(64, 5344, 3000, DngProfile.Mipi16, DngProfile.RGGB, 0, matrixChooserParameter.GetCustomMatrix(MatrixChooserParameter.G4)); } return null; } @Override public void SetFocusArea(FocusRect focusAreas) { if (focusAreas != null) { Camera.Area a = new Camera.Area(new Rect(focusAreas.left, focusAreas.top, focusAreas.right, focusAreas.bottom), 1000); ArrayList<Camera.Area> ar = new ArrayList<>(); ar.add(a); parameters.setFocusAreas(ar); } else parameters.setFocusAreas(null); parametersHandler.SetParametersToCamera(parameters); } }
gpl-2.0
luizperes/TStepProject
app/src/main/java/org/telegram/ui/Components/SeekBar.java
4659
/* * This is the source code of Telegram 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. */ package org.telegram.ui.Components; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.view.MotionEvent; import org.telegram.android.AndroidUtilities; import project.main.steptaneous.R; public class SeekBar { public interface SeekBarDelegate { void onSeekBarDrag(float progress); } private static Drawable thumbDrawable1; private static Drawable thumbDrawablePressed1; private static Drawable thumbDrawable2; private static Drawable thumbDrawablePressed2; private static Paint innerPaint1 = new Paint(); private static Paint outerPaint1 = new Paint(); private static Paint innerPaint2 = new Paint(); private static Paint outerPaint2 = new Paint(); private static int thumbWidth; private static int thumbHeight; public int type; public int thumbX = 0; public int thumbDX = 0; private boolean pressed = false; public int width; public int height; public SeekBarDelegate delegate; public SeekBar(Context context) { if (thumbDrawable1 == null) { thumbDrawable1 = context.getResources().getDrawable(R.mipmap.player1); thumbDrawablePressed1 = context.getResources().getDrawable(R.mipmap.player1_pressed); thumbDrawable2 = context.getResources().getDrawable(R.mipmap.player2); thumbDrawablePressed2 = context.getResources().getDrawable(R.mipmap.player2_pressed); innerPaint1.setColor(0xffb4e396); outerPaint1.setColor(0xff6ac453); innerPaint2.setColor(0xffd9e2eb); outerPaint2.setColor(0xff86c5f8); thumbWidth = thumbDrawable1.getIntrinsicWidth(); thumbHeight = thumbDrawable1.getIntrinsicHeight(); } } public boolean onTouch(int action, float x, float y) { if (action == MotionEvent.ACTION_DOWN) { int additionWidth = (height - thumbWidth) / 2; if (thumbX - additionWidth <= x && x <= thumbX + thumbWidth + additionWidth && y >= 0 && y <= height) { pressed = true; thumbDX = (int)(x - thumbX); return true; } } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { if (pressed) { if (action == MotionEvent.ACTION_UP && delegate != null) { delegate.onSeekBarDrag((float)thumbX / (float)(width - thumbWidth)); } pressed = false; return true; } } else if (action == MotionEvent.ACTION_MOVE) { if (pressed) { thumbX = (int)(x - thumbDX); if (thumbX < 0) { thumbX = 0; } else if (thumbX > width - thumbWidth) { thumbX = width - thumbWidth; } return true; } } return false; } public void setProgress(float progress) { thumbX = (int)Math.ceil((width - thumbWidth) * progress); if (thumbX < 0) { thumbX = 0; } else if (thumbX > width - thumbWidth) { thumbX = width - thumbWidth; } } public boolean isDragging() { return pressed; } public void draw(Canvas canvas) { Drawable thumb = null; Paint inner = null; Paint outer = null; if (type == 0) { if (!pressed) { thumb = thumbDrawable1; } else { thumb = thumbDrawablePressed1; } inner = innerPaint1; outer = outerPaint1; } else if (type == 1) { if (!pressed) { thumb = thumbDrawable2; } else { thumb = thumbDrawablePressed2; } inner = innerPaint2; outer = outerPaint2; } int y = (height - thumbHeight) / 2; canvas.drawRect(thumbWidth / 2, height / 2 - AndroidUtilities.dp(1), width - thumbWidth / 2, height / 2 + AndroidUtilities.dp(1), inner); canvas.drawRect(thumbWidth / 2, height / 2 - AndroidUtilities.dp(1), thumbWidth / 2 + thumbX, height / 2 + AndroidUtilities.dp(1), outer); thumb.setBounds(thumbX, y, thumbX + thumbWidth, y + thumbHeight); thumb.draw(canvas); } }
gpl-2.0
graalvm/fastr
com.oracle.truffle.r.test/src/com/oracle/truffle/r/test/builtins/TestBuiltin_rev.java
1366
/* * 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., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (c) 2012-2014, Purdue University * Copyright (c) 2013, 2018, Oracle and/or its affiliates * * All rights reserved. */ package com.oracle.truffle.r.test.builtins; import org.junit.Test; import com.oracle.truffle.r.test.TestBase; // Checkstyle: stop line length check public class TestBuiltin_rev extends TestBase { @Test public void testrev1() { assertEval("argv <- structure(list(x = c('#FF0000FF', '#FFFF00FF', '#00FF00FF')), .Names = 'x');do.call('rev', argv)"); } @Test public void testRev() { assertEval("{ rev(1:3) }"); assertEval("{ rev(c(1+1i, 2+2i)) }"); } }
gpl-2.0
ratschlab/ASP
examples/undocumented/java_modular/classifier_larank_modular.java
1206
import org.shogun.*; import org.jblas.*; import static org.shogun.MulticlassLabels.obtain_from_generic; public class classifier_larank_modular { static { System.loadLibrary("modshogun"); } public static void main(String argv[]) { modshogun.init_shogun_with_defaults(); double width = 2.1; double epsilon = 1e-5; double C = 1.0; DoubleMatrix traindata_real = Load.load_numbers("../data/fm_train_real.dat"); DoubleMatrix testdata_real = Load.load_numbers("../data/fm_test_real.dat"); DoubleMatrix trainlab = Load.load_labels("../data/label_train_multiclass.dat"); RealFeatures feats_train = new RealFeatures(); feats_train.set_feature_matrix(traindata_real); RealFeatures feats_test = new RealFeatures(); feats_test.set_feature_matrix(testdata_real); GaussianKernel kernel = new GaussianKernel(feats_train, feats_train, width); MulticlassLabels labels = new MulticlassLabels(trainlab); LaRank svm = new LaRank(C, kernel, labels); svm.set_batch_mode(false); svm.set_epsilon(epsilon); svm.train(); DoubleMatrix out_labels = obtain_from_generic(svm.apply(feats_train)).get_labels(); System.out.println(out_labels.toString()); modshogun.exit_shogun(); } }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashMarshaller.java
1079
/* * Licensed to the University Corporation for Advanced Internet Development, * Inc. (UCAID) under one or more contributor license agreements. See the * NOTICE file distributed with this work for additional information regarding * copyright ownership. The UCAID 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.opensaml.ws.wstrust.impl; import org.opensaml.xml.schema.impl.XSBase64BinaryMarshaller; /** * Marshaller for the CombinedHash element. * */ public class CombinedHashMarshaller extends XSBase64BinaryMarshaller { }
gpl-2.0
itsazzad/zanata-server
zanata-war/src/main/java/org/zanata/action/ProcessManagerAction.java
2661
/* * Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the * @author tags. See the copyright.txt file in the distribution for a full * listing of individual contributors. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF * site: http://www.fsf.org. */ package org.zanata.action; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.zanata.security.annotations.CheckLoggedIn; import org.zanata.security.annotations.CheckPermission; import org.zanata.security.annotations.CheckRole; import org.zanata.async.AsyncTaskHandle; import org.zanata.async.AsyncTaskHandleManager; import org.zanata.security.annotations.ZanataSecured; /** * @author Carlos Munoz <a * href="mailto:camunoz@redhat.com">camunoz@redhat.com</a> */ @Name("processManagerAction") @Scope(ScopeType.EVENT) @ZanataSecured @CheckRole("admin") public class ProcessManagerAction { @In private AsyncTaskHandleManager asyncTaskHandleManager; public Collection<AsyncTaskHandle> getRunningProcesses() { ArrayList<AsyncTaskHandle> allHandles = new ArrayList<AsyncTaskHandle>(); allHandles.addAll(asyncTaskHandleManager.getAllHandles()); return allHandles; } public int getRunningCount() { int running = 0; for (AsyncTaskHandle h : asyncTaskHandleManager.getAllHandles()) { if (!h.isDone()) { running++; } } return running; } public int getStoppedCount() { return asyncTaskHandleManager.getAllHandles().size() - getRunningCount(); } public Date getDateFromLong(long value) { return new Date(value); } public void cancel(AsyncTaskHandle handle) { handle.cancel(true); } }
gpl-2.0
mkorobeynikov/jhipster-radriges
src/main/java/ru/radriges/site/security/CustomPersistentRememberMeServices.java
9022
package ru.radriges.site.security; import ru.radriges.site.domain.PersistentToken; import ru.radriges.site.domain.User; import ru.radriges.site.repository.PersistentTokenRepository; import ru.radriges.site.repository.UserRepository; import org.joda.time.LocalDate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import org.springframework.dao.DataAccessException; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.codec.Base64; import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices; import org.springframework.security.web.authentication.rememberme.CookieTheftException; import org.springframework.security.web.authentication.rememberme.InvalidCookieException; import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.security.SecureRandom; import java.util.Arrays; /** * Custom implementation of Spring Security's RememberMeServices. * <p/> * Persistent tokens are used by Spring Security to automatically log in users. * <p/> * This is a specific implementation of Spring Security's remember-me authentication, but it is much * more powerful than the standard implementations: * <ul> * <li>It allows a user to see the list of his currently opened sessions, and invalidate them</li> * <li>It stores more information, such as the IP address and the user agent, for audit purposes<li> * <li>When a user logs out, only his current session is invalidated, and not all of his sessions</li> * </ul> * <p/> * This is inspired by: * <ul> * <li><a href="http://jaspan.com/improved_persistent_login_cookie_best_practice">Improved Persistent Login Cookie * Best Practice</a></li> * <li><a href="https://github.com/blog/1661-modeling-your-app-s-user-session">Github's "Modeling your App's User Session"</a></li></li> * </ul> * <p/> * The main algorithm comes from Spring Security's PersistentTokenBasedRememberMeServices, but this class * couldn't be cleanly extended. * <p/> */ @Service public class CustomPersistentRememberMeServices extends AbstractRememberMeServices { private final Logger log = LoggerFactory.getLogger(CustomPersistentRememberMeServices.class); // Token is valid for one month private static final int TOKEN_VALIDITY_DAYS = 31; private static final int TOKEN_VALIDITY_SECONDS = 60 * 60 * 24 * TOKEN_VALIDITY_DAYS; private static final int DEFAULT_SERIES_LENGTH = 16; private static final int DEFAULT_TOKEN_LENGTH = 16; private SecureRandom random; @Inject private PersistentTokenRepository persistentTokenRepository; @Inject private UserRepository userRepository; @Inject public CustomPersistentRememberMeServices(Environment env, org.springframework.security.core.userdetails.UserDetailsService userDetailsService) { super(env.getProperty("jhipster.security.rememberme.key"), userDetailsService); random = new SecureRandom(); } @Override @Transactional protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) { PersistentToken token = getPersistentToken(cookieTokens); String login = token.getUser().getLogin(); // Token also matches, so login is valid. Update the token value, keeping the *same* series number. log.debug("Refreshing persistent login token for user '{}', series '{}'", login, token.getSeries()); token.setTokenDate(new LocalDate()); token.setTokenValue(generateTokenData()); token.setIpAddress(request.getRemoteAddr()); token.setUserAgent(request.getHeader("User-Agent")); try { persistentTokenRepository.save(token); addCookie(token, request, response); } catch (DataAccessException e) { log.error("Failed to update token: ", e); throw new RememberMeAuthenticationException("Autologin failed due to data access problem", e); } return getUserDetailsService().loadUserByUsername(login); } @Override protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { String login = successfulAuthentication.getName(); log.debug("Creating new persistent login for user {}", login); PersistentToken token = userRepository.findOneByLogin(login).map(u -> { PersistentToken t = new PersistentToken(); t.setSeries(generateSeriesData()); t.setUser(u); t.setTokenValue(generateTokenData()); t.setTokenDate(new LocalDate()); t.setIpAddress(request.getRemoteAddr()); t.setUserAgent(request.getHeader("User-Agent")); return t; }).orElseThrow(() -> new UsernameNotFoundException("User " + login + " was not found in the database")); try { persistentTokenRepository.save(token); addCookie(token, request, response); } catch (DataAccessException e) { log.error("Failed to save persistent token ", e); } } /** * When logout occurs, only invalidate the current token, and not all user sessions. * <p/> * The standard Spring Security implementations are too basic: they invalidate all tokens for the * current user, so when he logs out from one browser, all his other sessions are destroyed. */ @Override @Transactional public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { String rememberMeCookie = extractRememberMeCookie(request); if (rememberMeCookie != null && rememberMeCookie.length() != 0) { try { String[] cookieTokens = decodeCookie(rememberMeCookie); PersistentToken token = getPersistentToken(cookieTokens); persistentTokenRepository.delete(token); } catch (InvalidCookieException ice) { log.info("Invalid cookie, no persistent token could be deleted"); } catch (RememberMeAuthenticationException rmae) { log.debug("No persistent token found, so no token could be deleted"); } } super.logout(request, response, authentication); } /** * Validate the token and return it. */ private PersistentToken getPersistentToken(String[] cookieTokens) { if (cookieTokens.length != 2) { throw new InvalidCookieException("Cookie token did not contain " + 2 + " tokens, but contained '" + Arrays.asList(cookieTokens) + "'"); } String presentedSeries = cookieTokens[0]; String presentedToken = cookieTokens[1]; PersistentToken token = persistentTokenRepository.findOne(presentedSeries); if (token == null) { // No series match, so we can't authenticate using this cookie throw new RememberMeAuthenticationException("No persistent token found for series id: " + presentedSeries); } // We have a match for this user/series combination log.info("presentedToken={} / tokenValue={}", presentedToken, token.getTokenValue()); if (!presentedToken.equals(token.getTokenValue())) { // Token doesn't match series value. Delete this session and throw an exception. persistentTokenRepository.delete(token); throw new CookieTheftException("Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack."); } if (token.getTokenDate().plusDays(TOKEN_VALIDITY_DAYS).isBefore(LocalDate.now())) { persistentTokenRepository.delete(token); throw new RememberMeAuthenticationException("Remember-me login has expired"); } return token; } private String generateSeriesData() { byte[] newSeries = new byte[DEFAULT_SERIES_LENGTH]; random.nextBytes(newSeries); return new String(Base64.encode(newSeries)); } private String generateTokenData() { byte[] newToken = new byte[DEFAULT_TOKEN_LENGTH]; random.nextBytes(newToken); return new String(Base64.encode(newToken)); } private void addCookie(PersistentToken token, HttpServletRequest request, HttpServletResponse response) { setCookie( new String[]{token.getSeries(), token.getTokenValue()}, TOKEN_VALIDITY_SECONDS, request, response); } }
gpl-2.0
tbaumeist/FreeNet-Source
src/freenet/io/xfer/BlockTransmitter.java
22277
/* * Dijjer - A Peer to Peer HTTP Cache * Copyright (C) 2004,2005 Change.Tv, Inc * * 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 freenet.io.xfer; import java.util.HashSet; import java.util.LinkedList; import freenet.io.comm.AsyncMessageCallback; import freenet.io.comm.AsyncMessageFilterCallback; import freenet.io.comm.ByteCounter; import freenet.io.comm.DMT; import freenet.io.comm.DisconnectedException; import freenet.io.comm.Message; import freenet.io.comm.MessageCore; import freenet.io.comm.MessageFilter; import freenet.io.comm.NotConnectedException; import freenet.io.comm.PeerContext; import freenet.io.comm.PeerRestartedException; import freenet.io.comm.RetrievalException; import freenet.node.MessageItem; import freenet.io.comm.SlowAsyncMessageFilterCallback; import freenet.node.PrioRunnable; import freenet.node.SyncSendWaitedTooLongException; import freenet.support.BitArray; import freenet.support.Executor; import freenet.support.LogThresholdCallback; import freenet.support.Logger; import freenet.support.Ticker; import freenet.support.TimeUtil; import freenet.support.Logger.LogLevel; import freenet.support.io.NativeThread; import freenet.support.math.MedianMeanRunningAverage; /** * @author ian * * Given a PartiallyReceivedBlock retransmit to another node (to be received by BlockReceiver). * Since a PRB can be concurrently transmitted to many peers NOWHERE in this class is prb.abort() to be called. */ public class BlockTransmitter { private static volatile boolean logMINOR; static { Logger.registerLogThresholdCallback(new LogThresholdCallback(){ @Override public void shouldUpdate(){ logMINOR = Logger.shouldLog(LogLevel.MINOR, this); } }); } public static final int SEND_TIMEOUT = 60000; final MessageCore _usm; final PeerContext _destination; private boolean _sentSendAborted; final long _uid; private final boolean realTime; final PartiallyReceivedBlock _prb; private LinkedList<Integer> _unsent; private BlockSenderJob _senderThread = new BlockSenderJob(); private BitArray _sentPackets; final PacketThrottle throttle; private long timeAllSent = -1; final ByteCounter _ctr; final int PACKET_SIZE; private final ReceiverAbortHandler abortHandler; private HashSet<MessageItem> itemsPending = new HashSet<MessageItem>(); private final Ticker _ticker; private final Executor _executor; private final BlockTransmitterCompletion _callback; /** Have we received a completion acknowledgement from the other side - either a * sendAborted or allReceived? */ private boolean _receivedSendCompletion; /** Was it an allReceived? */ private boolean _receivedSendSuccess; /** Have we completed i.e. called the callback? */ private boolean _completed; /** Have we failed e.g. due to PRB abort, disconnection? */ private boolean _failed; static int runningBlockTransmits = 0; class BlockSenderJob implements PrioRunnable { private boolean running = false; public void run() { synchronized(this) { if(running) return; running = true; } try { while(true) { int packetNo = -1; synchronized(_senderThread) { if(_failed || _receivedSendCompletion || _completed) return; if(_unsent.size() == 0) { // Wait for PRB callback to tell us we have more packets. return; } else packetNo = _unsent.removeFirst(); } if(!innerRun(packetNo)) return; } } finally { synchronized(this) { running = false; } } } public void schedule() { if(_failed || _receivedSendCompletion || _completed) return; _executor.execute(this, "BlockTransmitter block sender for "+_uid+" to "+_destination); } /** @return True . */ private boolean innerRun(int packetNo) { try { MessageItem item = _destination.sendThrottledMessage(DMT.createPacketTransmit(_uid, packetNo, _sentPackets, _prb.getPacket(packetNo), realTime), _prb._packetSize, _ctr, SEND_TIMEOUT, false, new MyAsyncMessageCallback()); synchronized(itemsPending) { itemsPending.add(item); } } catch (PeerRestartedException e) { onDisconnect(); return false; } catch (NotConnectedException e) { onDisconnect(); return false; } catch (AbortedException e) { Logger.normal(this, "Terminating send due to abort: "+e); // The PRB callback will deal with this. return false; } catch (WaitedTooLongException e) { Logger.normal(this, "Waited too long to send packet, aborting on "+BlockTransmitter.this); Future fail; synchronized(_senderThread) { fail = maybeFail(RetrievalException.TIMED_OUT, "Sender unable to send packets quickly enough"); } fail.execute(); cancelItemsPending(); return false; } catch (SyncSendWaitedTooLongException e) { // Impossible, but lets cancel it anyway Future fail; synchronized(_senderThread) { fail = maybeFail(RetrievalException.UNKNOWN, "Impossible: SyncSendWaitedTooLong"); } Logger.error(this, "Impossible: Caught "+e+" on "+BlockTransmitter.this, e); fail.execute(); return false; } boolean success = false; boolean complete = false; synchronized (_senderThread) { _sentPackets.setBit(packetNo, true); if(_unsent.size() == 0 && getNumSent() == _prb._packets) { //No unsent packets, no unreceived packets sendAllSentNotification(); if(maybeAllSent()) { if(maybeComplete()) { complete = true; success = _receivedSendSuccess; } else return false; } else { return false; } } } if(complete) { callCallback(success); return false; // No more blocks to send. } return true; // More blocks to send. } public int getPriority() { return NativeThread.HIGH_PRIORITY; } } public BlockTransmitter(MessageCore usm, Ticker ticker, PeerContext destination, long uid, PartiallyReceivedBlock source, ByteCounter ctr, ReceiverAbortHandler abortHandler, BlockTransmitterCompletion callback, boolean realTime) { this.realTime = realTime; _ticker = ticker; _executor = _ticker.getExecutor(); _callback = callback; this.abortHandler = abortHandler; _usm = usm; _destination = destination; _uid = uid; _prb = source; _ctr = ctr; if(_ctr == null) throw new NullPointerException(); PACKET_SIZE = DMT.packetTransmitSize(_prb._packetSize, _prb._packets) + destination.getOutgoingMangler().fullHeadersLengthOneMessage(); try { _sentPackets = new BitArray(_prb.getNumPackets()); } catch (AbortedException e) { Logger.error(this, "Aborted during setup"); // Will throw on running } throttle = _destination.getThrottle(); } private Runnable timeoutJob; public void scheduleTimeoutAfterBlockSends() { synchronized(_senderThread) { if(_receivedSendCompletion) return; if(timeoutJob != null) return; if(logMINOR) Logger.minor(this, "Scheduling timeout on "+this); timeoutJob = new PrioRunnable() { public void run() { String timeString; String abortReason; Future fail; synchronized(_senderThread) { if(_completed) return; if(!_receivedSendCompletion) { _receivedSendCompletion = true; _receivedSendSuccess = false; } //SEND_TIMEOUT (one minute) after all packets have been transmitted, terminate the send. if(_failed) { // Already failed, we were just waiting for the acknowledgement sendAborted. Logger.error(this, "Terminating send after failure on "+this); abortReason = "Already failed and no acknowledgement"; } else { timeString=TimeUtil.formatTime((System.currentTimeMillis() - timeAllSent), 2, true); Logger.error(this, "Terminating send "+_uid+" to "+_destination+" from "+_destination.getSocketHandler()+" as we haven't heard from receiver in "+timeString+ '.'); abortReason = "Haven't heard from you (receiver) in "+timeString; } fail = maybeFail(RetrievalException.RECEIVER_DIED, abortReason); } fail.execute(); } public int getPriority() { return NativeThread.NORM_PRIORITY; } }; _ticker.queueTimedJob(timeoutJob, "Timeout for "+this, SEND_TIMEOUT, false, false); } } /** LOCKING: Must be called with _senderThread held. * @return True if everything has been sent and we are now just waiting for an * acknowledgement or timeout from the other side. */ public boolean maybeAllSent() { if(blockSendsPending == 0 && _unsent.size() == 0 && getNumSent() == _prb._packets) { timeAllSent = System.currentTimeMillis(); if(logMINOR) Logger.minor(this, "Sent all blocks, none unsent on "+this); _senderThread.notifyAll(); return true; } if(blockSendsPending == 0 && _failed) { timeAllSent = System.currentTimeMillis(); if(logMINOR) Logger.minor(this, "Sent blocks and failed on "+this); return true; } if(logMINOR) Logger.minor(this, "maybeAllSent: block sends pending = "+blockSendsPending+" unsent = "+_unsent.size()+" sent = "+getNumSent()+" on "+this); return false; } /** Complete? maybeAllSent() must have already returned true. This method checks * _sendCompleted and then uses _completed to complete only once. LOCKING: Must be * called with _senderThread held. * Caller must call the callback then call cleanup() outside the lock if this returns true. */ public boolean maybeComplete() { if(!_receivedSendCompletion) { if(logMINOR) Logger.minor(this, "maybeComplete() not completing because send not completed on "+this); // All the block sends have completed, wait for the other side to acknowledge or timeout. scheduleTimeoutAfterBlockSends(); return false; } if(_completed) { if(logMINOR) Logger.minor(this, "maybeComplete() already completed on "+this); return false; } if(logMINOR) Logger.minor(this, "maybeComplete() completing on "+this); _completed = true; decRunningBlockTransmits(); return true; } interface Future { void execute(); } private final Future nullFuture = new Future() { public void execute() { // Do nothing. } }; /** Only fail once. Called on a drastic failure e.g. disconnection. Unless we are sure * that we don't need to (e.g. on disconnection), the caller must call prepareSendAborted * afterwards, and if that returns true, send the sendAborted via innerSendAborted. * LOCKING: Must be called inside the _senderThread lock. * @return A Future which the caller must execute() outside the lock. */ public Future maybeFail(final int reason, final String description) { if(_completed) { if(logMINOR) Logger.minor(this, "maybeFail() already completed on "+this); return nullFuture; } _failed = true; if(!_receivedSendCompletion) { // Don't actually timeout until after we have an acknowledgement of the transfer cancel. // This is important for keeping track of how many transfers are actually running, which will be important for load management later on. // The caller will immediately call prepareSendAbort() then innerSendAborted(). if(logMINOR) Logger.minor(this, "maybeFail() waiting for acknowledgement on "+this); if(_sentSendAborted) { scheduleTimeoutAfterBlockSends(); return nullFuture; // Do nothing, waiting for timeout. } else { _sentSendAborted = true; // Send the aborted, then wait. return new Future() { public void execute() { try { innerSendAborted(reason, description); scheduleTimeoutAfterBlockSends(); } catch (NotConnectedException e) { onDisconnect(); } } }; } } if(blockSendsPending != 0) { if(logMINOR) Logger.minor(this, "maybeFail() waiting for "+blockSendsPending+" block sends on "+this); return nullFuture; // Wait for blockSendsPending to reach 0 } if(logMINOR) Logger.minor(this, "maybeFail() completing on "+this); _completed = true; decRunningBlockTransmits(); return new Future() { public void execute() { callCallback(false); } }; } /** Abort the send, and then send the sendAborted message. Don't do anything if the * send has already been aborted. */ public void abortSend(int reason, String desc) throws NotConnectedException { if(logMINOR) Logger.minor(this, "Aborting send on "+this); Future fail; synchronized(_senderThread) { _failed = true; fail = maybeFail(reason, desc); } fail.execute(); cancelItemsPending(); } public void innerSendAborted(int reason, String desc) throws NotConnectedException { _usm.send(_destination, DMT.createSendAborted(_uid, reason, desc), _ctr); } private void sendAllSentNotification() { try { _usm.send(_destination, DMT.createAllSent(_uid), _ctr); } catch (NotConnectedException e) { Logger.normal(this, "disconnected for allSent()"); } } public interface ReceiverAbortHandler { /** @return True to cancel the PRB and thus cascade the cancel to the downstream * transfer, false otherwise. */ public boolean onAbort(); } public static final ReceiverAbortHandler ALWAYS_CASCADE = new ReceiverAbortHandler() { public boolean onAbort() { return true; } }; public static final ReceiverAbortHandler NEVER_CASCADE = new ReceiverAbortHandler() { public boolean onAbort() { return false; } }; public interface BlockTransmitterCompletion { public void blockTransferFinished(boolean success); } private PartiallyReceivedBlock.PacketReceivedListener myListener = null; private MessageFilter mfAllReceived; private MessageFilter mfSendAborted; private AsyncMessageFilterCallback cbAllReceived = new SlowAsyncMessageFilterCallback() { public void onMatched(Message m) { if(logMINOR) { long endTime = System.currentTimeMillis(); long transferTime = (endTime - startTime); synchronized(avgTimeTaken) { avgTimeTaken.report(transferTime); Logger.minor(this, "Block send took "+transferTime+" : "+avgTimeTaken+" on "+BlockTransmitter.this); } } synchronized(_senderThread) { _receivedSendCompletion = true; _receivedSendSuccess = true; if(!maybeAllSent()) return; if(!maybeComplete()) return; } callCallback(true); } public boolean shouldTimeout() { synchronized(_senderThread) { // We are waiting for the send completion, which is set on timeout as well as on receiving a message. // In some corner cases we might want to get the allReceived after setting _failed, so don't timeout on _failed. // We do want to timeout on _completed because that means everything is finished - it is only set in maybeComplete() and maybeFail(). if(_receivedSendCompletion || _completed) return true; } return false; } public void onTimeout() { // Do nothing } public void onDisconnect(PeerContext ctx) { BlockTransmitter.this.onDisconnect(); } public void onRestarted(PeerContext ctx) { BlockTransmitter.this.onDisconnect(); } public int getPriority() { return NativeThread.NORM_PRIORITY; } }; private AsyncMessageFilterCallback cbSendAborted = new SlowAsyncMessageFilterCallback() { public void onMatched(Message msg) { if(abortHandler.onAbort()) _prb.abort(RetrievalException.CANCELLED_BY_RECEIVER, "Cascading cancel from receiver"); Future fail; synchronized(_senderThread) { _receivedSendCompletion = true; _receivedSendSuccess = false; fail = maybeFail(msg.getInt(DMT.REASON), msg.getString(DMT.DESCRIPTION)); if(logMINOR) Logger.minor(this, "Transfer got sendAborted on "+BlockTransmitter.this); } fail.execute(); cancelItemsPending(); } public boolean shouldTimeout() { synchronized(_senderThread) { // We are waiting for the send completion, which is set on timeout as well as on receiving a message. // We don't want to timeout on _failed because we can set _failed, send sendAborted, and then wait for the acknowledging sendAborted. // We do want to timeout on _completed because that means everything is finished - it is only set in maybeComplete() and maybeFail(). if(_receivedSendCompletion || _completed) return true; } return false; } public void onTimeout() { // Do nothing } public void onDisconnect(PeerContext ctx) { BlockTransmitter.this.onDisconnect(); } public void onRestarted(PeerContext ctx) { BlockTransmitter.this.onDisconnect(); } public int getPriority() { return NativeThread.NORM_PRIORITY; } }; private void onDisconnect() { throttle.maybeDisconnected(); Logger.normal(this, "Terminating send "+_uid+" to "+_destination+" from "+_destination.getSocketHandler()+" because node disconnected while waiting"); //They disconnected, can't send an abort to them then can we? Future fail; synchronized(_senderThread) { _receivedSendCompletion = true; // effectively fail = maybeFail(RetrievalException.SENDER_DISCONNECTED, "Sender disconnected"); } fail.execute(); } private void onAborted(int reason, String description) { if(logMINOR) Logger.minor(this, "Aborting on "+this); Future fail; synchronized(_senderThread) { timeAllSent = -1; _failed = true; _senderThread.notifyAll(); fail = maybeFail(reason, description); } fail.execute(); cancelItemsPending(); } private long startTime; /** Send the data, off-thread. */ public void sendAsync() { startTime = System.currentTimeMillis(); if(logMINOR) Logger.minor(this, "Starting async send on "+this); incRunningBlockTransmits(); try { synchronized(_prb) { _unsent = _prb.addListener(myListener = new PartiallyReceivedBlock.PacketReceivedListener() {; public void packetReceived(int packetNo) { synchronized(_senderThread) { _unsent.addLast(packetNo); timeAllSent = -1; _sentPackets.setBit(packetNo, false); _senderThread.schedule(); } } public void receiveAborted(int reason, String description) { onAborted(reason, description); } }); } _senderThread.schedule(); mfAllReceived = MessageFilter.create().setType(DMT.allReceived).setField(DMT.UID, _uid).setSource(_destination).setNoTimeout(); mfSendAborted = MessageFilter.create().setType(DMT.sendAborted).setField(DMT.UID, _uid).setSource(_destination).setNoTimeout(); try { _usm.addAsyncFilter(mfAllReceived, cbAllReceived, _ctr); _usm.addAsyncFilter(mfSendAborted, cbSendAborted, _ctr); } catch (DisconnectedException e) { onDisconnect(); } } catch (AbortedException e) { onAborted(_prb._abortReason, _prb._abortDescription); } } private void cancelItemsPending() { MessageItem[] items; synchronized(itemsPending) { items = itemsPending.toArray(new MessageItem[itemsPending.size()]); itemsPending.clear(); } for(MessageItem item : items) { if(!_destination.unqueueMessage(item)) { // Race condition, can happen if(logMINOR) Logger.minor(this, "Message not queued ?!?!?!? on "+this+" : "+item); } } } long timeLastBlockSendCompleted = -1; private static synchronized void incRunningBlockTransmits() { runningBlockTransmits++; if(logMINOR) Logger.minor(BlockTransmitter.class, "Started a block transmit, running: "+runningBlockTransmits); } private static synchronized void decRunningBlockTransmits() { runningBlockTransmits--; if(logMINOR) Logger.minor(BlockTransmitter.class, "Finished a block transmit, running: "+runningBlockTransmits); } private void cleanup() { // FIXME remove filters // shouldTimeout() should deal with them adequately, maybe we don't need to explicitly remove them. if (myListener!=null) _prb.removeListener(myListener); } private class MyAsyncMessageCallback implements AsyncMessageCallback { MyAsyncMessageCallback() { synchronized(_senderThread) { blockSendsPending++; } } private boolean completed = false; public void sent() { if(logMINOR) Logger.minor(this, "Sent block on "+BlockTransmitter.this); // Wait for acknowledged } public void acknowledged() { complete(); } public void disconnected() { // FIXME kill transfer complete(); } public void fatalError() { // FIXME kill transfer complete(); } private void complete() { if(logMINOR) Logger.minor(this, "Completed send on a block for "+BlockTransmitter.this); boolean success; synchronized(_senderThread) { if(completed) return; completed = true; blockSendsPending--; if(logMINOR) Logger.minor(this, "Pending: "+blockSendsPending); if(!maybeAllSent()) return; if(!maybeComplete()) return; success = _receivedSendSuccess; } callCallback(success); } }; private int blockSendsPending = 0; private static MedianMeanRunningAverage avgTimeTaken = new MedianMeanRunningAverage(); public int getNumSent() { int ret = 0; for (int x=0; x<_sentPackets.getSize(); x++) { if (_sentPackets.bitAt(x)) { ret++; } } return ret; } public void callCallback(final boolean success) { if(_callback != null) { _executor.execute(new Runnable() { public void run() { try { _callback.blockTransferFinished(success); } finally { cleanup(); } } }, "BlockTransmitter completion callback"); } else { cleanup(); } } public PeerContext getDestination() { return _destination; } @Override public String toString() { return "BlockTransmitter for "+_uid+" to "+_destination.shortToString(); } public synchronized static int getRunningSends() { return runningBlockTransmits; } }
gpl-2.0
biscuit-team/TuningFork
src/main/java/cn/sotou/tuningfork/util/provider/PipeUtilProvider.java
611
package cn.sotou.tuningfork.util.provider; import java.util.LinkedList; import java.util.List; import cn.sotou.tuningfork.util.PipeUtil; public class PipeUtilProvider { private List<IUtilProvider> providers = new LinkedList<IUtilProvider>(); public PipeUtilProvider() { providers.add(new BuiltinUtilProvider()); } public PipeUtil get(String name) { for (IUtilProvider provider : providers) { PipeUtil util = provider.get(name); if (util != null) { return util; } } return null; } public void setUtilProviders(List<IUtilProvider> providers) { this.providers = providers; } }
gpl-2.0
isandlaTech/cohorte-utilities
extra/org.cohorte.utilities.installer/src/org/cohorte/utilities/installer/panels/CPanelTreePacks.java
1043
package org.cohorte.utilities.installer.panels; import org.cohorte.utilities.installer.panels.treepacks.CTreePacksPanel; import com.izforge.izpack.api.data.Panel; import com.izforge.izpack.api.resource.Locales; import com.izforge.izpack.api.resource.Resources; import com.izforge.izpack.api.rules.RulesEngine; import com.izforge.izpack.installer.data.GUIInstallData; import com.izforge.izpack.installer.gui.InstallerFrame; /** * MOD_OG_20160715 console mode * * @author ogattaz * */ @Deprecated public class CPanelTreePacks extends CTreePacksPanel { /** * */ private static final long serialVersionUID = 2735989402646225915L; /** * Constructor of Welcome Panel. * * @param panel * @param parent * @param installData * @param resources * @param log */ public CPanelTreePacks(final Panel panel, final InstallerFrame parent, final GUIInstallData installData, final Resources resources, final Locales locals, final RulesEngine rules) { super(panel, parent, installData, resources, locals, rules); } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest04879.java
2031
/** * 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 Nick Sanidas <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("/BenchmarkTest04879") public class BenchmarkTest04879 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 { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request ); String param = scr.getTheParameter("foo"); String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param); try { javax.naming.directory.InitialDirContext idc = org.owasp.benchmark.helpers.Utils.getInitialDirContext(); idc.search("name", bar, new javax.naming.directory.SearchControls()); } catch (javax.naming.NamingException e) { throw new ServletException(e); } } }
gpl-2.0
graalvm/fastr
com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/nmath/distr/QBeta.java
32250
/* * Copyright (c) 1995, 1996, Robert Gentleman and Ross Ihaka * Copyright (c) 1998-2015, The R Core Team * Copyright (c) 2016, 2019, Oracle and/or its affiliates * * 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.R-project.org/Licenses/ */ /* * based on code (C) 1979 and later Royal Statistical Society * * Reference: * Cran, G. W., K. J. Martin and G. E. Thomas (1977). * Remark AS R19 and Algorithm AS 109, * Applied Statistics, 26(1), 111-114. * Remark AS R83 (v.39, 309-310) and the correction (v.40(1) p.236) * have been incorporated in this version. */ package com.oracle.truffle.r.runtime.nmath.distr; import static com.oracle.truffle.r.runtime.nmath.Arithmetic.powDi; import static com.oracle.truffle.r.runtime.nmath.LBeta.lbeta; import static com.oracle.truffle.r.runtime.nmath.MathConstants.DBL_MANT_DIG; import static com.oracle.truffle.r.runtime.nmath.MathConstants.DBL_MIN; import static com.oracle.truffle.r.runtime.nmath.MathConstants.DBL_MIN_EXP; import static com.oracle.truffle.r.runtime.nmath.MathConstants.ML_NAN; import static com.oracle.truffle.r.runtime.nmath.MathConstants.M_LN2; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.r.runtime.Utils; import com.oracle.truffle.r.runtime.RError.Message; import com.oracle.truffle.r.runtime.nmath.DPQ; import com.oracle.truffle.r.runtime.nmath.MathFunctions.Function3_2; import com.oracle.truffle.r.runtime.nmath.RMath; import com.oracle.truffle.r.runtime.nmath.RMathError; import com.oracle.truffle.r.runtime.nmath.RMathError.MLError; public final class QBeta implements Function3_2 { public static QBeta create() { return new QBeta(); } public static QBeta getUncached() { return new QBeta(); } private static final double USE_LOG_X_CUTOFF = -5.; private static final int N_NEWTON_FREE = 4; // TODO: find out why this??? Is swap_01 R logical?? private static final int MLOGICAL_NA = -1; @Override public double evaluate(double alpha, double p, double q, boolean lowerTail, boolean logP) { if (Double.isNaN(p) || Double.isNaN(q) || Double.isNaN(alpha)) { return p + q + alpha; } if (p < 0. || q < 0.) { return RMathError.defaultError(); } // allowing p==0 and q==0 <==> treat as one- or two-point mass double[] qbet = new double[2]; // = { qbeta(), 1 - qbeta() } new QBetaRawMethod().qbeta_raw(alpha, p, q, lowerTail, logP, MLOGICAL_NA, USE_LOG_X_CUTOFF, N_NEWTON_FREE, qbet); return qbet[0]; } /** * Debugging printfs should print exactly the same output as GnuR, this can help with debugging. */ @SuppressWarnings("unused") private static void debugPrintf(String fmt, Object... args) { // System.out.printf(fmt + "\n", args); } private static final double acu_min = 1e-300; private static final double log_eps_c = M_LN2 * (1. - DBL_MANT_DIG); // = log(DBL_EPSILON) = // -36.04..; private static final double fpu = 3e-308; private static final double p_lo = fpu; private static final double p_hi = 1 - 2.22e-16; private static final double const1 = 2.30753; private static final double const2 = 0.27061; private static final double const3 = 0.99229; private static final double const4 = 0.04481; private static final double DBL_very_MIN = DBL_MIN / 4.; private static final double DBL_log_v_MIN = M_LN2 * (DBL_MIN_EXP - 2); private static final double DBL_1__eps = 0x1.fffffffffffffp-1; // = 1 - 2^-53 // The fields and variables are named after local variables from GnuR, we keep the original // names for the ease of debugging // Checkstyle: stop field name check private static final class QBetaRawMethod { private boolean give_log_q; private boolean use_log_x; private boolean add_N_step; private double logbeta; private boolean swap_tail; private double a; private double la; private double pp; private double qq; private double r; private double t; private double tx; private double u_n; private double xinbta; private double u; private boolean warned; private double acu; private double y; private double w; private boolean log_; // or u < log_q_cut below private double p_; private double u0; private double s; private double h; boolean bad_u; boolean bad_init; private double g; private double D; /** * * @param alpha parameter of beta distribution * @param p probability * @param q quantile * @param lower_tail whether to use lower tail of the distribution function * @param log_p is the probability given as log(p) * @param swap_01 {true, NA, false}: if NA, algorithm decides swap_tail * @param log_q_cut if == Inf: return Math.log(qbeta(..)); otherwise, if finite: the bound * for switching to Math.log(x)-scale; see use_log_x * @param n_N number of "unconstrained" Newton steps before switching to constrained * @param qb The result will be saved to this 2 dimensional array = qb[0:1] = { qbeta(), 1 - * qbeta() }. */ @TruffleBoundary private void qbeta_raw(double alpha, double p, double q, boolean lower_tail, boolean log_p, int swap_01, double log_q_cut, int n_N, double[] qb) { give_log_q = (log_q_cut == Double.POSITIVE_INFINITY); use_log_x = give_log_q; add_N_step = true; y = -1.; // Assuming p >= 0, q >= 0 here ... // Deal with boundary cases here: if (alpha == DPQ.rdt0(lower_tail, log_p)) { returnQ0(qb, give_log_q); return; } if (alpha == DPQ.rdt1(lower_tail, log_p)) { returnQ1(qb, give_log_q); return; } // check alpha {*before* transformation which may all accuracy}: if ((log_p && alpha > 0) || (!log_p && (alpha < 0 || alpha > 1))) { // alpha is outside debugPrintf("qbeta(alpha=%g, %g, %g, .., log_p=%d): %s%s\n", alpha, p, q, log_p, "alpha not in ", log_p ? "[-Inf, 0]" : "[0,1]"); // ML_ERR_return_NAN : RMathError.error(MLError.DOMAIN, ""); qb[0] = qb[1] = ML_NAN; return; } // p==0, q==0, p = Inf, q = Inf <==> treat as one- or two-point mass if (p == 0 || q == 0 || !Double.isFinite(p) || !Double.isFinite(q)) { // We know 0 < T(alpha) < 1 : pbeta() is constant and trivial in {0, 1/2, 1} debugPrintf( "qbeta(%g, %g, %g, lower_t=%d, log_p=%d): (p,q)-boundary: trivial\n", alpha, p, q, lower_tail, log_p); if (p == 0 && q == 0) { // point mass 1/2 at each of {0,1} : if (alpha < DPQ.rdhalf(log_p)) { returnQ0(qb, give_log_q); } else if (alpha > DPQ.rdhalf(log_p)) { returnQ1(qb, give_log_q); } else { returnQHalf(qb, give_log_q); } return; } else if (p == 0 || p / q == 0) { // point mass 1 at 0 - "flipped around" returnQ0(qb, give_log_q); } else if (q == 0 || q / p == 0) { // point mass 1 at 0 - "flipped around" returnQ1(qb, give_log_q); } else { // else: p = q = Inf : point mass 1 at 1/2 returnQHalf(qb, give_log_q); } return; } p_ = DPQ.rdtqiv(alpha, lower_tail, log_p); logbeta = lbeta(p, q); boolean swap_choose = (swap_01 == MLOGICAL_NA); swap_tail = swap_choose ? (p_ > 0.5) : swap_01 != 0; if (swap_tail) { /* change tail, swap p <-> q : */ a = DPQ.rdtciv(alpha, lower_tail, log_p); // = 1 - p_ < 1/2 /* la := log(a), but without numerical cancellation: */ la = DPQ.rdtclog(alpha, lower_tail, log_p); pp = q; qq = p; } else { a = p_; la = DPQ.rdtlog(alpha, lower_tail, log_p); pp = p; qq = q; } /* calculate the initial approximation */ /* * Desired accuracy for Newton iterations (below) should depend on (a,p) This is from * Remark .. on AS 109, adapted. However, it's not clear if this is "optimal" for IEEE * double prec. * * acu = fmax2(acu_min, pow(10., -25. - 5./(pp * pp) - 1./(a * a))); * * NEW: 'acu' accuracy NOT for squared adjustment, but simple; ---- i.e., "new acu" = * sqrt(old acu) */ acu = Math.max(acu_min, Math.pow(10., -13. - 2.5 / (pp * pp) - 0.5 / (a * a))); // try to catch "extreme left tail" early u0 = (la + Math.log(pp) + logbeta) / pp; // = log(x_0) r = pp * (1. - qq) / (pp + 1.); t = 0.2; debugPrintf( "qbeta(%g, %g, %g, lower_t=%b, log_p=%b):%s\n" + " swap_tail=%b, la=%g, u0=%g (bnd: %g (%g)) ", alpha, p, q, lower_tail, log_p, (log_p && (p_ == 0. || p_ == 1.)) ? (p_ == 0. ? " p_=0" : " p_=1") : "", swap_tail, la, u0, (t * log_eps_c - Math.log(Math.abs(pp * (1. - qq) * (2. - qq) / (2. * (pp + 2.))))) / 2., t * log_eps_c - Math.log(Math.abs(r))); tx = 0.; if (M_LN2 * DBL_MIN_EXP < u0 && // cannot allow exp(u0) = 0 ==> exp(u1) = exp(u0) = 0 u0 < -0.01 && // (must: u0 < 0, but too close to 0 <==> x = exp(u0) = // 0.99..) // qq <= 2 && // <--- "arbitrary" // u0 < t*log_eps_c - log(fabs(r)) && u0 < (t * log_eps_c - Math.log(Math.abs(pp * (1. - qq) * (2. - qq) / (2. * (pp + 2.))))) / 2.) { // TODO: maybe jump here from below, when initial u "fails" ? // L_tail_u: // MM's one-step correction (cheaper than 1 Newton!) r = r * Math.exp(u0); // = r*x0 if (r > -1.) { u = u0 - RMath.log1p(r) / pp; debugPrintf("u1-u0=%9.3g --> choosing u = u1\n", u - u0); } else { u = u0; debugPrintf("cannot cheaply improve u0\n"); } tx = xinbta = Math.exp(u); use_log_x = true; // or (u < log_q_cut) ?? newton(n_N, log_p, qb); return; } // y := y_\alpha in AS 64 := Hastings(1955) approximation of qnorm(1 - a) : r = Math.sqrt(-2 * la); y = r - (const1 + const2 * r) / (1. + (const3 + const4 * r) * r); if (pp > 1 && qq > 1) { // use Carter(1947), see AS 109, remark '5.' r = (y * y - 3.) / 6.; s = 1. / (pp + pp - 1.); t = 1. / (qq + qq - 1.); h = 2. / (s + t); w = y * Math.sqrt(h + r) / h - (t - s) * (r + 5. / 6. - 2. / (3. * h)); debugPrintf("p,q > 1 => w=%g", w); if (w > 300) { // Math.exp(w+w) is huge or overflows t = w + w + Math.log(qq) - Math.log(pp); // = argument of log1pMath.exp(.) u = // Math.log(xinbta) = - log1p(qq/pp * Math.exp(w+w)) = -Math.log(1 + // Math.exp(t)) (t <= 18) ? -RMath.log1p(Math.exp(t)) : -t - Math.exp(-t); xinbta = Math.exp(u); } else { xinbta = pp / (pp + qq * Math.exp(w + w)); u = // Math.log(xinbta) -RMath.log1p(qq / pp * Math.exp(w + w)); } } else { // use the original AS 64 proposal, Scheffé-Tukey (1944) and Wilson-Hilferty r = qq + qq; /* * A slightly more stable version of t := \chi^2_{alpha} of AS 64 t = 1. / (9. * * qq); t = r * R_pow_di(1. - t + y * Math.sqrt(t), 3); */ t = 1. / (3. * Math.sqrt(qq)); t = r * powDi(1. + t * (-t + y), 3); // = \chi^2_{alpha} of AS 64 s = 4. * pp + r - 2.; // 4p + 2q - 2 = numerator of new t = (...) / chi^2 debugPrintf("min(p,q) <= 1: t=%g", t); if (t == 0 || (t < 0. && s >= t)) { // cannot use chisq approx // x0 = 1 - { (1-a)*q*B(p,q) } ^{1/q} {AS 65} // xinbta = 1. - Math.exp((Math.log(1-a)+ Math.log(qq) + logbeta) / qq); double l1ma; /* * := Math.log(1-a), directly from alpha (as 'la' above): FIXME: * not worth it? log1p(-a) always the same ?? */ if (swap_tail) { l1ma = DPQ.rdtlog(alpha, lower_tail, log_p); } else { l1ma = DPQ.rdtclog(alpha, lower_tail, log_p); } debugPrintf(" t <= 0 : log1p(-a)=%.15g, better l1ma=%.15g\n", RMath.log1p(-a), l1ma); double xx = (l1ma + Math.log(qq) + logbeta) / qq; if (xx <= 0.) { xinbta = -RMath.expm1(xx); u = DPQ.rlog1exp(xx); // = Math.log(xinbta) = Math.log(1 - // Math.exp(...A...)) } else { // xx > 0 ==> 1 - e^xx < 0 .. is nonsense debugPrintf(" xx=%g > 0: xinbta:= 1-e^xx < 0\n", xx); xinbta = 0; u = Double.NEGATIVE_INFINITY; /// FIXME can do better? } } else { t = s / t; debugPrintf(" t > 0 or s < t < 0: new t = %g ( > 1 ?)\n", t); if (t <= 1.) { // cannot use chisq, either u = (la + Math.log(pp) + logbeta) / pp; xinbta = Math.exp(u); } else { // (1+x0)/(1-x0) = t, solved for x0 : xinbta = 1. - 2. / (t + 1.); u = RMath.log1p(-2. / (t + 1.)); } } } // Problem: If initial u is completely wrong, we make a wrong decision here if (swap_choose && ((swap_tail && u >= -Math.exp(log_q_cut)) || // ==> "swap back" (!swap_tail && u >= -Math.exp(4 * log_q_cut) && pp / qq < 1000.))) { // ==> // "swap // now" // (much // less // easily) // "revert swap" -- and use_log_x swap_tail = !swap_tail; debugPrintf(" u = %g (e^u = xinbta = %.16g) ==> ", u, xinbta); if (swap_tail) { a = DPQ.rdtciv(alpha, lower_tail, log_p); // needed ? la = DPQ.rdtclog(alpha, lower_tail, log_p); pp = q; qq = p; } else { a = p_; la = DPQ.rdtlog(alpha, lower_tail, log_p); pp = p; qq = q; } debugPrintf("\"%s\"; la = %g\n", (swap_tail ? "swap now" : "swap back"), la); // we could redo computations above, but this should be stable u = DPQ.rlog1exp(u); xinbta = Math.exp(u); /* * Careful: "swap now" should not fail if 1) the above initial xinbta is * "completely wrong" 2) The correction step can go outside (u_n > 0 ==> e^u > 1 is * illegal) e.g., for qbeta(0.2066, 0.143891, 0.05) */ } if (!use_log_x) { use_log_x = (u < log_q_cut); // (per default) <==> xinbta = e^u < 4.54e-5 } bad_u = !Double.isFinite(u); bad_init = bad_u || xinbta > p_hi; debugPrintf(" -> u = %g, e^u = xinbta = %.16g, (Newton acu=%g%s)\n", u, xinbta, acu, (bad_u ? ", ** bad u **" : (use_log_x ? ", on u = Math.log(x) scale" : ""))); u_n = 1.; tx = xinbta; // keeping "original initial x" (for now) if (bad_u || u < log_q_cut) { /* * e.g. qbeta(0.21, .001, 0.05) try "left border" quickly, * i.e., try at smallest positive number: */ w = Pbeta.pbetaRaw(DBL_very_MIN, pp, qq, true, log_p); if (w > (log_p ? la : a)) { debugPrintf(" quantile is left of smallest positive number; \"convergence\"\n"); if (log_p || Math.abs(w - a) < Math.abs(0 - a)) { // DBL_very_MIN is better than // 0 tx = DBL_very_MIN; u_n = DBL_log_v_MIN; // = Math.log(DBL_very_MIN) } else { tx = 0.; u_n = Double.NEGATIVE_INFINITY; } use_log_x = log_p; add_N_step = false; finalStep(log_p, qb); return; } else { debugPrintf(" pbeta(smallest pos.) = %g <= %g --> continuing\n", w, (log_p ? la : a)); if (u < DBL_log_v_MIN) { u = DBL_log_v_MIN; // = Math.log(DBL_very_MIN) xinbta = DBL_very_MIN; } } } /* Sometimes the approximation is negative (and == 0 is also not "ok") */ if (bad_init && !(use_log_x && tx > 0)) { if (Utils.identityEquals(u, Double.NEGATIVE_INFINITY)) { debugPrintf(" u = -Inf;"); u = M_LN2 * DBL_MIN_EXP; xinbta = DBL_MIN; } else { debugPrintf(" bad_init: u=%g, xinbta=%g;", u, xinbta); xinbta = (xinbta > 1.1) // i.e. "way off" ? 0.5 // otherwise, keep the respective boundary: : ((xinbta < p_lo) ? Math.exp(u) : p_hi); if (bad_u) { u = Math.log(xinbta); } // otherwise: not changing "potentially better" u than the above } debugPrintf(" -> (partly)new u=%g, xinbta=%g\n", u, xinbta); } newton(n_N, log_p, qb); // note: newton calls converged which calls finalStep } private void newton(int n_N, boolean log_p, double[] qb) { /* * -------------------------------------------------------------------- * * Solve for x by a modified Newton-Raphson method, using pbeta_raw() */ r = 1 - pp; t = 1 - qq; double wprev = 0.; double prev = 1.; double adj = 1.; if (use_log_x) { // find Math.log(xinbta) -- work in u := Math.log(x) scale // if (bad_init && tx > 0) { xinbta = tx; }// may have been better for (int i_pb = 0; i_pb < 1000; i_pb++) { // using log_p == true unconditionally here // FIXME: if Math.exp(u) = xinbta underflows to 0, like different formula // pbeta_Math.log(u, *) y = Pbeta.pbetaRaw(xinbta, pp, qq, /* lower_tail = */ true, true); /* * w := Newton step size for L(u) = log F(e^u) =!= 0; u := Math.log(x) = (L(.) - * la) / L'(.); L'(u)= (F'(e^u) * e^u ) / F(e^u) = (L(.) - la)*F(.) / {F'(e^u) * * e^u } = = (L(.) - la) * e^L(.) * e^{-log F'(e^u) - u} = ( y - la) * e^{ y - u * -log F'(e^u)} and -log F'(x)= -log f(x) = + logbeta + (1-p) Math.log(x) + * (1-q) Math.log(1-x) = logbeta + (1-p) u + (1-q) Math.log(1-e^u) */ w = (y == Double.NEGATIVE_INFINITY) // y = -Inf well possible: we are on // log scale! ? 0. : (y - la) * Math.exp(y - u + logbeta + r * u + t * DPQ.rlog1exp(u)); if (!Double.isFinite(w)) { break; } if (i_pb >= n_N && w * wprev <= 0.) { prev = RMath.fmax2(Math.abs(adj), fpu); } debugPrintf("N(i=%2d): u=%g, pb(e^u)=%g, w=%g, %s prev=%g,", i_pb, u, y, w, (w * wprev <= 0.) ? "new" : "old", prev); g = 1; int i_inn; for (i_inn = 0; i_inn < 1000; i_inn++) { adj = g * w; // take full Newton steps at the beginning; only then safe guard: if (i_pb < n_N || Math.abs(adj) < prev) { u_n = u - adj; // u_{n+1} = u_n - g*w if (u_n <= 0.) { // <==> 0 < xinbta := e^u <= 1 if (prev <= acu || Math.abs(w) <= acu) { /* R_ifDEBUG_printf(" -adj=%g, %s <= acu ==> convergence\n", */ /* -adj, (prev <= acu) ? "prev" : "|w|"); */ debugPrintf(" it{in}=%d, -adj=%g, %s <= acu ==> convergence\n", i_inn, -adj, (prev <= acu) ? "prev" : "|w|"); converged(log_p, qb); return; } // if (u_n != Double.NEGATIVE_INFINITY && u_n != 1) break; } } g /= 3; } // (cancellation in (u_n -u) => may differ from adj: D = RMath.fmin2(Math.abs(adj), Math.abs(u_n - u)); /* R_ifDEBUG_printf(" delta(u)=%g\n", u_n - u); */ debugPrintf(" it{in}=%d, delta(u)=%.3g, D/|.|=%.3g\n", i_inn, u_n - u, D / Math.abs(u_n + u)); if (D <= 4e-16 * Math.abs(u_n + u)) { converged(log_p, qb); return; } u = u_n; xinbta = Math.exp(u); wprev = w; } // for(i ) } else { for (int i_pb = 0; i_pb < 1000; i_pb++) { y = Pbeta.pbetaRaw(xinbta, pp, qq, /* lower_tail = */ true, log_p); // delta{y} : d_y = y - (log_p ? la : a); if (!Double.isFinite(y) && !(log_p && y == Double.NEGATIVE_INFINITY)) { // y = // -Inf // is ok if // (log_p) RMathError.error(MLError.DOMAIN, ""); qb[0] = qb[1] = ML_NAN; return; } /* * w := Newton step size (F(.) - a) / F'(.) or, -- log: (lF - la) / (F' / F) = * Math.exp(lF) * (lF - la) / F' */ w = log_p ? (y - la) * Math.exp(y + logbeta + r * Math.log(xinbta) + t * Math.log1p(-xinbta)) : (y - a) * Math.exp(logbeta + r * Math.log(xinbta) + t * Math.log1p(-xinbta)); if (i_pb >= n_N && w * wprev <= 0.) { prev = RMath.fmax2(Math.abs(adj), fpu); } debugPrintf("N(i=%d): x0=%.15g, pb(x0)=%.15g, w=%.15g, %s prev=%g,", i_pb, xinbta, y, w, (w * wprev <= 0.) ? "new" : "old", prev); g = 1; int i_inn; for (i_inn = 0; i_inn < 1000; i_inn++) { adj = g * w; // take full Newton steps at the beginning; only then safe guard: if (i_pb < n_N || Math.abs(adj) < prev) { tx = xinbta - adj; // x_{n+1} = x_n - g*w if (0. <= tx && tx <= 1.) { if (prev <= acu || Math.abs(w) <= acu) { debugPrintf(" it{in}=%d, delta(x)=%g, %s <= acu ==> convergence\n", i_inn, -adj, (prev <= acu) ? "prev" : "|w|"); converged(log_p, qb); return; } if (tx != 0. && tx != 1) { break; } } } g /= 3; } debugPrintf(" it{in}=%d, delta(x)=%g\n", i_inn, tx - xinbta); if (Math.abs(tx - xinbta) <= 4e-16 * (tx + xinbta)) { // "<=" : (.) == 0 converged(log_p, qb); return; } xinbta = tx; if (tx == 0) { // "we have lost" break; } wprev = w; } } /*-- NOT converged: Iteration count --*/ warned = true; RMathError.error(MLError.PRECISION, "qbeta"); converged(log_p, qb); } private void converged(boolean log_p, double[] qb) { log_ = log_p || use_log_x; // only for printing debugPrintf(" %s: Final delta(y) = %g%s\n", warned ? "_NO_ convergence" : "converged", y - (log_ ? la : a), (log_ ? " (log_)" : "")); if ((log_ && y == Double.NEGATIVE_INFINITY) || (!log_ && y == 0)) { // stuck at left, try if smallest positive number is "better" w = Pbeta.pbetaRaw(DBL_very_MIN, pp, qq, true, log_); if (log_ || Math.abs(w - a) <= Math.abs(y - a)) { tx = DBL_very_MIN; u_n = DBL_log_v_MIN; // = Math.log(DBL_very_MIN) } add_N_step = false; // not trying to do better anymore } else if (!warned && (log_ ? Math.abs(y - la) > 3 : Math.abs(y - a) > 1e-4)) { if (!(log_ && y == Double.NEGATIVE_INFINITY && // e.g. qbeta(-1e-10, .2, .03, log=true) cannot get accurate ==> do // NOT // warn Pbeta.pbetaRaw(DBL_1__eps, // = 1 - eps pp, qq, true, true) > la + 2)) { RMathError.warning(Message.QBETA_ACURACY_WARNING, (log_ ? ", log_" : ""), Math.abs(y - (log_ ? la : a))); } } finalStep(log_p, qb); } /** * Represents a block of code that is labelled "L_return" in the original source, should be * followed by a return. */ private void finalStep(boolean log_p, double[] qb) { if (give_log_q) { // ==> use_log_x , too if (!use_log_x) { // (see if claim above is true) RMathError.warning(Message.GENERIC, "qbeta() L_return, u_n=%g; give_log_q=true but use_log_x=false -- please report!", u_n); } double rr = DPQ.rlog1exp(u_n); swapTail(qb, swap_tail, u_n, rr); } else { if (use_log_x) { if (add_N_step) { /* * add one last Newton step on original x scale, e.g., for qbeta(2^-98, * 0.125, 2^-96) */ double tmpXinbta = Math.exp(u_n); y = Pbeta.pbetaRaw(tmpXinbta, pp, qq, /* lower_tail = */ true, log_p); w = log_p ? (y - la) * Math.exp(y + logbeta + r * Math.log(tmpXinbta) + t * RMath.log1p(-tmpXinbta)) : (y - a) * Math.exp(logbeta + r * Math.log(tmpXinbta) + t * RMath.log1p(-tmpXinbta)); tx = tmpXinbta - w; debugPrintf( "Final Newton correction(non-log scale): xinbta=%.16g, y=%g, w=%g. => new tx=%.16g\n", tmpXinbta, y, w, tx); } else { swapTail(qb, swap_tail, Math.exp(u_n), -RMath.expm1(u_n)); return; } } swapTail(qb, swap_tail, tx, 1 - tx); } } private static void swapTail(double[] qb, boolean swap_tail, double val0, double val1) { if (swap_tail) { qb[0] = val1; qb[1] = val0; } else { qb[0] = val0; qb[1] = val1; } } private static void returnQ0(double[] qb, boolean give_log_q) { qb[0] = DPQ.rd0(give_log_q); qb[1] = DPQ.rd1(give_log_q); } private static void returnQ1(double[] qb, boolean give_log_q) { qb[0] = DPQ.rd1(give_log_q); qb[1] = DPQ.rd0(give_log_q); } private static void returnQHalf(double[] qb, boolean give_log_q) { qb[0] = DPQ.rdhalf(give_log_q); qb[1] = DPQ.rdhalf(give_log_q); } } }
gpl-2.0
jrtex/primeTime
pt/src/main/java/pt/HitRemapper.java
694
/* * Created on 22.02.2005 * * $Header: /Users/wova/laufend/cvs/pt/pt/HitRemapper.java,v 1.1 2005/03/01 20:58:44 wova Exp $ */ package pt; import java.util.*; import de.vahrson.pt.OrfHitRemapper; import de.vahrson.pt.PrimerFinder; /** * @author wova * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class HitRemapper { public static void main(String[] args) { try { RuntimeSupport.getInstance(); OrfHitRemapper runner= new OrfHitRemapper(Integer.parseInt(args[0])); runner.run(); } catch (Exception e) { System.err.println(e); e.printStackTrace(System.err); } } }
gpl-2.0
CanadianRepublican/DDNS_Server
src/com/khoja/dao/ValidateDao.java
12152
package com.khoja.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.text.SimpleDateFormat; import com.khoja.classes.DB; import com.khoja.classes.DynUser; import com.khoja.classes.KeyGenerator; public class ValidateDao { public static boolean setEnabled(int userID, DB dbinfo) { boolean result = false; Connection conn = null; PreparedStatement pst = null; int recordUpdated = 0; try { Class.forName(dbinfo.getDriver()).newInstance(); conn = DriverManager .getConnection(dbinfo.getDBURL() + dbinfo.getDBName(), dbinfo.getUsername(), dbinfo.getPassword()); pst = conn .prepareStatement("UPDATE dyn_server_db.dyn_users SET dyn_users.enabled=1, dyn_users.key1=?, dyn_users.key2=?, dyn_users.enable_date=? WHERE dyn_users.id=? AND dyn_users.forgot=0"); pst.setString(1, KeyGenerator.GenerateKey()); pst.setString(2, KeyGenerator.GenerateKey()); pst.setTimestamp(3, new Timestamp(System.currentTimeMillis())); pst.setInt(4, userID); recordUpdated = pst.executeUpdate(); if (recordUpdated > 0) { result = true; } } catch (Exception e) { System.out.println(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } } return result; } public static boolean setNotForgot(int userID, DB dbinfo) { boolean result = false; Connection conn = null; PreparedStatement pst = null; int recordUpdated = 0; try { Class.forName(dbinfo.getDriver()).newInstance(); conn = DriverManager .getConnection(dbinfo.getDBURL() + dbinfo.getDBName(), dbinfo.getUsername(), dbinfo.getPassword()); pst = conn .prepareStatement("UPDATE dyn_server_db.dyn_users SET dyn_users.forgot=0, dyn_users.key1=?, dyn_users.key2=? WHERE dyn_users.id=? AND dyn_users.enabled=1"); pst.setString(1, KeyGenerator.GenerateKey()); pst.setString(2, KeyGenerator.GenerateKey()); pst.setInt(3, userID); recordUpdated = pst.executeUpdate(); if (recordUpdated > 0) { result = true; } } catch (Exception e) { System.out.println(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } } return result; } public static boolean checkForgot(String email, String key1, String key2, DB dbinfo) { boolean result = false; Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; try { Class.forName(dbinfo.getDriver()).newInstance(); conn = DriverManager .getConnection(dbinfo.getDBURL() + dbinfo.getDBName(), dbinfo.getUsername(), dbinfo.getPassword()); pst = conn.prepareStatement("SELECT dyn_users.id, dyn_users.email, dyn_users.user, dyn_users.enabled, dyn_users.create_date, dyn_users.admin, dyn_users.forgot FROM dyn_server_db.dyn_users WHERE dyn_users.email=? AND dyn_users.key1=? AND dyn_users.key2=? AND dyn_users.enabled=1 AND dyn_users.forgot=1 LIMIT 1;"); pst.setString(1, email); pst.setString(2, key1); pst.setString(3, key2); rs = pst.executeQuery(); if (!rs.next()) { result = true; } } catch (Exception e) { System.out.println(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return result; } public static boolean enableUserZone( String username , DB dbinfo) { boolean result = false; Connection conn = null; PreparedStatement pst = null; int updated = 0; try { Class.forName(dbinfo.getDriver()).newInstance(); conn = DriverManager .getConnection(dbinfo.getDBURL() + dbinfo.getDBName(), dbinfo.getUsername(), dbinfo.getPassword()); pst = conn.prepareStatement("insert into dyn_user_roles (user, role_name) values (?, ?);"); pst.setString(1, username); pst.setString(2, "dynusers"); updated = pst.executeUpdate(); if (updated > 0) { result = true; } } catch (Exception e) { System.out.println(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } } return result; } public static boolean checkNotEnabled(String email, String key1, String key2, DB dbinfo) { boolean result = false; Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; try { Class.forName(dbinfo.getDriver()).newInstance(); conn = DriverManager .getConnection(dbinfo.getDBURL() + dbinfo.getDBName(), dbinfo.getUsername(), dbinfo.getPassword()); pst = conn.prepareStatement("SELECT dyn_users.id, dyn_users.email, dyn_users.user, dyn_users.enabled, dyn_users.create_date, dyn_users.admin, dyn_users.forgot FROM dyn_server_db.dyn_users WHERE dyn_users.email=? AND dyn_users.key1=? AND dyn_users.key2=? AND dyn_users.enabled=0 AND dyn_users.forgot=0 LIMIT 1;"); pst.setString(1, email); pst.setString(2, key1); pst.setString(3, key2); rs = pst.executeQuery(); if (!rs.next()) { result = true; } } catch (Exception e) { System.out.println(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return result; } public static DynUser loadUser(String email, String key1, String key2, DB dbinfo) { Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; DynUser output = null; try { Class.forName(dbinfo.getDriver()).newInstance(); conn = DriverManager .getConnection(dbinfo.getDBURL() + dbinfo.getDBName(), dbinfo.getUsername(), dbinfo.getPassword()); pst = conn.prepareStatement("SELECT dyn_users.id, dyn_users.email, dyn_users.user, dyn_users.enabled, dyn_users.create_date, dyn_users.admin, dyn_users.forgot FROM dyn_server_db.dyn_users WHERE dyn_users.email=? AND dyn_users.key1=? AND dyn_users.key2=?;"); pst.setString(1, email); pst.setString(2, key1); pst.setString(3, key2); rs = pst.executeQuery(); while (rs.next()) { System.out.println("User Account Validated - User Email: "+email); int userid = rs.getInt("id"); String uname = rs.getString("user"); boolean admin = rs.getBoolean("admin"); boolean enabled = rs.getBoolean("enabled"); boolean forgot = rs.getBoolean("forgot"); String uemail = rs.getString("email"); String ucreatedate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(rs.getTimestamp("create_date")); output = new DynUser(uemail, userid, admin, uname, enabled, ucreatedate, forgot); } } catch (Exception e) { System.out.println(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return output; } public static boolean validateUser(String email, String key1, String key2, DB dbinfo) { Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; boolean output = false; try { Class.forName(dbinfo.getDriver()).newInstance(); conn = DriverManager .getConnection(dbinfo.getDBURL() + dbinfo.getDBName(), dbinfo.getUsername(), dbinfo.getPassword()); pst = conn.prepareStatement("SELECT dyn_users.id, dyn_users.email, dyn_users.user, dyn_users.enabled, dyn_users.create_date, dyn_users.admin FROM dyn_server_db.dyn_users WHERE dyn_users.email=? AND dyn_users.key1=? AND dyn_users.key2=?;"); pst.setString(1, email); pst.setString(2, key1); pst.setString(3, key2); rs = pst.executeQuery(); while (rs.next()) { System.out.println("User Account Validated - User Email: "+email); output = true; } } catch (Exception e) { System.out.println(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return output; } }
gpl-2.0
tech-team/decider-android
app/src/main/java/org/techteam/decider/rest/processors/PollVoteProcessor.java
3037
package org.techteam.decider.rest.processors; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.content.Context; import android.os.Bundle; import android.util.Log; import com.activeandroid.ActiveAndroid; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.techteam.decider.content.entities.PollItemEntry; import org.techteam.decider.rest.OperationType; import org.techteam.decider.rest.api.InvalidAccessTokenException; import org.techteam.decider.rest.api.PollVoteRequest; import org.techteam.decider.rest.api.ServerErrorException; import org.techteam.decider.rest.api.TokenRefreshFailException; import org.techteam.decider.rest.service_helper.ServiceCallback; import java.io.IOException; public class PollVoteProcessor extends RequestProcessor<PollVoteRequest> { private static final String TAG = PollVoteProcessor.class.getName(); public PollVoteProcessor(Context context, PollVoteRequest request) { super(context, request); } @Override protected String getTag() { return TAG; } @Override public JSONObject executeRequest() throws ServerErrorException, OperationCanceledException, IOException, JSONException, InvalidAccessTokenException, AuthenticatorException { return apiUI.pollVote(getRequest()); } @Override public void postExecute(JSONObject response, Bundle result) throws JSONException { JSONArray data = response.getJSONArray("data"); int requestedItemVotesCount = -1; ActiveAndroid.beginTransaction(); try { for (int i = 0; i < data.length(); ++i) { JSONObject item = data.getJSONObject(i); int pollItemId = item.getInt("poll_item_id"); int votesCount = item.getInt("votes_count"); boolean voted = item.has("voted") ? item.getBoolean("voted") : false; if (pollItemId == getRequest().getPollItemId()) { requestedItemVotesCount = votesCount; if (!voted) { voted = true; } } PollItemEntry entry = PollItemEntry.byPId(pollItemId); entry.votesCount = votesCount; entry.voted = voted; entry.save(); } ActiveAndroid.setTransactionSuccessful(); } finally { ActiveAndroid.endTransaction(); } result.putInt(ServiceCallback.PollVoteExtras.VOTES_COUNT, requestedItemVotesCount); } @Override protected Bundle getInitialBundle() { Bundle data = new Bundle(); data.putInt(ServiceCallback.PollVoteExtras.ENTRY_POSITION, getRequest().getEntryPosition()); data.putInt(ServiceCallback.PollVoteExtras.QUESTION_ID, getRequest().getQuestionId()); data.putInt(ServiceCallback.PollVoteExtras.POLL_ITEM_ID, getRequest().getPollItemId()); return data; } }
gpl-2.0
ohpauleez/soymacchiato
src/langtools/src/share/classes/com/sun/tools/doclets/formats/html/TagletWriterImpl.java
11085
/* * Copyright (c) 2003, 2010, 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.tools.doclets.formats.html; import com.sun.javadoc.*; import com.sun.tools.doclets.internal.toolkit.*; import com.sun.tools.doclets.internal.toolkit.builders.SerializedFormBuilder; import com.sun.tools.doclets.internal.toolkit.taglets.*; import com.sun.tools.doclets.internal.toolkit.util.*; /** * The taglet writer that writes HTML. * * @since 1.5 * @author Jamie Ho * @author Bhavesh Patel (Modified) */ public class TagletWriterImpl extends TagletWriter { private HtmlDocletWriter htmlWriter; public TagletWriterImpl(HtmlDocletWriter htmlWriter, boolean isFirstSentence) { this.htmlWriter = htmlWriter; this.isFirstSentence = isFirstSentence; } /** * {@inheritDoc} */ public TagletOutput getOutputInstance() { return new TagletOutputImpl(""); } /** * {@inheritDoc} */ public TagletOutput getDocRootOutput() { return new TagletOutputImpl(htmlWriter.relativepathNoSlash); } /** * {@inheritDoc} */ public TagletOutput deprecatedTagOutput(Doc doc) { StringBuffer output = new StringBuffer(); Tag[] deprs = doc.tags("deprecated"); if (doc instanceof ClassDoc) { if (Util.isDeprecated((ProgramElementDoc) doc)) { output.append("<span class=\"strong\">" + ConfigurationImpl.getInstance(). getText("doclet.Deprecated") + "</span>&nbsp;"); if (deprs.length > 0) { Tag[] commentTags = deprs[0].inlineTags(); if (commentTags.length > 0) { output.append(commentTagsToOutput(null, doc, deprs[0].inlineTags(), false).toString() ); } } } } else { MemberDoc member = (MemberDoc) doc; if (Util.isDeprecated((ProgramElementDoc) doc)) { output.append("<span class=\"strong\">" + ConfigurationImpl.getInstance(). getText("doclet.Deprecated") + "</span>&nbsp;"); if (deprs.length > 0) { output.append("<i>"); output.append(commentTagsToOutput(null, doc, deprs[0].inlineTags(), false).toString()); output.append("</i>"); } } else { if (Util.isDeprecated(member.containingClass())) { output.append("<span class=\"strong\">" + ConfigurationImpl.getInstance(). getText("doclet.Deprecated") + "</span>&nbsp;"); } } } return new TagletOutputImpl(output.toString()); } /** * {@inheritDoc} */ public MessageRetriever getMsgRetriever() { return htmlWriter.configuration.message; } /** * {@inheritDoc} */ public TagletOutput getParamHeader(String header) { StringBuffer result = new StringBuffer(); result.append("<dt>"); result.append("<span class=\"strong\">" + header + "</span></dt>"); return new TagletOutputImpl(result.toString()); } /** * {@inheritDoc} */ public TagletOutput paramTagOutput(ParamTag paramTag, String paramName) { TagletOutput result = new TagletOutputImpl("<dd><code>" + paramName + "</code>" + " - " + htmlWriter.commentTagsToString(paramTag, null, paramTag.inlineTags(), false) + "</dd>"); return result; } /** * {@inheritDoc} */ public TagletOutput returnTagOutput(Tag returnTag) { TagletOutput result = new TagletOutputImpl(DocletConstants.NL + "<dt>" + "<span class=\"strong\">" + htmlWriter.configuration.getText("doclet.Returns") + "</span>" + "</dt>" + "<dd>" + htmlWriter.commentTagsToString(returnTag, null, returnTag.inlineTags(), false) + "</dd>"); return result; } /** * {@inheritDoc} */ public TagletOutput seeTagOutput(Doc holder, SeeTag[] seeTags) { String result = ""; if (seeTags.length > 0) { result = addSeeHeader(result); for (int i = 0; i < seeTags.length; ++i) { if (i > 0) { result += ", " + DocletConstants.NL; } result += htmlWriter.seeTagToString(seeTags[i]); } } if (holder.isField() && ((FieldDoc)holder).constantValue() != null && htmlWriter instanceof ClassWriterImpl) { //Automatically add link to constant values page for constant fields. result = addSeeHeader(result); result += htmlWriter.getHyperLinkString(htmlWriter.relativePath + ConfigurationImpl.CONSTANTS_FILE_NAME + "#" + ((ClassWriterImpl) htmlWriter).getClassDoc().qualifiedName() + "." + ((FieldDoc) holder).name(), htmlWriter.configuration.getText("doclet.Constants_Summary")); } if (holder.isClass() && ((ClassDoc)holder).isSerializable()) { //Automatically add link to serialized form page for serializable classes. if ((SerializedFormBuilder.serialInclude(holder) && SerializedFormBuilder.serialInclude(((ClassDoc)holder).containingPackage()))) { result = addSeeHeader(result); result += htmlWriter.getHyperLinkString(htmlWriter.relativePath + "serialized-form.html", ((ClassDoc)holder).qualifiedName(), htmlWriter.configuration.getText("doclet.Serialized_Form"), false); } } return result.equals("") ? null : new TagletOutputImpl(result + "</dd>"); } private String addSeeHeader(String result) { if (result != null && result.length() > 0) { return result + ", " + DocletConstants.NL; } else { return "<dt><span class=\"strong\">" + htmlWriter.configuration().getText("doclet.See_Also") + "</span></dt><dd>"; } } /** * {@inheritDoc} */ public TagletOutput simpleTagOutput(Tag[] simpleTags, String header) { String result = "<dt><span class=\"strong\">" + header + "</span></dt>" + DocletConstants.NL + " <dd>"; for (int i = 0; i < simpleTags.length; i++) { if (i > 0) { result += ", "; } result += htmlWriter.commentTagsToString(simpleTags[i], null, simpleTags[i].inlineTags(), false); } result += "</dd>" + DocletConstants.NL; return new TagletOutputImpl(result); } /** * {@inheritDoc} */ public TagletOutput simpleTagOutput(Tag simpleTag, String header) { return new TagletOutputImpl("<dt><span class=\"strong\">" + header + "</span></dt>" + " <dd>" + htmlWriter.commentTagsToString(simpleTag, null, simpleTag.inlineTags(), false) + "</dd>" + DocletConstants.NL); } /** * {@inheritDoc} */ public TagletOutput getThrowsHeader() { return new TagletOutputImpl(DocletConstants.NL + "<dt>" + "<span class=\"strong\">" + htmlWriter.configuration().getText("doclet.Throws") + "</span></dt>"); } /** * {@inheritDoc} */ public TagletOutput throwsTagOutput(ThrowsTag throwsTag) { String result = DocletConstants.NL + "<dd>"; result += throwsTag.exceptionType() == null ? htmlWriter.codeText(throwsTag.exceptionName()) : htmlWriter.codeText( htmlWriter.getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_MEMBER, throwsTag.exceptionType()))); TagletOutput text = new TagletOutputImpl( htmlWriter.commentTagsToString(throwsTag, null, throwsTag.inlineTags(), false)); if (text != null && text.toString().length() > 0) { result += " - " + text; } result += "</dd>"; return new TagletOutputImpl(result); } /** * {@inheritDoc} */ public TagletOutput throwsTagOutput(Type throwsType) { return new TagletOutputImpl(DocletConstants.NL + "<dd>" + htmlWriter.codeText(htmlWriter.getLink( new LinkInfoImpl(LinkInfoImpl.CONTEXT_MEMBER, throwsType))) + "</dd>"); } /** * {@inheritDoc} */ public TagletOutput valueTagOutput(FieldDoc field, String constantVal, boolean includeLink) { return new TagletOutputImpl(includeLink ? htmlWriter.getDocLink(LinkInfoImpl.CONTEXT_VALUE_TAG, field, constantVal, false) : constantVal); } /** * {@inheritDoc} */ public TagletOutput commentTagsToOutput(Tag holderTag, Tag[] tags) { return commentTagsToOutput(holderTag, null, tags, false); } /** * {@inheritDoc} */ public TagletOutput commentTagsToOutput(Doc holderDoc, Tag[] tags) { return commentTagsToOutput(null, holderDoc, tags, false); } /** * {@inheritDoc} */ public TagletOutput commentTagsToOutput(Tag holderTag, Doc holderDoc, Tag[] tags, boolean isFirstSentence) { return new TagletOutputImpl(htmlWriter.commentTagsToString( holderTag, holderDoc, tags, isFirstSentence)); } /** * {@inheritDoc} */ public Configuration configuration() { return htmlWriter.configuration(); } /** * Return an instance of a TagletWriter that knows how to write HTML. * * @return an instance of a TagletWriter that knows how to write HTML. */ public TagletOutput getTagletOutputInstance() { return new TagletOutputImpl(""); } }
gpl-2.0
JonathanGeoffroy/ZorbsCity
ZorbsCity/src/jonathan/geoffroy/zorbscity/model/cityObjects/resources/Wheat.java
523
package jonathan.geoffroy.zorbscity.model.cityObjects.resources; import jonathan.geoffroy.zorbscity.model.helpers.ResourcesList; public class Wheat extends Resource { /** * Auto-generated serial (using eclipse) */ private static final long serialVersionUID = 2724836764771770818L; public Wheat() { super(); } public Wheat(int amount) { super(amount); } @Override public String getName() { return "Wheat"; } @Override public int getResourceNumber() { return ResourcesList.FOOD1_RESOURCE; } }
gpl-2.0
anatolian/field-photographs
excavation/app/src/module/sample/SampleimgListProcessor.java
3105
package module.sample; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import module.all.ImageBean; import module.common.bean.ResponseData; import module.common.bean.SimpleData; import module.common.constants.AppConstants; import module.common.constants.MessageConstants; import module.common.http.HttpOperation; import module.common.http.HttpProcessor; import module.common.http.HttpRequester; import module.common.http.Request; import module.common.http.Response; import module.common.http.Response.RESPONSE_RESULT; import module.common.http.Response.STANDARD; import module.common.http.bean.HttpObject; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class SampleimgListProcessor extends HttpOperation implements HttpProcessor { String ip_address; public SampleimgListProcessor(String ip_address) { // TODO Auto-generated constructor stub this.ip_address=ip_address; } @Override public HttpObject getHttp(Map<Request, String> mapParams) { HttpObject object = new HttpObject(); object.setInfo(HttpRequester.GET_LISTING); object.setUrl(generateUrlWithParams(HttpRequester.GET_LISTING, mapParams,ip_address)); return object; } public enum LIST_SAMPLE_RESPONSE implements Response { file_type,image_path; } @SuppressWarnings("unchecked") @Override public ResponseData parseObject(HttpObject object) { return null; } public enum IMG_SAMPLE_REQUESTER implements Request { mode,listing_type, area_easting, area_northing, context_number,sample_number,sample_photo_type,base_image_path,sample_subpath; @Override public String getParameter() { return this.name(); } } @SuppressWarnings("unchecked") @Override public List<SimpleData> parseList(HttpObject object) { SortedMap<Integer, SimpleData> map = new TreeMap<Integer, SimpleData>(); SimpleData data = new SimpleData(); object = request(object); checkHttpStatus(object, data); if (data.result == RESPONSE_RESULT.failed) { return new LinkedList<SimpleData>(map.values()); } try { JSONObject resObj = new JSONObject(object.getResponseString()); JSONObject resData = resObj.getJSONObject(STANDARD.responseData .name()); Iterator<String> resIter = resData.keys(); while (resIter.hasNext()) { String key = resIter.next(); JSONObject resItem = resData.getJSONObject(key); SimpleData dataObject = parseObject(resItem); map.put(Integer.parseInt(key), dataObject); } resIter = null; resData = null; resObj = null; } catch (Exception e) { e.printStackTrace(); } finally { data = null; object.release(); object = null; } return new LinkedList<SimpleData>(map.values()); } @SuppressWarnings("unchecked") @Override public SimpleData parseObject(JSONObject object) throws JSONException { SimpleData data = new SimpleData(); data.id = get(LIST_SAMPLE_RESPONSE.file_type.name(), object); return data; } }
gpl-2.0
vicklin/stock-AI
app/src/main/java/cn/iyowei/stockai/web/filter/LoggerMDCFilter.java
2114
package cn.iyowei.stockai.web.filter; import org.apache.commons.lang.StringUtils; import org.apache.log4j.MDC; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; import java.util.UUID; /** * 存放在MDC中的数据,log4j可以直接引用并作为日志信息打印出来. * <p/> * <pre> * 示例使用: * log4j.appender.stdout.layout.conversionPattern=%d [%X{loginUserId}/%X{req.remoteAddr}/%X{req.id} - %X{req.requestURI}?%X{req.queryString}] %-5p %c{2} - %m%n * </pre> * * @author badqiu */ public class LoggerMDCFilter extends OncePerRequestFilter implements Filter { protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { try { //示例为一个固定的登陆用户,请直接修改代码 String tokenId = request.getParameter("tokenId"); MDC.put("loginUserId", tokenId == null ? "anonymous" : tokenId); MDC.put("req.requestURI", StringUtils.defaultString(request.getRequestURI())); MDC.put("req.queryString", StringUtils.defaultString(request.getQueryString())); MDC.put("req.requestURIWithQueryString", request.getRequestURI() + (request.getQueryString() == null ? "" : "?" + request.getQueryString())); MDC.put("req.remoteAddr", StringUtils.defaultString(request.getRemoteAddr())); //为每一个请求创建一个ID,方便查找日志时可以根据ID查找出一个http请求所有相关日志 MDC.put("req.id", StringUtils.remove(UUID.randomUUID().toString(), "-")); chain.doFilter(request, response); } finally { clearMDC(); } } private void clearMDC() { Map<?, ?> map = MDC.getContext(); if (map != null) { map.clear(); } } }
gpl-2.0
MatzeB/bytecode2firm
testsuite/CreateObject.java
244
public class CreateObject { public int x; public String toString() { return "=" + x; } public static void main(String[] args) { CreateObject o = new CreateObject(); o.x = 42; System.out.println(o.x); System.out.println(o); } }
gpl-2.0
sungsoo/esper
esper/src/test/java/com/espertech/esper/client/TestConfigurationParser.java
39568
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.client; import com.espertech.esper.client.scopetest.EPAssertionUtil; import com.espertech.esper.client.soda.StreamSelector; import com.espertech.esper.collection.Pair; import com.espertech.esper.type.StringPatternSet; import com.espertech.esper.type.StringPatternSetLike; import com.espertech.esper.type.StringPatternSetRegex; import junit.framework.TestCase; import javax.xml.xpath.XPathConstants; import java.math.RoundingMode; import java.net.URI; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class TestConfigurationParser extends TestCase { private Configuration config; public void setUp() { config = new Configuration(); } public void testConfigureFromStream() throws Exception { URL url = this.getClass().getClassLoader().getResource(TestConfiguration.ESPER_TEST_CONFIG); ConfigurationParser.doConfigure(config, url.openStream(), url.toString()); assertFileConfig(config); } public void testEngineDefaults() { config = new Configuration(); assertTrue(config.getEngineDefaults().getThreading().isInsertIntoDispatchPreserveOrder()); assertEquals(100, config.getEngineDefaults().getThreading().getInsertIntoDispatchTimeout()); assertTrue(config.getEngineDefaults().getThreading().isListenerDispatchPreserveOrder()); assertEquals(1000, config.getEngineDefaults().getThreading().getListenerDispatchTimeout()); assertTrue(config.getEngineDefaults().getThreading().isInternalTimerEnabled()); assertEquals(100, config.getEngineDefaults().getThreading().getInternalTimerMsecResolution()); assertEquals(ConfigurationEngineDefaults.Threading.Locking.SPIN, config.getEngineDefaults().getThreading().getInsertIntoDispatchLocking()); assertEquals(ConfigurationEngineDefaults.Threading.Locking.SPIN, config.getEngineDefaults().getThreading().getListenerDispatchLocking()); assertFalse(config.getEngineDefaults().getThreading().isThreadPoolInbound()); assertFalse(config.getEngineDefaults().getThreading().isThreadPoolOutbound()); assertFalse(config.getEngineDefaults().getThreading().isThreadPoolRouteExec()); assertFalse(config.getEngineDefaults().getThreading().isThreadPoolTimerExec()); assertEquals(2, config.getEngineDefaults().getThreading().getThreadPoolInboundNumThreads()); assertEquals(2, config.getEngineDefaults().getThreading().getThreadPoolOutboundNumThreads()); assertEquals(2, config.getEngineDefaults().getThreading().getThreadPoolRouteExecNumThreads()); assertEquals(2, config.getEngineDefaults().getThreading().getThreadPoolTimerExecNumThreads()); assertEquals(null, config.getEngineDefaults().getThreading().getThreadPoolInboundCapacity()); assertEquals(null, config.getEngineDefaults().getThreading().getThreadPoolOutboundCapacity()); assertEquals(null, config.getEngineDefaults().getThreading().getThreadPoolRouteExecCapacity()); assertEquals(null, config.getEngineDefaults().getThreading().getThreadPoolTimerExecCapacity()); assertFalse(config.getEngineDefaults().getThreading().isEngineFairlock()); assertFalse(config.getEngineDefaults().getMetricsReporting().isJmxEngineMetrics()); assertEquals(Configuration.PropertyResolutionStyle.CASE_SENSITIVE, config.getEngineDefaults().getEventMeta().getClassPropertyResolutionStyle()); assertEquals(ConfigurationEventTypeLegacy.AccessorStyle.JAVABEAN, config.getEngineDefaults().getEventMeta().getDefaultAccessorStyle()); assertEquals(Configuration.EventRepresentation.MAP, config.getEngineDefaults().getEventMeta().getDefaultEventRepresentation()); assertEquals(5, config.getEngineDefaults().getEventMeta().getAnonymousCacheSize()); assertTrue(config.getEngineDefaults().getViewResources().isShareViews()); assertFalse(config.getEngineDefaults().getViewResources().isAllowMultipleExpiryPolicies()); assertFalse(config.getEngineDefaults().getLogging().isEnableExecutionDebug()); assertTrue(config.getEngineDefaults().getLogging().isEnableTimerDebug()); assertFalse(config.getEngineDefaults().getLogging().isEnableQueryPlan()); assertFalse(config.getEngineDefaults().getLogging().isEnableJDBC()); assertNull(config.getEngineDefaults().getLogging().getAuditPattern()); assertEquals(15000, config.getEngineDefaults().getVariables().getMsecVersionRelease()); assertEquals(null, config.getEngineDefaults().getPatterns().getMaxSubexpressions()); assertEquals(true, config.getEngineDefaults().getPatterns().isMaxSubexpressionPreventStart()); assertEquals(ConfigurationEngineDefaults.TimeSourceType.MILLI, config.getEngineDefaults().getTimeSource().getTimeSourceType()); assertFalse(config.getEngineDefaults().getExecution().isPrioritized()); assertFalse(config.getEngineDefaults().getExecution().isDisableLocking()); assertEquals(ConfigurationEngineDefaults.ThreadingProfile.NORMAL, config.getEngineDefaults().getExecution().getThreadingProfile()); assertEquals(StreamSelector.ISTREAM_ONLY, config.getEngineDefaults().getStreamSelection().getDefaultStreamSelector()); assertFalse(config.getEngineDefaults().getLanguage().isSortUsingCollator()); assertFalse(config.getEngineDefaults().getExpression().isIntegerDivision()); assertFalse(config.getEngineDefaults().getExpression().isDivisionByZeroReturnsNull()); assertTrue(config.getEngineDefaults().getExpression().isSelfSubselectPreeval()); assertTrue(config.getEngineDefaults().getExpression().isUdfCache()); assertTrue(config.getEngineDefaults().getExpression().isExtendedAggregation()); assertFalse(config.getEngineDefaults().getExpression().isDuckTyping()); assertNull(config.getEngineDefaults().getExpression().getMathContext()); assertNull(config.getEngineDefaults().getExceptionHandling().getHandlerFactories()); assertNull(config.getEngineDefaults().getConditionHandling().getHandlerFactories()); assertEquals("js", config.getEngineDefaults().getScripts().getDefaultDialect()); ConfigurationEventTypeXMLDOM domType = new ConfigurationEventTypeXMLDOM(); assertFalse(domType.isXPathPropertyExpr()); assertTrue(domType.isXPathResolvePropertiesAbsolute()); assertTrue(domType.isEventSenderValidatesRoot()); assertTrue(domType.isAutoFragment()); } protected static void assertFileConfig(Configuration config) throws Exception { // assert name for class assertEquals(2, config.getEventTypeAutoNamePackages().size()); assertEquals("com.mycompany.eventsone", config.getEventTypeAutoNamePackages().toArray()[0]); assertEquals("com.mycompany.eventstwo", config.getEventTypeAutoNamePackages().toArray()[1]); // assert name for class assertEquals(3, config.getEventTypeNames().size()); assertEquals("com.mycompany.myapp.MySampleEventOne", config.getEventTypeNames().get("MySampleEventOne")); assertEquals("com.mycompany.myapp.MySampleEventTwo", config.getEventTypeNames().get("MySampleEventTwo")); assertEquals("com.mycompany.package.MyLegacyTypeEvent", config.getEventTypeNames().get("MyLegacyTypeEvent")); // assert auto imports assertEquals(8, config.getImports().size()); assertEquals("java.lang.*", config.getImports().get(0)); assertEquals("java.math.*", config.getImports().get(1)); assertEquals("java.text.*", config.getImports().get(2)); assertEquals("java.util.*", config.getImports().get(3)); assertEquals("com.espertech.esper.client.annotation.*", config.getImports().get(4)); assertEquals("com.espertech.esper.dataflow.ops.*", config.getImports().get(5)); assertEquals("com.mycompany.myapp.*", config.getImports().get(6)); assertEquals("com.mycompany.myapp.ClassOne", config.getImports().get(7)); // assert XML DOM - no schema assertEquals(2, config.getEventTypesXMLDOM().size()); ConfigurationEventTypeXMLDOM noSchemaDesc = config.getEventTypesXMLDOM().get("MyNoSchemaXMLEventName"); assertEquals("MyNoSchemaEvent", noSchemaDesc.getRootElementName()); assertEquals("/myevent/element1", noSchemaDesc.getXPathProperties().get("element1").getXpath()); assertEquals(XPathConstants.NUMBER, noSchemaDesc.getXPathProperties().get("element1").getType()); assertEquals(null, noSchemaDesc.getXPathProperties().get("element1").getOptionalCastToType()); assertNull(noSchemaDesc.getXPathFunctionResolver()); assertNull(noSchemaDesc.getXPathVariableResolver()); assertFalse(noSchemaDesc.isXPathPropertyExpr()); // assert XML DOM - with schema ConfigurationEventTypeXMLDOM schemaDesc = config.getEventTypesXMLDOM().get("MySchemaXMLEventName"); assertEquals("MySchemaEvent", schemaDesc.getRootElementName()); assertEquals("MySchemaXMLEvent.xsd", schemaDesc.getSchemaResource()); assertEquals("actual-xsd-text-here", schemaDesc.getSchemaText()); assertEquals("samples:schemas:simpleSchema", schemaDesc.getRootElementNamespace()); assertEquals("default-name-space", schemaDesc.getDefaultNamespace()); assertEquals("/myevent/element2", schemaDesc.getXPathProperties().get("element2").getXpath()); assertEquals(XPathConstants.STRING, schemaDesc.getXPathProperties().get("element2").getType()); assertEquals(Long.class, schemaDesc.getXPathProperties().get("element2").getOptionalCastToType()); assertEquals("/bookstore/book", schemaDesc.getXPathProperties().get("element3").getXpath()); assertEquals(XPathConstants.NODESET, schemaDesc.getXPathProperties().get("element3").getType()); assertEquals(null, schemaDesc.getXPathProperties().get("element3").getOptionalCastToType()); assertEquals("MyOtherXMLNodeEvent", schemaDesc.getXPathProperties().get("element3").getOptionaleventTypeName()); assertEquals(1, schemaDesc.getNamespacePrefixes().size()); assertEquals("samples:schemas:simpleSchema", schemaDesc.getNamespacePrefixes().get("ss")); assertFalse(schemaDesc.isXPathResolvePropertiesAbsolute()); assertEquals("com.mycompany.OptionalFunctionResolver", schemaDesc.getXPathFunctionResolver()); assertEquals("com.mycompany.OptionalVariableResolver", schemaDesc.getXPathVariableResolver()); assertTrue(schemaDesc.isXPathPropertyExpr()); assertFalse(schemaDesc.isEventSenderValidatesRoot()); assertFalse(schemaDesc.isAutoFragment()); assertEquals("startts", schemaDesc.getStartTimestampPropertyName()); assertEquals("endts", schemaDesc.getEndTimestampPropertyName()); // assert mapped events assertEquals(1, config.getEventTypesMapEvents().size()); assertTrue(config.getEventTypesMapEvents().keySet().contains("MyMapEvent")); Map<String, String> expectedProps = new HashMap<String, String>(); expectedProps.put("myInt", "int"); expectedProps.put("myString", "string"); assertEquals(expectedProps, config.getEventTypesMapEvents().get("MyMapEvent")); assertEquals(1, config.getMapTypeConfigurations().size()); Set<String> superTypes = config.getMapTypeConfigurations().get("MyMapEvent").getSuperTypes(); EPAssertionUtil.assertEqualsExactOrder(new Object[]{"MyMapSuperType1", "MyMapSuperType2"}, superTypes.toArray()); assertEquals("startts", config.getMapTypeConfigurations().get("MyMapEvent").getStartTimestampPropertyName()); assertEquals("endts", config.getMapTypeConfigurations().get("MyMapEvent").getEndTimestampPropertyName()); // assert objectarray events assertEquals(1, config.getEventTypesNestableObjectArrayEvents().size()); assertTrue(config.getEventTypesNestableObjectArrayEvents().containsKey("MyObjectArrayEvent")); Map<String, String> expectedPropsObjectArray = new HashMap<String, String>(); expectedPropsObjectArray.put("myInt", "int"); expectedPropsObjectArray.put("myString", "string"); assertEquals(expectedPropsObjectArray, config.getEventTypesNestableObjectArrayEvents().get("MyObjectArrayEvent")); assertEquals(1, config.getObjectArrayTypeConfigurations().size()); Set<String> superTypesOA = config.getObjectArrayTypeConfigurations().get("MyObjectArrayEvent").getSuperTypes(); EPAssertionUtil.assertEqualsExactOrder(new Object[]{"MyObjectArraySuperType1", "MyObjectArraySuperType2"}, superTypesOA.toArray()); assertEquals("startts", config.getObjectArrayTypeConfigurations().get("MyObjectArrayEvent").getStartTimestampPropertyName()); assertEquals("endts", config.getObjectArrayTypeConfigurations().get("MyObjectArrayEvent").getEndTimestampPropertyName()); // assert legacy type declaration assertEquals(1, config.getEventTypesLegacy().size()); ConfigurationEventTypeLegacy legacy = config.getEventTypesLegacy().get("MyLegacyTypeEvent"); assertEquals(ConfigurationEventTypeLegacy.CodeGeneration.ENABLED, legacy.getCodeGeneration()); assertEquals(ConfigurationEventTypeLegacy.AccessorStyle.PUBLIC, legacy.getAccessorStyle()); assertEquals(1, legacy.getFieldProperties().size()); assertEquals("myFieldName", legacy.getFieldProperties().get(0).getAccessorFieldName()); assertEquals("myfieldprop", legacy.getFieldProperties().get(0).getName()); assertEquals(1, legacy.getMethodProperties().size()); assertEquals("myAccessorMethod", legacy.getMethodProperties().get(0).getAccessorMethodName()); assertEquals("mymethodprop", legacy.getMethodProperties().get(0).getName()); assertEquals(Configuration.PropertyResolutionStyle.CASE_INSENSITIVE, legacy.getPropertyResolutionStyle()); assertEquals("com.mycompany.myapp.MySampleEventFactory.createMyLegacyTypeEvent", legacy.getFactoryMethod()); assertEquals("myCopyMethod", legacy.getCopyMethod()); assertEquals("startts", legacy.getStartTimestampPropertyName()); assertEquals("endts", legacy.getEndTimestampPropertyName()); // assert database reference - data source config assertEquals(3, config.getDatabaseReferences().size()); ConfigurationDBRef configDBRef = config.getDatabaseReferences().get("mydb1"); ConfigurationDBRef.DataSourceConnection dsDef = (ConfigurationDBRef.DataSourceConnection) configDBRef.getConnectionFactoryDesc(); assertEquals("java:comp/env/jdbc/mydb", dsDef.getContextLookupName()); assertEquals("{java.naming.provider.url=iiop://localhost:1050, java.naming.factory.initial=com.myclass.CtxFactory}", dsDef.getEnvProperties().toString()); assertEquals(ConfigurationDBRef.ConnectionLifecycleEnum.POOLED, configDBRef.getConnectionLifecycleEnum()); assertNull(configDBRef.getConnectionSettings().getAutoCommit()); assertNull(configDBRef.getConnectionSettings().getCatalog()); assertNull(configDBRef.getConnectionSettings().getReadOnly()); assertNull(configDBRef.getConnectionSettings().getTransactionIsolation()); ConfigurationLRUCache lruCache = (ConfigurationLRUCache) configDBRef.getDataCacheDesc(); assertEquals(10, lruCache.getSize()); assertEquals(ConfigurationDBRef.ColumnChangeCaseEnum.LOWERCASE, configDBRef.getColumnChangeCase()); assertEquals(ConfigurationDBRef.MetadataOriginEnum.SAMPLE, configDBRef.getMetadataRetrievalEnum()); assertEquals(2, configDBRef.getSqlTypesMapping().size()); assertEquals("int", configDBRef.getSqlTypesMapping().get(2)); assertEquals("float", configDBRef.getSqlTypesMapping().get(6)); // assert database reference - driver manager config configDBRef = config.getDatabaseReferences().get("mydb2"); ConfigurationDBRef.DriverManagerConnection dmDef = (ConfigurationDBRef.DriverManagerConnection) configDBRef.getConnectionFactoryDesc(); assertEquals("my.sql.Driver", dmDef.getClassName()); assertEquals("jdbc:mysql://localhost", dmDef.getUrl()); assertEquals("myuser1", dmDef.getOptionalUserName()); assertEquals("mypassword1", dmDef.getOptionalPassword()); assertEquals("{user=myuser2, password=mypassword2, somearg=someargvalue}", dmDef.getOptionalProperties().toString()); assertEquals(ConfigurationDBRef.ConnectionLifecycleEnum.RETAIN, configDBRef.getConnectionLifecycleEnum()); assertEquals((Boolean) false, configDBRef.getConnectionSettings().getAutoCommit()); assertEquals("test", configDBRef.getConnectionSettings().getCatalog()); assertEquals(Boolean.TRUE, configDBRef.getConnectionSettings().getReadOnly()); assertEquals(new Integer(3), configDBRef.getConnectionSettings().getTransactionIsolation()); ConfigurationExpiryTimeCache expCache = (ConfigurationExpiryTimeCache) configDBRef.getDataCacheDesc(); assertEquals(60.5, expCache.getMaxAgeSeconds()); assertEquals(120.1, expCache.getPurgeIntervalSeconds()); assertEquals(ConfigurationCacheReferenceType.HARD, expCache.getCacheReferenceType()); assertEquals(ConfigurationDBRef.ColumnChangeCaseEnum.UPPERCASE, configDBRef.getColumnChangeCase()); assertEquals(ConfigurationDBRef.MetadataOriginEnum.METADATA, configDBRef.getMetadataRetrievalEnum()); assertEquals(1, configDBRef.getSqlTypesMapping().size()); assertEquals("java.lang.String", configDBRef.getSqlTypesMapping().get(99)); // assert database reference - data source factory and DBCP config configDBRef = config.getDatabaseReferences().get("mydb3"); ConfigurationDBRef.DataSourceFactory dsFactory = (ConfigurationDBRef.DataSourceFactory) configDBRef.getConnectionFactoryDesc(); assertEquals("org.apache.commons.dbcp.BasicDataSourceFactory", dsFactory.getFactoryClassname()); assertEquals("jdbc:mysql://localhost/test", dsFactory.getProperties().getProperty("url")); assertEquals("myusername", dsFactory.getProperties().getProperty("username")); assertEquals("mypassword", dsFactory.getProperties().getProperty("password")); assertEquals("com.mysql.jdbc.Driver", dsFactory.getProperties().getProperty("driverClassName")); assertEquals("2", dsFactory.getProperties().getProperty("initialSize")); // assert custom view implementations List<ConfigurationPlugInView> configViews = config.getPlugInViews(); assertEquals(2, configViews.size()); for (int i = 0; i < configViews.size(); i++) { ConfigurationPlugInView entry = configViews.get(i); assertEquals("ext" + i, entry.getNamespace()); assertEquals("myview" + i, entry.getName()); assertEquals("com.mycompany.MyViewFactory" + i, entry.getFactoryClassName()); } // assert custom virtual data window implementations List<ConfigurationPlugInVirtualDataWindow> configVDW = config.getPlugInVirtualDataWindows(); assertEquals(2, configVDW.size()); for (int i = 0; i < configVDW.size(); i++) { ConfigurationPlugInVirtualDataWindow entry = configVDW.get(i); assertEquals("vdw" + i, entry.getNamespace()); assertEquals("myvdw" + i, entry.getName()); assertEquals("com.mycompany.MyVdwFactory" + i, entry.getFactoryClassName()); if (i == 1) { assertEquals("abc", entry.getConfig()); } } // assert adapter loaders parsed List<ConfigurationPluginLoader> plugins = config.getPluginLoaders(); assertEquals(2, plugins.size()); ConfigurationPluginLoader pluginOne = plugins.get(0); assertEquals("Loader1", pluginOne.getLoaderName()); assertEquals("com.espertech.esper.support.plugin.SupportLoaderOne", pluginOne.getClassName()); assertEquals(2, pluginOne.getConfigProperties().size()); assertEquals("val1", pluginOne.getConfigProperties().get("name1")); assertEquals("val2", pluginOne.getConfigProperties().get("name2")); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><sample-initializer><some-any-xml-can-be-here>This section for use by a plugin loader.</some-any-xml-can-be-here></sample-initializer>", pluginOne.getConfigurationXML()); ConfigurationPluginLoader pluginTwo = plugins.get(1); assertEquals("Loader2", pluginTwo.getLoaderName()); assertEquals("com.espertech.esper.support.plugin.SupportLoaderTwo", pluginTwo.getClassName()); assertEquals(0, pluginTwo.getConfigProperties().size()); // assert plug-in aggregation function loaded assertEquals(4, config.getPlugInAggregationFunctions().size()); ConfigurationPlugInAggregationFunction pluginAgg = config.getPlugInAggregationFunctions().get(0); assertEquals("com.mycompany.MyMatrixAggregationMethod0DEPRECATED", pluginAgg.getFunctionClassName()); assertEquals("func1", pluginAgg.getName()); assertEquals(null, pluginAgg.getFactoryClassName()); pluginAgg = config.getPlugInAggregationFunctions().get(1); assertEquals("com.mycompany.MyMatrixAggregationMethod1DEPRECATED", pluginAgg.getFunctionClassName()); assertEquals("func2", pluginAgg.getName()); assertEquals(null, pluginAgg.getFactoryClassName()); pluginAgg = config.getPlugInAggregationFunctions().get(2); assertEquals(null, pluginAgg.getFunctionClassName()); assertEquals("func1a", pluginAgg.getName()); assertEquals("com.mycompany.MyMatrixAggregationMethod0Factory", pluginAgg.getFactoryClassName()); pluginAgg = config.getPlugInAggregationFunctions().get(3); assertEquals(null, pluginAgg.getFunctionClassName()); assertEquals("func2a", pluginAgg.getName()); assertEquals("com.mycompany.MyMatrixAggregationMethod1Factory", pluginAgg.getFactoryClassName()); // assert plug-in aggregation multi-function loaded assertEquals(1, config.getPlugInAggregationMultiFunctions().size()); ConfigurationPlugInAggregationMultiFunction pluginMultiAgg = config.getPlugInAggregationMultiFunctions().get(0); EPAssertionUtil.assertEqualsExactOrder(new String[] {"func1", "func2"}, pluginMultiAgg.getFunctionNames()); assertEquals("com.mycompany.MyAggregationMultiFunctionFactory", pluginMultiAgg.getMultiFunctionFactoryClassName()); assertEquals(1, pluginMultiAgg.getAdditionalConfiguredProperties().size()); assertEquals("value1", pluginMultiAgg.getAdditionalConfiguredProperties().get("prop1")); // assert plug-in singlerow function loaded assertEquals(2, config.getPlugInSingleRowFunctions().size()); ConfigurationPlugInSingleRowFunction pluginSingleRow = config.getPlugInSingleRowFunctions().get(0); assertEquals("com.mycompany.MyMatrixSingleRowMethod0", pluginSingleRow.getFunctionClassName()); assertEquals("method1", pluginSingleRow.getFunctionMethodName()); assertEquals("func3", pluginSingleRow.getName()); assertEquals(ConfigurationPlugInSingleRowFunction.ValueCache.DISABLED, pluginSingleRow.getValueCache()); assertEquals(ConfigurationPlugInSingleRowFunction.FilterOptimizable.ENABLED, pluginSingleRow.getFilterOptimizable()); assertFalse(pluginSingleRow.isRethrowExceptions()); pluginSingleRow = config.getPlugInSingleRowFunctions().get(1); assertEquals("com.mycompany.MyMatrixSingleRowMethod1", pluginSingleRow.getFunctionClassName()); assertEquals("func4", pluginSingleRow.getName()); assertEquals("method2", pluginSingleRow.getFunctionMethodName()); assertEquals(ConfigurationPlugInSingleRowFunction.ValueCache.ENABLED, pluginSingleRow.getValueCache()); assertEquals(ConfigurationPlugInSingleRowFunction.FilterOptimizable.DISABLED, pluginSingleRow.getFilterOptimizable()); assertTrue(pluginSingleRow.isRethrowExceptions()); // assert plug-in guard objects loaded assertEquals(4, config.getPlugInPatternObjects().size()); ConfigurationPlugInPatternObject pluginPattern = config.getPlugInPatternObjects().get(0); assertEquals("com.mycompany.MyGuardFactory0", pluginPattern.getFactoryClassName()); assertEquals("ext0", pluginPattern.getNamespace()); assertEquals("guard1", pluginPattern.getName()); assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.GUARD, pluginPattern.getPatternObjectType()); pluginPattern = config.getPlugInPatternObjects().get(1); assertEquals("com.mycompany.MyGuardFactory1", pluginPattern.getFactoryClassName()); assertEquals("ext1", pluginPattern.getNamespace()); assertEquals("guard2", pluginPattern.getName()); assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.GUARD, pluginPattern.getPatternObjectType()); pluginPattern = config.getPlugInPatternObjects().get(2); assertEquals("com.mycompany.MyObserverFactory0", pluginPattern.getFactoryClassName()); assertEquals("ext0", pluginPattern.getNamespace()); assertEquals("observer1", pluginPattern.getName()); assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.OBSERVER, pluginPattern.getPatternObjectType()); pluginPattern = config.getPlugInPatternObjects().get(3); assertEquals("com.mycompany.MyObserverFactory1", pluginPattern.getFactoryClassName()); assertEquals("ext1", pluginPattern.getNamespace()); assertEquals("observer2", pluginPattern.getName()); assertEquals(ConfigurationPlugInPatternObject.PatternObjectType.OBSERVER, pluginPattern.getPatternObjectType()); // assert engine defaults assertFalse(config.getEngineDefaults().getThreading().isInsertIntoDispatchPreserveOrder()); assertEquals(3000, config.getEngineDefaults().getThreading().getInsertIntoDispatchTimeout()); assertEquals(ConfigurationEngineDefaults.Threading.Locking.SUSPEND, config.getEngineDefaults().getThreading().getInsertIntoDispatchLocking()); assertFalse(config.getEngineDefaults().getThreading().isListenerDispatchPreserveOrder()); assertEquals(2000, config.getEngineDefaults().getThreading().getListenerDispatchTimeout()); assertEquals(ConfigurationEngineDefaults.Threading.Locking.SUSPEND, config.getEngineDefaults().getThreading().getListenerDispatchLocking()); assertTrue(config.getEngineDefaults().getThreading().isThreadPoolInbound()); assertTrue(config.getEngineDefaults().getThreading().isThreadPoolOutbound()); assertTrue(config.getEngineDefaults().getThreading().isThreadPoolRouteExec()); assertTrue(config.getEngineDefaults().getThreading().isThreadPoolTimerExec()); assertEquals(1, config.getEngineDefaults().getThreading().getThreadPoolInboundNumThreads()); assertEquals(2, config.getEngineDefaults().getThreading().getThreadPoolOutboundNumThreads()); assertEquals(3, config.getEngineDefaults().getThreading().getThreadPoolTimerExecNumThreads()); assertEquals(4, config.getEngineDefaults().getThreading().getThreadPoolRouteExecNumThreads()); assertEquals(1000, (int) config.getEngineDefaults().getThreading().getThreadPoolInboundCapacity()); assertEquals(1500, (int) config.getEngineDefaults().getThreading().getThreadPoolOutboundCapacity()); assertEquals(null, config.getEngineDefaults().getThreading().getThreadPoolTimerExecCapacity()); assertEquals(2000, (int) config.getEngineDefaults().getThreading().getThreadPoolRouteExecCapacity()); assertFalse(config.getEngineDefaults().getThreading().isInternalTimerEnabled()); assertEquals(1234567, config.getEngineDefaults().getThreading().getInternalTimerMsecResolution()); assertFalse(config.getEngineDefaults().getViewResources().isShareViews()); assertTrue(config.getEngineDefaults().getViewResources().isAllowMultipleExpiryPolicies()); assertEquals(Configuration.PropertyResolutionStyle.DISTINCT_CASE_INSENSITIVE, config.getEngineDefaults().getEventMeta().getClassPropertyResolutionStyle()); assertEquals(ConfigurationEventTypeLegacy.AccessorStyle.PUBLIC, config.getEngineDefaults().getEventMeta().getDefaultAccessorStyle()); assertEquals(Configuration.EventRepresentation.MAP, config.getEngineDefaults().getEventMeta().getDefaultEventRepresentation()); assertEquals(100, config.getEngineDefaults().getEventMeta().getAnonymousCacheSize()); assertTrue(config.getEngineDefaults().getLogging().isEnableExecutionDebug()); assertFalse(config.getEngineDefaults().getLogging().isEnableTimerDebug()); assertTrue(config.getEngineDefaults().getLogging().isEnableQueryPlan()); assertTrue(config.getEngineDefaults().getLogging().isEnableJDBC()); assertEquals("[%u] %m", config.getEngineDefaults().getLogging().getAuditPattern()); assertEquals(30000, config.getEngineDefaults().getVariables().getMsecVersionRelease()); assertEquals(3L, (long) config.getEngineDefaults().getPatterns().getMaxSubexpressions()); assertEquals(false, config.getEngineDefaults().getPatterns().isMaxSubexpressionPreventStart()); assertEquals(StreamSelector.RSTREAM_ISTREAM_BOTH, config.getEngineDefaults().getStreamSelection().getDefaultStreamSelector()); assertEquals(ConfigurationEngineDefaults.TimeSourceType.NANO, config.getEngineDefaults().getTimeSource().getTimeSourceType()); assertTrue(config.getEngineDefaults().getExecution().isPrioritized()); assertTrue(config.getEngineDefaults().getExecution().isFairlock()); assertTrue(config.getEngineDefaults().getExecution().isDisableLocking()); assertEquals(ConfigurationEngineDefaults.ThreadingProfile.LARGE, config.getEngineDefaults().getExecution().getThreadingProfile()); ConfigurationMetricsReporting metrics = config.getEngineDefaults().getMetricsReporting(); assertTrue(metrics.isEnableMetricsReporting()); assertEquals(4000L, metrics.getEngineInterval()); assertEquals(500L, metrics.getStatementInterval()); assertFalse(metrics.isThreading()); assertEquals(2, metrics.getStatementGroups().size()); assertTrue(metrics.isJmxEngineMetrics()); ConfigurationMetricsReporting.StmtGroupMetrics def = metrics.getStatementGroups().get("MyStmtGroup"); assertEquals(5000, def.getInterval()); assertTrue(def.isDefaultInclude()); assertEquals(50, def.getNumStatements()); assertTrue(def.isReportInactive()); assertEquals(5, def.getPatterns().size()); assertEquals(def.getPatterns().get(0), new Pair<StringPatternSet, Boolean>(new StringPatternSetRegex(".*"), true)); assertEquals(def.getPatterns().get(1), new Pair<StringPatternSet, Boolean>(new StringPatternSetRegex(".*test.*"), false)); assertEquals(def.getPatterns().get(2), new Pair<StringPatternSet, Boolean>(new StringPatternSetLike("%MyMetricsStatement%"), false)); assertEquals(def.getPatterns().get(3), new Pair<StringPatternSet, Boolean>(new StringPatternSetLike("%MyFraudAnalysisStatement%"), true)); assertEquals(def.getPatterns().get(4), new Pair<StringPatternSet, Boolean>(new StringPatternSetLike("%SomerOtherStatement%"), true)); def = metrics.getStatementGroups().get("MyStmtGroupTwo"); assertEquals(200, def.getInterval()); assertFalse(def.isDefaultInclude()); assertEquals(100, def.getNumStatements()); assertFalse(def.isReportInactive()); assertEquals(0, def.getPatterns().size()); assertTrue(config.getEngineDefaults().getLanguage().isSortUsingCollator()); assertTrue(config.getEngineDefaults().getExpression().isIntegerDivision()); assertTrue(config.getEngineDefaults().getExpression().isDivisionByZeroReturnsNull()); assertFalse(config.getEngineDefaults().getExpression().isSelfSubselectPreeval()); assertFalse(config.getEngineDefaults().getExpression().isUdfCache()); assertFalse(config.getEngineDefaults().getExpression().isExtendedAggregation()); assertTrue(config.getEngineDefaults().getExpression().isDuckTyping()); assertEquals(2, config.getEngineDefaults().getExpression().getMathContext().getPrecision()); assertEquals(RoundingMode.CEILING, config.getEngineDefaults().getExpression().getMathContext().getRoundingMode()); assertEquals(2, config.getEngineDefaults().getExceptionHandling().getHandlerFactories().size()); assertEquals("my.company.cep.LoggingExceptionHandlerFactory", config.getEngineDefaults().getExceptionHandling().getHandlerFactories().get(0)); assertEquals("my.company.cep.AlertExceptionHandlerFactory", config.getEngineDefaults().getExceptionHandling().getHandlerFactories().get(1)); assertEquals(2, config.getEngineDefaults().getConditionHandling().getHandlerFactories().size()); assertEquals("my.company.cep.LoggingConditionHandlerFactory", config.getEngineDefaults().getConditionHandling().getHandlerFactories().get(0)); assertEquals("my.company.cep.AlertConditionHandlerFactory", config.getEngineDefaults().getConditionHandling().getHandlerFactories().get(1)); assertEquals("abc", config.getEngineDefaults().getScripts().getDefaultDialect()); // variables assertEquals(3, config.getVariables().size()); ConfigurationVariable variable = config.getVariables().get("var1"); assertEquals(Integer.class.getName(), variable.getType()); assertEquals("1", variable.getInitializationValue()); assertFalse(variable.isConstant()); variable = config.getVariables().get("var2"); assertEquals(String.class.getName(), variable.getType()); assertEquals(null, variable.getInitializationValue()); assertFalse(variable.isConstant()); variable = config.getVariables().get("var3"); assertTrue(variable.isConstant()); // method references assertEquals(2, config.getMethodInvocationReferences().size()); ConfigurationMethodRef methodRef = config.getMethodInvocationReferences().get("abc"); expCache = (ConfigurationExpiryTimeCache) methodRef.getDataCacheDesc(); assertEquals(91.0, expCache.getMaxAgeSeconds()); assertEquals(92.2, expCache.getPurgeIntervalSeconds()); assertEquals(ConfigurationCacheReferenceType.WEAK, expCache.getCacheReferenceType()); methodRef = config.getMethodInvocationReferences().get("def"); lruCache = (ConfigurationLRUCache) methodRef.getDataCacheDesc(); assertEquals(20, lruCache.getSize()); // plug-in event representations assertEquals(2, config.getPlugInEventRepresentation().size()); ConfigurationPlugInEventRepresentation rep = config.getPlugInEventRepresentation().get(new URI("type://format/rep/name")); assertEquals("com.mycompany.MyPlugInEventRepresentation", rep.getEventRepresentationClassName()); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><anyxml>test string event rep init</anyxml>", rep.getInitializer()); rep = config.getPlugInEventRepresentation().get(new URI("type://format/rep/name2")); assertEquals("com.mycompany.MyPlugInEventRepresentation2", rep.getEventRepresentationClassName()); assertEquals(null, rep.getInitializer()); // plug-in event types assertEquals(2, config.getPlugInEventTypes().size()); ConfigurationPlugInEventType type = config.getPlugInEventTypes().get("MyEvent"); assertEquals(2, type.getEventRepresentationResolutionURIs().length); assertEquals("type://format/rep", type.getEventRepresentationResolutionURIs()[0].toString()); assertEquals("type://format/rep2", type.getEventRepresentationResolutionURIs()[1].toString()); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><anyxml>test string event type init</anyxml>", type.getInitializer()); type = config.getPlugInEventTypes().get("MyEvent2"); assertEquals(1, type.getEventRepresentationResolutionURIs().length); assertEquals("type://format/rep2", type.getEventRepresentationResolutionURIs()[0].toString()); assertEquals(null, type.getInitializer()); // plug-in event representation resolution URIs when using a new name in a statement assertEquals(2, config.getPlugInEventTypeResolutionURIs().length); assertEquals("type://format/rep", config.getPlugInEventTypeResolutionURIs()[0].toString()); assertEquals("type://format/rep2", config.getPlugInEventTypeResolutionURIs()[1].toString()); // revision types assertEquals(1, config.getRevisionEventTypes().size()); ConfigurationRevisionEventType configRev = config.getRevisionEventTypes().get("MyRevisionEvent"); assertEquals(1, configRev.getNameBaseEventTypes().size()); assertTrue(configRev.getNameBaseEventTypes().contains("MyBaseEventName")); assertTrue(configRev.getNameDeltaEventTypes().contains("MyDeltaEventNameOne")); assertTrue(configRev.getNameDeltaEventTypes().contains("MyDeltaEventNameTwo")); EPAssertionUtil.assertEqualsAnyOrder(new String[]{"id", "id2"}, configRev.getKeyPropertyNames()); assertEquals(ConfigurationRevisionEventType.PropertyRevision.MERGE_NON_NULL, configRev.getPropertyRevision()); // variance types assertEquals(1, config.getVariantStreams().size()); ConfigurationVariantStream configVStream = config.getVariantStreams().get("MyVariantStream"); assertEquals(2, configVStream.getVariantTypeNames().size()); assertTrue(configVStream.getVariantTypeNames().contains("MyEvenTypetNameOne")); assertTrue(configVStream.getVariantTypeNames().contains("MyEvenTypetNameTwo")); assertEquals(ConfigurationVariantStream.TypeVariance.ANY, configVStream.getTypeVariance()); } }
gpl-2.0
yvesh/maklerpoint-office
src/de/maklerpoint/office/Gui/Configuration/NeuTagDialog.java
14306
/* * Program: MaklerPoint System * Module: Main * Language: Java / Swing * Date: 2010/09/03 13:10 * Web: http://www.maklerpoint.de * Version: 0.6.1 * * Copyright (C) 2010 Yves Hoppe. All Rights Reserved. * See License.txt or http://www.maklerpoint.de/copyright for details. * * This software is distributed WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * above copyright notices for details. */ /* * NeuTag.java * * Created on Jul 19, 2010, 2:53:44 PM */ package de.maklerpoint.office.Gui.Configuration; import de.maklerpoint.office.Tags.InitializeTags; import de.maklerpoint.office.Tags.TagObj; import de.maklerpoint.office.Tags.Tags; import java.awt.Color; import javax.swing.JColorChooser; /** * * @author Yves Hoppe <info at yves-hoppe.de> */ public class NeuTagDialog extends javax.swing.JDialog { private boolean update = false; private TagObj tag = null; private Color bgColor = null; private Color fontColor = null; /** Creates new form NeuTag */ public NeuTagDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); setUpTitle(); } public NeuTagDialog(java.awt.Frame parent, boolean modal, TagObj tag) { super(parent, modal); this.tag = tag; this.update = true; initComponents(); loadTag(); setUpTitle(); } private void setUpTitle() { if (update == false) { this.setTitle("Neue Markierung (Tag)"); } else { this.setTitle("Markierung bearbeiten: " + tag.getName()); } } private void loadTag() { if (update == false) { return; } fontColor = new Color(Integer.valueOf(tag.getFontColor())); bgColor = new Color(Integer.valueOf(tag.getTagColor())); this.fieldTagname.setText(tag.getName()); this.panel_beispiel.setBackground(bgColor); this.label_beispiel.setForeground(fontColor); this.panel_beispiel.revalidate(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); fieldTagname = new javax.swing.JTextField(); btnBgcolor = new javax.swing.JButton(); btnSave = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); btnFontcolor = new javax.swing.JButton(); panel_beispiel = new javax.swing.JPanel(); label_beispiel = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(de.maklerpoint.office.start.CRM.class).getContext().getResourceMap(NeuTagDialog.class); setTitle(resourceMap.getString("tagDialog.title")); // NOI18N setName("tagDialog"); // NOI18N setResizable(false); jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N fieldTagname.setText(resourceMap.getString("fieldTagname.text")); // NOI18N fieldTagname.setName("fieldTagname"); // NOI18N btnBgcolor.setIcon(resourceMap.getIcon("btnBgcolor.icon")); // NOI18N btnBgcolor.setText(resourceMap.getString("btnBgcolor.text")); // NOI18N btnBgcolor.setName("btnBgcolor"); // NOI18N btnBgcolor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBgcolorActionPerformed(evt); } }); btnSave.setMnemonic('S'); btnSave.setText(resourceMap.getString("btnSave.text")); // NOI18N btnSave.setName("btnSave"); // NOI18N btnSave.setPreferredSize(new java.awt.Dimension(90, 27)); btnSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSaveActionPerformed(evt); } }); btnCancel.setMnemonic('A'); btnCancel.setText(resourceMap.getString("btnCancel.text")); // NOI18N btnCancel.setName("btnCancel"); // NOI18N btnCancel.setPreferredSize(new java.awt.Dimension(90, 27)); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); btnFontcolor.setIcon(resourceMap.getIcon("btnFontcolor.icon")); // NOI18N btnFontcolor.setText(resourceMap.getString("btnFontcolor.text")); // NOI18N btnFontcolor.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); btnFontcolor.setName("btnFontcolor"); // NOI18N btnFontcolor.setPreferredSize(new java.awt.Dimension(107, 28)); btnFontcolor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFontcolorActionPerformed(evt); } }); panel_beispiel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); panel_beispiel.setName("panel_beispiel"); // NOI18N label_beispiel.setText(resourceMap.getString("label_beispiel.text")); // NOI18N label_beispiel.setName("label_beispiel"); // NOI18N javax.swing.GroupLayout panel_beispielLayout = new javax.swing.GroupLayout(panel_beispiel); panel_beispiel.setLayout(panel_beispielLayout); panel_beispielLayout.setHorizontalGroup( panel_beispielLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_beispielLayout.createSequentialGroup() .addGap(43, 43, 43) .addComponent(label_beispiel) .addContainerGap(43, Short.MAX_VALUE)) ); panel_beispielLayout.setVerticalGroup( panel_beispielLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label_beispiel, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE) ); jSeparator1.setName("jSeparator1"); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(panel_beispiel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(fieldTagname, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnFontcolor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnBgcolor, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE))) .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(fieldTagname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btnBgcolor)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(btnFontcolor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(panel_beispiel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 7, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnBgcolorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBgcolorActionPerformed Color chColor = null; try { if (update == false) { chColor = JColorChooser.showDialog(this, "Hintergrundfarbe", Color.white); } else { chColor = JColorChooser.showDialog(this, "Hintergrundfarbe", Color.getColor(tag.getTagColor())); } } catch (NullPointerException e) { } if(chColor == null) return; bgColor = chColor; this.panel_beispiel.setBackground(bgColor); this.panel_beispiel.revalidate(); }//GEN-LAST:event_btnBgcolorActionPerformed private void btnFontcolorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFontcolorActionPerformed Color chColor = null; if (update == false) { chColor = JColorChooser.showDialog(null, "Schriftfarbe", Color.black); } else { chColor = JColorChooser.showDialog(null, "Schriftfarbe", new Color(Integer.valueOf(tag.getFontColor()))); } if(chColor == null) { return; } fontColor = chColor; this.label_beispiel.setForeground(fontColor); }//GEN-LAST:event_btnFontcolorActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed this.dispose(); }//GEN-LAST:event_btnCancelActionPerformed private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed String oldname = null; if (update == false) { tag = new TagObj(); } else { oldname = tag.getName(); } tag.setTagColor(bgColor.toString()); tag.setFontColor(fontColor.toString()); tag.setName(this.fieldTagname.getText()); if (!update) { Tags.addTag(tag); } else { Tags.updateTag(tag, oldname); } this.dispose(); }//GEN-LAST:event_btnSaveActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { NeuTagDialog dialog = new NeuTagDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnBgcolor; private javax.swing.JButton btnCancel; private javax.swing.JButton btnFontcolor; private javax.swing.JButton btnSave; private javax.swing.JTextField fieldTagname; private javax.swing.JLabel jLabel1; private javax.swing.JSeparator jSeparator1; private javax.swing.JLabel label_beispiel; private javax.swing.JPanel panel_beispiel; // End of variables declaration//GEN-END:variables }
gpl-2.0
meijmOrg/Repo-test
freelance-component/src/java/com/yh/component/approvalnode/service/impl/ApprovalNodeServiceImpl.java
1445
package com.yh.component.approvalnode.service.impl; import java.util.List; import com.yh.component.approvalnode.bo.ApprovalNodeDetail; import com.yh.component.approvalnode.queryhelper.ApprovalNodeQueryHelper; import com.yh.component.approvalnode.service.ApprovalNodeService; import com.yh.platform.core.exception.ServiceException; /** * @description 审批环节定义service实现类 * @author wangx * @date 2017-05-16 * @version 1.0 */ public class ApprovalNodeServiceImpl implements ApprovalNodeService { /** * 通过事项编码和事项环节编码查询该环节之后的所有审批环节 * @param itemCode * @param itemNodeCode * @return * @throws ServiceException */ public List<ApprovalNodeDetail> getApprovalNodeListByItemCodeAndItemNodeCode( String itemCode, String itemNodeCode) throws ServiceException { return ApprovalNodeQueryHelper.getApprovalNodeListByItemCodeAndItemNodeCode(itemCode, itemNodeCode); } /** * 通过事项编码、事项环节编码和审批环节编码查询该审批环节 * @param itemCode * @param itemNodeCode * @param nodeCode * @return * @throws ServiceException */ public ApprovalNodeDetail getApprovalNodeByItemCodeAndItemNodeCodeAndNodeCode( String itemCode, String itemNodeCode, String nodeCode) throws ServiceException { return ApprovalNodeQueryHelper.getApprovalNodeByItemCodeAndItemNodeCodeAndNodeCode(itemCode, itemNodeCode, nodeCode); } }
gpl-2.0
weSPOT/wespot_badges
OpenBadgesAPI/src/org/be/kuleuven/hci/openbadges/persistanceLayer/OfyService.java
1894
/******************************************************************************* * Copyright (c) 2014 KU Leuven * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * Jose Luis Santos *******************************************************************************/ package org.be.kuleuven.hci.openbadges.persistanceLayer; import java.util.Hashtable; import org.be.kuleuven.hci.openbadges.model.AuthorizedKey; import org.be.kuleuven.hci.openbadges.model.AwardedBadge; import org.be.kuleuven.hci.openbadges.model.Badge; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; public class OfyService { private static OfyService _ofyService; OfyService (){ factory().register(AuthorizedKey.class); factory().register(AwardedBadge.class); factory().register(Badge.class); } public static synchronized OfyService getOfyService() { if (_ofyService == null) { _ofyService = new OfyService(); } return _ofyService; } public static Objectify ofy() { return ObjectifyService.ofy(); } public static ObjectifyFactory factory() { return ObjectifyService.factory(); } }
gpl-2.0
diogoo296/warc-parser
lemurproject/src/main/java/edu/cmu/lemurproject/Main.java
685
package edu.cmu.lemurproject; import java.io.File; import java.io.IOException; import java.util.List; public class Main { public static void main(String[] args) { try { File folder = new File(args[0]); File[] files = folder.listFiles(); for (File file : files) { // System.out.println("Reading file " + file.getCanonicalPath()); WarcHelper.readFile(file.getCanonicalPath()); /* List<WarcDocument> docs = WarcHelper.readFile("/var/scratch/diogomarques/crawler-govbr/sample.warc.gz"); for(WarcDocument doc : docs) { System.out.println(doc); } */ } } catch (IOException e) { System.out.println("Problem reading file!"); } } }
gpl-2.0
graalvm/fastr
com.oracle.truffle.r.test/src/com/oracle/truffle/r/test/builtins/TestBuiltin_expression.java
1738
/* * 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., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (c) 2012-2014, Purdue University * Copyright (c) 2013, 2019, Oracle and/or its affiliates * * All rights reserved. */ package com.oracle.truffle.r.test.builtins; import org.junit.Test; import com.oracle.truffle.r.test.TestBase; // Checkstyle: stop line length check public class TestBuiltin_expression extends TestBase { @Test public void testExpression() { assertEval("{ f <- function(z) {z}; e<-c(expression(f), 7); eval(e) }"); assertEval("{ f <- function(z) {z}; e<-expression(f); e2<-c(e, 7); eval(e2) }"); assertEval("{ x<-expression(1); y<-c(x,2); typeof(y[[2]]) }"); assertEval("{ class(expression(1)) }"); assertEval("{ x<-expression(1); typeof(x[[1]]) }"); assertEval("{ x<-expression(a); typeof(x[[1]]) }"); assertEval("{ x<-expression(1); y<-c(x,2); typeof(y[[1]]) }"); assertEval(Ignored.OutputFormatting, "{ expression(a=1, 2, b=3) }"); assertEval("{ names(expression(a=1, 2, b=3)) }"); } }
gpl-2.0
lamsfoundation/lams
lams_bb_integration/src/org/lamsfoundation/bb/integration/Constants.java
2710
/**************************************************************** * Copyright (C) 2007 LAMS Foundation (http://lamsfoundation.org) * ============================================================= * License Information: http://lamsfoundation.org/licensing/lams/2.0/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2.0 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA * * http://www.gnu.org/licenses/gpl.txt * **************************************************************** */ package org.lamsfoundation.bb.integration; /** * Constants used for blackboard integration * * @author <a href="mailto:lfoxton@melcoe.mq.edu.au">Luke Foxton</a> */ public class Constants { public static final String PARAM_USER_ID = "uid"; public static final String PARAM_SERVER_ID = "sid"; public static final String PARAM_TIMESTAMP = "ts"; public static final String PARAM_HASH = "hash"; // public static final String PARAM_URL = "url"; public static final String PARAM_METHOD = "method"; public static final String PARAM_LESSON_ID = "lsId"; public static final String PARAM_LEARNING_DESIGN_ID = "ldid"; public static final String PARAM_COURSE_ID = "course_id"; public static final String PARAM_FOLDER_ID = "folderId"; public static final String PARAM_IS_USER_DETAILS_REQUIRED = "isUserDetailsRequired"; public static final String SERVLET_LOGIN_REQUEST = "/lams/LoginRequest"; public static final String SERVLET_ACTION_REQUEST = "/LamsActionRequest"; public static final String URLDECODER_CODING = "US-ASCII"; public static final String METHOD_AUTHOR = "author"; public static final String METHOD_MONITOR = "monitor"; public static final String METHOD_LEARNER = "learner"; public static final String GRADEBOOK_LINEITEM_TYPE = "LAMS grades"; public static final int GRADEBOOK_POINTS_POSSIBLE = 100; // XML format constnats public static final String ELEM_FOLDER = "Folder"; public static final String ELEM_LEARNING_DESIGN = "LearningDesign"; public static final String ATTR_NAME = "name"; public static final String ATTR_RESOURCE_ID = "resourceId"; }
gpl-2.0
ulfjack/cqs
Engine/net/cqs/engine/battles/BattleFleetListener.java
202
package net.cqs.engine.battles; import net.cqs.engine.Fleet; public interface BattleFleetListener { void won(Fleet f, long time); void lost(Fleet f, long time); void withdraw(Fleet f, long time); }
gpl-2.0
shakalaca/RecyclerViewSample
app/src/main/java/com/corner23/android/sample/recyclerviewsample/RecyclerViewAdapter.java
2799
package com.corner23.android.sample.recyclerviewsample; import android.graphics.BitmapFactory; import android.support.v7.graphics.Palette; import android.support.v7.graphics.PaletteItem; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; public class RecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> { private static final int ALPHA_VAL = 144; private List<PhotoCard> mPhotoCards; public RecyclerViewAdapter(List<PhotoCard> cards) { this.mPhotoCards = cards; } private int getAlphaColor(int color, int alpha) { return (alpha << 24) | (color & 0x00ffffff); } @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false); return new ViewHolder(v); } @Override public void onBindViewHolder(final ViewHolder viewHolder, int pos) { final PhotoCard card = mPhotoCards.get(pos); viewHolder.imageView.setImageResource(card.getImageId()); viewHolder.textView.setText(card.getTitle()); viewHolder.textView.setTag(card); viewHolder.itemView.setTag(card); Palette.generateAsync(BitmapFactory.decodeResource(viewHolder.itemView.getResources(), card.getImageId()), new Palette.PaletteAsyncListener() { @Override public void onGenerated(Palette palette) { PaletteItem textPalette = palette.getLightMutedColor(); if (textPalette != null) { int color = textPalette.getRgb(); viewHolder.textView.setTextColor(color); } PaletteItem backgroundPalette = palette.getDarkVibrantColor(); if (backgroundPalette != null) { int color = backgroundPalette.getRgb(); viewHolder.decoView.setBackgroundColor(getAlphaColor(color, ALPHA_VAL)); } } } ); } @Override public int getItemCount() { return mPhotoCards.size(); } public void remove(PhotoCard card) { int position = getItemPosition(card); if (position != -1) { mPhotoCards.remove(position); notifyItemRemoved(position); } } public void add(PhotoCard card, int position) { mPhotoCards.add(position, card); notifyItemInserted(position); } public int getItemPosition(PhotoCard card) { return mPhotoCards.indexOf(card); } }
gpl-2.0
graalvm/fastr
com.oracle.truffle.r.launcher/src/com/oracle/truffle/r/launcher/DelegatingConsoleHandler.java
1491
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3 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 3 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 * 3 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.truffle.r.launcher; import java.util.function.Supplier; /** * Represents a console handler that may delegate its operations to the given {@link ConsoleHandler} * . This is used for R embedding where the user may provide custom overrides of some console * functions. */ public abstract class DelegatingConsoleHandler extends ConsoleHandler { public abstract void setDelegate(Supplier<ConsoleHandler> handler); }
gpl-2.0
linpingchuan/misc
java/framework/src/main/java/com/moon/proxy/ProxyManager.java
747
package com.moon.proxy; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; import java.util.List; /** * 代理管理器 * Created by Paul on 2017/2/8. */ public class ProxyManager { public static <T> T createProxy(final Class<?> targetClass, final List<Proxy> proxyList) { return (T) Enhancer.create(targetClass, new MethodInterceptor() { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { return new ProxyChain(targetClass, o, method, methodProxy, objects, proxyList).proxyChain(); } }); } }
gpl-2.0
wintonBy/areca-backup-release-mirror
src/com/myJava/file/delta/bucket/NewBytesBucket.java
2141
package com.myJava.file.delta.bucket; import java.io.IOException; import java.io.InputStream; import com.myJava.file.delta.Constants; import com.myJava.file.delta.tools.IOHelper; import com.myJava.object.ToStringHelper; /** * [NEW_BYTES_SIGNATURE : 8 bytes][SIZE : 4 bytes][DATA : *SIZE* bytes] * <BR> * @author Olivier PETRUCCI * <BR> * */ /* Copyright 2005-2014, Olivier PETRUCCI. This file is part of Areca. Areca 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. Areca 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 Areca; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ public class NewBytesBucket extends AbstractBucket implements Bucket, Constants { private byte[] tmp = new byte[4]; private long length; private long readOffset = 0; public long getLength() { return length; } public void init(InputStream in) throws IOException { IOHelper.readFully(in, tmp); this.readOffset = 0; this.length = IOHelper.get32(tmp, 0); } public long getSignature() { return SIG_NEW; } public long getReadOffset() { return readOffset; } public void setReadOffset(long readOffset) { this.readOffset = readOffset; } public String toString() { StringBuffer sb = ToStringHelper.init(this); ToStringHelper.append("From", from, sb); ToStringHelper.append("To", from + getLength() - 1, sb); ToStringHelper.append("Length", length, sb); ToStringHelper.append("ReadOffset", readOffset, sb); return ToStringHelper.close(sb); } }
gpl-2.0