repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
lxqfirst/mySchool
src/main/java/com/school/www/office/bo/Grade.java
154
package com.school.www.office.bo; public class Grade extends GradeBase{ /** * */ private static final long serialVersionUID = 1L; }
gpl-2.0
cloudvega/vegadrive
src/com/owncloud/android/network/OwnCloudClientUtils.java
14256
/* ownCloud Android client application * Copyright (C) 2012-2013 ownCloud Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.owncloud.android.network; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier; import org.apache.http.conn.ssl.X509HostnameVerifier; import com.owncloud.android.authentication.AccountAuthenticator; import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.authentication.AccountUtils.AccountNotFoundException; import com.owncloud.android.Log_OC; import eu.alefzero.webdav.WebdavClient; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.Bundle; public class OwnCloudClientUtils { final private static String TAG = OwnCloudClientUtils.class.getSimpleName(); /** Default timeout for waiting data from the server */ public static final int DEFAULT_DATA_TIMEOUT = 60000; /** Default timeout for establishing a connection */ public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; /** Connection manager for all the WebdavClients */ private static MultiThreadedHttpConnectionManager mConnManager = null; private static Protocol mDefaultHttpsProtocol = null; private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null; private static X509HostnameVerifier mHostnameVerifier = null; /** * Creates a WebdavClient setup for an ownCloud account * * Do not call this method from the main thread. * * @param account The ownCloud account * @param appContext Android application context * @return A WebdavClient object ready to be used * @throws AuthenticatorException If the authenticator failed to get the authorization token for the account. * @throws OperationCanceledException If the authenticator operation was cancelled while getting the authorization token for the account. * @throws IOException If there was some I/O error while getting the authorization token for the account. * @throws AccountNotFoundException If 'account' is unknown for the AccountManager */ public static WebdavClient createOwnCloudClient (Account account, Context appContext) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException { //Log_OC.d(TAG, "Creating WebdavClient associated to " + account.name); Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account)); AccountManager am = AccountManager.get(appContext); boolean isOauth2 = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null; // TODO avoid calling to getUserData here boolean isSamlSso = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null; WebdavClient client = createOwnCloudClient(uri, appContext, !isSamlSso); if (isOauth2) { String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false); client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token } else if (isSamlSso) { // TODO avoid a call to getUserData here String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, false); client.setSsoSessionCookie(accessToken); } else { String username = account.name.substring(0, account.name.lastIndexOf('@')); //String password = am.getPassword(account); String password = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, false); client.setBasicCredentials(username, password); } return client; } public static WebdavClient createOwnCloudClient (Account account, Context appContext, Activity currentActivity) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException { Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account)); AccountManager am = AccountManager.get(appContext); boolean isOauth2 = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null; // TODO avoid calling to getUserData here boolean isSamlSso = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null; WebdavClient client = createOwnCloudClient(uri, appContext, !isSamlSso); if (isOauth2) { // TODO avoid a call to getUserData here AccountManagerFuture<Bundle> future = am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, null, currentActivity, null, null); Bundle result = future.getResult(); String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN); if (accessToken == null) throw new AuthenticatorException("WTF!"); client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token } else if (isSamlSso) { // TODO avoid a call to getUserData here AccountManagerFuture<Bundle> future = am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, null, currentActivity, null, null); Bundle result = future.getResult(); String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN); if (accessToken == null) throw new AuthenticatorException("WTF!"); client.setSsoSessionCookie(accessToken); } else { String username = account.name.substring(0, account.name.lastIndexOf('@')); //String password = am.getPassword(account); //String password = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, false); AccountManagerFuture<Bundle> future = am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, null, currentActivity, null, null); Bundle result = future.getResult(); String password = result.getString(AccountManager.KEY_AUTHTOKEN); client.setBasicCredentials(username, password); } return client; } /** * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client connections. * * @param uri URL to the ownCloud server * @param context Android context where the WebdavClient is being created. * @return A WebdavClient object ready to be used */ public static WebdavClient createOwnCloudClient(Uri uri, Context context, boolean followRedirects) { try { registerAdvancedSslContext(true, context); } catch (GeneralSecurityException e) { Log_OC.e(TAG, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e); } catch (IOException e) { Log_OC.e(TAG, "The local server truststore could not be read. Default SSL management in the system will be used for HTTPS connections", e); } WebdavClient client = new WebdavClient(getMultiThreadedConnManager()); client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT); client.setBaseUri(uri); client.setFollowRedirects(followRedirects); return client; } /** * Registers or unregisters the proper components for advanced SSL handling. * @throws IOException */ private static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException { Protocol pr = null; try { pr = Protocol.getProtocol("https"); if (pr != null && mDefaultHttpsProtocol == null) { mDefaultHttpsProtocol = pr; } } catch (IllegalStateException e) { // nothing to do here; really } boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory); if (register && !isRegistered) { Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443)); } else if (!register && isRegistered) { if (mDefaultHttpsProtocol != null) { Protocol.registerProtocol("https", mDefaultHttpsProtocol); } } } public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException { if (mAdvancedSslSocketFactory == null) { KeyStore trustStore = getKnownServersStore(context); AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore); TrustManager[] tms = new TrustManager[] { trustMgr }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tms, null); mHostnameVerifier = new BrowserCompatHostnameVerifier(); mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier); } return mAdvancedSslSocketFactory; } private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks"; private static String LOCAL_TRUSTSTORE_PASSWORD = "password"; private static KeyStore mKnownServersStore = null; /** * Returns the local store of reliable server certificates, explicitly accepted by the user. * * Returns a KeyStore instance with empty content if the local store was never created. * * Loads the store from the storage environment if needed. * * @param context Android context where the operation is being performed. * @return KeyStore instance with explicitly-accepted server certificates. * @throws KeyStoreException When the KeyStore instance could not be created. * @throws IOException When an existing local trust store could not be loaded. * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm. * @throws CertificateException When an exception occurred while loading the certificates from the local trust store. */ private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { if (mKnownServersStore == null) { //mKnownServersStore = KeyStore.getInstance("BKS"); mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType()); File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME); Log_OC.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath()); if (localTrustStoreFile.exists()) { InputStream in = new FileInputStream(localTrustStoreFile); try { mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } finally { in.close(); } } else { mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance } } return mKnownServersStore; } public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore knownServers = getKnownServersStore(context); knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert); FileOutputStream fos = null; try { fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE); knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } finally { fos.close(); } } static private MultiThreadedHttpConnectionManager getMultiThreadedConnManager() { if (mConnManager == null) { mConnManager = new MultiThreadedHttpConnectionManager(); mConnManager.getParams().setDefaultMaxConnectionsPerHost(5); mConnManager.getParams().setMaxTotalConnections(5); } return mConnManager; } }
gpl-2.0
shazangroup/Mobograph
TMessagesProj/src/main/java/org/telegram/ui/Components/PickerBottomLayout.java
4787
/* * This is the source code of Telegram for Android v. 2.0.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-2016. */ package org.telegram.ui.Components; import android.content.Context; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.LocaleController; import com.finalsoft.messenger.R; import org.telegram.ui.ActionBar.Theme; public class PickerBottomLayout extends FrameLayout { public LinearLayout doneButton; public TextView cancelButton; public TextView doneButtonTextView; public TextView doneButtonBadgeTextView; private boolean isDarkTheme; public PickerBottomLayout(Context context) { this(context, true); } public PickerBottomLayout(Context context, boolean darkTheme) { super(context); isDarkTheme = darkTheme; setBackgroundColor(isDarkTheme ? 0xff1a1a1a : 0xffffffff); cancelButton = new TextView(context); cancelButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); cancelButton.setTextColor(isDarkTheme ? 0xffffffff : 0xff19a7e8); cancelButton.setGravity(Gravity.CENTER); cancelButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(isDarkTheme ? Theme.ACTION_BAR_PICKER_SELECTOR_COLOR : Theme.ACTION_BAR_AUDIO_SELECTOR_COLOR, false)); cancelButton.setPadding(AndroidUtilities.dp(29), 0, AndroidUtilities.dp(29), 0); cancelButton.setText(LocaleController.getString("Cancel", R.string.Cancel).toUpperCase()); cancelButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); addView(cancelButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); doneButton = new LinearLayout(context); doneButton.setOrientation(LinearLayout.HORIZONTAL); doneButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(isDarkTheme ? Theme.ACTION_BAR_PICKER_SELECTOR_COLOR : Theme.ACTION_BAR_AUDIO_SELECTOR_COLOR, false)); doneButton.setPadding(AndroidUtilities.dp(29), 0, AndroidUtilities.dp(29), 0); addView(doneButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.RIGHT)); doneButtonBadgeTextView = new TextView(context); doneButtonBadgeTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); doneButtonBadgeTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); doneButtonBadgeTextView.setTextColor(0xffffffff); doneButtonBadgeTextView.setGravity(Gravity.CENTER); doneButtonBadgeTextView.setBackgroundResource(isDarkTheme ? R.drawable.photobadge : R.drawable.bluecounter); doneButtonBadgeTextView.setMinWidth(AndroidUtilities.dp(23)); doneButtonBadgeTextView.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), AndroidUtilities.dp(1)); doneButton.addView(doneButtonBadgeTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 23, Gravity.CENTER_VERTICAL, 0, 0, 10, 0)); doneButtonTextView = new TextView(context); doneButtonTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); doneButtonTextView.setTextColor(isDarkTheme ? 0xffffffff : 0xff19a7e8); doneButtonTextView.setGravity(Gravity.CENTER); doneButtonTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8)); doneButtonTextView.setText(LocaleController.getString("Send", R.string.Send).toUpperCase()); doneButtonTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); doneButton.addView(doneButtonTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL)); } public void updateSelectedCount(int count, boolean disable) { if (count == 0) { doneButtonBadgeTextView.setVisibility(View.GONE); if (disable) { doneButtonTextView.setTextColor(0xff999999); doneButton.setEnabled(false); } else { doneButtonTextView.setTextColor(isDarkTheme ? 0xffffffff : 0xff19a7e8); } } else { doneButtonBadgeTextView.setVisibility(View.VISIBLE); doneButtonBadgeTextView.setText(String.format("%d", count)); doneButtonTextView.setTextColor(isDarkTheme ? 0xffffffff : 0xff19a7e8); if (disable) { doneButton.setEnabled(true); } } } }
gpl-2.0
djLead/modelead
src/java/com/djlead/leadmod/blocks/WhishSoil.java
7746
package com.djlead.leadmod.blocks; import com.djlead.leadmod.Reference; import com.djlead.leadmod.sys.LogOut; import com.djlead.leadmod.sys.MyBlocks; import com.djlead.leadmod.sys.MyTab; import com.sun.scenario.effect.Crop; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.EnumPlantType; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.util.ForgeDirection; import java.util.Random; /** * Created by Lead on 5-10-2015. */ public class WhishSoil extends BaseBlock { @SideOnly(Side.CLIENT) private IIcon field_149824_a; @SideOnly(Side.CLIENT) private IIcon field_149823_b; private static final String __OBFID = "CL_00000241"; public WhishSoil(){ super(Material.ground); this.setTickRandomly(true); // this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.9375F, 1.0F); // this.setLightOpacity(255); this.setBlockTextureName("whishsoil"); this.setBlockName("whishsoil"); this.setHardness(1.0F); this.setResistance(2.0F); this.setHarvestLevel("shovel", 1); this.setCreativeTab(MyTab.CreaTab); } /** * Returns a bounding box from the pool of bounding boxes (this means this box can change after the pool has been * cleared to be reused) */ // public AxisAlignedBB getCollisionBoundingBoxFromPool(World p_149668_1_, int p_149668_2_, int p_149668_3_, int p_149668_4_){ // return AxisAlignedBB.getBoundingBox((double)(p_149668_2_ + 0), (double)(p_149668_3_ + 0), (double)(p_149668_4_ + 0), (double)(p_149668_2_ + 1), (double)(p_149668_3_ + 1), (double)(p_149668_4_ + 1)); // } /** * Is this block (a) opaque and (b) a full 1m cube? This determines whether or not to render the shared face of two * adjacent blocks and also whether the player can attach torches, redstone wire, etc to this block. */ public boolean isOpaqueCube() { return false; } /** * If this block doesn't render as an ordinary block it will return False (examples: signs, buttons, stairs, etc) */ public boolean renderAsNormalBlock() { return false; } /** * Gets the block's texture. Args: side, meta */ @SideOnly(Side.CLIENT) public IIcon getIcon(int p_149691_1_, int p_149691_2_){ return p_149691_1_ == 1 ? (p_149691_2_ > 0 ? this.field_149824_a : this.field_149823_b) : Blocks.dirt.getBlockTextureFromSide(p_149691_1_); } /** * Ticks the block if it's been scheduled */ public void updateTick(World world, int posX, int posY, int posZ, Random random) { Block block = world.getBlock(posX, posY, posZ); if(block.getTickRandomly()){ block.updateTick(world, posX, posY + 1, posZ, random); } if (!this.func_149821_m(world, posX, posY, posZ) && !world.canLightningStrikeAt(posX, posY + 1, posZ)){ int l = world.getBlockMetadata(posX, posY, posZ); if (l > 0){ world.setBlockMetadataWithNotify(posX, posY, posZ, l - 1, 2); }else if (!this.func_149822_e(world, posX, posY, posZ)) { // if no water around, change block in dirt // world.setBlock(posX, posY, posZ, Blocks.dirt); } } else{ world.setBlockMetadataWithNotify(posX, posY, posZ, 7, 2); } } /** * Block's chance to react to an entity falling on it. */ // public void onFallenUpon(World p_149746_1_, int p_149746_2_, int p_149746_3_, int p_149746_4_, Entity p_149746_5_, float p_149746_6_){ // if (!p_149746_1_.isRemote && p_149746_1_.rand.nextFloat() < p_149746_6_ - 0.5F) // { // if (!(p_149746_5_ instanceof EntityPlayer) && !p_149746_1_.getGameRules().getGameRuleBooleanValue("mobGriefing")) // { // return; // } // // // p_149746_1_.setBlock(p_149746_2_, p_149746_3_, p_149746_4_, Blocks.dirt); // } // } private boolean func_149822_e(World p_149822_1_, int p_149822_2_, int p_149822_3_, int p_149822_4_){ byte b0 = 0; for (int l = p_149822_2_ - b0; l <= p_149822_2_ + b0; ++l){ for (int i1 = p_149822_4_ - b0; i1 <= p_149822_4_ + b0; ++i1){ Block block = p_149822_1_.getBlock(l, p_149822_3_ + 1, i1); if (block instanceof IPlantable && canSustainPlant(p_149822_1_, p_149822_2_, p_149822_3_, p_149822_4_, ForgeDirection.UP, (IPlantable)block)){ return true; } } } return false; } private boolean func_149821_m(World world, int posX, int posY, int posZ) { for (int l = posX - 4; l <= posX + 4; ++l) { for (int i1 = posY; i1 <= posY + 1; ++i1){ for (int j1 = posZ - 4; j1 <= posZ + 4; ++j1) { if (world.getBlock(l, i1, j1).getMaterial() == Material.water){ return true; } } } } return false; // return true; // always act like water in area } /** * Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed (coordinates passed are * their own) Args: x, y, z, neighbor Block */ public void onNeighborBlockChange(World world, int posX, int posY, int posZ, Block block){ // replace farmland with dirt when a solid block placed on top super.onNeighborBlockChange(world, posX, posY, posZ, block); Material material = world.getBlock(posX, posY + 1, posZ).getMaterial(); if (material.isSolid()){ // world.setBlock(posX, posY, posZ, Blocks.dirt); } } public Item getItemDropped(int p_149650_1_, Random random, int p_149650_3_){ return MyBlocks.whishSoil.getItemDropped(0, random, p_149650_3_); } /** * Gets an item for the block being called on. Args: world, x, y, z */ @SideOnly(Side.CLIENT) public Item getItem(World world, int posX, int posY, int posZ) { return Item.getItemFromBlock(MyBlocks.whishSoil); } @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister icon) { this.field_149824_a = icon.registerIcon(Reference.MODID + ":" + this.getTextureName()); this.field_149823_b = icon.registerIcon(Reference.MODID + ":" + this.getTextureName()); // top part } //////////////////////////////////// // Sligthly more fertile than dirt, like tilled dirt near water @Override public boolean isFertile(World world, int posX, int posY, int posZ){ return true; } // better soil : all plans grow directly on it, no tilling required @Override public boolean canSustainPlant(IBlockAccess world, int posX, int posY, int posZ, ForgeDirection direction, IPlantable plantable) { Block plant = plantable.getPlant(world, posX, posY + 1, posZ); EnumPlantType plantType = plantable.getPlantType(world, posX, posY + 1, posZ); ///// // switch (plantType) { // case Crop: // return true; // default: // return super.canSustainPlant(world, posX, posY, posZ, direction, plantable); return true; // otherwise seed gets popped out // // } } }
gpl-2.0
hz7k-nzw/lapin
src/lapin/lang/Nil.java
1219
/** * Copyright (C) 2009 Kenji Nozawa * This file is part of LAPIN. * * 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 lapin.lang; /** * Symbol that denotes both "false" and "empty list". */ public final class Nil extends Symbol implements lapin.lang.List { Nil() { super(Package.LISP, "NIL", true); } public Object car() { return this; } public Object cdr() { return this; } public boolean isEnd() { return true; } public int length() { return 0; } }
gpl-2.0
fiji/SPIM_Registration
src/main/java/mpicbg/spim/fusion/MappingFusionParalellMaxWeight.java
16106
/*- * #%L * Fiji distribution of ImageJ for the life sciences. * %% * Copyright (C) 2007 - 2021 Fiji developers. * %% * 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% */ package mpicbg.spim.fusion; import java.util.ArrayList; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; import spim.vecmath.Point3d; import spim.vecmath.Point3f; import mpicbg.imglib.cursor.LocalizableByDimCursor; import mpicbg.imglib.cursor.LocalizableCursor; import mpicbg.imglib.image.Image; import mpicbg.imglib.image.ImageFactory; import mpicbg.imglib.interpolation.Interpolator; import mpicbg.imglib.interpolation.linear.LinearInterpolatorFactory; import mpicbg.imglib.multithreading.SimpleMultiThreading; import mpicbg.imglib.outofbounds.OutOfBoundsStrategyValueFactory; import mpicbg.imglib.type.numeric.real.FloatType; import mpicbg.imglib.util.Util; import mpicbg.models.AbstractAffineModel3D; import mpicbg.models.NoninvertibleModelException; import mpicbg.spim.io.IOFunctions; import mpicbg.spim.registration.ViewDataBeads; import mpicbg.spim.registration.ViewStructure; public class MappingFusionParalellMaxWeight extends SPIMImageFusion { final Image<FloatType> fusedImage; public MappingFusionParalellMaxWeight( final ViewStructure viewStructure, final ViewStructure referenceViewStructure, final ArrayList<IsolatedPixelWeightenerFactory<?>> isolatedWeightenerFactories, final ArrayList<CombinedPixelWeightenerFactory<?>> combinedWeightenerFactories ) { super( viewStructure, referenceViewStructure, isolatedWeightenerFactories, combinedWeightenerFactories ); if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN ) IOFunctions.println("(" + new Date(System.currentTimeMillis()) + "): Reserving memory for fused image."); final ImageFactory<FloatType> fusedImageFactory = new ImageFactory<FloatType>( new FloatType(), conf.processImageFactory ); fusedImage = fusedImageFactory.createImage( new int[]{ imgW, imgH, imgD }, "Fused image"); if (fusedImage == null) { if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_ERRORONLY ) IOFunctions.println("MappingFusionParalell.constructor: Cannot create output image: " + conf.processImageFactory.getErrorMessage()); return; } } @Override public void fuseSPIMImages( final int channelIndex ) { if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN ) IOFunctions.println("Loading source images (Channel " + channelIndex + ")."); // // update views so that only the current channel is being fused // final ArrayList<ViewDataBeads> views = new ArrayList<ViewDataBeads>(); for ( final ViewDataBeads view : viewStructure.getViews() ) if ( view.getChannelIndex() == channelIndex ) views.add( view ); final int numViews = views.size(); // clear the previous output image if ( channelIndex > 0 ) for ( final FloatType type : fusedImage ) type.set( 0 ); // load images for ( final ViewDataBeads view : views ) view.getImage( false ); if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN && isolatedWeightenerFactories.size() > 0 ) { String methods = "(" + isolatedWeightenerFactories.get(0).getDescriptiveName(); for ( int i = 1; i < isolatedWeightenerFactories.size(); ++i ) methods += ", " + isolatedWeightenerFactories.get(i).getDescriptiveName(); methods += ")"; IOFunctions.println( "(" + new Date(System.currentTimeMillis()) + "): Init isolated weighteners for all views " + methods ); } // init isolated pixel weighteners final AtomicInteger ai = new AtomicInteger(0); Thread[] threads = SimpleMultiThreading.newThreads(conf.numberOfThreads); final int numThreads = threads.length; // compute them all in paralell ( computation done while opening ) IsolatedPixelWeightener<?>[][] isoWinit = new IsolatedPixelWeightener<?>[ isolatedWeightenerFactories.size() ][ numViews ]; for (int j = 0; j < isoWinit.length; j++) { final int i = j; final IsolatedPixelWeightener<?>[][] isoW = isoWinit; for (int ithread = 0; ithread < threads.length; ++ithread) threads[ithread] = new Thread(new Runnable() { @Override public void run() { final int myNumber = ai.getAndIncrement(); for (int view = 0; view < numViews; view++) if ( view % numThreads == myNumber) { IOFunctions.println( "Computing " + isolatedWeightenerFactories.get( i ).getDescriptiveName() + " for " + views.get( view ) ); isoW[i][view] = isolatedWeightenerFactories.get(i).createInstance( views.get(view) ); } } }); SimpleMultiThreading.startAndJoin( threads ); } // test if the isolated weighteners were successfull... try { boolean successful = true; for ( final IsolatedPixelWeightener[] iso : isoWinit ) for ( final IsolatedPixelWeightener i : iso ) if ( i == null ) successful = false; if ( !successful ) { IOFunctions.println( "Not enough memory for running the content-based fusion, running without it" ); isoWinit = new IsolatedPixelWeightener[ 0 ][ 0 ]; } } catch (final Exception e) { IOFunctions.println( "Not enough memory for running the content-based fusion, running without it" ); isoWinit = new IsolatedPixelWeightener[ 0 ][ 0 ]; } final IsolatedPixelWeightener<?>[][] isoW = isoWinit; if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN ) IOFunctions.println( "(" + new Date(System.currentTimeMillis()) + "): Computing output image (Channel " + channelIndex + ")."); // cache the views, imageSizes and models that we use final boolean useView[] = new boolean[ numViews ]; final AbstractAffineModel3D<?> models[] = new AbstractAffineModel3D[ numViews ]; for ( int i = 0; i < numViews; ++i ) { useView[ i ] = Math.max( views.get( i ).getViewErrorStatistics().getNumConnectedViews(), views.get( i ).getTile().getConnectedTiles().size() ) > 0 || views.get( i ).getViewStructure().getNumViews() == 1; // if a corresponding view that was used for registration is valid, this one is too if ( views.get( i ).getUseForRegistration() == false ) { final int angle = views.get( i ).getAcqusitionAngle(); final int timepoint = views.get( i ).getViewStructure().getTimePoint(); for ( final ViewDataBeads view2 : viewStructure.getViews() ) if ( view2.getAcqusitionAngle() == angle && timepoint == view2.getViewStructure().getTimePoint() && view2.getUseForRegistration() == true ) useView[ i ] = true; } models[ i ] = (AbstractAffineModel3D<?>)views.get( i ).getTile().getModel(); } // we want the image to be not normalized to [0...1] for (int view = 0; view < numViews ; view++) views.get( view ).unnormalizeImage(); final int[][] imageSizes = new int[numViews][]; for ( int i = 0; i < numViews; ++i ) imageSizes[ i ] = views.get( i ).getImageSize(); ai.set( 0 ); threads = SimpleMultiThreading.newThreads( numThreads ); for (int ithread = 0; ithread < threads.length; ++ithread) threads[ithread] = new Thread(new Runnable() { @Override public void run() { try { final int myNumber = ai.getAndIncrement(); // temporary float array final double[] tmp = new double[ 3 ]; // init combined pixel weighteners if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN && combinedWeightenerFactories.size() > 0 ) { String methods = "(" + combinedWeightenerFactories.get(0).getDescriptiveName(); for ( int i = 1; i < combinedWeightenerFactories.size(); ++i ) methods += ", " + combinedWeightenerFactories.get(i).getDescriptiveName(); methods += ")"; if ( myNumber == 0 ) IOFunctions.println("Initialize combined weighteners for all views " + methods ); } final CombinedPixelWeightener<?>[] combW = new CombinedPixelWeightener<?>[combinedWeightenerFactories.size()]; for (int i = 0; i < combW.length; i++) combW[i] = combinedWeightenerFactories.get(i).createInstance( views ); // get iterators for isolated weights final LocalizableByDimCursor<FloatType> isoIterators[][] = new LocalizableByDimCursor[ isoW.length ][ numViews ]; for (int i = 0; i < isoW.length; i++) for (int view = 0; view < isoW[i].length; view++) isoIterators[i][view] = isoW[i][view].getResultIterator(); final Point3d[] tmpCoordinates = new Point3d[ numViews ]; final int[][] loc = new int[ numViews ][ 3 ]; final double[][] locd = new double[ numViews ][ 3 ]; final boolean[] use = new boolean[ numViews ]; for ( int i = 0; i < numViews; ++i ) tmpCoordinates[ i ] = new Point3d(); final LocalizableCursor<FloatType> it = fusedImage.createLocalizableCursor(); // create Interpolated Iterators for the input images (every thread need own ones!) final Interpolator<FloatType>[] imageInterpolators = new Interpolator[ numViews ]; for (int view = 0; view < numViews ; view++) imageInterpolators[ view ] = views.get( view ).getImage( false ).createInterpolator( conf.interpolatorFactorOutput ); // create Interpolators for weights final Interpolator<FloatType>[][] weightInterpolators = new Interpolator[ isoW.length ][ numViews ]; for (int i = 0; i < isoW.length; i++) for (int view = 0; view < numViews ; view++) weightInterpolators[i][ view ] = isoW[i][view].getResultImage().createInterpolator( new LinearInterpolatorFactory<FloatType>( new OutOfBoundsStrategyValueFactory<FloatType>()) ); while (it.hasNext()) { it.fwd(); if (it.getPosition(2) % numThreads == myNumber) { // get the coordinates if cropped final int x = it.getPosition(0) + cropOffsetX; final int y = it.getPosition(1) + cropOffsetY; final int z = it.getPosition(2) + cropOffsetZ; int num = 0; for (int i = 0; i < numViews; ++i) { if ( useView[ i ] ) { tmpCoordinates[ i ].x = x * scale + min.x; tmpCoordinates[ i ].y = y * scale + min.y; tmpCoordinates[ i ].z = z * scale + min.z; mpicbg.spim.mpicbg.Java3d.applyInverseInPlace( models[i], tmpCoordinates[i], tmp ); loc[i][0] = (int)Util.round( tmpCoordinates[i].x ); loc[i][1] = (int)Util.round( tmpCoordinates[i].y ); loc[i][2] = (int)Util.round( tmpCoordinates[i].z ); locd[i][0] = tmpCoordinates[i].x; locd[i][1] = tmpCoordinates[i].y; locd[i][2] = tmpCoordinates[i].z; // do we hit the source image? if ( loc[ i ][ 0 ] >= 0 && loc[ i ][ 1 ] >= 0 && loc[ i ][ 2 ] >= 0 && loc[ i ][ 0 ] < imageSizes[ i ][ 0 ] && loc[ i ][ 1 ] < imageSizes[ i ][ 1 ] && loc[ i ][ 2 ] < imageSizes[ i ][ 2 ] ) { use[i] = true; ++num; } else { use[i] = false; } } } if (num > 0) { // update combined weighteners if (combW.length > 0) for (final CombinedPixelWeightener<?> w : combW) w.updateWeights(locd, use); //float sumWeights = 0; //float value = 0; int maxView = -1; float maxWeight = -1; for (int view = 0; view < numViews; ++view) if (use[view]) { float weight = 1; // multiplicate combined weights if (combW.length > 0) for (final CombinedPixelWeightener<?> w : combW) weight *= w.getWeight(view); tmp[ 0 ] = tmpCoordinates[view].x; tmp[ 1 ] = tmpCoordinates[view].y; tmp[ 2 ] = tmpCoordinates[view].z; for (int i = 0; i < isoW.length; i++) { weightInterpolators[i][view].setPosition( tmp ); weight = weightInterpolators[i][view].getType().get(); } if ( weight > maxWeight ) { maxWeight = weight; maxView = view; } /* tmp[ 0 ] = tmpCoordinates[view].x; tmp[ 1 ] = tmpCoordinates[view].y; tmp[ 2 ] = tmpCoordinates[view].z; interpolators[view].moveTo( tmp ); value += weight * interpolators[view].getType().get(); sumWeights += weight; */ } if ( maxView != -1 ) { /* // set label it.getType().set( views.get( maxView ).getAcqusitionAngle() + 10 ); */ // set intensity of the maxview tmp[ 0 ] = tmpCoordinates[maxView].x; tmp[ 1 ] = tmpCoordinates[maxView].y; tmp[ 2 ] = tmpCoordinates[maxView].z; imageInterpolators[maxView].setPosition( tmp ); it.getType().set( imageInterpolators[maxView].getType().get() ); } } } // myThread loop } // iterator loop it.close(); for (int i = 0; i < isoW.length; i++) for (int view = 0; view < numViews; view++) weightInterpolators[i][view].close(); for (int view = 0; view < numViews; view++) imageInterpolators[view].close(); // close combined pixel weighteners for (int i = 0; i < combW.length; i++) combW[i].close(); // close isolated iterators for (int i = 0; i < isoW.length; i++) for (int view = 0; view < isoW[i].length; view++) isoIterators[i][view].close(); } catch (final NoninvertibleModelException e) { if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_ERRORONLY ) IOFunctions.println( "MappingFusionParalell(): Model not invertible for " + viewStructure ); } }// Thread.run loop }); SimpleMultiThreading.startAndJoin(threads); if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN ) IOFunctions.println("(" + new Date(System.currentTimeMillis()) + "): Closing all input images (Channel " + channelIndex + ")."); // unload images for ( final ViewDataBeads view : views ) view.closeImage(); // close weighteners // close isolated pixel weighteners try { for (int i = 0; i < isoW.length; i++) for (int view = 0; view < numViews; view++) isoW[i][view].close(); } catch (final Exception e ) { // this will fail if there was not enough memory... } if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN ) IOFunctions.println("(" + new Date(System.currentTimeMillis()) + "): Done computing output image (Channel " + channelIndex + ")."); } @Override public Image<FloatType> getFusedImage() { return fusedImage; } }
gpl-2.0
10211509/maketaobao
app/src/main/java/nobugs/team/shopping/mvp/interactor/ProductInteractor.java
689
package nobugs.team.shopping.mvp.interactor; import java.util.List; import nobugs.team.shopping.mvp.model.Product; import nobugs.team.shopping.mvp.model.ProductType; import nobugs.team.shopping.mvp.model.Shop; /** * Created by xiayong on 2015/8/31. */ public interface ProductInteractor { void getProducts(String shopid,Callback callback); void getProductUnit(TypeCallback callback); interface Callback { void onSuccess(List<Product> products); void onNetWorkError(); void onFailure(); } interface TypeCallback{ void onTypeSuccess(List<String> productUnits); void onNetWorkError(); void onFailure(); } }
gpl-2.0
fbarthelery/RoomConnect
android-slack/src/main/java/com/genymobile/android_slack/internal/RtmStartSlackResponse.java
203
package com.genymobile.android_slack.internal; /** * Response to an rtm.start api call. */ public class RtmStartSlackResponse extends SlackResponse { public String url; // all other things }
gpl-2.0
soldierkam/spring-retry
src/main/java/org/github/soldierkam/retry/RetryApply.java
1100
package org.github.soldierkam.retry; import java.lang.reflect.Method; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * * @author soldier */ class RetryApply implements Apply { private final Retry anno; private final Method method; private final ExpressionEvaluator eval; private int c = 0; RetryApply(Retry anno, Method method, final ExpressionEvaluator outer) { Assert.notNull(anno); Assert.notNull(method); Assert.notNull(outer); this.eval = outer; this.anno = anno; this.method = method; } @Override public boolean matching(Object[] args, Object result, Exception exception) { if (!anno.on().isInstance(exception)) { return false; } if (StringUtils.isEmpty(anno.condition())) { return true; } else { return eval.condition(anno.condition(), method, args, result, exception); } } @Override public boolean canTryAgain() { c++; return c < anno.attempts(); } }
gpl-2.0
charlyz/graphic-engine
src/representation/TexCoord2f.java
964
package representation; import java.io.Serializable; public class TexCoord2f extends Tuple2f implements Serializable { /** * Constructs and initializes a TexCoord2f to (0,0). */ public TexCoord2f() { } /** * Constructs and initializes a TexCoord2f from the specified xy coordinates. * @param x * @param y */ public TexCoord2f(float x, float y) { super(x, y); } /** * Constructs and initializes a TexCoord2f from the specified array. * @param t */ public TexCoord2f(float t[]) { super(t); } /** * Constructs and initializes a TexCoord2f from the specified TexCoord2f. * @param t */ public TexCoord2f(TexCoord2f t) { super(t); } /** * Constructs and initializes a TexCoord2f from the specified Tuple2f. * @param t */ public TexCoord2f(Tuple2f t) { super(t); } }
gpl-2.0
MatrixPeckham/Ray-Tracer-Ground-Up-Java
RayTracer-BookBuild/src/com/matrixpeckham/raytracer/build/figures/ch28/BuildFigure47.java
5632
/* * Copyright (C) 2016 William Matrix Peckham * * 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.matrixpeckham.raytracer.build.figures.ch28; import com.matrixpeckham.raytracer.cameras.Pinhole; import com.matrixpeckham.raytracer.geometricobjects.Instance; import com.matrixpeckham.raytracer.geometricobjects.compound.Compound; import com.matrixpeckham.raytracer.geometricobjects.primitives.Plane; import com.matrixpeckham.raytracer.geometricobjects.primitives.Sphere; import com.matrixpeckham.raytracer.lights.Ambient; import com.matrixpeckham.raytracer.lights.Directional; import com.matrixpeckham.raytracer.materials.Dielectric; import com.matrixpeckham.raytracer.materials.Reflective; import com.matrixpeckham.raytracer.materials.SV_Matte; import com.matrixpeckham.raytracer.textures.procedural.Checker3D; import com.matrixpeckham.raytracer.tracers.Whitted; import com.matrixpeckham.raytracer.util.Normal; import com.matrixpeckham.raytracer.util.Point3D; import com.matrixpeckham.raytracer.util.RGBColor; import com.matrixpeckham.raytracer.util.Utility; import com.matrixpeckham.raytracer.world.BuildWorldFunction; import com.matrixpeckham.raytracer.world.World; /** * * @author William Matrix Peckham */ public class BuildFigure47 implements BuildWorldFunction { @Override public void build(World w) { // Copyright (C) Kevin Suffern 2000-2007. // This C++ code is for non-commercial purposes only. // This C++ code is licensed under the GNU General Public License Version 2. // See the file COPYING.txt for the full license. // This renders the scene for Figure 28.47 int numSamples = 25; w.vp.setHres(600); w.vp.setVres(600); w.vp.setSamples(numSamples); // w.vp.setMaxDepth(3); // for Figure 28.47(a) // w.vp.setMaxDepth(4); // for Figure 28.47(b) // w.vp.setMaxDepth(6); // for Figure 28.47(c) w.vp.setMaxDepth(8); // for Figure 28.47(d) w.backgroundColor = new RGBColor(0.0, 0.13, 0.1); w.tracer = new Whitted(w); Ambient ambientPtr = new Ambient(); ambientPtr.setColor(0.45, 0.5, 0.45); ambientPtr.scaleRadiance(0.25); w.setAmbient(ambientPtr); // zoomed view of reflective sphere rotated 164 degrees Pinhole pinholePtr = new Pinhole(); pinholePtr.setEye(0, 0, 10); pinholePtr.setLookat(0.5, 0.0, 0.0); pinholePtr.setViewDistance(9000.0); pinholePtr.computeUVW(); w.setCamera(pinholePtr); Directional lightPtr1 = new Directional(); lightPtr1.setDirection(10, 10, 10); lightPtr1.scaleRadiance(7.0); lightPtr1.setShadows(false); w.addLight(lightPtr1); Directional lightPtr2 = new Directional(); lightPtr2.setDirection(-1, 0, 0); lightPtr2.scaleRadiance(7.0); lightPtr2.setShadows(false); w.addLight(lightPtr2); // transparent unit sphere at the origin Dielectric dielectricPtr = new Dielectric(); dielectricPtr.setIorIn(1.5); // glass dielectricPtr.setIorOut(1.0); // air dielectricPtr.setCfIn(Utility.WHITE); dielectricPtr.setCfOut(Utility.WHITE); Sphere spherePtr1 = new Sphere(); spherePtr1.setMaterial(dielectricPtr); // Utility.RED reflective sphere inside the transparent sphere // the Reflective parameters below are for the reflective sphere in a glass sphere // they are too dark for the diamond sphere because of the etas Reflective reflectivePtr = new Reflective(); reflectivePtr.setKa(0.1); reflectivePtr.setKd(0.7); reflectivePtr.setCd(Utility.RED); reflectivePtr.setKs(0.3); reflectivePtr.setExp(200.0); reflectivePtr.setKr(0.5); reflectivePtr.setCr(Utility.WHITE); double radius = 0.1; double distance = 0.8; // from center of transparent sphere Sphere spherePtr2 = new Sphere(new Point3D(0, 0, distance), radius); spherePtr2.setMaterial(reflectivePtr); // store the spheres in a compound object Compound spheresPtr = new Compound(); spheresPtr.addObject(spherePtr1); spheresPtr.addObject(spherePtr2); // now store compound object in an instance so that we can rotate it Instance rotatedSpheresPtr = new Instance(spheresPtr); rotatedSpheresPtr.rotateY(164.0); w.addObject(rotatedSpheresPtr); // ground plane Checker3D checker3DPtr = new Checker3D(); checker3DPtr.setSize(50.0); checker3DPtr.setColor1(0.5); checker3DPtr.setColor2(1.0); SV_Matte svMattePtr = new SV_Matte(); svMattePtr.setKa(0.25); svMattePtr.setKd(0.5); svMattePtr.setCd(checker3DPtr); Plane planePtr = new Plane(new Point3D(0, -40.5, 0), new Normal(0, 1, 0)); planePtr.setMaterial(svMattePtr); w.addObject(planePtr); } }
gpl-2.0
cortinico/tdp
TDP/src/it/ncorti/tdp/user/rmi/RemoteServer.java
1585
package it.ncorti.tdp.user.rmi; import it.ncorti.tdp.user.GameFacade; import it.ncorti.tdp.user.Log; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; /** * Classe di test che rappresenta il gioco in esecuzione su un server remoto * * @author Nicola Corti * */ public class RemoteServer { /** TAG per le stampe di debug */ private static final String TAG = "<RMI> RemoteServer"; /** Nome del servizio RMI */ public final static String SERVICE_NAME = "StarCastle"; /** * Metodo main * * @param args Parametri di invocazione */ public static void main(String[] args) { if (args.length < 2) { System.err.println("Invalid invocation!"); System.err.println("Usage: java it.ncorti.tdp.user.rmi.RemoteServer"); System.err.println("\t \t \t <hostname> <port>"); System.exit(-1); } String hostname = args[0]; int port = Integer.parseInt(args[1]); // Imposta l'hostname System.setProperty("java.rmi.server.hostname", hostname); Log.e(TAG, "Setted hostname to: " + hostname); try { // Recupera il registro RMI Registry registry; try { registry = LocateRegistry.createRegistry(port); } catch (RemoteException e) { registry = LocateRegistry.getRegistry(port); } Log.e(TAG, "Getted registry on port: " + port); GameFacade game = new GameFacade(false); registry.rebind(SERVICE_NAME, game); Log.e(TAG, "!!!Server ready!!! -> rmi://" + hostname + ":" + port + "/" + SERVICE_NAME); } catch (RemoteException e) { e.printStackTrace(); } } }
gpl-2.0
fidy1995/SE223-Database
Bookstore-SSH/src/dpp/bookstore/dao/UserDaoImp.java
1698
package dpp.bookstore.dao; import java.util.Vector; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import dpp.bookstore.pojo.User; public class UserDaoImp implements UserDao { private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } @Autowired public void setSessionFactory(SessionFactory ses) { sessionFactory = ses; } public Session getCurrentSession() { return sessionFactory.getCurrentSession(); } @Override public void addUser(User user) throws Exception { // TODO Auto-generated method stub if (user != null) { getCurrentSession().save(user); } } @Override public void updateUser(User user) throws Exception { // TODO Auto-generated method stub if (user != null) { getCurrentSession().update(user); } } @Override public void deleteUserByName(String username) throws Exception { // TODO Auto-generated method stub User user = (User) getCurrentSession() .get(dpp.bookstore.pojo.User.class, new String(username)); if (user != null) { getCurrentSession().delete(user); } } @Override public Vector<User> queryAll() throws Exception { // TODO Auto-generated method stub Query user = getCurrentSession().createQuery("from dpp.bookstore.pojo.User"); Vector<User> users = new Vector<User>(user.list()); return users; } @Override public User queryByName(String username) throws Exception { // TODO Auto-generated method stub User user = (User)getCurrentSession() .get(dpp.bookstore.pojo.User.class, new String(username)); return user; } }
gpl-2.0
sourceress-project/archestica
src/games/stendhal/server/maps/ados/market/package-info.java
999
/** * logic for Ados market. */ package games.stendhal.server.maps.ados.market; /* $Id: package-info.java,v 1.1 2010/11/29 22:52:31 nhnb Exp $ */ /*************************************************************************** * (C) Copyright 2003-2010 - Stendhal * *************************************************************************** *************************************************************************** * * * 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. * * * ***************************************************************************/
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/src/share/classes/sun/java2d/pipe/SpanShapeRenderer.java
7502
/* * Copyright 1998-2007 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. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun 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 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 sun.java2d.pipe; import sun.java2d.SunGraphics2D; import sun.java2d.SurfaceData; import java.awt.Rectangle; import java.awt.Shape; import java.awt.BasicStroke; import java.awt.geom.PathIterator; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import sun.awt.SunHints; /** * This class is used to convert raw geometry into a span iterator * object using a simple flattening polygon scan converter. * The iterator can be passed on to special SpanFiller loops to * perform the actual rendering. */ public abstract class SpanShapeRenderer implements ShapeDrawPipe { final static RenderingEngine RenderEngine = RenderingEngine.getInstance(); public static class Composite extends SpanShapeRenderer { CompositePipe comppipe; public Composite(CompositePipe pipe) { comppipe = pipe; } public Object startSequence(SunGraphics2D sg, Shape s, Rectangle devR, int[] bbox) { return comppipe.startSequence(sg, s, devR, bbox); } public void renderBox(Object ctx, int x, int y, int w, int h) { comppipe.renderPathTile(ctx, null, 0, w, x, y, w, h); } public void endSequence(Object ctx) { comppipe.endSequence(ctx); } } public static class Simple extends SpanShapeRenderer implements LoopBasedPipe { public Object startSequence(SunGraphics2D sg, Shape s, Rectangle devR, int[] bbox) { return sg; } public void renderBox(Object ctx, int x, int y, int w, int h) { SunGraphics2D sg2d = (SunGraphics2D) ctx; SurfaceData sd = sg2d.getSurfaceData(); sg2d.loops.fillRectLoop.FillRect(sg2d, sd, x, y, w, h); } public void endSequence(Object ctx) { } } public void draw(SunGraphics2D sg, Shape s) { if (sg.stroke instanceof BasicStroke) { ShapeSpanIterator sr = LoopPipe.getStrokeSpans(sg, s); try { renderSpans(sg, sg.getCompClip(), s, sr); } finally { sr.dispose(); } } else { fill(sg, sg.stroke.createStrokedShape(s)); } } public static final int NON_RECTILINEAR_TRANSFORM_MASK = (AffineTransform.TYPE_GENERAL_TRANSFORM | AffineTransform.TYPE_GENERAL_ROTATION); public void fill(SunGraphics2D sg, Shape s) { if (s instanceof Rectangle2D && (sg.transform.getType() & NON_RECTILINEAR_TRANSFORM_MASK) == 0) { renderRect(sg, (Rectangle2D) s); return; } Region clipRegion = sg.getCompClip(); ShapeSpanIterator sr = LoopPipe.getFillSSI(sg); try { sr.setOutputArea(clipRegion); sr.appendPath(s.getPathIterator(sg.transform)); renderSpans(sg, clipRegion, s, sr); } finally { sr.dispose(); } } public abstract Object startSequence(SunGraphics2D sg, Shape s, Rectangle devR, int[] bbox); public abstract void renderBox(Object ctx, int x, int y, int w, int h); public abstract void endSequence(Object ctx); public void renderRect(SunGraphics2D sg, Rectangle2D r) { double corners[] = { r.getX(), r.getY(), r.getWidth(), r.getHeight(), }; corners[2] += corners[0]; corners[3] += corners[1]; if (corners[2] <= corners[0] || corners[3] <= corners[1]) { return; } sg.transform.transform(corners, 0, corners, 0, 2); if (corners[2] < corners[0]) { double t = corners[2]; corners[2] = corners[0]; corners[0] = t; } if (corners[3] < corners[1]) { double t = corners[3]; corners[3] = corners[1]; corners[1] = t; } int abox[] = { (int) corners[0], (int) corners[1], (int) corners[2], (int) corners[3], }; Rectangle devR = new Rectangle(abox[0], abox[1], abox[2] - abox[0], abox[3] - abox[1]); Region clipRegion = sg.getCompClip(); clipRegion.clipBoxToBounds(abox); if (abox[0] >= abox[2] || abox[1] >= abox[3]) { return; } Object context = startSequence(sg, r, devR, abox); if (clipRegion.isRectangular()) { renderBox(context, abox[0], abox[1], abox[2] - abox[0], abox[3] - abox[1]); } else { SpanIterator sr = clipRegion.getSpanIterator(abox); while (sr.nextSpan(abox)) { renderBox(context, abox[0], abox[1], abox[2] - abox[0], abox[3] - abox[1]); } } endSequence(context); } public void renderSpans(SunGraphics2D sg, Region clipRegion, Shape s, ShapeSpanIterator sr) { Object context = null; int abox[] = new int[4]; try { sr.getPathBox(abox); Rectangle devR = new Rectangle(abox[0], abox[1], abox[2] - abox[0], abox[3] - abox[1]); clipRegion.clipBoxToBounds(abox); if (abox[0] >= abox[2] || abox[1] >= abox[3]) { return; } sr.intersectClipBox(abox[0], abox[1], abox[2], abox[3]); context = startSequence(sg, s, devR, abox); spanClipLoop(context, sr, clipRegion, abox); } finally { if (context != null) { endSequence(context); } } } public void spanClipLoop(Object ctx, SpanIterator sr, Region r, int[] abox) { if (!r.isRectangular()) { sr = r.filter(sr); } while (sr.nextSpan(abox)) { int x = abox[0]; int y = abox[1]; renderBox(ctx, x, y, abox[2] - x, abox[3] - y); } } }
gpl-2.0
whyceewhite/json2thrift
src/main/java/puck/thrifty/MergerException.java
1022
package puck.thrifty; import puck.thrifty.datatype.Element; /** * <p> * Represents an error that occurred during the merger process. * </p> * * @author ywhite * */ public class MergerException extends RuntimeException { private static final long serialVersionUID = 1L; public MergerException() { super(); } public MergerException(String message) { super(message); } /** * <p> * Create an instance of this class to indicate a merge error. The two * parameters represent 1) the element being merged and 2) the element * receiving the merge. * </p> * * @param mergeRecipient The element receiving the merge. Required. * @param mergeDonor The element that is being merged into another * element. Required. */ public MergerException(Element mergeRecipient, Element mergeDonor) { super("The element type of " + mergeDonor.getClass().getName() + " cannot be merged into " + mergeRecipient.getClass().getName()); } }
gpl-2.0
hdadler/sensetrace-src
com.ipv.sensetrace.RDFDatamanager/jena-2.11.0/jena-fuseki/src/main/java/org/apache/jena/fuseki/FusekiCmd.java
18735
/* * 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.jena.fuseki; import static org.apache.jena.fuseki.Fuseki.serverLog ; import java.io.InputStream ; import java.util.List ; import org.apache.jena.atlas.io.IO ; import org.apache.jena.atlas.lib.FileOps ; import org.apache.jena.atlas.lib.StrUtils ; import org.apache.jena.atlas.logging.Log ; import org.apache.jena.fuseki.mgt.ManagementServer ; import org.apache.jena.fuseki.server.FusekiConfig ; import org.apache.jena.fuseki.server.SPARQLServer ; import org.apache.jena.fuseki.server.ServerConfig ; import org.apache.jena.riot.Lang ; import org.apache.jena.riot.RDFDataMgr ; import org.apache.jena.riot.RDFLanguages ; import org.apache.jena.riot.SysRIOT ; import org.eclipse.jetty.server.Server ; import org.slf4j.Logger ; import arq.cmd.CmdException ; import arq.cmdline.ArgDecl ; import arq.cmdline.CmdARQ ; import arq.cmdline.ModDatasetAssembler ; import com.hp.hpl.jena.query.ARQ ; import com.hp.hpl.jena.query.Dataset ; import com.hp.hpl.jena.sparql.core.DatasetGraph ; import com.hp.hpl.jena.sparql.core.DatasetGraphFactory ; import com.hp.hpl.jena.tdb.TDB ; import com.hp.hpl.jena.tdb.TDBFactory ; import com.hp.hpl.jena.tdb.transaction.TransactionManager ; public class FusekiCmd extends CmdARQ { private static String log4Jsetup = StrUtils.strjoinNL( "## Plain output to stdout" , "log4j.appender.jena.plain=org.apache.log4j.ConsoleAppender" , "log4j.appender.jena.plain.target=System.out" , "log4j.appender.jena.plain.layout=org.apache.log4j.PatternLayout" , "log4j.appender.jena.plain.layout.ConversionPattern=%d{HH:mm:ss} %-5p %m%n" , "## Plain output with level, to stderr" , "log4j.appender.jena.plainlevel=org.apache.log4j.ConsoleAppender" , "log4j.appender.jena.plainlevel.target=System.err" , "log4j.appender.jena.plainlevel.layout=org.apache.log4j.PatternLayout" , "log4j.appender.jena.plainlevel.layout.ConversionPattern=%d{HH:mm:ss} %-5p %m%n" , "## Everything" , "log4j.rootLogger=INFO, jena.plain" , "log4j.logger.com.hp.hpl.jena=WARN" , "log4j.logger.org.openjena=WARN" , "log4j.logger.org.apache.jena=WARN" , "# Server log." , "log4j.logger.org.apache.jena.fuseki.Server=INFO" , "# Request log." , "log4j.logger.org.apache.jena.fuseki.Fuseki=INFO" , "log4j.logger.org.apache.jena.tdb.loader=INFO" , "log4j.logger.org.eclipse.jetty=ERROR" , "## Parser output" , "log4j.additivity."+SysRIOT.riotLoggerName+"=false" , "log4j.logger."+SysRIOT.riotLoggerName+"=INFO, jena.plainlevel " ) ; static { // Check if default command logging. if ( "set".equals(System.getProperty("log4j.configuration", "set") ) ) Log.resetLogging(log4Jsetup) ; } // Arguments: // --update // Specific switches: // --admin=on/off // --http-update // --http-get // --sparql-query // --sparql-update // pages/validators/ // pages/control/ // pages/query/ or /pages/sparql/ private static ArgDecl argMgtPort = new ArgDecl(ArgDecl.HasValue, "mgtPort", "mgtport") ; private static ArgDecl argMem = new ArgDecl(ArgDecl.NoValue, "mem") ; private static ArgDecl argAllowUpdate = new ArgDecl(ArgDecl.NoValue, "update", "allowUpdate") ; private static ArgDecl argFile = new ArgDecl(ArgDecl.HasValue, "file") ; private static ArgDecl argMemTDB = new ArgDecl(ArgDecl.NoValue, "memtdb", "memTDB") ; private static ArgDecl argTDB = new ArgDecl(ArgDecl.HasValue, "loc", "location") ; private static ArgDecl argPort = new ArgDecl(ArgDecl.HasValue, "port") ; private static ArgDecl argLocalhost = new ArgDecl(ArgDecl.NoValue, "localhost", "local") ; private static ArgDecl argTimeout = new ArgDecl(ArgDecl.HasValue, "timeout") ; private static ArgDecl argFusekiConfig = new ArgDecl(ArgDecl.HasValue, "config", "conf") ; private static ArgDecl argJettyConfig = new ArgDecl(ArgDecl.HasValue, "jetty-config") ; private static ArgDecl argGZip = new ArgDecl(ArgDecl.HasValue, "gzip") ; private static ArgDecl argUber = new ArgDecl(ArgDecl.NoValue, "uber", "über") ; // Use the überservlet (experimental) private static ArgDecl argBasicAuth = new ArgDecl(ArgDecl.HasValue, "basic-auth") ; private static ArgDecl argGSP = new ArgDecl(ArgDecl.NoValue, "gsp") ; // GSP compliance mode private static ArgDecl argHome = new ArgDecl(ArgDecl.HasValue, "home") ; private static ArgDecl argPages = new ArgDecl(ArgDecl.HasValue, "pages") ; //private static ModLocation modLocation = new ModLocation() ; private static ModDatasetAssembler modDataset = new ModDatasetAssembler() ; // fuseki [--mem|--desc assembler.ttl] [--port PORT] **** /datasetURI static public void main(String...argv) { // Just to make sure ... ARQ.init() ; TDB.init() ; Fuseki.init() ; new FusekiCmd(argv).mainRun() ; } private int port = 3030 ; private int mgtPort = -1 ; private boolean listenLocal = false ; private DatasetGraph dsg = null ; private String datasetPath = null ; private boolean allowUpdate = false ; private String fusekiConfigFile = null ; private boolean enableCompression = true ; private String jettyConfigFile = null ; private String authConfigFile = null ; private String homeDir = null ; private String pagesDir = null ; public FusekiCmd(String...argv) { super(argv) ; if ( false ) // Consider ... TransactionManager.QueueBatchSize = TransactionManager.QueueBatchSize / 2 ; getUsage().startCategory("Fuseki") ; addModule(modDataset) ; add(argMem, "--mem", "Create an in-memory, non-persistent dataset for the server") ; add(argFile, "--file=FILE", "Create an in-memory, non-persistent dataset for the server, initialised with the contents of the file") ; add(argTDB, "--loc=DIR", "Use an existing TDB database (or create if does not exist)") ; add(argMemTDB, "--memTDB", "Create an in-memory, non-persistent dataset using TDB (testing only)") ; add(argPort, "--port", "Listen on this port number") ; add(argPages, "--pages=DIR", "Set of pages to serve as static content") ; // Set via jetty config file. add(argLocalhost, "--localhost", "Listen only on the localhost interface") ; add(argTimeout, "--timeout=", "Global timeout applied to queries (value in ms) -- format is X[,Y] ") ; add(argAllowUpdate, "--update", "Allow updates (via SPARQL Update and SPARQL HTTP Update)") ; add(argFusekiConfig, "--config=", "Use a configuration file to determine the services") ; add(argJettyConfig, "--jetty-config=FILE", "Set up the server (not services) with a Jetty XML file") ; add(argBasicAuth, "--basic-auth=FILE", "Configure basic auth using provided Jetty realm file, ignored if --jetty-config is used") ; add(argMgtPort, "--mgtPort=port", "Enable the management commands on the given port") ; add(argHome, "--home=DIR", "Root of Fuseki installation (overrides environment variable FUSEKI_HOME)") ; add(argGZip, "--gzip=on|off", "Enable GZip compression (HTTP Accept-Encoding) if request header set") ; add(argUber) ; //add(argGSP) ; super.modVersion.addClass(TDB.class) ; super.modVersion.addClass(Fuseki.class) ; } static String argUsage = "[--config=FILE] [--mem|--desc=AssemblerFile|--file=FILE] [--port PORT] /DatasetPathName" ; @Override protected String getSummary() { return getCommandName()+" "+argUsage ; } @Override protected void processModulesAndArgs() { int x = 0 ; Logger log = Fuseki.serverLog ; if ( contains(argFusekiConfig) ) fusekiConfigFile = getValue(argFusekiConfig) ; ArgDecl assemblerDescDecl = new ArgDecl(ArgDecl.HasValue, "desc", "dataset") ; if ( contains(argMem) ) x++ ; if ( contains(argFile) ) x++ ; if ( contains(assemblerDescDecl) ) x++ ; if ( contains(argTDB) ) x++ ; if ( contains(argMemTDB) ) x++ ; if ( fusekiConfigFile != null ) { if ( x > 1 ) throw new CmdException("Dataset specificed on the command line and also a configuration file specificed.") ; } else { if ( x == 0 ) throw new CmdException("Required: either --config=FILE or one of --mem, --file, --loc or --desc") ; } if ( contains(argMem) ) { log.info("Dataset: in-memory") ; dsg = DatasetGraphFactory.createMem() ; } if ( contains(argFile) ) { dsg = DatasetGraphFactory.createMem() ; // replace by RiotLoader after ARQ refresh. String filename = getValue(argFile) ; log.info("Dataset: in-memory: load file: "+filename) ; if ( ! FileOps.exists(filename) ) throw new CmdException("File not found: "+filename) ; Lang language = RDFLanguages.filenameToLang(filename) ; if ( language == null ) throw new CmdException("Can't guess language for file: "+filename) ; InputStream input = IO.openFile(filename) ; if ( RDFLanguages.isQuads(language) ) RDFDataMgr.read(dsg, filename) ; else RDFDataMgr.read(dsg.getDefaultGraph(), filename) ; } if ( contains(argMemTDB) ) { log.info("TDB dataset: in-memory") ; dsg = TDBFactory.createDatasetGraph() ; } if ( contains(argTDB) ) { String dir = getValue(argTDB) ; log.info("TDB dataset: directory="+dir) ; if ( ! FileOps.exists(dir) ) throw new CmdException("Directory not found: "+dir) ; dsg = TDBFactory.createDatasetGraph(dir) ; } // Otherwise if ( contains(assemblerDescDecl) ) { log.info("Dataset from assembler") ; Dataset ds = modDataset.createDataset() ; if ( ds != null ) dsg = ds.asDatasetGraph() ; } if ( contains(argFusekiConfig) ) { if ( dsg != null ) throw new CmdException("Dataset specificed on the command line and also a configuration file specificed.") ; fusekiConfigFile = getValue(argFusekiConfig) ; } if ( contains(argPort) ) { String portStr = getValue(argPort) ; try { port = Integer.parseInt(portStr) ; } catch (NumberFormatException ex) { throw new CmdException(argPort.getKeyName()+" : bad port number: "+portStr) ; } } if ( contains(argMgtPort) ) { String mgtPortStr = getValue(argMgtPort) ; try { mgtPort = Integer.parseInt(mgtPortStr) ; } catch (NumberFormatException ex) { throw new CmdException(argMgtPort.getKeyName()+" : bad port number: "+mgtPortStr) ; } } if ( contains(argLocalhost) ) listenLocal = true ; if ( fusekiConfigFile == null && dsg == null ) throw new CmdException("No dataset defined and no configuration file: "+argUsage) ; if ( dsg != null ) { if ( getPositional().size() == 0 ) throw new CmdException("No dataset path name given") ; if ( getPositional().size() > 1 ) throw new CmdException("Multiple dataset path names given") ; datasetPath = getPositionalArg(0) ; if ( datasetPath.length() > 0 && ! datasetPath.startsWith("/") ) throw new CmdException("Dataset path name must begin with a /: "+datasetPath) ; allowUpdate = contains(argAllowUpdate) ; } if ( contains(argTimeout) ) { String str = getValue(argTimeout) ; ARQ.getContext().set(ARQ.queryTimeout, str) ; } if ( contains(argJettyConfig) ) { jettyConfigFile = getValue(argJettyConfig) ; if ( !FileOps.exists(jettyConfigFile) ) throw new CmdException("No such file: "+jettyConfigFile) ; } if ( contains(argBasicAuth) ) { authConfigFile = getValue(argBasicAuth) ; if ( !FileOps.exists(authConfigFile) ) throw new CmdException("No such file: " + authConfigFile) ; } if ( contains(argHome) ) { List<String> args = super.getValues(argHome) ; homeDir = args.get(args.size()-1) ; } if ( contains(argPages) ) { List<String> args = super.getValues(argPages) ; pagesDir = args.get(args.size()-1) ; } if ( contains(argGZip) ) { if ( ! hasValueOfTrue(argGZip) && ! hasValueOfFalse(argGZip) ) throw new CmdException(argGZip.getNames().get(0)+": Not understood: "+getValue(argGZip)) ; enableCompression = super.hasValueOfTrue(argGZip) ; } if ( contains(argUber) ) SPARQLServer.überServlet = true ; if ( contains(argGSP) ) { SPARQLServer.überServlet = true ; Fuseki.graphStoreProtocolPostCreate = true ; } } private static String sort_out_dir(String path) { path.replace('\\', '/') ; if ( ! path.endsWith("/")) path = path +"/" ; return path ; } @Override protected void exec() { if ( homeDir == null ) { if ( System.getenv(Fuseki.FusekiHomeEnv) != null ) homeDir = System.getenv(Fuseki.FusekiHomeEnv) ; else homeDir = "." ; } homeDir = sort_out_dir(homeDir) ; Fuseki.configLog.info("Home Directory: " + FileOps.fullDirectoryPath(homeDir)); if ( ! FileOps.exists(homeDir) ) Fuseki.configLog.warn("No such directory for Fuseki home: "+homeDir) ; String staticContentDir = pagesDir ; if ( staticContentDir == null ) staticContentDir = homeDir+Fuseki.PagesStatic ; Fuseki.configLog.debug("Static Content Directory: "+ FileOps.fullDirectoryPath(staticContentDir)) ; if ( ! FileOps.exists(staticContentDir) ) { Fuseki.configLog.warn("No such directory for static content: " + FileOps.fullDirectoryPath(staticContentDir)) ; Fuseki.configLog.warn("You may need to set the --pages or --home option to configure static content correctly"); } if ( jettyConfigFile != null ) Fuseki.configLog.info("Jetty configuration: "+jettyConfigFile) ; ServerConfig serverConfig ; if ( fusekiConfigFile != null ) { Fuseki.configLog.info("Configuration file: "+fusekiConfigFile) ; serverConfig = FusekiConfig.configure(fusekiConfigFile) ; } else serverConfig = FusekiConfig.defaultConfiguration(datasetPath, dsg, allowUpdate, listenLocal) ; // TODO Get from parsing config file. serverConfig.port = port ; serverConfig.pages = staticContentDir ; serverConfig.mgtPort = mgtPort ; serverConfig.pagesPort = port ; serverConfig.loopback = listenLocal ; serverConfig.enableCompression = enableCompression ; serverConfig.jettyConfigFile = jettyConfigFile ; serverConfig.authConfigFile = authConfigFile ; serverConfig.verboseLogging = ( super.isVerbose() || super.isDebug() ) ; SPARQLServer server = new SPARQLServer(serverConfig) ; // Temporary Fuseki.setServer(server) ; Server mgtServer = null ; if ( mgtPort > 0 ) { Fuseki.configLog.info("Management services on port "+mgtPort) ; mgtServer = ManagementServer.createManagementServer(mgtPort) ; try { mgtServer.start() ; } catch (java.net.BindException ex) { serverLog.error("SPARQLServer: Failed to start management server: " + ex.getMessage()) ; System.exit(1) ; } catch (Exception ex) { serverLog.error("SPARQLServer: Failed to start management server: " + ex.getMessage(), ex) ; System.exit(1) ; } } server.start() ; try { server.getServer().join() ; } catch (Exception ex) {} if ( mgtServer != null ) { try { mgtServer.stop() ; } catch (Exception e) { serverLog.warn("Failed to cleanly stop the management server", e) ; } } System.exit(0) ; } @Override protected String getCommandName() { return "fuseki" ; } }
gpl-2.0
andi-git/boatpos
regkas-server/regkas-server-service/regkas-server-service-api/src/test/java/org/regkas/service/api/bean/TaxElementBeanTest.java
348
package org.regkas.service.api.bean; import org.boatpos.common.test.JavaBeanTest; import org.junit.Test; import java.math.BigDecimal; public class TaxElementBeanTest extends JavaBeanTest<TaxElementBean> { @Test public void testConstructor() { new TaxElementBean(20, 1, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO); } }
gpl-2.0
ambekarzeneil/android-storage
TestModule/Test/app/src/main/java/com/focus/example/corestoragetester/app/testObjects/SimpleTestObject.java
6951
package com.focus.example.corestoragetester.app.testObjects; import com.zva.android.data.annotations.CoreStorageEntity; import com.zva.android.data.annotations.PrimaryKey; import com.zva.android.data.annotations.QueryColumn; import java.util.Date; import java.util.List; import java.util.Map; /** * Copyright CoreStorageTester 2015 Created by zeneilambekar on 31/07/15. */ @CoreStorageEntity public class SimpleTestObject { @PrimaryKey private String keyField; @QueryColumn private String simpleString; @QueryColumn private Boolean simpleBoolean; @QueryColumn private Long simpleLong; private String nonQueryColumn; @QueryColumn private Date createdAt; @QueryColumn(sqlType = "VARCHAR(20)") private String customString; private transient String transientData; private Map<String, String> stringToStringMap; private Map<String, Class<?>> stringToClassMap; private Map<String, List<Map<String, Class<?>>>> complexDataStructure; public String getSimpleString() { return simpleString; } public SimpleTestObject setSimpleString(String simpleString) { this.simpleString = simpleString; return this; } public Boolean getSimpleBoolean() { return simpleBoolean; } public SimpleTestObject setSimpleBoolean(Boolean simpleBoolean) { this.simpleBoolean = simpleBoolean; return this; } public Long getSimpleLong() { return simpleLong; } public SimpleTestObject setSimpleLong(Long simpleLong) { this.simpleLong = simpleLong; return this; } public Map<String, String> getStringToStringMap() { return stringToStringMap; } public SimpleTestObject setStringToStringMap(Map<String, String> stringToStringMap) { this.stringToStringMap = stringToStringMap; return this; } public Map<String, Class<?>> getStringToClassMap() { return stringToClassMap; } public SimpleTestObject setStringToClassMap(Map<String, Class<?>> stringToClassMap) { this.stringToClassMap = stringToClassMap; return this; } public String getKeyField() { return keyField; } public SimpleTestObject setKeyField(String keyField) { this.keyField = keyField; return this; } public String getNonQueryColumn() { return nonQueryColumn; } public SimpleTestObject setNonQueryColumn(String nonQueryColumn) { this.nonQueryColumn = nonQueryColumn; return this; } public String getTransientData() { return transientData; } public SimpleTestObject setTransientData(String transientData) { this.transientData = transientData; return this; } public Map<String, List<Map<String, Class<?>>>> getComplexDataStructure() { return complexDataStructure; } public SimpleTestObject setComplexDataStructure(Map<String, List<Map<String, Class<?>>>> complexDataStructure) { this.complexDataStructure = complexDataStructure; return this; } public Date getCreatedAt() { return createdAt; } public SimpleTestObject setCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } @Override public String toString() { return "SimpleTestObject{" + "keyField='" + keyField + '\'' + ", simpleString='" + simpleString + '\'' + ", simpleBoolean=" + simpleBoolean + ", simpleLong=" + simpleLong + ", nonQueryColumn='" + nonQueryColumn + '\'' + ", createdAt=" + createdAt + ", customString='" + customString + '\'' + ", transientData='" + transientData + '\'' + ", stringToStringMap=" + stringToStringMap + ", stringToClassMap=" + stringToClassMap + ", complexDataStructure=" + complexDataStructure + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleTestObject that = (SimpleTestObject) o; return !(keyField != null ? !keyField.equals(that.keyField) : that.keyField != null) && !(simpleString != null ? !simpleString.equals(that.simpleString) : that.simpleString != null) && !(simpleBoolean != null ? !simpleBoolean.equals(that.simpleBoolean) : that.simpleBoolean != null) && !(simpleLong != null ? !simpleLong.equals(that.simpleLong) : that.simpleLong != null) && !(nonQueryColumn != null ? !nonQueryColumn.equals(that.nonQueryColumn) : that.nonQueryColumn != null) && !(createdAt != null ? !createdAt.equals(that.createdAt) : that.createdAt != null) && !(customString != null ? !customString.equals(that.customString) : that.customString != null) && !(transientData != null ? !transientData.equals(that.transientData) : that.transientData != null) && !(stringToStringMap != null ? !stringToStringMap.equals(that.stringToStringMap) : that.stringToStringMap != null) && !(stringToClassMap != null ? !stringToClassMap.equals(that.stringToClassMap) : that.stringToClassMap != null) && !(complexDataStructure != null ? !complexDataStructure.equals(that.complexDataStructure) : that.complexDataStructure != null); } @Override public int hashCode() { int result = keyField != null ? keyField.hashCode() : 0; result = 31 * result + (simpleString != null ? simpleString.hashCode() : 0); result = 31 * result + (simpleBoolean != null ? simpleBoolean.hashCode() : 0); result = 31 * result + (simpleLong != null ? simpleLong.hashCode() : 0); result = 31 * result + (nonQueryColumn != null ? nonQueryColumn.hashCode() : 0); result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0); result = 31 * result + (customString != null ? customString.hashCode() : 0); result = 31 * result + (transientData != null ? transientData.hashCode() : 0); result = 31 * result + (stringToStringMap != null ? stringToStringMap.hashCode() : 0); result = 31 * result + (stringToClassMap != null ? stringToClassMap.hashCode() : 0); result = 31 * result + (complexDataStructure != null ? complexDataStructure.hashCode() : 0); return result; } public String getCustomString() { return customString; } public SimpleTestObject setCustomString(String customString) { this.customString = customString; return this; } }
gpl-2.0
Nikolopoulos/MScThesis
aggregators/MicazAggregator/src/lib/Poll_Request.java
4360
package lib; /** * This class is automatically generated by mig. DO NOT EDIT THIS FILE. * This class implements a Java interface to the 'Poll_Request' * message type. */ public class Poll_Request extends net.tinyos.message.Message { /** The default size of this message type in bytes. */ public static final int DEFAULT_MESSAGE_SIZE = 2; /** The Active Message type associated with this message. */ public static final int AM_TYPE = 66; /** Create a new Poll_Request of size 2. */ public Poll_Request() { super(DEFAULT_MESSAGE_SIZE); amTypeSet(AM_TYPE); } /** Create a new Poll_Request of the given data_length. */ public Poll_Request(int data_length) { super(data_length); amTypeSet(AM_TYPE); } /** * Create a new Poll_Request with the given data_length * and base offset. */ public Poll_Request(int data_length, int base_offset) { super(data_length, base_offset); amTypeSet(AM_TYPE); } /** * Create a new Poll_Request using the given byte array * as backing store. */ public Poll_Request(byte[] data) { super(data); amTypeSet(AM_TYPE); } /** * Create a new Poll_Request using the given byte array * as backing store, with the given base offset. */ public Poll_Request(byte[] data, int base_offset) { super(data, base_offset); amTypeSet(AM_TYPE); } /** * Create a new Poll_Request using the given byte array * as backing store, with the given base offset and data length. */ public Poll_Request(byte[] data, int base_offset, int data_length) { super(data, base_offset, data_length); amTypeSet(AM_TYPE); } /** * Create a new Poll_Request embedded in the given message * at the given base offset. */ public Poll_Request(net.tinyos.message.Message msg, int base_offset) { super(msg, base_offset, DEFAULT_MESSAGE_SIZE); amTypeSet(AM_TYPE); } /** * Create a new Poll_Request embedded in the given message * at the given base offset and length. */ public Poll_Request(net.tinyos.message.Message msg, int base_offset, int data_length) { super(msg, base_offset, data_length); amTypeSet(AM_TYPE); } /** /* Return a String representation of this message. Includes the * message type name and the non-indexed field values. */ public String toString() { String s = "Message <Poll_Request> \n"; try { s += " [messageType=0x"+Long.toHexString(get_messageType())+"]\n"; } catch (ArrayIndexOutOfBoundsException aioobe) { /* Skip field */ } return s; } // Message-type-specific access methods appear below. ///////////////////////////////////////////////////////// // Accessor methods for field: messageType // Field type: int, unsigned // Offset (bits): 0 // Size (bits): 16 ///////////////////////////////////////////////////////// /** * Return whether the field 'messageType' is signed (false). */ public static boolean isSigned_messageType() { return false; } /** * Return whether the field 'messageType' is an array (false). */ public static boolean isArray_messageType() { return false; } /** * Return the offset (in bytes) of the field 'messageType' */ public static int offset_messageType() { return (0 / 8); } /** * Return the offset (in bits) of the field 'messageType' */ public static int offsetBits_messageType() { return 0; } /** * Return the value (as a int) of the field 'messageType' */ public int get_messageType() { return (int)getUIntBEElement(offsetBits_messageType(), 16); } /** * Set the value of the field 'messageType' */ public void set_messageType(int value) { setUIntBEElement(offsetBits_messageType(), 16, value); } /** * Return the size, in bytes, of the field 'messageType' */ public static int size_messageType() { return (16 / 8); } /** * Return the size, in bits, of the field 'messageType' */ public static int sizeBits_messageType() { return 16; } }
gpl-2.0
dmlloyd/openjdk-modules
jdk/src/java.base/share/classes/java/util/zip/Deflater.java
20477
/* * Copyright (c) 1996, 2017, 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 java.util.zip; /** * This class provides support for general purpose compression using the * popular ZLIB compression library. The ZLIB compression library was * initially developed as part of the PNG graphics standard and is not * protected by patents. It is fully described in the specifications at * the <a href="package-summary.html#package_description">java.util.zip * package description</a>. * * <p>The following code fragment demonstrates a trivial compression * and decompression of a string using {@code Deflater} and * {@code Inflater}. * * <blockquote><pre> * try { * // Encode a String into bytes * String inputString = "blahblahblah"; * byte[] input = inputString.getBytes("UTF-8"); * * // Compress the bytes * byte[] output = new byte[100]; * Deflater compresser = new Deflater(); * compresser.setInput(input); * compresser.finish(); * int compressedDataLength = compresser.deflate(output); * compresser.end(); * * // Decompress the bytes * Inflater decompresser = new Inflater(); * decompresser.setInput(output, 0, compressedDataLength); * byte[] result = new byte[100]; * int resultLength = decompresser.inflate(result); * decompresser.end(); * * // Decode the bytes into a String * String outputString = new String(result, 0, resultLength, "UTF-8"); * } catch(java.io.UnsupportedEncodingException ex) { * // handle * } catch (java.util.zip.DataFormatException ex) { * // handle * } * </pre></blockquote> * * @see Inflater * @author David Connelly */ public class Deflater { private final ZStreamRef zsRef; private byte[] buf = new byte[0]; private int off, len; private int level, strategy; private boolean setParams; private boolean finish, finished; private long bytesRead; private long bytesWritten; /** * Compression method for the deflate algorithm (the only one currently * supported). */ public static final int DEFLATED = 8; /** * Compression level for no compression. */ public static final int NO_COMPRESSION = 0; /** * Compression level for fastest compression. */ public static final int BEST_SPEED = 1; /** * Compression level for best compression. */ public static final int BEST_COMPRESSION = 9; /** * Default compression level. */ public static final int DEFAULT_COMPRESSION = -1; /** * Compression strategy best used for data consisting mostly of small * values with a somewhat random distribution. Forces more Huffman coding * and less string matching. */ public static final int FILTERED = 1; /** * Compression strategy for Huffman coding only. */ public static final int HUFFMAN_ONLY = 2; /** * Default compression strategy. */ public static final int DEFAULT_STRATEGY = 0; /** * Compression flush mode used to achieve best compression result. * * @see Deflater#deflate(byte[], int, int, int) * @since 1.7 */ public static final int NO_FLUSH = 0; /** * Compression flush mode used to flush out all pending output; may * degrade compression for some compression algorithms. * * @see Deflater#deflate(byte[], int, int, int) * @since 1.7 */ public static final int SYNC_FLUSH = 2; /** * Compression flush mode used to flush out all pending output and * reset the deflater. Using this mode too often can seriously degrade * compression. * * @see Deflater#deflate(byte[], int, int, int) * @since 1.7 */ public static final int FULL_FLUSH = 3; static { /* Zip library is loaded from System.initializeSystemClass */ initIDs(); } /** * Creates a new compressor using the specified compression level. * If 'nowrap' is true then the ZLIB header and checksum fields will * not be used in order to support the compression format used in * both GZIP and PKZIP. * @param level the compression level (0-9) * @param nowrap if true then use GZIP compatible compression */ public Deflater(int level, boolean nowrap) { this.level = level; this.strategy = DEFAULT_STRATEGY; this.zsRef = new ZStreamRef(init(level, DEFAULT_STRATEGY, nowrap)); } /** * Creates a new compressor using the specified compression level. * Compressed data will be generated in ZLIB format. * @param level the compression level (0-9) */ public Deflater(int level) { this(level, false); } /** * Creates a new compressor with the default compression level. * Compressed data will be generated in ZLIB format. */ public Deflater() { this(DEFAULT_COMPRESSION, false); } /** * Sets input data for compression. This should be called whenever * needsInput() returns true indicating that more input data is required. * @param b the input data bytes * @param off the start offset of the data * @param len the length of the data * @see Deflater#needsInput */ public void setInput(byte[] b, int off, int len) { if (b== null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { this.buf = b; this.off = off; this.len = len; } } /** * Sets input data for compression. This should be called whenever * needsInput() returns true indicating that more input data is required. * @param b the input data bytes * @see Deflater#needsInput */ public void setInput(byte[] b) { setInput(b, 0, b.length); } /** * Sets preset dictionary for compression. A preset dictionary is used * when the history buffer can be predetermined. When the data is later * uncompressed with Inflater.inflate(), Inflater.getAdler() can be called * in order to get the Adler-32 value of the dictionary required for * decompression. * @param b the dictionary data bytes * @param off the start offset of the data * @param len the length of the data * @see Inflater#inflate * @see Inflater#getAdler */ public void setDictionary(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { ensureOpen(); setDictionary(zsRef.address(), b, off, len); } } /** * Sets preset dictionary for compression. A preset dictionary is used * when the history buffer can be predetermined. When the data is later * uncompressed with Inflater.inflate(), Inflater.getAdler() can be called * in order to get the Adler-32 value of the dictionary required for * decompression. * @param b the dictionary data bytes * @see Inflater#inflate * @see Inflater#getAdler */ public void setDictionary(byte[] b) { setDictionary(b, 0, b.length); } /** * Sets the compression strategy to the specified value. * * <p> If the compression strategy is changed, the next invocation * of {@code deflate} will compress the input available so far with * the old strategy (and may be flushed); the new strategy will take * effect only after that invocation. * * @param strategy the new compression strategy * @exception IllegalArgumentException if the compression strategy is * invalid */ public void setStrategy(int strategy) { switch (strategy) { case DEFAULT_STRATEGY: case FILTERED: case HUFFMAN_ONLY: break; default: throw new IllegalArgumentException(); } synchronized (zsRef) { if (this.strategy != strategy) { this.strategy = strategy; setParams = true; } } } /** * Sets the compression level to the specified value. * * <p> If the compression level is changed, the next invocation * of {@code deflate} will compress the input available so far * with the old level (and may be flushed); the new level will * take effect only after that invocation. * * @param level the new compression level (0-9) * @exception IllegalArgumentException if the compression level is invalid */ public void setLevel(int level) { if ((level < 0 || level > 9) && level != DEFAULT_COMPRESSION) { throw new IllegalArgumentException("invalid compression level"); } synchronized (zsRef) { if (this.level != level) { this.level = level; setParams = true; } } } /** * Returns true if the input data buffer is empty and setInput() * should be called in order to provide more input. * @return true if the input data buffer is empty and setInput() * should be called in order to provide more input */ public boolean needsInput() { synchronized (zsRef) { return len <= 0; } } /** * When called, indicates that compression should end with the current * contents of the input buffer. */ public void finish() { synchronized (zsRef) { finish = true; } } /** * Returns true if the end of the compressed data output stream has * been reached. * @return true if the end of the compressed data output stream has * been reached */ public boolean finished() { synchronized (zsRef) { return finished; } } /** * Compresses the input data and fills specified buffer with compressed * data. Returns actual number of bytes of compressed data. A return value * of 0 indicates that {@link #needsInput() needsInput} should be called * in order to determine if more input data is required. * * <p>This method uses {@link #NO_FLUSH} as its compression flush mode. * An invocation of this method of the form {@code deflater.deflate(b, off, len)} * yields the same result as the invocation of * {@code deflater.deflate(b, off, len, Deflater.NO_FLUSH)}. * * @param b the buffer for the compressed data * @param off the start offset of the data * @param len the maximum number of bytes of compressed data * @return the actual number of bytes of compressed data written to the * output buffer */ public int deflate(byte[] b, int off, int len) { return deflate(b, off, len, NO_FLUSH); } /** * Compresses the input data and fills specified buffer with compressed * data. Returns actual number of bytes of compressed data. A return value * of 0 indicates that {@link #needsInput() needsInput} should be called * in order to determine if more input data is required. * * <p>This method uses {@link #NO_FLUSH} as its compression flush mode. * An invocation of this method of the form {@code deflater.deflate(b)} * yields the same result as the invocation of * {@code deflater.deflate(b, 0, b.length, Deflater.NO_FLUSH)}. * * @param b the buffer for the compressed data * @return the actual number of bytes of compressed data written to the * output buffer */ public int deflate(byte[] b) { return deflate(b, 0, b.length, NO_FLUSH); } /** * Compresses the input data and fills the specified buffer with compressed * data. Returns actual number of bytes of data compressed. * * <p>Compression flush mode is one of the following three modes: * * <ul> * <li>{@link #NO_FLUSH}: allows the deflater to decide how much data * to accumulate, before producing output, in order to achieve the best * compression (should be used in normal use scenario). A return value * of 0 in this flush mode indicates that {@link #needsInput()} should * be called in order to determine if more input data is required. * * <li>{@link #SYNC_FLUSH}: all pending output in the deflater is flushed, * to the specified output buffer, so that an inflater that works on * compressed data can get all input data available so far (In particular * the {@link #needsInput()} returns {@code true} after this invocation * if enough output space is provided). Flushing with {@link #SYNC_FLUSH} * may degrade compression for some compression algorithms and so it * should be used only when necessary. * * <li>{@link #FULL_FLUSH}: all pending output is flushed out as with * {@link #SYNC_FLUSH}. The compression state is reset so that the inflater * that works on the compressed output data can restart from this point * if previous compressed data has been damaged or if random access is * desired. Using {@link #FULL_FLUSH} too often can seriously degrade * compression. * </ul> * * <p>In the case of {@link #FULL_FLUSH} or {@link #SYNC_FLUSH}, if * the return value is {@code len}, the space available in output * buffer {@code b}, this method should be invoked again with the same * {@code flush} parameter and more output space. Make sure that * {@code len} is greater than 6 to avoid flush marker (5 bytes) being * repeatedly output to the output buffer every time this method is * invoked. * * @param b the buffer for the compressed data * @param off the start offset of the data * @param len the maximum number of bytes of compressed data * @param flush the compression flush mode * @return the actual number of bytes of compressed data written to * the output buffer * * @throws IllegalArgumentException if the flush mode is invalid * @since 1.7 */ public int deflate(byte[] b, int off, int len, int flush) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || off > b.length - len) { throw new ArrayIndexOutOfBoundsException(); } synchronized (zsRef) { ensureOpen(); if (flush == NO_FLUSH || flush == SYNC_FLUSH || flush == FULL_FLUSH) { int thisLen = this.len; int n = deflateBytes(zsRef.address(), b, off, len, flush); bytesWritten += n; bytesRead += (thisLen - this.len); return n; } throw new IllegalArgumentException(); } } /** * Returns the ADLER-32 value of the uncompressed data. * @return the ADLER-32 value of the uncompressed data */ public int getAdler() { synchronized (zsRef) { ensureOpen(); return getAdler(zsRef.address()); } } /** * Returns the total number of uncompressed bytes input so far. * * <p>Since the number of bytes may be greater than * Integer.MAX_VALUE, the {@link #getBytesRead()} method is now * the preferred means of obtaining this information.</p> * * @return the total number of uncompressed bytes input so far */ public int getTotalIn() { return (int) getBytesRead(); } /** * Returns the total number of uncompressed bytes input so far. * * @return the total (non-negative) number of uncompressed bytes input so far * @since 1.5 */ public long getBytesRead() { synchronized (zsRef) { ensureOpen(); return bytesRead; } } /** * Returns the total number of compressed bytes output so far. * * <p>Since the number of bytes may be greater than * Integer.MAX_VALUE, the {@link #getBytesWritten()} method is now * the preferred means of obtaining this information.</p> * * @return the total number of compressed bytes output so far */ public int getTotalOut() { return (int) getBytesWritten(); } /** * Returns the total number of compressed bytes output so far. * * @return the total (non-negative) number of compressed bytes output so far * @since 1.5 */ public long getBytesWritten() { synchronized (zsRef) { ensureOpen(); return bytesWritten; } } /** * Resets deflater so that a new set of input data can be processed. * Keeps current compression level and strategy settings. */ public void reset() { synchronized (zsRef) { ensureOpen(); reset(zsRef.address()); finish = false; finished = false; off = len = 0; bytesRead = bytesWritten = 0; } } /** * Closes the compressor and discards any unprocessed input. * This method should be called when the compressor is no longer * being used, but will also be called automatically by the * finalize() method. Once this method is called, the behavior * of the Deflater object is undefined. */ public void end() { synchronized (zsRef) { long addr = zsRef.address(); zsRef.clear(); if (addr != 0) { end(addr); buf = null; } } } /** * Closes the compressor when garbage is collected. * * @deprecated The {@code finalize} method has been deprecated. * Subclasses that override {@code finalize} in order to perform cleanup * should be modified to use alternative cleanup mechanisms and * to remove the overriding {@code finalize} method. * When overriding the {@code finalize} method, its implementation must explicitly * ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}. * See the specification for {@link Object#finalize()} for further * information about migration options. */ @Deprecated(since="9") protected void finalize() { end(); } private void ensureOpen() { assert Thread.holdsLock(zsRef); if (zsRef.address() == 0) throw new NullPointerException("Deflater has been closed"); } private static native void initIDs(); private static native long init(int level, int strategy, boolean nowrap); private static native void setDictionary(long addr, byte[] b, int off, int len); private native int deflateBytes(long addr, byte[] b, int off, int len, int flush); private static native int getAdler(long addr); private static native void reset(long addr); private static native void end(long addr); }
gpl-2.0
thesam/trubbl
trubbl-issues/src/main/java/trubbl/issues/domain/Issue.java
545
package trubbl.issues.domain; import com.fasterxml.jackson.annotation.JsonProperty; import trubbl.sharedkernel.domain.Key; import trubbl.sharedkernel.domain.Keyable; public class Issue implements Keyable { @JsonProperty private Key key; @JsonProperty private String title; @JsonProperty private String description; public Issue(String title, String description) { this(); this.title = title; this.description = description; } public Key key() { return this.key; } // REST public Issue() { this.key = new Key(); } }
gpl-2.0
elecnix/gnu-qif
src/gnu/qif/doc-files/Sample1.java
2988
import gnu.qif.RecordArray; import gnu.qif.AccountRecord; import gnu.qif.QIFRecord; /* The gnu.qif package: A tool for creating QIF files. Copyright (C) 2001 Nicolas Marchildon 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. */ import gnu.qif.BankTransaction; import gnu.qif.OpeningBalanceRecord; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.DriverManager; import java.util.Date; /** * <p>A sample usage of the gnu.qif package, used to show how to * transfer funds from "First Account" to "Second Account" * back and forth.</p> * * <p>You can run this sample by first setting your CLASSPATH * so that it included the gnu.qif classes (maybe the jar file), * by compiling it ("javac Sample1.java"), and running it ("java Sample1").</p> * * @see gnu.qif * * @author <a href="mailto:nicolas@marchildon.net">Nicolas Marchildon</a> * @version $Id: Sample1.java,v 1.1 2001/11/17 07:29:07 nicolas Exp $ */ public class Sample1 { public static void main(String[] args) throws Exception { RecordArray records = new RecordArray(); String firstAccountName = "First account"; String secondAccountName = "Second account"; /* First, we define the first account */ AccountRecord firstAccount = new AccountRecord(firstAccountName); records.addRecord(firstAccount); /* This means we deposit 2$ into firstAccount, from secondAccount */ BankTransaction tr = new BankTransaction(); tr.setNumber("1"); tr.setTotal(2); // Deposit if positive, withdrawal when negative tr.setDate(new Date()); tr.setMemo("Memo1"); tr.setPayee("Payee1"); tr.setAccount(secondAccountName); records.addRecord(tr); /* Now we define the second account */ AccountRecord secondAccount = new AccountRecord(secondAccountName); records.addRecord(secondAccount); /* Deposit of 4$ into secondAccount from firstAccount */ BankTransaction tr2 = new BankTransaction(); tr2.setNumber("3"); tr2.setTotal(4); tr2.setDate(new Date()); tr2.setMemo("Memo2"); tr2.setPayee("Payee2"); tr2.setAccount(firstAccountName); records.addRecord(tr2); System.out.println(records.toString()); } }
gpl-2.0
panbasten/imeta
imeta2.x/imeta-src/imeta/src/main/java/com/panet/imeta/job/entries/zipfile/Messages.java
2273
/* * Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package com.panet.imeta.job.entries.zipfile; import com.panet.imeta.i18n.BaseMessages; public class Messages { public static final String packageName = Messages.class.getPackage().getName(); public static String getString(String key) { return BaseMessages.getString(packageName, key); } public static String getString(String key, String param1) { return BaseMessages.getString(packageName, key, param1); } public static String getString(String key, String param1, String param2) { return BaseMessages.getString(packageName, key, param1, param2); } public static String getString(String key, String param1, String param2, String param3) { return BaseMessages.getString(packageName, key, param1, param2, param3); } public static String getString(String key, String param1, String param2, String param3, String param4) { return BaseMessages.getString(packageName, key, param1, param2, param3, param4); } public static String getString(String key, String param1, String param2, String param3, String param4, String param5) { return BaseMessages.getString(packageName, key, param1, param2, param3, param4, param5); } public static String getString(String key, String param1, String param2, String param3, String param4, String param5, String param6) { return BaseMessages.getString(packageName, key, param1, param2, param3, param4, param5, param6); } }
gpl-2.0
isandlaTech/cohorte-utilities
extra/org.cohorte.utilities.sql/src/org/cohorte/utilities/sql/pool/CDBPool.java
6719
package org.cohorte.utilities.sql.pool; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.cohorte.utilities.sql.DBException; import org.cohorte.utilities.sql.IDBConnection; import org.cohorte.utilities.sql.IDBPool; import org.cohorte.utilities.sql.exec.CDBConnectionFactory; import org.cohorte.utilities.sql.exec.CDBConnectionInfos; import org.psem2m.utilities.logging.CActivityLoggerNull; import org.psem2m.utilities.logging.IActivityLogger; /** * @author ogattaz * */ public class CDBPool implements IDBPool { // The max unused duration of a dbconnection (default 15 minutes = // 15*60*1000) private static long DB_POOL_MAX_UNUSED_DURATION = 15 * 60 * 1000; private final List<IDBConnection> pConnections = new LinkedList<IDBConnection>(); private CDBConnectionInfos pDBConnectionInfos; private IActivityLogger pLogger; /** * Gestion des connexions innutilisées dans le pool de connexion de la base * agiliumdb */ private final long pMaxUnusedDuration; private final AtomicBoolean pOpened = new AtomicBoolean(); private final CDBPoolMonitor pPoolMonitor; /** * */ public CDBPool(final CDBConnectionInfos aDBConnectionInfos) { this(null, aDBConnectionInfos); } /** * */ public CDBPool(final IActivityLogger aLogger, final CDBConnectionInfos aDBConnectionInfos) { super(); setLogger(aLogger); setDBConnectionInfos(aDBConnectionInfos); pMaxUnusedDuration = DB_POOL_MAX_UNUSED_DURATION; pPoolMonitor = new CDBPoolMonitor(this); pLogger.logInfo(this, "<init>", "MaxUnusedDuration=[%d] NbConnection=[%d]", pMaxUnusedDuration, getNbConnection()); } /** * @throws Exception */ IDBConnection addNewDbConnection() throws DBException { return addNewDbConnection(createDbConnection()); } /** * @return * @throws ClusterStorageException */ private IDBConnection addNewDbConnection(final IDBConnection aConnection) throws DBException { if (!aConnection.isOpened()) { boolean wOpened = aConnection.open(); pLogger.logInfo(this, "addNewDbConnection", "NbConnection=[%d] Idx=[%d] Opened=[%b]", getNbConnection(), aConnection.getIdx(), wOpened); } synchronized (pConnections) { pConnections.add(aConnection); } return aConnection; } /* * (non-Javadoc) * * @see fr.agilium.ng.commons.sql.IDBPool#checkIn(fr.agilium.ng.commons.sql. * IDBConnection) */ @Override public void checkIn(final IDBConnection aDbConn) { // MOD_172 if (aDbConn != null) { // if no SQLException occurs during thes usage if (aDbConn.isValid()) { aDbConn.setBusyOff(); } else { aDbConn.close(); synchronized (pConnections) { pConnections.remove(aDbConn); } } } } /* * (non-Javadoc) * * @see fr.agilium.ng.commons.sql.IDBPool#checkOut() */ @Override public IDBConnection checkOut() throws IllegalStateException, Exception { if (!isConnected()) { throw new IllegalStateException("DBPool is not opened"); } IDBConnection wConnection = findFirstFree(); if (wConnection == null) { wConnection = createDbConnection(); wConnection.setBusyOn(); addNewDbConnection(wConnection); pLogger.logInfo(this, "checkOut", "NbConnection=[%d] NewConnectionIdx=[%d]", getNbConnection(), wConnection.getIdx()); } return wConnection; } /** * */ private void close() { pPoolMonitor.stopMonitor(); pLogger.logInfo(this, "close(): NbConnection to close=[%d]", getNbConnection()); synchronized (pConnections) { for (IDBConnection wConnection : pConnections) { wConnection.close(); } pConnections.clear(); } } /** * @return * @throws ClusterStorageException */ IDBConnection createDbConnection() throws DBException { return CDBConnectionFactory .newDbConnection(pLogger, pDBConnectionInfos); } /* * (non-Javadoc) * * @see fr.agilium.ng.commons.sql.IDBBase#dbClose() */ @Override public boolean dbClose() throws IllegalStateException { if (!isConnected()) { throw new IllegalStateException("DBPool is not opened"); } close(); pOpened.set(false); return true; } /* * (non-Javadoc) * * @see fr.agilium.ng.commons.sql.IDBBase#dbOpen() */ @Override public boolean dbOpen() throws IllegalStateException, Exception { if (isConnected()) { throw new IllegalStateException("DBPool is already opened"); } try { // add a new connection according the current DBConnectionInfos addNewDbConnection(); pOpened.set(true); } catch (Exception e) { pLogger.logSevere(this, "<init>", "Unable to create a connection to open the pool: %s", e); } return false; } @Override public boolean dbOpen(final CDBConnectionInfos aDBConnectionInfos) throws Exception { if (isConnected()) { throw new Exception("Pool is already opened"); } setDBConnectionInfos(aDBConnectionInfos); return dbOpen(); } /** * * detect and invalidate the unused connexions since more that the max * autorized unused duration * * @return the first "unbusy" db connexion found in the list */ private IDBConnection findFirstFree() { synchronized (pConnections) { for (IDBConnection wConnection : pConnections) { // if not used and always valid if (!wConnection.isBusy() && wConnection.isValid()) { // if unused since too much time if (wConnection.isUnusedTooLoong()) { wConnection.invalidate(); } else { wConnection.setBusyOn(); return wConnection; } } } } return null; } /** * MOD_99 * * @return */ List<IDBConnection> getConnections() { return pConnections; } /* * (non-Javadoc) * * @see fr.agilium.ng.commons.sql.IDBBase#getDBConnection() */ @Override public IDBConnection getDBConnection() throws Exception { return checkOut(); } /** * @return */ @Override public CDBConnectionInfos getDBConnectionInfos() { return pDBConnectionInfos; } /** * @return */ IActivityLogger getLogger() { return pLogger; } /** * @return */ public int getNbConnection() { synchronized (pConnections) { return pConnections.size(); } } /* * (non-Javadoc) * * @see fr.agilium.ng.commons.sql.IDBBase#isConnected() */ @Override public boolean isConnected() { return pOpened.get(); } /** * @param aDBConnectionInfos */ private void setDBConnectionInfos( final CDBConnectionInfos aDBConnectionInfos) { pDBConnectionInfos = aDBConnectionInfos; } /** * @param aLogger * @return the logger */ public void setLogger(final IActivityLogger aLogger) { pLogger = (aLogger != null) ? aLogger : CActivityLoggerNull .getInstance(); } }
gpl-2.0
cyberpython/java-gnome
src/bindings/org/gnome/gtk/MenuToolButton.java
4952
/* * java-gnome, a UI library for writing GTK and GNOME programs from Java! * * Copyright © 2007-2010 Operational Dynamics Consulting, Pty Ltd and Others * * The code in this file, and the program it is a part of, is made available * to you by its authors as open source software: you can redistribute it * and/or modify it under the terms of the GNU General Public License version * 2 ("GPL") 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 GPL for more details. * * You should have received a copy of the GPL along with this program. If not, * see http://www.gnu.org/licenses/. The authors of this program may be * contacted through http://java-gnome.sourceforge.net/. * * Linking this library statically or dynamically with other modules is making * a combined work based on this library. Thus, the terms and conditions of * the GPL cover the whole combination. As a special exception (the * "Claspath Exception"), the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. An independent * module is a module which is not derived from or based on this library. If * you modify this library, you may extend the Classpath Exception to your * version of the library, but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. */ package org.gnome.gtk; /** * A MenuToolButton is an special kind of ToolButton that has an additional * drop-down Menu. * * <p> * Next to the ToolButton itself, a MenuToolButton shows another little Button * with an arrow. When the user clicks this additional Button, a drop-down * Menu pops up. * * <p> * The main usage of a MenuToolButton is to provide access to several related * actions in a Toolbar without wasting too much screen space. For example, * your application can have a MenuToolButton for the "New Document" action, * using the attached Menu to let users choose what kind of new document they * want to create. * * <p> * A MenuToolButton has a default action, to be executed when user clicks the * main Button itself and not the the arrow Button. You can capture that * default event with the {@link ToolButton.Clicked} signal. User Menu * selections are captured with the usual {@link MenuItem.Activate} signal of * each <code>MenuItem</code>. * * @see Toolbar * @see Menu * * @author Vreixo Formoso * @since 4.0.4 */ public class MenuToolButton extends ToolButton { protected MenuToolButton(long pointer) { super(pointer); } /** * Creates a new MenuToolButton using the given icon and Label. * * @param iconWidget * The Widget to be used as the icon for the MenuToolButton. * Usually you will want to use a Widget display an image, such * as {@link Image}. Use <code>null</code> if you do not want * an icon. * @param label * The Label for the MenuToolButton, or <code>null</code> to * provide not Label. */ public MenuToolButton(Widget iconWidget, String label) { super(GtkMenuToolButton.createMenuToolButton(iconWidget, label)); } /** * Creates a new MenuToolButton from the specific stock item. Both the * Label and icon will be set properly from the stock item. By using a * system stock item, the newly created MenuToolButton with use the same * Label and Image as other GNOME applications. To ensure consistent look * and feel between applications, it is highly recommended that you use * provided stock items whenever possible. * * @param stock * The StockId that will determine the Label and icon of the * MenuToolButton. */ public MenuToolButton(Stock stock) { super(GtkMenuToolButton.createMenuToolButtonFromStock(stock.getStockId())); } /** * Sets the Menu to be popped up when the user clicks the arrow Button. * * <p> * You can pass <code>null</code> to make arrow insensitive. */ public void setMenu(Menu menu) { GtkMenuToolButton.setMenu(this, menu); } /** * Get the Menu associated with the MenuToolButton. * * @return The associated Menu or <code>null</code> if no Menu has been * set. */ public Menu getMenu() { return (Menu) GtkMenuToolButton.getMenu(this); } }
gpl-2.0
mikrosimage/jebu-core
src/main/java/ebu/metadata_schema/ebucore_2015/PositionInteractionRangeType.java
2653
package ebu.metadata_schema.ebucore_2015; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * <p>Classe Java pour positionInteractionRangeType complex type. * * <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe. * * <pre> * &lt;complexType name="positionInteractionRangeType"> * &lt;simpleContent> * &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>float"> * &lt;attribute name="coordinate" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="bound" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "positionInteractionRangeType", propOrder = { "value" }) public class PositionInteractionRangeType implements Serializable { private final static long serialVersionUID = -1L; @XmlValue protected float value; @XmlAttribute(name = "coordinate") protected java.lang.String coordinate; @XmlAttribute(name = "bound") protected java.lang.String bound; /** * Obtient la valeur de la propriété value. * */ public float getValue() { return value; } /** * Définit la valeur de la propriété value. * */ public void setValue(float value) { this.value = value; } /** * Obtient la valeur de la propriété coordinate. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getCoordinate() { return coordinate; } /** * Définit la valeur de la propriété coordinate. * * @param value * allowed object is * {@link java.lang.String } * */ public void setCoordinate(java.lang.String value) { this.coordinate = value; } /** * Obtient la valeur de la propriété bound. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getBound() { return bound; } /** * Définit la valeur de la propriété bound. * * @param value * allowed object is * {@link java.lang.String } * */ public void setBound(java.lang.String value) { this.bound = value; } }
gpl-2.0
kankaungmalay/Mweather
app/src/main/java/com/visittomm/mweather/fragments/CachedCityListFragment.java
4581
package com.visittomm.mweather.fragments; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import com.visittomm.mweather.R; import com.visittomm.mweather.interfaces.FragmentListener; import com.visittomm.mweather.utils.Utils; import org.json.JSONArray; import org.json.JSONObject; import java.io.FileInputStream; import java.util.ArrayList; /** * Created by monmon on 1/4/16. */ public class CachedCityListFragment extends Fragment { public static final String TAG = "com.visittomm.mweather.fragments.CachedCityListFragment"; private static final String JSON_CACHE_FILE = "city-cache.json"; private Context mContext = null; private View mView = null; ListView mListView = null; ArrayAdapter<String> mAdapter; ArrayList<String> stringArrayList; public CachedCityListFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); Log.d(TAG, " =>> CachedCityListFragment"); mView = inflater.inflate(R.layout.fragment_cached_city_list, container, false); mContext = this.getActivity(); // change toolbar title of current Fragment Fragment f = getActivity().getFragmentManager().findFragmentById(R.id.fragment); if (f instanceof CachedCityListFragment) ((AppCompatActivity) mContext).getSupportActionBar().setTitle("Mweather"); mListView = (ListView) mView.findViewById(R.id.lvCachedRecordListing); // Read selected cities object from cache String jsonContent = null; try { FileInputStream jsonCache = mContext.openFileInput(JSON_CACHE_FILE); jsonContent = Utils.readStream(jsonCache); JSONArray jsonArray = new JSONArray(jsonContent); stringArrayList = new ArrayList<String>(); for(int i=0;i<jsonArray.length();i++){ JSONObject json_data = jsonArray.getJSONObject(i); stringArrayList.add(json_data.getString("name")); // add to arraylist } } catch (Exception exception) { Log.e(TAG, exception.getMessage()); } mAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_2, android.R.id.text2, stringArrayList); mListView.setAdapter(mAdapter); onCityClick(); checkAddEditBtnClick(); return mView; } private void onCityClick() { mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { view.animate().setDuration(2000).alpha(0) .withEndAction(new Runnable() { @Override public void run() { view.setAlpha(1); } }); String value = (String)parent.getItemAtPosition(position); Log.d(TAG, "clicked value >> " + value); WeatherDetailFragment fragment = new WeatherDetailFragment(); Bundle fragBundle = new Bundle(); fragBundle.putString("selectedCity", value); fragment.setArguments(fragBundle); FragmentListener fragmentListener = (FragmentListener) getActivity(); fragmentListener.startMainFragment(fragment, true); } }); } private void checkAddEditBtnClick() { Button myButton = (Button) mView.findViewById(R.id.addEditCity); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CityListFragment fragment = new CityListFragment(); FragmentListener fragmentListener = (FragmentListener) getActivity(); fragmentListener.startMainFragment(fragment, true); } }); } }
gpl-2.0
tommykent1210/ChemCraft
Development/src/main/java/me/tomkent/chemcraft/Blocks/oreBarium.java
655
package me.tomkent.chemcraft.Blocks; import me.tomkent.chemcraft.ChemCraft; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; public class oreBarium extends Block{ private static String blockName = "Barium Ore"; private static String blockTexture = "missing"; private static String blockNameSafe = "oreBarium"; public oreBarium() { super(Material.rock); setBlockName(ChemCraft.MODID + "_" + blockNameSafe); setCreativeTab(ChemCraft.tabChemcraft); setBlockTextureName("chemcraft:" + blockTexture); setHarvestLevel("pickaxe", 1); setHardness(5F); } }
gpl-2.0
TomasJuocepis/CS342-ChatApp
src/cs342/Chat/GUI/custom/ChatArea.java
3081
package cs342.Chat.GUI.custom; import javax.swing.*; import javax.swing.border.LineBorder; import javax.swing.text.*; import java.awt.*; import java.util.HashMap; public class ChatArea { private ChatPane cstmPane; private JScrollBar vertical; public final JScrollPane SCROLL_PANE; private HashMap<String, StyledDocument> CONVO_TO_DOC; public ChatArea() { SCROLL_PANE = new JScrollPane(); CONVO_TO_DOC = new HashMap<String, StyledDocument>(); cstmPane = new ChatPane(); SCROLL_PANE.setViewportBorder(new LineBorder(new Color(0, 0, 0))); SCROLL_PANE.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); SCROLL_PANE.setViewportView(cstmPane); vertical = SCROLL_PANE.getVerticalScrollBar(); } public void showChat(String entry) { cstmPane.doc = CONVO_TO_DOC.get(entry); cstmPane.setStyledDocument(cstmPane.doc); } public void createNewChat(String convo) { CONVO_TO_DOC.put(convo, new DefaultStyledDocument()); } public void removeChat(String convo) { CONVO_TO_DOC.remove(convo); } public void clientPrint(String line, String who, String where) { cstmPane.doc = CONVO_TO_DOC.get(where); cstmPane.clientPrint(line, who); setScrollBarMinimum(); } public void serverPrint(String line, String who, String where) { cstmPane.doc = CONVO_TO_DOC.get(where); cstmPane.serverPrint(line, who); setScrollBarMinimum(); } private void setScrollBarMinimum() { vertical.setValue( vertical.getMinimum()); } private class ChatPane extends JTextPane { private static final long serialVersionUID = 1L; private StyledDocument doc; private Style style; private SimpleAttributeSet align; private Color BACKGROUND = new Color(47, 79, 79); private Color CLIENT_COLOR = new Color(255, 69, 0); private Color SERVER_COLOR = new Color(0, 69, 255).brighter(); private Insets MARGINS = new Insets(5, 5, 5, 5); private String FONT_NAME = "Calibri"; private int FONT_SIZE = 16; private ChatPane() { super(); super.setEditorKit(new WrapEditorKit()); super.setEditable(false); super.setBackground(BACKGROUND); super.setMargin(MARGINS); style = this.addStyle("STYLE", null); align = new SimpleAttributeSet(); StyleConstants.setFontFamily(style, FONT_NAME); StyleConstants.setFontSize(style, FONT_SIZE); StyleConstants.setBold(style, true); } private void clientPrint(String line, String who) { StyleConstants.setAlignment(align, StyleConstants.ALIGN_RIGHT); StyleConstants.setForeground(style, CLIENT_COLOR); print(line + "\n"); } private void serverPrint(String line, String who) { StyleConstants.setAlignment(align, StyleConstants.ALIGN_LEFT); StyleConstants.setForeground(style, SERVER_COLOR.brighter()); print(who + ": "); StyleConstants.setForeground(style, SERVER_COLOR); print(line + "\n"); } private void print(String line) { try { doc.setParagraphAttributes(doc.getLength(), line.length(), align, false); doc.insertString(doc.getLength(), line, style); } catch (BadLocationException e) { } } } }
gpl-2.0
angryip/ipscan
src/net/azib/ipscan/gui/MainWindow.java
8737
/* This file is a part of Angry IP Scanner source code, see http://www.angryip.org/ for more information. Licensed under GPLv2. */ package net.azib.ipscan.gui; import net.azib.ipscan.config.GUIConfig; import net.azib.ipscan.config.Labels; import net.azib.ipscan.config.Platform; import net.azib.ipscan.config.Version; import net.azib.ipscan.core.state.ScanningState; import net.azib.ipscan.core.state.StateMachine; import net.azib.ipscan.core.state.StateMachine.Transition; import net.azib.ipscan.core.state.StateTransitionListener; import net.azib.ipscan.gui.actions.StartStopScanningAction; import net.azib.ipscan.gui.actions.ToolsActions; import net.azib.ipscan.gui.feeders.ControlsArea; import net.azib.ipscan.gui.feeders.FeederArea; import net.azib.ipscan.gui.feeders.FeederGUIRegistry; import net.azib.ipscan.gui.feeders.FeederSelectionCombo; import net.azib.ipscan.gui.menu.ResultsContextMenu; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import static net.azib.ipscan.gui.util.LayoutHelper.formData; import static net.azib.ipscan.gui.util.LayoutHelper.icon; /** * Main window of Angry IP Scanner. * Contains the menu, IP resultTable, status bar (with progress bar) and * a Composite area, which can be substituted dynamically based on * the selected feeder. * * @author Anton Keks */ public class MainWindow { private final Shell shell; private final GUIConfig guiConfig; private Composite feederArea; private Button startStopButton; private Combo feederSelectionCombo; private FeederGUIRegistry feederRegistry; private StatusBar statusBar; private ToolBar prefsButton; private ToolBar fetchersButton; /** * Creates and initializes the main window. */ public MainWindow(Shell shell, GUIConfig guiConfig, FeederArea feederArea, ControlsArea controlsArea, FeederSelectionCombo feederSelectionCombo, Button startStopButton, StartStopScanningAction startStopScanningAction, ResultTable resultTable, StatusBar statusBar, ResultsContextMenu resultsContextMenu, FeederGUIRegistry feederGUIRegistry, final StateMachine stateMachine, ToolsActions.Preferences preferencesListener, ToolsActions.ChooseFetchers chooseFetchersListener, MainMenu menuBar /* don't delete: initiates main menu creation */ ) { this.shell = shell; this.guiConfig = guiConfig; this.statusBar = statusBar; initShell(shell); initFeederArea(feederArea, feederGUIRegistry); initControlsArea(controlsArea, feederSelectionCombo, startStopButton, startStopScanningAction, preferencesListener, chooseFetchersListener); initTableAndStatusBar(resultTable, resultsContextMenu, statusBar); // after all controls are initialized, resize and open shell.setSize(guiConfig.getMainWindowSize()); shell.open(); if (guiConfig.isMainWindowMaximized) { shell.setMaximized(true); } stateMachine.addTransitionListener(new EnablerDisabler()); Display.getCurrent().asyncExec(() -> { // asynchronously run init handlers outside of the constructor stateMachine.init(); }); } /** * This method initializes shell */ private void initShell(final Shell shell) { shell.setLayout(new FormLayout()); // load and set icon Image image = new Image(shell.getDisplay(), getClass().getResourceAsStream("/images/icon.png")); shell.setImage(image); shell.addListener(SWT.Close, event -> { // save dimensions! guiConfig.setMainWindowSize(shell.getSize(), shell.getMaximized()); }); } /** * @return the underlying shell, used by the Main class */ public Shell getShell() { return shell; } /** * @return true if the underlying shell is disposed */ public boolean isDisposed() { return shell.isDisposed(); } /** * This method initializes resultTable */ private void initTableAndStatusBar(ResultTable resultTable, Menu resultsContextMenu, StatusBar statusBar) { resultTable.setLayoutData(formData(new FormAttachment(0), new FormAttachment(100), new FormAttachment(feederArea), new FormAttachment(statusBar.getComposite()))); resultTable.setMenu(resultsContextMenu); } private void initFeederArea(Composite feederArea, FeederGUIRegistry feederRegistry) { // feederArea is the placeholder for the visible feeder this.feederArea = feederArea; feederArea.setLayoutData(formData(new FormAttachment(0), null, new FormAttachment(0), null)); this.feederRegistry = feederRegistry; } /** * This method initializes main controls of the main window */ private void initControlsArea(Composite controlsArea, Combo feederSelectionCombo, Button startStopButton, StartStopScanningAction startStopScanningAction, ToolsActions.Preferences preferencesListener, ToolsActions.ChooseFetchers chooseFetchersListsner) { controlsArea.setLayoutData(formData(new FormAttachment(feederArea), null, new FormAttachment(0), new FormAttachment(feederArea, 0, SWT.BOTTOM))); // start/stop button this.startStopButton = startStopButton; shell.setDefaultButton(startStopButton); startStopButton.pack(); startStopButton.addSelectionListener(startStopScanningAction); startStopButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // feeder selection combobox this.feederSelectionCombo = feederSelectionCombo; feederSelectionCombo.pack(); IPFeederSelectionListener feederSelectionListener = new IPFeederSelectionListener(); feederSelectionCombo.addSelectionListener(feederSelectionListener); // initialize the selected feeder GUI feederSelectionCombo.select(guiConfig.activeFeeder); feederSelectionCombo.setToolTipText(Labels.getLabel("combobox.feeder.tooltip")); // traverse the button before the combo (and don't traverse other buttons at all) controlsArea.setTabList(new Control[] {startStopButton, feederSelectionCombo}); prefsButton = createToolbarButton(controlsArea); ToolItem item = new ToolItem(prefsButton, SWT.PUSH); item.setImage(icon("buttons/prefs")); item.setToolTipText(Labels.getLabel("title.preferences")); item.addListener(SWT.Selection, preferencesListener); fetchersButton = createToolbarButton(controlsArea); item = new ToolItem(fetchersButton, SWT.PUSH); item.setImage(icon("buttons/fetchers")); item.setToolTipText(Labels.getLabel("title.fetchers")); item.addListener(SWT.Selection, chooseFetchersListsner); feederSelectionListener.widgetSelected(null); } private ToolBar createToolbarButton(Composite controlsArea) { ToolBar bar = new ToolBar(controlsArea, SWT.FLAT); bar.setCursor(bar.getDisplay().getSystemCursor(SWT.CURSOR_HAND)); return bar; } private void relayoutControls() { Point feederSize = feederRegistry.current().getSize(); Point buttonSize = startStopButton.getSize(); Point comboSize = feederSelectionCombo.getSize(); int sizeDiff = feederSize.y - buttonSize.y - comboSize.y; if (sizeDiff >= 0) { GridLayout layout = new GridLayout(2, false); layout.verticalSpacing = Platform.MAC_OS && sizeDiff == 11 ? 1 : sizeDiff / 3; startStopButton.getParent().setLayout(layout); prefsButton.moveAbove(startStopButton); } else { startStopButton.getParent().setLayout(new GridLayout(4, false)); startStopButton.moveAbove(prefsButton); } } /** * IP Feeder selection listener. Updates the GUI according to the IP Feeder selection. */ class IPFeederSelectionListener extends SelectionAdapter { public void widgetSelected(SelectionEvent e) { feederRegistry.select(feederSelectionCombo.getSelectionIndex()); // all this 'magic' is needed in order to resize everything properly // and accommodate feeders with different sizes Rectangle bounds = feederRegistry.current().getBounds(); FormData feederAreaLayoutData = ((FormData)feederArea.getLayoutData()); feederAreaLayoutData.height = bounds.height; feederAreaLayoutData.width = bounds.width; relayoutControls(); shell.layout(); // reset main window title shell.setText(feederRegistry.current().getFeederName() + " - " + Version.NAME); } } class EnablerDisabler implements StateTransitionListener { public void transitionTo(final ScanningState state, Transition transition) { if (transition != Transition.START && transition != Transition.COMPLETE) return; boolean enabled = state == ScanningState.IDLE; feederArea.setEnabled(enabled); feederSelectionCombo.setEnabled(enabled); prefsButton.setEnabled(enabled); fetchersButton.setEnabled(enabled); statusBar.setEnabled(enabled); } } }
gpl-2.0
jackvt93/T3-Project--Tic---Tac---Toe-Game-Online-
T3Project/T3Server/src/com/t3/server/database/businesslogic/UserHelper.java
4019
package com.t3.server.database.businesslogic; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.t3.server.database.entities.User; public class UserHelper { public final static int CREATE_USER_SUCCESS = 0x0001; public final static int CREATE_USER_EXISTED = 0x0002; public final static int CREATE_USER_FAIL = 0x0003; private final static String TABLE_NAME = "User"; private final static String NAME = "Name"; private final static String RATING = "Rating"; private final static String WINS = "Wins"; private final static String LOSES = "Loses"; private final static String DRAWS = "Draws"; private final static String AID = "AID"; private Connection conn; public UserHelper() throws Exception { conn = ConnectionFactory.getInstance(); } /** * @param accountId : need for get user * @return database user object * @throws SQLException */ public User getUser(int accountId) throws SQLException { String sql = "SELECT TOP(1) * FROM [" + TABLE_NAME + "] WHERE " + AID + " = ?"; PreparedStatement statement = conn.prepareStatement(sql); statement.setInt(1, accountId); ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return new User(resultSet.getString(NAME), resultSet.getInt(RATING), resultSet.getInt(WINS), resultSet.getInt(LOSES), resultSet.getInt(DRAWS), resultSet.getInt(AID)); } return null; } public User getUser(String username) throws SQLException { String sql = "SELECT TOP(1) * FROM [" + TABLE_NAME + "] WHERE " + NAME + " LIKE ?"; PreparedStatement statement = conn.prepareStatement(sql); statement.setString(1, username); ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return new User(resultSet.getString(NAME), resultSet.getInt(RATING), resultSet.getInt(WINS), resultSet.getInt(LOSES), resultSet.getInt(DRAWS), resultSet.getInt(AID)); } return null; } /** * This method for get common user for send from server to client * @param accountId * @return * @throws SQLException */ public com.t3.common.models.User getCommonUser(int accountId) throws SQLException { String sql = "SELECT TOP(1) * FROM [" + TABLE_NAME + "] WHERE " + AID + " = ?"; PreparedStatement statement = conn.prepareStatement(sql); statement.setInt(1, accountId); ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { return new com.t3.common.models.User(resultSet.getString(NAME), resultSet.getInt(RATING), resultSet.getInt(WINS), resultSet.getInt(LOSES), resultSet.getInt(DRAWS)); } return null; } /** * @param user object need to create new * @return true if create success, false if create fail * @throws SQLException */ public int create(User user) throws SQLException { if (getUser(user.getName()) != null) { return CREATE_USER_EXISTED; } String sql = "INSERT INTO [" + TABLE_NAME + "]" + " ([" + NAME + "], [" + AID + "])" + " VALUES (?, ?)"; PreparedStatement statement = conn.prepareStatement(sql); statement.setString(1, user.getName()); statement.setInt(2, user.getAid()); return (statement.executeUpdate() > 0) ? CREATE_USER_SUCCESS : CREATE_USER_FAIL; } public boolean update(com.t3.common.models.User user) throws SQLException { String sql = "UPDATE [" + TABLE_NAME + "] SET " + RATING + " = ?, " + WINS + " = ?, " + LOSES + " = ?, " + DRAWS + " = ? WHERE " + NAME + " LIKE ?"; PreparedStatement statement = conn.prepareStatement(sql); statement.setInt(1, user.getRating()); statement.setInt(2, user.getWins()); statement.setInt(3, user.getLoses()); statement.setInt(4, user.getDraws()); statement.setString(5, user.getName()); return statement.executeUpdate() > 0; } }
gpl-2.0
rampage128/hombot-control
mobile/src/main/java/de/jlab/android/hombot/sections/JoySection.java
8519
package de.jlab.android.hombot.sections; import android.content.SharedPreferences; import android.graphics.PorterDuff; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import de.jlab.android.hombot.R; import de.jlab.android.hombot.SectionFragment; import de.jlab.android.hombot.SettingsActivity; import de.jlab.android.hombot.common.settings.SharedSettings; import de.jlab.android.hombot.core.HttpRequestEngine; import de.jlab.android.hombot.common.utils.JoyTouchListener; import de.jlab.android.hombot.utils.Colorizer; /** * A {@link SectionFragment} subclass. * Activities that contain this fragment must implement the * {@link SectionFragment.SectionInteractionListener} interface * to handle interaction events. * Use the {@link JoySection#newInstance} factory method to * create an instance of this fragment. */ public class JoySection extends SectionFragment { private static class ViewHolder { Button commandMySpace; Button commandSpiral; Button commandTurbo; Button commandHome; View joy; TextView joyLabel; } private ViewHolder mViewHolder; public static JoySection newInstance(int sectionNumber) { JoySection fragment = new JoySection(); fragment.register(sectionNumber); return fragment; } private class InstaCleanHandler extends Handler { public static final int SPIRAL = 1; private boolean mInsta; public InstaCleanHandler(boolean insta) { mInsta = insta; } public void handleMessage(Message msg) { switch (msg.what) { case 1: sendCommand(HttpRequestEngine.Command.MODE_SPIRAL); if (mInsta) { try { Thread.sleep(1500); } catch (InterruptedException ignored) {} sendCommand(HttpRequestEngine.Command.START); } } } } private InstaCleanHandler mInstaCleanHandler; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment final View view = inflater.inflate(R.layout.fragment_section_joy, container, false); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mInstaCleanHandler = new InstaCleanHandler(sp.getBoolean(SettingsActivity.PREF_JOY_INSTACLEAN, false)); mViewHolder = new ViewHolder(); mViewHolder.commandMySpace = (Button) view.findViewById(R.id.cm_mode_myspace); mViewHolder.commandSpiral = (Button) view.findViewById(R.id.cm_mode_spiral); mViewHolder.commandTurbo = (Button) view.findViewById(R.id.cm_turbo); mViewHolder.commandHome = (Button) view.findViewById(R.id.cm_home); mViewHolder.joy = view.findViewById(R.id.ct_joy); mViewHolder.joyLabel = (TextView)view.findViewById(R.id.ct_joy_label); mViewHolder.commandMySpace.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { sendCommand(HttpRequestEngine.Command.MODE_MYSPACE); } }); mViewHolder.commandSpiral.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (!mInstaCleanHandler.hasMessages(InstaCleanHandler.SPIRAL)) { mInstaCleanHandler.sendEmptyMessage(InstaCleanHandler.SPIRAL); } } }); mViewHolder.commandTurbo.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { sendCommand(HttpRequestEngine.Command.TURBO); } }); mViewHolder.commandHome.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { sendCommand(HttpRequestEngine.Command.HOME); } }); int intervalDrive = Integer.parseInt(sp.getString(SharedSettings.PREF_JOY_INTERVAL_DRIVE, "800")); int intervalTurn = Integer.parseInt(sp.getString(SharedSettings.PREF_JOY_INTERVAL_TURN, "800")); mViewHolder.joy.setOnTouchListener(new JoyTouchListener(intervalDrive, intervalTurn, new JoyTouchListener.PushListener[]{ new JoyTouchListener.PushListener() { @Override public void onPush() { sendCommand(HttpRequestEngine.Command.JOY_FORWARD); Log.d("MOT", "F"); } @Override public void onRelease() { sendCommand(HttpRequestEngine.Command.JOY_RELEASE); Log.d("MOT", "-"); } }, new JoyTouchListener.PushListener() { @Override public void onPush() { sendCommand(HttpRequestEngine.Command.JOY_RIGHT); Log.d("MOT", "R"); } @Override public void onRelease() { sendCommand(HttpRequestEngine.Command.JOY_RELEASE); Log.d("MOT", "-"); } }, new JoyTouchListener.PushListener() { @Override public void onPush() { sendCommand(HttpRequestEngine.Command.JOY_BACK); Log.d("MOT", "B"); } @Override public void onRelease() { sendCommand(HttpRequestEngine.Command.JOY_RELEASE); Log.d("MOT", "-"); } }, new JoyTouchListener.PushListener() { @Override public void onPush() { sendCommand(HttpRequestEngine.Command.JOY_LEFT); Log.d("MOT", "L"); } @Override public void onRelease() { sendCommand(HttpRequestEngine.Command.JOY_RELEASE); Log.d("MOT", "-"); } }, new JoyTouchListener.PushListener() { @Override public void onPush() { sendCommand(HttpRequestEngine.Command.PAUSE); Log.d("MOT", "P"); } @Override public void onRelease() { /* NO RELEASE FOR CENTER COMMAND */ } } })); // MAKE JOYPAD "SQUARE" ACCORDING TO THE SMALLER AVAILABLE DIMENSION FIXME BUGGY ON ORIENTATION CHANGE if (mViewHolder.joy.getViewTreeObserver().isAlive()) { mViewHolder.joy.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int finalSize = Math.min(mViewHolder.joy.getMeasuredWidth(), mViewHolder.joy.getMeasuredHeight()); mViewHolder.joy.setLayoutParams(new RelativeLayout.LayoutParams(finalSize, finalSize)); view.invalidate(); } }); } return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Colorizer colorizer = getColorizer(); int textColor = colorizer.getColorText(); colorizer.colorizeButton(mViewHolder.commandHome, textColor); colorizer.colorizeButton(mViewHolder.commandSpiral, textColor); colorizer.colorizeButton(mViewHolder.commandMySpace, textColor); colorizer.colorizeButton(mViewHolder.commandTurbo, textColor); mViewHolder.joy.getBackground().setColorFilter(textColor, PorterDuff.Mode.SRC_ATOP); mViewHolder.joyLabel.setTextColor(textColor); } }
gpl-2.0
ppartida/com.fifino.gptw
src/main/java/com/fifino/gptw/screens/LoadingScreen.java
2852
package com.fifino.gptw.screens; import android.graphics.Point; import com.fifino.framework.assets.Assets; import com.fifino.framework.entities.MenuItem; import com.fifino.gptw.flags.AutoRun; import com.fifino.gptw.helpers.GPTWResources; import com.kilobolt.framework.Game; import com.kilobolt.framework.Graphics; import com.kilobolt.framework.Image; import com.kilobolt.framework.Input.TouchEvent; import com.kilobolt.framework.implementation.AndroidImage; import java.util.HashMap; import java.util.List; import java.util.Set; public class LoadingScreen extends GPTWScreen implements AutoRun { boolean doneLoading = false; public LoadingScreen(Game game) { super(game); this.state = GameState.Running; } Point last = null; @Override protected void drawRunningUI(List<TouchEvent> touchEvents, float deltaTime){ Graphics g = game.getGraphics(); loadingScreen.draw(g); if(last != null){ g.drawCircle(last.x, last.y, 50, paintB); } } @Override protected void updateRunning(List<TouchEvent> touchEvents, float deltaTime) { int len = touchEvents.size(); TouchEvent event = null; if (len > 0) { for (int i = 0; i < len; i++) { if (touchEvents.size() < len) { // Handles out of bounds exception for the list getting empty // after getting the size. return; } event = touchEvents.get(i); last = new Point(event.x, event.y); // if (event.type == TouchEvent.TOUCH_DOWN) { // state = GameState.GameOver; // } } } if(!doneLoading){ doneLoading = true; loadMenuScreen(); } } private void loadMenuScreen(){ this.state = GameState.Paused; MainMenu menuScreen = new MainMenu(game); this.game.setScreen(menuScreen); } /** * Initializes the main loading screen asset. */ @Override protected void initializeAssets() { Graphics g = game.getGraphics(); String key = "loading"; if(Assets.getImage(key) == null){ Image bgImage = g.newImage(Assets.IMAGES_PATH + "/loading.png", Graphics.ImageFormat.RGB565); Assets.addImage(key, bgImage); } } MenuItem loadingScreen; @Override protected void setupEntities() { AndroidImage image = Assets.getAndroidImage("loading"); loadingScreen = new MenuItem(image, 0, 0); doneLoading = false; } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { } @Override public void backButton() { System.exit(0); } }
gpl-2.0
SRF-Consulting/NDOR-IRIS
src/us/mn/state/dot/tms/server/comm/ntcip/OpUpdateDMSBrightness.java
4901
/* * IRIS -- Intelligent Roadway Information System * Copyright (C) 2008-2015 Minnesota Department of Transportation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package us.mn.state.dot.tms.server.comm.ntcip; import java.io.IOException; import java.util.LinkedList; import java.util.List; import us.mn.state.dot.tms.EventType; import us.mn.state.dot.tms.server.DMSImpl; import us.mn.state.dot.tms.server.comm.CommMessage; import us.mn.state.dot.tms.server.comm.PriorityLevel; import us.mn.state.dot.tms.server.comm.ntcip.mib1203.*; import static us.mn.state.dot.tms.server.comm.ntcip.mib1203.MIB1203.*; import us.mn.state.dot.tms.server.comm.snmp.ASN1Enum; import us.mn.state.dot.tms.server.comm.snmp.ASN1Integer; /** * Operation to incorporate brightness feedback for a DMS. * * @author Douglas Lau */ public class OpUpdateDMSBrightness extends OpDMS { /** Event type (DMS_BRIGHT_GOOD, DMS_BRIGHT_LOW or DMS_BRIGHT_HIGH) */ private final EventType event_type; /** Illumination control */ private final ASN1Enum<DmsIllumControl> control = new ASN1Enum<DmsIllumControl>(DmsIllumControl.class, dmsIllumControl.node); /** Maximum photocell level */ private final ASN1Integer max_level = dmsIllumMaxPhotocellLevel.makeInt(); /** Photocell level status */ private final ASN1Integer p_level = dmsIllumPhotocellLevelStatus.makeInt(); /** Light output status */ private final ASN1Integer light = dmsIllumLightOutputStatus.makeInt(); /** Total number of supported brightness levels */ private final ASN1Integer b_levels = dmsIllumNumBrightLevels.makeInt(); /** Brightness table */ private final DmsIllumBrightnessValues brightness = new DmsIllumBrightnessValues(); /** Create a new DMS brightness feedback operation */ public OpUpdateDMSBrightness(DMSImpl d, EventType et) { super(PriorityLevel.COMMAND, d); event_type = et; } /** Create the second phase of the operation */ @Override protected Phase phaseTwo() { return new QueryBrightness(); } /** Phase to query the brightness status */ protected class QueryBrightness extends Phase { /** Query the DMS brightness status */ protected Phase poll(CommMessage mess) throws IOException { mess.add(max_level); mess.add(p_level); mess.add(light); mess.queryProps(); logQuery(max_level); logQuery(p_level); logQuery(light); dms.feedbackBrightness(event_type, p_level.getInteger(), light.getInteger()); return new QueryBrightnessTable(); } } /** Phase to get the brightness table */ protected class QueryBrightnessTable extends Phase { /** Get the brightness table */ protected Phase poll(CommMessage mess) throws IOException { mess.add(b_levels); mess.add(brightness); mess.add(control); mess.queryProps(); logQuery(b_levels); logQuery(brightness); logQuery(control); if (control.getEnum() == DmsIllumControl.photocell) return new SetManualControl(); else return new SetBrightnessTable(); } } /** Phase to set manual control mode */ protected class SetManualControl extends Phase { /** Set the manual control mode */ protected Phase poll(CommMessage mess) throws IOException { control.setEnum(DmsIllumControl.manual); mess.add(control); logStore(control); mess.storeProps(); return new SetBrightnessTable(); } } /** Phase to set a new brightness table */ protected class SetBrightnessTable extends Phase { /** Set the brightness table */ protected Phase poll(CommMessage mess) throws IOException { // NOTE: if the existing table is not valid, don't mess // with it. This check is needed for a certain // vendor, which has a wacky brightness table. if (brightness.isValid()) { brightness.setTable(calculateTable()); mess.add(brightness); logStore(brightness); mess.storeProps(); } return new SetPhotocellControl(); } } /** Calculate a new brightness table */ private BrightnessLevel[] calculateTable() { BrightnessLevel[] table = brightness.getTable(); dms.queryBrightnessFeedback(new BrightnessTable(table)); return table; } /** Phase to set photocell control mode */ protected class SetPhotocellControl extends Phase { /** Set the photocell control mode */ protected Phase poll(CommMessage mess) throws IOException { control.setEnum(DmsIllumControl.photocell); mess.add(control); logStore(control); mess.storeProps(); return null; } } }
gpl-2.0
ireyoner/SensorDataAquisitor
src/project/devices/Device.java
193
package project.devices; public abstract class Device { protected String name; public Device(String name){ this.name = name; } public String getName(){ return name; } }
gpl-2.0
CrazyDude1994/android-navigation-handler
app/src/main/java/com/crazydude/navigationhandlerdemo/fragments/ThirdFragment.java
3525
package com.crazydude.navigationhandlerdemo.fragments; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.crazydude.navigationhandlerdemo.R; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link ThirdFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link ThirdFragment#newInstance} factory method to * create an instance of this fragment. */ public class ThirdFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FirstFragment. */ // TODO: Rename and change types and number of parameters public static ThirdFragment newInstance(String param1, String param2) { ThirdFragment fragment = new ThirdFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public ThirdFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } setRetainInstance(true); Log.d("Lifecycle", "Created 3 fragment"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_third, container, false); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onDestroy() { super.onDestroy(); Log.d("Lifecycle", "Destroyed 3 fragment"); } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Uri uri); } }
gpl-2.0
joezxh/DATAX-UI
eshbase-proxy/src/main/java/com/github/eswrapper/model/MonitorLogDetail.java
7024
package com.github.eswrapper.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.guess.core.orm.IdEntity; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * 监控记录明细Entity * @author Joe.zhang * @version 2016-08-05 */ @Entity @Table(name = "es_monitor_log_detail") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class MonitorLogDetail extends IdEntity { /** * 集群名 */ @Column(name = "cluster_name") private String clusterName; /** * 接点 */ @Column(name = "node") private String node; /** * 成功次数 */ @Column(name = "success_count") private Long successCount; /** * 成功TPS */ @Column(name = "success_tps") private float successTps; /** * 失败次数 */ @Column(name = "failure_count") private Long failureCount; /** * 失败Tps */ @Column(name = "failure_tps") private float failureTps; /** * 线程池最小值 */ @Column(name = "concurrent_min") private Long concurrentMin; /** * 线程池平均值 */ @Column(name = "concurrent_ave") private float concurrentAve; /** * 线程池最大值 */ @Column(name = "concurrent_max") private Long concurrentMax; /** * logId */ @Column(name = "log_id",insertable=false,updatable=false) private Long logId; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "log_id") @NotFound(action = NotFoundAction.IGNORE) @JsonIgnoreProperties(value = { "creater","updater","logDetails"}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private MonitorLog log; @Column(name = "elapsed_min") private Long elapsedMin; /** * 耗时平均值 */ @Column(name = "elapsed_ave") private float elapsedAve; /** * 耗时最大值 */ @Column(name = "elapsed_max") private Long elapsedMax; @Column(name = "writequeue_min") private Long writequeueMin; /** * 写入队列平均值 */ @Column(name = "writequeue_ave") private float writequeueAve; /** * 写入队列最大值 */ @Column(name = "writequeue_max") private Long writequeueMax; @Column(name = "writepool_min") private Long writepoolMin; /** * 写入队列平均值 */ @Column(name = "writepool_ave") private float writepoolAve; /** * 写入队列最大值 */ @Column(name = "writepool_max") private Long writepoolMax; @Column(name = "searchqueue_min") private Long searchqueueMin; /** * 写入队列平均值 */ @Column(name = "searchqueue_ave") private float searchqueueAve; /** * 写入队列最大值 */ @Column(name = "searchqueue_max") private Long searchqueueMax; @Column(name = "searchpool_min") private Long searchpoolMin; /** * 写入队列平均值 */ @Column(name = "searchpool_ave") private float searchpoolAve; /** * 写入队列最大值 */ @Column(name = "searchpool_max") private Long searchpoolMax; public MonitorLog getLog() { return log; } public void setLog(MonitorLog log) { this.log = log; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public Long getElapsedMin() { return elapsedMin; } public void setElapsedMin(Long elapsedMin) { this.elapsedMin = elapsedMin; } public float getElapsedAve() { return elapsedAve; } public void setElapsedAve(float elapsedAve) { this.elapsedAve = elapsedAve; } public Long getElapsedMax() { return elapsedMax; } public void setElapsedMax(Long elapsedMax) { this.elapsedMax = elapsedMax; } public Long getWritequeueMin() { return writequeueMin; } public void setWritequeueMin(Long writequeueMin) { this.writequeueMin = writequeueMin; } public float getWritequeueAve() { return writequeueAve; } public void setWritequeueAve(float writequeueAve) { this.writequeueAve = writequeueAve; } public Long getWritequeueMax() { return writequeueMax; } public void setWritequeueMax(Long writequeueMax) { this.writequeueMax = writequeueMax; } public Long getWritepoolMin() { return writepoolMin; } public void setWritepoolMin(Long writepoolMin) { this.writepoolMin = writepoolMin; } public float getWritepoolAve() { return writepoolAve; } public void setWritepoolAve(float writepoolAve) { this.writepoolAve = writepoolAve; } public Long getWritepoolMax() { return writepoolMax; } public void setWritepoolMax(Long writepoolMax) { this.writepoolMax = writepoolMax; } public Long getSearchqueueMin() { return searchqueueMin; } public void setSearchqueueMin(Long searchqueueMin) { this.searchqueueMin = searchqueueMin; } public float getSearchqueueAve() { return searchqueueAve; } public void setSearchqueueAve(float searchqueueAve) { this.searchqueueAve = searchqueueAve; } public Long getSearchqueueMax() { return searchqueueMax; } public void setSearchqueueMax(Long searchqueueMax) { this.searchqueueMax = searchqueueMax; } public Long getSearchpoolMin() { return searchpoolMin; } public void setSearchpoolMin(Long searchpoolMin) { this.searchpoolMin = searchpoolMin; } public float getSearchpoolAve() { return searchpoolAve; } public void setSearchpoolAve(float searchpoolAve) { this.searchpoolAve = searchpoolAve; } public Long getSearchpoolMax() { return searchpoolMax; } public void setSearchpoolMax(Long searchpoolMax) { this.searchpoolMax = searchpoolMax; } public String getNode() { return node; } public void setNode(String node) { this.node = node; } public Long getSuccessCount() { return successCount; } public void setSuccessCount(Long successCount) { this.successCount = successCount; } public float getSuccessTps() { return successTps; } public void setSuccessTps(float successTps) { this.successTps = successTps; } public Long getFailureCount() { return failureCount; } public void setFailureCount(Long failureCount) { this.failureCount = failureCount; } public float getFailureTps() { return failureTps; } public void setFailureTps(float failureTps) { this.failureTps = failureTps; } public Long getConcurrentMin() { return concurrentMin; } public void setConcurrentMin(Long concurrentMin) { this.concurrentMin = concurrentMin; } public float getConcurrentAve() { return concurrentAve; } public void setConcurrentAve(float concurrentAve) { this.concurrentAve = concurrentAve; } public Long getConcurrentMax() { return concurrentMax; } public void setConcurrentMax(Long concurrentMax) { this.concurrentMax = concurrentMax; } public Long getLogId() { return logId; } public void setLogId(Long logId) { this.logId = logId; } }
gpl-2.0
JesusOrtegaVilchez/JAVA
Ejercicio_Herencia/Principal.java
822
/** * @author jesus * */ public class Principal { public static void main(String[] args) { Persona alumno1 = new Alumno("03181199T","Jesus","Ortega Vilchez",true,true,8); Persona profesor1 = new Profesor("0156478M","Jose Carlos","Villar",true,false,1500.50); Persona profesorFP1 = new ProfesorFP("02314566G","Javier","Olmedo Garcia",true,false,7); Persona profesorESO1 = new ProfesorESO("02415874M","Jose Luis","Fernandez Pérez",true,false,"Informatica"); System.out.println("DATOS: "+alumno1.toString()); System.out.println("Es miembro? "+alumno1.esMiembro()); System.out.println("DATOS: "+profesor1.toString()); System.out.println("Es miembro? "+profesor1.esMiembro()); System.out.println("DATOS: "+profesorFP1.toString()); System.out.println("DATOS: "+profesorESO1.toString()); } }
gpl-2.0
GITNE/icedtea-web
tests/reproducers/simple/AllStackTraces/testcases/AllStackTracesTest.java
2595
/* AllStackTracesTest.java Copyright (C) 2011 Red Hat, Inc. This file is part of IcedTea. IcedTea 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. IcedTea 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 IcedTea; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ import net.sourceforge.jnlp.ProcessResult; import net.sourceforge.jnlp.ServerAccess; import org.junit.Assert; import org.junit.Test; public class AllStackTracesTest { private static final ServerAccess server = new ServerAccess(); @Test public void AllStackTracesTest1() throws Exception { ProcessResult pr=server.executeJavawsHeadless(null,"/AllStackTraces.jnlp"); String c = "(?s).*java.security.AccessControlException.{0,5}access denied.{0,5}java.lang.RuntimePermission.{0,5}" + "getStackTrace" + ".*"; Assert.assertTrue("stderr should match `"+c+"`, but didn't ",pr.stderr.matches(c)); String cc="ClassNotFoundException"; Assert.assertFalse("stderr should NOT contains `"+cc+"`, but did ",pr.stderr.contains(cc)); Assert.assertFalse("AllStackTracesTest1 should not be terminated, but was",pr.wasTerminated); Assert.assertEquals((Integer)1, pr.returnValue); } }
gpl-2.0
UnboundID/ldapsdk
tests/unit/src/com/unboundid/util/ssl/cert/SubjectAlternativeNameExtensionTestCase.java
7738
/* * Copyright 2017-2020 Ping Identity Corporation * All Rights Reserved. */ /* * Copyright 2017-2020 Ping Identity Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2017-2020 Ping Identity Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (GPLv2 only) * or the terms of the GNU Lesser General Public License (LGPLv2.1 only) * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. */ package com.unboundid.util.ssl.cert; import java.net.InetAddress; import org.testng.annotations.Test; import com.unboundid.asn1.ASN1OctetString; import com.unboundid.ldap.sdk.DN; import com.unboundid.ldap.sdk.LDAPSDKTestCase; import com.unboundid.util.OID; /** * This class provides a set of test cases for the * SubjectAlternativeNameExtension class. */ public final class SubjectAlternativeNameExtensionTestCase extends LDAPSDKTestCase { /** * Tests a subject alternative name extension with just a single DNS name. * * @throws Exception If an unexpected problem occurs. */ @Test() public void testSingleDNSName() throws Exception { SubjectAlternativeNameExtension e = new SubjectAlternativeNameExtension( false, new GeneralNamesBuilder().addDNSName("ldap.example.com").build()); e = new SubjectAlternativeNameExtension(e); assertNotNull(e.getOID()); assertEquals(e.getOID().toString(), "2.5.29.17"); assertFalse(e.isCritical()); assertNotNull(e.getValue()); assertNotNull(e.getGeneralNames()); assertNotNull(e.getOtherNames()); assertTrue(e.getOtherNames().isEmpty()); assertNotNull(e.getRFC822Names()); assertTrue(e.getRFC822Names().isEmpty()); assertNotNull(e.getDNSNames()); assertFalse(e.getDNSNames().isEmpty()); assertNotNull(e.getX400Addresses()); assertTrue(e.getX400Addresses().isEmpty()); assertNotNull(e.getDirectoryNames()); assertTrue(e.getDirectoryNames().isEmpty()); assertNotNull(e.getEDIPartyNames()); assertTrue(e.getEDIPartyNames().isEmpty()); assertNotNull(e.getUniformResourceIdentifiers()); assertTrue(e.getUniformResourceIdentifiers().isEmpty()); assertNotNull(e.getIPAddresses()); assertTrue(e.getIPAddresses().isEmpty()); assertNotNull(e.getRegisteredIDs()); assertTrue(e.getRegisteredIDs().isEmpty()); assertNotNull(e.getExtensionName()); assertFalse(e.getExtensionName().equals("2.5.29.17")); assertNotNull(e.toString()); } /** * Tests a subject alternative name extension with multiple values for all * types of names. * * @throws Exception If an unexpected problem occurs. */ @Test() public void testMultipleValuesForAllTypesOfNames() throws Exception { final GeneralNames names = new GeneralNamesBuilder(). addOtherName(new OID("1.2.3.4"), new ASN1OctetString("otherName1")). addOtherName(new OID("1.2.3.5"), new ASN1OctetString("otherName2")). addRFC822Name("user1@example.com"). addRFC822Name("user2@example.com"). addDNSName("ldap1.example.com"). addDNSName("ldap2.example.com"). addX400Address(new ASN1OctetString("x.400Address1")). addX400Address(new ASN1OctetString("x.400Address2")). addDirectoryName(new DN("dc=example,dc=com")). addDirectoryName(new DN("o=example.com")). addEDIPartyName(new ASN1OctetString("ediPartyName1")). addEDIPartyName(new ASN1OctetString("ediPartyName2")). addUniformResourceIdentifier("ldap://ds1.example.com:389/"). addUniformResourceIdentifier("ldap://ds2.example.com:389/"). addIPAddress(InetAddress.getByName("127.0.0.1")). addIPAddress(InetAddress.getByName("::1")). addRegisteredID(new OID("1.2.3.6")). addRegisteredID(new OID("1.2.3.7")). build(); SubjectAlternativeNameExtension e = new SubjectAlternativeNameExtension(true, names); e = new SubjectAlternativeNameExtension(e); assertNotNull(e.getOID()); assertEquals(e.getOID().toString(), "2.5.29.17"); assertTrue(e.isCritical()); assertNotNull(e.getValue()); assertNotNull(e.getGeneralNames()); assertNotNull(e.getOtherNames()); assertFalse(e.getOtherNames().isEmpty()); assertNotNull(e.getRFC822Names()); assertFalse(e.getRFC822Names().isEmpty()); assertNotNull(e.getDNSNames()); assertFalse(e.getDNSNames().isEmpty()); assertNotNull(e.getX400Addresses()); assertFalse(e.getX400Addresses().isEmpty()); assertNotNull(e.getDirectoryNames()); assertFalse(e.getDirectoryNames().isEmpty()); assertNotNull(e.getEDIPartyNames()); assertFalse(e.getEDIPartyNames().isEmpty()); assertNotNull(e.getUniformResourceIdentifiers()); assertFalse(e.getUniformResourceIdentifiers().isEmpty()); assertNotNull(e.getIPAddresses()); assertFalse(e.getIPAddresses().isEmpty()); assertNotNull(e.getRegisteredIDs()); assertFalse(e.getRegisteredIDs().isEmpty()); assertNotNull(e.getExtensionName()); assertFalse(e.getExtensionName().equals("2.5.29.17")); assertNotNull(e.toString()); } /** * Tests a subject alternative name extension with an invalid OID as a * registered ID value. * * @throws Exception If an unexpected problem occurs. */ @Test(expectedExceptions = { CertException.class }) public void testInvalidRegisteredID() throws Exception { new SubjectAlternativeNameExtension(false, new GeneralNamesBuilder().addRegisteredID(new OID("1234.56")).build()); } /** * Tests the behavior when trying to decode a subject alternative name * extension from a malformed extension when using the correct OID for the * subject alternative name extension. * * @throws Exception If an unexpected problem occurs. */ @Test(expectedExceptions = { CertException.class }) public void testDecodeMalformedExtensionWithCorrectOID() throws Exception { new SubjectAlternativeNameExtension( new X509CertificateExtension(new OID("2.5.29.17"), false, "invalid value".getBytes("UTF-8"))); } /** * Tests the behavior when trying to decode a subject alternative name * extension from a malformed extension when not using the correct OID for the * subject alternative name extension. * * @throws Exception If an unexpected problem occurs. */ @Test(expectedExceptions = { CertException.class }) public void testDecodeMalformedExtensionWithIncorrectOID() throws Exception { new SubjectAlternativeNameExtension( new X509CertificateExtension(new OID("1.2.3.4"), false, "invalid value".getBytes("UTF-8"))); } }
gpl-2.0
ManWithAJawharp/kikker
core/src/nl/abevos/kikker/level/Level.java
2508
package nl.abevos.kikker.level; import nl.abevos.kikker.KikkerGame; import nl.abevos.kikker.actor.Frog; import nl.abevos.kikker.environment.Platform; import nl.abevos.kikker.environment.Wall; import nl.abevos.kikker.manager.AssetManager; import nl.abevos.kikker.manager.ContactListener; import nl.abevos.kikker.screen.GameScreen; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; import com.badlogic.gdx.physics.box2d.World; public class Level { private static World staticWorld; private static Camera staticCamera; private static Frog staticFrog; private GameScreen screen; private World world; private Box2DDebugRenderer debugRenderer; private Frog frog; private Texture texture; private Platform floor; private Platform platform1; private Platform ceiling; private Wall leftWall; private Wall rightWall; public Level (GameScreen screen) { this.screen = screen; } public void load () { world = new World(new Vector2(0, -9.8f), true); world.setContactListener(new ContactListener()); Level.staticWorld = world; Level.staticCamera = screen.getCamera(); frog = new Frog(0, 0, world); Level.staticFrog = frog; texture = AssetManager.getTexture("food"); floor = new Platform(0, - 256); platform1 = new Platform(160, -170); ceiling = new Platform(0, 256); leftWall = new Wall(- 256, 0); rightWall = new Wall(256, 0); debugRenderer = new Box2DDebugRenderer(); } public void cameraUpdate (OrthographicCamera camera) { camera.position.lerp(new Vector3(frog.getPosition().x, frog.getPosition().y, 0), camera.position.dst(frog.getPosition().x, frog.getPosition().y, 0) / 100f); } public void update (float delta) { world.step(1f / 30, 6, 4); frog.update(delta); } public void draw () { KikkerGame.batch().draw(texture, 0, 0); floor.draw(); platform1.draw(); ceiling.draw(); leftWall.draw(); rightWall.draw(); frog.draw(); } public void postDraw () { debugRenderer.render(world, getCamera().combined); } public void dispose () { world.dispose(); } public static World getWorld () { return Level.staticWorld; } public static Camera getCamera () { return Level.staticCamera; } public static Frog getFrog () { return Level.staticFrog; } }
gpl-2.0
werdnanoslen/eBusker
UI/app/src/main/java/com/example/lpeng/tiptap/StartActivity.java
2293
package com.example.lpeng.tiptap; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.TextView; import java.util.Timer; public class StartActivity extends AppCompatActivity { public void runMain() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); //setContentView(R.layout.activity_main); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start); /*Timer timer = new Timer(); timer.schedule();*/ new android.os.Handler().postDelayed( new Runnable() { public void run() { //Log.i("tag", "This'll run 3000 milliseconds later"); TextView searchingText = (TextView) findViewById(R.id.searchingText); searchingText.setVisibility(View.VISIBLE); new android.os.Handler().postDelayed( new Runnable() { public void run() { //Log.i("tag", "Again, This'll run 3000 milliseconds later"); runMain(); } }, 3000); } }, 3000); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_start, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
gpl-2.0
squallyou/LScore
src/sjy/elwg/notation/OrnamentDialog.java
6587
package sjy.elwg.notation; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; public class OrnamentDialog extends JDialog implements ActionListener{ /** * ÐòÁкŠ*/ private static final long serialVersionUID = 2647829265264720382L; /** * ´°¿Ú´óС */ private static final int DIALOG_WIDTH = 100; private static final int DIALOG_HEIGHT = 135; /** * ÑÝ×à·ûºÅÀàÐÍ */ private String symboleType = "none"; ImageIcon iconMarcato = new ImageIcon(("pic/marcato.png")); ImageIcon iconMartellatoDown = new ImageIcon(("pic/martellatoDown.png")); ImageIcon iconMartellatoUp = new ImageIcon(("pic/martellatoUp.png")); ImageIcon iconStaccato = new ImageIcon(("pic/staccato.png")); ImageIcon iconTenuto = new ImageIcon(("pic/tenuto.png")); ImageIcon iconStaccatissimoDown = new ImageIcon(("pic/staccatissimoDown.png")); ImageIcon iconStaccatissimoUp = new ImageIcon(("pic/staccatissimoUp.png")); ImageIcon iconStaccatoTenutoUp = new ImageIcon(("pic/staccatoTenutoUp.png")); ImageIcon iconStaccatoTenutoDown = new ImageIcon(("pic/staccatoTenutoDown.png")); ImageIcon iconFermata = new ImageIcon(("pic/fermata.png")); ImageIcon iconPedalStart = new ImageIcon(("pic/pedalstart.png")); ImageIcon iconPedalEnd = new ImageIcon(("pic/pedalend.png")); ImageIcon iconBreath = new ImageIcon(("pic/breath.png")); // ImageIcon iconTremoloBeam1 = new ImageIcon(("pic/TremoloBeam1.png")); // ImageIcon iconTremoloBeam2 = new ImageIcon(("pic/TremoloBeam2.png")); // ImageIcon iconTremoloBeam3 = new ImageIcon(("pic/TremoloBeam3.png")); /** * °´Å¥ */ private JButton btMarcato = new JButton(iconMarcato); private JButton btMartellatoDown = new JButton(iconMartellatoDown); private JButton btMartellatoUp = new JButton(iconMartellatoUp); private JButton btStaccato = new JButton(iconStaccato); private JButton btTenuto = new JButton(iconTenuto); private JButton btStaccatissimoDown = new JButton(iconStaccatissimoDown); private JButton btStaccatissimoUp = new JButton(iconStaccatissimoUp); private JButton btStaccatoTenutoUp = new JButton(iconStaccatoTenutoUp); private JButton btStaccatoTenutoDown = new JButton(iconStaccatoTenutoDown); private JButton btFermata = new JButton(iconFermata); private JButton btPedalStart = new JButton(iconPedalStart); private JButton btPedalEnd = new JButton(iconPedalEnd); private JButton btBreath = new JButton(iconBreath); // private JButton btTremoloBeam1 = new JButton(iconTremoloBeam1); // private JButton btTremoloBeam2 = new JButton(iconTremoloBeam2); // private JButton btTremoloBeam3 = new JButton(iconTremoloBeam3); public OrnamentDialog(){ super(); setLayout(null); setSize(DIALOG_WIDTH, DIALOG_HEIGHT); initComponents(); setModal(true); addFunctionListener(this); } void addFunctionListener(ActionListener l) { // TODO Auto-generated method stub btMarcato.addActionListener(l); btMartellatoDown.addActionListener(l); btMartellatoUp.addActionListener(l); btStaccato.addActionListener(l); btTenuto.addActionListener(l); btStaccatissimoDown.addActionListener(l); btStaccatissimoUp.addActionListener(l); btStaccatoTenutoUp.addActionListener(l); btStaccatoTenutoDown.addActionListener(l); btFermata.addActionListener(l); btPedalStart.addActionListener(l); btPedalEnd.addActionListener(l); btBreath.addActionListener(l); // btTremoloBeam1.addActionListener(l); // btTremoloBeam2.addActionListener(l); // btTremoloBeam3.addActionListener(l); } /** * ³õʼ»¯°´Å¥ */ public void initComponents(){ setLayout(null); add(btMarcato); add(btMartellatoDown); add(btMartellatoUp); add(btStaccato); add(btTenuto); add(btStaccatissimoDown); add(btStaccatissimoUp); add(btStaccatoTenutoUp); add(btStaccatoTenutoDown); add(btFermata); add(btPedalStart); add(btPedalEnd); add(btBreath); // add(btTremoloBeam1); // add(btTremoloBeam2); // add(btTremoloBeam3); int x = 8; int y = 5; btMarcato.setBounds(x, y, 20, 25); x += 20; btMartellatoDown.setBounds(x, y, 20, 25); x += 20; btMartellatoUp.setBounds(x, y, 20, 25); x += 20; btStaccato.setBounds(x, y, 20, 25); x += 20; btTenuto.setBounds(x, y, 20, 25); x = 8; y += 30; btStaccatissimoDown.setBounds(x, y, 20, 25); x += 20; btStaccatissimoUp.setBounds(x, y, 20, 25); x += 20; btStaccatoTenutoUp.setBounds(x, y, 20, 25); x += 20; btStaccatoTenutoDown.setBounds(x, y, 20, 25); x += 20; btFermata.setBounds(x, y, 20, 25); x = 8; y+= 30; btPedalStart.setBounds(x, y, 20, 25); x += 20; btPedalEnd.setBounds(x, y, 20, 25); x += 20; btBreath.setBounds(x, y, 20, 25); x += 20; // btTremoloBeam1.setBounds(x, y, 20, 25); // x += 20; // btTremoloBeam2.setBounds(x, y, 20, 25); // x = 8; y+= 30; // btTremoloBeam3.setBounds(x, y, 20, 25); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource() == btMarcato){ symboleType = "accent"; dispose(); }else if(e.getSource() == btMartellatoDown){ symboleType = "strongAccentDown"; dispose(); }else if(e.getSource() == btMartellatoUp){ symboleType = "strongAccentUp"; dispose(); }else if(e.getSource() == btStaccato){ symboleType = "staccato"; dispose(); }else if(e.getSource() == btTenuto){ symboleType = "tenuto"; dispose(); }else if(e.getSource() == btStaccatissimoDown){ symboleType = "staccatissimoDown"; dispose(); }else if(e.getSource() == btStaccatissimoUp){ symboleType = "staccatissimoUp"; dispose(); }else if(e.getSource() == btStaccatoTenutoUp){ symboleType = "staccatoTenutoUp"; dispose(); }else if(e.getSource() == btStaccatoTenutoDown){ symboleType = "staccatoTenutoDown"; dispose(); }else if(e.getSource() == btFermata){ symboleType = "fermata"; dispose(); }else if(e.getSource() == btPedalStart){ symboleType = "pedalStart"; dispose(); }else if(e.getSource() == btPedalEnd){ symboleType = "pedalEnd"; dispose(); }else if(e.getSource() == btBreath){ symboleType = "breath"; dispose(); } // else if(e.getSource() == btTremoloBeam1){ // type = "tremoloBeam1"; // dispose(); // }else if(e.getSource() == btTremoloBeam2){ // type = "tremoloBeam2"; // dispose(); // }else if(e.getSource() == btTremoloBeam3){ // type = "tremoloBeam3"; // dispose(); // } } public String getSymbolType() { return symboleType; } public void setType(String type) { this.symboleType = type; } }
gpl-2.0
maiklos-mirrors/jfx78
modules/graphics/src/main/java/com/sun/glass/ui/lens/LensView.java
8152
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.glass.ui.lens; import java.util.Map; import com.sun.glass.ui.Pixels; import com.sun.glass.ui.View; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.Buffer; import com.sun.glass.events.ViewEvent; final class LensView extends View { protected LensView() { super(); } // Constants private static long multiClickTime = 300; private static int multiClickMaxX = 2; private static int multiClickMaxY = 2; // view variables private int x; private int y; private long nativePtr; protected static long _getMultiClickTime() { if (multiClickTime == -1) { //multiClickTime = _getMultiClickTime_impl(); //currently calling a native function is meaningless multiClickTime = 300; } return multiClickTime; } protected static int _getMultiClickMaxX() { if (multiClickMaxX == -1) { //multiClickMaxX = _getMultiClickMaxX_impl(); //currently calling a native function is meaningless multiClickMaxX = 2; } return multiClickMaxX; } protected static int _getMultiClickMaxY() { if (multiClickMaxY == -1) { //multiClickMaxY = _getMultiClickMaxY_impl(); //currently calling a native function is meaningless multiClickMaxY = 2; } return multiClickMaxY; } native private void _paintInt(long ptr, int w, int h, IntBuffer ints, int[] array, int offset); native private void _paintByte(long ptr, int w, int h, ByteBuffer bytes, byte[] array, int offset); native private void _paintIntDirect(long ptr, int w, int h, Buffer buffer); @Override protected void _enableInputMethodEvents(long ptr, boolean enable) { } @Override protected long _getNativeView(long ptr) { //this method is a Windows hack, see View.java for more details // we just ignore it return ptr; } @Override protected int _getX(long ptr) { return x; } @Override protected int _getY(long ptr) { return y; } @Override protected void _scheduleRepaint(long ptr) { // native code is there but does nothing yet //throw new UnsupportedOperationException("Not supported yet."); LensLogger.getLogger().info("Ignoring repaint"); } @Override protected void _uploadPixels(long nativeViewPtr, Pixels pixels) { if (getWindow() != null) { Buffer data = pixels.getPixels(); int width = pixels.getWidth(); int height = pixels.getHeight(); if (data.isDirect() == true) { _paintIntDirect(nativeViewPtr, width, height, data); } else if (data.hasArray() == true) { if (pixels.getBytesPerComponent() == 1) { ByteBuffer bytes = (ByteBuffer)data; _paintByte(nativeViewPtr, width, height, bytes, bytes.array(), bytes.arrayOffset()); } else { IntBuffer ints = (IntBuffer)data; int[] intArray = ints.array(); _paintInt(nativeViewPtr, width, height, ints, intArray, ints.arrayOffset()); } } } } /** * Events */ protected void _notifyMove(int x, int y) { // used to update x,y for _getX(), _getY() this.x = x; this.y = y; notifyView(ViewEvent.MOVE); } protected void _notifyKey(int type, int keyCode, char[] keyChars, int modifiers) { notifyKey(type, keyCode, keyChars, modifiers); } protected void _notifyMouse(int type, int button, int x, int y, int xAbs, int yAbs, int modifiers, boolean isPopupTrigger, boolean isSynthesized) { notifyMouse(type, button, x, y, xAbs, yAbs, modifiers, isPopupTrigger, isSynthesized); } protected void _notifyScroll(int x, int y, int xAbs, int yAbs, double deltaX, double deltaY, int modifiers, int lines, int chars, int defaultLines, int defaultChars, double xMultiplier, double yMultiplier) { notifyScroll(x, y, xAbs, yAbs, deltaX, deltaY, modifiers, lines, chars, defaultLines, defaultChars, xMultiplier, yMultiplier); } protected void _notifyRepaint(int x, int y, int width, int height) { notifyRepaint(x, y, width, height); } protected void _notifyResize(int width, int height) { notifyResize(width, height); } protected void _notifyViewEvent(int viewEvent) { notifyView(viewEvent); } //DnD protected void _notifyDragEnter(int x, int y, int absx, int absy, int recommendedDropAction) { notifyDragEnter(x, y, absx, absy, recommendedDropAction); } protected void _notifyDragLeave() { notifyDragLeave(); } protected void _notifyDragDrop(int x, int y, int absx, int absy, int recommendedDropAction) { notifyDragDrop(x, y, absx, absy, recommendedDropAction); } protected void _notifyDragOver(int x, int y, int absx, int absy, int recommendedDropAction) { notifyDragOver(x, y, absx, absy, recommendedDropAction); } //Menu event - i.e context menu hint (usually mouse right click) protected void _notifyMenu(int x, int y, int xAbs, int yAbs, boolean isKeyboardTrigger) { notifyMenu(x, y, xAbs, yAbs, isKeyboardTrigger); } /** * Native methods */ @Override protected long _create(Map caps) { this.nativePtr = _createNativeView(caps); return this.nativePtr; } private native long _createNativeView(Map caps); /** * Assuming this is used to lock the surface for painting */ @Override native protected void _begin(long ptr); /** * Assuming this is used to unlock the surface after painting is * done */ @Override native protected void _end(long ptr); @Override native protected void _setParent(long ptr, long parentPtr); @Override native protected boolean _close(long ptr); @Override native protected boolean _enterFullscreen(long ptr, boolean animate, boolean keepRatio, boolean hideCursor); @Override native protected void _exitFullscreen(long ptr, boolean animate); @Override public String toString() { return "LensView[nativePtr=0x" + Long.toHexString(nativePtr) + "]"; } }
gpl-2.0
InspiredIdealist/Trace-Framework
src/main/java/org/inspire/guide/metadata/Action.java
1404
package org.inspire.guide.metadata; import java.util.ArrayList; import java.util.List; /** * Actions that can be performed within the * Bukkit scheduler framework. * <p/> * These actions are self-contained, so when run() is * executed, any action that will be performed does NOT require * any additional outside information. * <p/> * User: InspiredIdealist * Date: 1/11/14 */ public abstract class Action implements Runnable { private static List<Action> ACTIONS_AVAILABLE = new ArrayList<Action>(); private Type type; private String description; public Action(Type type, String description) { this.type = type; this.description = description; ACTIONS_AVAILABLE.add(this); //May need to place this elsewhere. But this should work for now. } public Type getType() { return type; } @Override public abstract String toString(); public String getDescription() { return description; } public static List<Action> getActionsAvailable() { return ACTIONS_AVAILABLE; } /** * Flag that denotes whether or not the rule can execute without * the user specifying it. * * @return true if it is autonomous, false if not */ public abstract boolean isAutonomous(); /** * The action to run. Call this to do the action. */ public abstract void run(); }
gpl-2.0
Waszker/IO_projekt
ComputationalCluster/src/ComputationalServer/ServerCore/ConnectionEstabilisherThread.java
1621
package ComputationalServer.ServerCore; import java.io.IOException; import java.net.Socket; import GenericCommonClasses.GenericProtocol; /** * <p> * ConnectionEstabilisherThread is responsible for asynchronous connection * estabilishment and asynchronous message retrieval. * </p> * <p> * Retrieved message is put into message queue and processes by other * ComputationalServer threads. * </p> * * @author Piotr Waszkiewicz * @version 1.0 * */ class ConnectionEstabilisherThread extends Thread { /******************/ /* VARIABLES */ /******************/ ComputationalServerCore core; /******************/ /* FUNCTIONS */ /******************/ /** * <p> * Create ConnectionEstabilisherThread with reference to server core. * </p> * * @param core */ ConnectionEstabilisherThread(ComputationalServerCore core) { super(); this.core = core; } @Override public void run() { while (true) { try { Socket clientSocket = core.serverSocket.accept(); retrieveClientMessage(clientSocket); } catch (IOException e) { } } } private void retrieveClientMessage(final Socket clientSocket) { // Start procedure in new thread to not block other connections new Thread(new Runnable() { @Override public void run() { try { core.messageQueue.add(new ClientMessage(GenericProtocol .receiveMessage(clientSocket), clientSocket)); core.queueSemaphore.release(); } catch (IOException e) { } // do not close input stream here // it should be done in message parsing routine! } }).start(); } }
gpl-2.0
smarr/Truffle
wasm/src/org.graalvm.wasm/src/org/graalvm/wasm/WasmMath.java
11005
/* * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.graalvm.wasm; import com.oracle.truffle.api.ExactMath; import static java.lang.Integer.compareUnsigned; /** * The class {@code WasmMath} contains methods for performing specific numeric operations such as * unsigned arithmetic, which are not built in Java nor provided by the {@link Math} class. */ public final class WasmMath { /** * The number of logical bits in the significand of a {@code double}, <strong>excluding</strong> * the implicit bit. */ private static final long DOUBLE_SIGNIFICAND_WIDTH = 52; /** * Bit mask to isolate the significand field of a <code>double</code>. */ public static final long DOUBLE_SIGNIFICAND_BIT_MASK = 0x000FFFFFFFFFFFFFL; /** * The spacing between two consecutive {@code float} values (aka Unit in the Last Place) in the * range [2^31, 2^32): 2^40. */ private static final long FLOAT_POWER_63_ULP = (long) Math.ulp(0x1p63f); /** * The spacing between two consecutive {@code double} values (aka Unit in the Last Place) in the * range [2^63, 2^64): 2^11. */ private static final long DOUBLE_POWER_63_ULP = (long) Math.ulp(0x1p63); /** * Don't let anyone instantiate this class. */ private WasmMath() { } /** * Returns the sum of two unsigned ints. * * @throws ArithmeticException if the operation overflows */ public static int addExactUnsigned(int a, int b) { // See GR-28305 for more background and possible intrinsification of this method. final int result = a + b; if (compareUnsigned(result, a) < 0) { throw new ArithmeticException("unsigned int overflow"); } return result; } /** * Returns the minimum of two unsigned ints. */ public static int minUnsigned(int a, int b) { return compareUnsigned(a, b) < 0 ? a : b; } /** * Returns the maximum of two unsigned ints. */ public static int maxUnsigned(int a, int b) { return compareUnsigned(a, b) > 0 ? a : b; } /** * Returns the value of the {@code long} argument as an {@code int}; throwing an exception if * the value overflows an unsigned {@code int}. * * @throws ArithmeticException if the argument is outside of the unsigned int32 range * @since 1.8 */ public static int toUnsignedIntExact(long value) { if (value < 0 || value > 0xffff_ffffL) { throw new ArithmeticException("unsigned int overflow"); } return (int) value; } /** * Converts the given unsigned {@code int} to the closest {@code float} value. */ public static float unsignedIntToFloat(int x) { return unsignedIntToLong(x); } /** * Converts the given unsigned {@code int} to the closest {@code double} value. */ public static double unsignedIntToDouble(int x) { return unsignedIntToLong(x); } /** * Converts the given unsigned {@code int} to the corresponding {@code long}. */ public static long unsignedIntToLong(int x) { // See https://stackoverflow.com/a/22938125. return x & 0xFFFFFFFFL; } /** * Converts the given unsigned {@code long} to the closest {@code float} value. */ public static float unsignedLongToFloat(long x) { if (x >= 0) { // If the first bit is not set, then we can simply cast which is faster. return x; } // Transpose x from [Integer.MIN_VALUE,-1] to [0, Integer.MAX_VALUE] final long shiftedX = x + Long.MIN_VALUE; // We cannot simply compute 0x1p63f + shiftedX because it yields incorrect results in some // edge cases due to rounding twice (conversion to long, and addition). See // https://github.com/WebAssembly/spec/issues/421 and mentioned test cases for more context. // Instead, we manually compute the offset from 0x1p63f. final boolean roundUp = shiftedX % FLOAT_POWER_63_ULP > FLOAT_POWER_63_ULP / 2; final long offset = (shiftedX / FLOAT_POWER_63_ULP) + (roundUp ? 1 : 0); // Return the offset-nth next floating-point value starting from 2^63. This is equivalent to // incrementing the significand (as Math.nextUp would do) offset times. return 0x1p63f + (offset * (float) FLOAT_POWER_63_ULP); } /** * Converts the given unsigned {@code long} to the closest {@code double} value. */ public static double unsignedLongToDouble(long x) { if (x >= 0) { // If the first bit is not set, then we can simply cast which is faster. return x; } // Transpose x from [Long.MIN_VALUE,-1] to [0, Long.MAX_VALUE]. final long shiftedX = x + Long.MIN_VALUE; // We cannot simply compute 0x1p63 + shiftedX because it yields incorrect results in some // edge cases due to rounding twice (conversion to long, and addition). See // https://github.com/WebAssembly/spec/issues/421 and mentioned test cases for more context. // Instead, we manually compute the offset from 0x1p63. final boolean roundUp = shiftedX % DOUBLE_POWER_63_ULP > DOUBLE_POWER_63_ULP / 2; final long offset = (shiftedX / DOUBLE_POWER_63_ULP) + (roundUp ? 1 : 0); // Return the offset-nth next floating-point value starting form 2^63. This is equivalent to // incrementing the significand (as Math.nextUp would do) offset times. return 0x1p63 + (offset * (double) DOUBLE_POWER_63_ULP); } /** * Removes the decimal part (aka truncation or rounds towards zero) of the given float and * converts it to a <strong>signed</strong> long. * <p> * The operation is saturating: if the float is smaller than {@link Integer#MIN_VALUE} or larger * than {@link Integer#MAX_VALUE}, then respectively {@link Integer#MIN_VALUE} or * {@link Integer#MAX_VALUE} is returned. */ public static long truncFloatToLong(float x) { return truncDoubleToLong(x); } /** * Removes the decimal part (aka truncation or rounds towards zero) of the given double and * converts it to a <strong>signed</strong> long. * <p> * The operation is saturating: if the double is smaller than {@link Long#MIN_VALUE} or larger * than {@link Long#MAX_VALUE}, then respectively {@link Long#MIN_VALUE} or * {@link Long#MAX_VALUE} is returned. */ public static long truncDoubleToLong(double x) { return (long) ExactMath.truncate(x); } /** * Removes the decimal part (aka truncation or rounds towards zero) of the given float and * converts it to an <strong>unsigned</strong> long. * <p> * The operation is saturating: if the float is smaller than 0 or larger than 2^32 - 1, then * respectively 0 or 2^32 - 1 is returned. */ public static long truncFloatToUnsignedLong(float x) { return truncDoubleToUnsignedLong(x); } /** * Removes the decimal part (aka truncation or rounds towards zero) of the given double and * converts it to an <strong>unsigned</strong> long. * <p> * The operation is saturating: if the double is smaller than 0 or larger than 2^64 - 1, then * respectively 0 or 2^64 - 1 is returned. */ public static long truncDoubleToUnsignedLong(double x) { if (x < Long.MAX_VALUE) { // If the first bit is not set, then we use the signed variant which is faster. return truncDoubleToLong(x); } // There is no direct way to convert a double to an _unsigned_ long in Java. Therefore we // manually split the binary representation of x into significand (aka base or mantissa) and // exponent, and compute the resulting long by shifting the significand. final long shift = Math.getExponent(x) - DOUBLE_SIGNIFICAND_WIDTH; final long xBits = Double.doubleToRawLongBits(x); final long significand = (1L << DOUBLE_SIGNIFICAND_WIDTH) | (xBits & DOUBLE_SIGNIFICAND_BIT_MASK); if (shift >= Long.SIZE - DOUBLE_SIGNIFICAND_WIDTH) { // Saturation: if x is too large to convert to a long, we return the highest possible // value (all bits set). return 0xffff_ffff_ffff_ffffL; } else if (shift > 0) { // Multiply significand by 2^shift. return significand << shift; } // Should not reach here because x >= Long.MAX_VALUE, so shift >= // (Math.getExponent(Long.MAX_VALUE) - DOUBLE_SIGNIFICAND_WIDTH) == 11. if (shift >= -DOUBLE_SIGNIFICAND_WIDTH) { // Multiply significand by 2^shift == divide significand by 2^(-shift). return significand >> -shift; } else { // Saturation: if x is too small to convert to a long, we return 0. return 0; } } }
gpl-2.0
Robert0Trebor/robert
TMessagesProj/src/main/java/org/vidogram/messenger/exoplayer/f/f.java
979
package org.vidogram.messenger.exoplayer.f; public final class f { public final int a; public final int b; public final int c; public final int d; public final int e; public final int f; public final int g; public final long h; public f(byte[] paramArrayOfByte, int paramInt) { paramArrayOfByte = new l(paramArrayOfByte); paramArrayOfByte.a(paramInt * 8); this.a = paramArrayOfByte.c(16); this.b = paramArrayOfByte.c(16); this.c = paramArrayOfByte.c(24); this.d = paramArrayOfByte.c(24); this.e = paramArrayOfByte.c(20); this.f = (paramArrayOfByte.c(3) + 1); this.g = (paramArrayOfByte.c(5) + 1); this.h = paramArrayOfByte.c(36); } public int a() { return this.g * this.e; } public long b() { return this.h * 1000000L / this.e; } } /* Location: G:\programs\dex2jar-2.0\vidogram-dex2jar.jar * Qualified Name: org.vidogram.messenger.exoplayer.f.f * JD-Core Version: 0.6.0 */
gpl-2.0
shunghsiyu/OpenJML_XOR
JMLAnnotations/src/org/jmlspecs/annotation/CodeJavaMath.java
254
package org.jmlspecs.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CodeJavaMath { }
gpl-2.0
rroart/pacman
src/main/java/roart/pacman/graphic/Shapes.java
4172
package roart.pacman.graphic; public interface Shapes { byte PACMAN0_BITS[]= {(byte) 0x3c,(byte) 0x7e,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0x7e,(byte) 0x3c}; byte PACMANRIGHT_BITS[]= {(byte) 0x3c,(byte) 0x68,(byte) 0xf0,(byte) 0xe0,(byte) 0xe0,(byte) 0xf0,(byte) 0x78,(byte) 0x3c}; byte PACMANLEFT_BITS[]={(byte) 0x3c,(byte) 0x16,(byte) 0x0f,(byte) 0x07,(byte) 0x07,(byte) 0x0f,(byte) 0x1e,(byte) 0x3c}; byte PACMANUP_BITS[]= {(byte) 0x00,(byte) 0x00,(byte) 0x81,(byte) 0xc3,(byte) 0xa7,(byte) 0xff,(byte) 0x7e,(byte) 0x3c}; byte PACMANDOWN_BITS[]= {(byte) 0x3c,(byte) 0x7e,(byte) 0xff,(byte) 0xa7,(byte) 0xc3,(byte) 0x81,(byte) 0x00,(byte) 0x00}; byte VERTWALL_BITS[]={(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c}; byte HORIWALL_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0x00,(byte) 0x00}; byte BLANK_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00}; byte CROSS_BITS[]={(byte) 0x3c,(byte) 0x3c,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0x3c,(byte) 0x3c}; byte FOOD_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x18,(byte) 0x3c,(byte) 0x3c,(byte) 0x18,(byte) 0x00,(byte) 0x00}; byte SUPERFOOD_BITS[]={(byte) 0x00,(byte) 0x3c,(byte) 0x7e,(byte) 0x7e,(byte) 0x7e,(byte) 0x7e,(byte) 0x3c,(byte) 0x00}; byte GHOST_BITS[]={(byte) 0x18,(byte) 0x7e,(byte) 0xff,(byte) 0xdb,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xa5}; byte CORNER1_BITS[]={(byte) 0x3c,(byte) 0x3e,(byte) 0x3f,(byte) 0x3f,(byte) 0x3f,(byte) 0x1f,(byte) 0x00,(byte) 0x00}; byte CORNER4_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x1f,(byte) 0x3f,(byte) 0x3f,(byte) 0x3f,(byte) 0x3e,(byte) 0x3c}; byte CORNER3_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0xf8,(byte) 0xfc,(byte) 0xfc,(byte) 0xfc,(byte) 0x7c,(byte) 0x3c}; byte CORNER2_BITS[]={(byte) 0x3c,(byte) 0x7c,(byte) 0xfc,(byte) 0xfc,(byte) 0xfc,(byte) 0xf8,(byte) 0x00,(byte) 0x00}; byte SPECWALL_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0xff,(byte) 0x00,(byte) 0x00,(byte) 0xff,(byte) 0x00,(byte) 0x00}; byte BONUSPOINT_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x24,(byte) 0x18,(byte) 0x18,(byte) 0x24,(byte) 0x00,(byte) 0x00}; byte BONUSLIFE_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x1c,(byte) 0x38,(byte) 0x38,(byte) 0x1c,(byte) 0x00,(byte) 0x00}; byte E0_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0xf8,(byte) 0xfc,(byte) 0xfc,(byte) 0xf8,(byte) 0x00,(byte) 0x00}; byte E90_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x18,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c}; byte E180_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x1f,(byte) 0x3f,(byte) 0x3f,(byte) 0x1f,(byte) 0x00,(byte) 0x00}; byte E270_BITS[]={(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x18,(byte) 0x00,(byte) 0x00}; byte T0_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0x7e,(byte) 0x3c}; byte T90_BITS[]={(byte) 0x3c,(byte) 0x3e,(byte) 0x3f,(byte) 0x3f,(byte) 0x3f,(byte) 0x3f,(byte) 0x3e,(byte) 0x3c}; byte T180_BITS[]={(byte) 0x3c,(byte) 0x7e,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0x00,(byte) 0x00}; byte T270_BITS[]={(byte) 0x3c,(byte) 0x7c,(byte) 0xfc,(byte) 0xfc,(byte) 0xfc,(byte) 0xfc,(byte) 0x7c,(byte) 0x3c}; // #elif defined VTX //vt??? unix only // byte pacman0_bits[]={'P'}; // byte pacmanleft_bits[]={'P'}; // byte pacmanright_bits[]={'P'}; // byte pacmanup_bits[]= {'P'}; // byte pacmandown_bits[]= {'P'}; // byte vertwall_bits[]={'|'}; // byte horiwall_bits[]={'-'}; // byte blank_bits[]={' '}; // byte cross_bits[]={'+'}; // byte food_bits[]={'.'}; // byte superfood_bits[]={'o'}; // byte ghost_bits[]={'G'}; // byte corner2_bits[]={'X'}; // byte corner3_bits[]={'X'}; // byte corner4_bits[]={'X'}; // byte corner1_bits[]={'X'}; // byte specwall_bits[]={'_'}; // byte bonuspoint_bits[]={'?'}; // byte bonuslife_bits[]={'p'}; // byte e180_bits[]={'-'}; // byte e90_bits[]={'|'}; // byte e0_bits[]={'-'}; // byte e270_bits[]={'|'}; // byte t0_bits[]={'-'}; // byte t270_bits[]={'|'}; // byte t180_bits[]={'-'}; // byte t90_bits[]={'|'}; // #endif }
gpl-2.0
crotwell/fissuresIDL
src/main/java/edu/iris/Fissures/IfNetwork/ResponseHelper.java
2254
// ********************************************************************** // // Generated by the ORBacus IDL to Java Translator // // Copyright (c) 2000 // Object Oriented Concepts, Inc. // Billerica, MA, USA // // All Rights Reserved // // ********************************************************************** // Version: 4.0.5 package edu.iris.Fissures.IfNetwork; // // IDL:iris.edu/Fissures/IfNetwork/Response:1.0 // final public class ResponseHelper { public static void insert(org.omg.CORBA.Any any, Response val) { org.omg.CORBA.portable.OutputStream out = any.create_output_stream(); write(out, val); any.read_value(out.create_input_stream(), type()); } public static Response extract(org.omg.CORBA.Any any) { if(any.type().equivalent(type())) return read(any.create_input_stream()); else throw new org.omg.CORBA.BAD_OPERATION(); } private static org.omg.CORBA.TypeCode typeCode_; public static org.omg.CORBA.TypeCode type() { if(typeCode_ == null) { org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(); org.omg.CORBA.StructMember[] members = new org.omg.CORBA.StructMember[2]; members[0] = new org.omg.CORBA.StructMember(); members[0].name = "the_sensitivity"; members[0].type = SensitivityHelper.type(); members[1] = new org.omg.CORBA.StructMember(); members[1].name = "stages"; members[1].type = StageSeqHelper.type(); typeCode_ = orb.create_struct_tc(id(), "Response", members); } return typeCode_; } public static String id() { return "IDL:iris.edu/Fissures/IfNetwork/Response:1.0"; } public static Response read(org.omg.CORBA.portable.InputStream in) { Response _ob_v = new Response(); _ob_v.the_sensitivity = SensitivityHelper.read(in); _ob_v.stages = StageSeqHelper.read(in); return _ob_v; } public static void write(org.omg.CORBA.portable.OutputStream out, Response val) { SensitivityHelper.write(out, val.the_sensitivity); StageSeqHelper.write(out, val.stages); } }
gpl-2.0
kompics/kola
src/main/java/se/sics/kola/node/PExpression.java
166
/* This file was generated by SableCC (http://www.sablecc.org/). */ package se.sics.kola.node; public abstract class PExpression extends Node { // Empty body }
gpl-2.0
FreeSivan/myJavaTest
src/main/java/com/designedpattern/abstractfactory/impl/MagicianA.java
224
package com.designedpattern.abstractfactory.impl; import com.designedpattern.abstractfactory.IMagician; public class MagicianA implements IMagician{ public void showMagician() { System.out.println("Magician A"); } }
gpl-2.0
vnu-dse/rtl
src/main/org/tzi/use/uml/ocl/type/VoidType.java
1632
package org.tzi.use.uml.ocl.type; import java.util.Set; public class VoidType extends Type { public Set<Type> allSupertypes() { throw new UnsupportedOperationException("Call to allSupertypes is invalid on OclVoid"); } public boolean equals(Object obj) { return obj instanceof VoidType; } public int hashCode() { return 0; } public boolean isVoidType() { return true; } public boolean isSubtypeOf(Type t) { return true; } @Override public boolean isBag() { return true; } @Override public boolean isBoolean() { return true; } @Override public boolean isCollection(boolean excludeVoid) { if (excludeVoid) return false; else return true; } @Override public boolean isDate() { return true; } @Override public boolean isEnum() { return true; } @Override public boolean isInstantiableCollection() { return true; } @Override public boolean isInteger() { return true; } @Override public boolean isNumber() { return true; } @Override public boolean isObjectType() { return true; } @Override public boolean isOrderedSet() { return true; } @Override public boolean isReal() { return true; } @Override public boolean isSequence() { return true; } @Override public boolean isSet() { return true; } @Override public boolean isString() { return true; } @Override public boolean isTupleType(boolean excludeVoid) { return !excludeVoid; } @Override public StringBuilder toString(StringBuilder sb) { return sb.append("OclVoid"); } @Override public boolean isVoidOrElementTypeIsVoid() { return true; } }
gpl-2.0
Superioz/MooProject
api/src/main/java/de/superioz/moo/api/logging/ConciseFormatter.java
1332
package de.superioz.moo.api.logging; import java.io.PrintWriter; import java.io.StringWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.logging.Formatter; import java.util.logging.LogRecord; /** * This is just a simple formatter for a logger */ public class ConciseFormatter extends Formatter { private final DateFormat date = new SimpleDateFormat("HH:mm:ss.sss"); private boolean stripColors = false; public ConciseFormatter(boolean stripColors) { this.stripColors = stripColors; } @Override @SuppressWarnings("ThrowableResultIgnored") public String format(LogRecord record) { StringBuilder formatted = new StringBuilder(); formatted.append("["); formatted.append(date.format(record.getMillis())); formatted.append(" "); formatted.append(record.getLevel().getName()); formatted.append("] "); formatted.append(stripColors ? ConsoleColor.stripColors(formatMessage(record)) : formatMessage(record)); formatted.append('\n'); if(record.getThrown() != null) { StringWriter writer = new StringWriter(); record.getThrown().printStackTrace(new PrintWriter(writer)); formatted.append(writer); } return formatted.toString(); } }
gpl-2.0
light88/dental-spring
web/src/main/java/com/dental/provider/DentalUserDetails.java
1589
package com.dental.provider; import com.dental.persistence.entity.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; /** * Created by admin on 27.05.2015. */ public class DentalUserDetails implements UserDetails { private Collection<? extends GrantedAuthority> grantedAuthorities; private String password; private String username; // private boolean isAccountNonLocked; // private boolean isAccountNonExpired; private User user; public DentalUserDetails(String username, String password, Collection<? extends GrantedAuthority> grantedAuthorities, User user) { this.username = username; this.password = password; // this.isAccountNonExpired = isAccountNonExpired; // this.isAccountNonLocked = isAccountNonLocked; this.grantedAuthorities = grantedAuthorities; this.user = user; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return this.grantedAuthorities; } @Override public String getPassword() { return this.password; } @Override public String getUsername() { return this.username; } @Override public boolean isAccountNonExpired() { return false; } @Override public boolean isAccountNonLocked() { return false; } @Override public boolean isCredentialsNonExpired() { return false; } @Override public boolean isEnabled() { return true; } public User getUser() { return this.user; } }
gpl-2.0
tn5250j/tn5250j
src/org/tn5250j/gui/ButtonTabComponent.java
11125
/** * $Id$ * <p> * Title: tn5250J * Copyright: Copyright (c) 2001,2009 * Company: * * @author: master_jaf * <p> * Description: * Tab component for displaying title text and icons. * <p> * <p> * 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, or (at your option) * any later version. * <p> * 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. * <p> * You should have received a copy of the GNU General Public License * along with this software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package org.tn5250j.gui; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import javax.swing.plaf.basic.BasicButtonUI; import org.tn5250j.TN5250jConstants; import org.tn5250j.event.SessionChangeEvent; import org.tn5250j.event.SessionListener; import org.tn5250j.event.TabClosedListener; import org.tn5250j.tools.LangTool; /** * Component to be used as tabComponent; Contains a JLabel to show the text and * a JButton to close the tab it belongs to.<br> * <br> * This class based on the ButtonTabComponent example from * Sun Microsystems, Inc. and was modified to use tool tips, other layout and stuff. */ public final class ButtonTabComponent extends JPanel implements SessionListener { private static final long serialVersionUID = 1L; private final JTabbedPane pane; private List<TabClosedListener> closeListeners; private final JLabel label; public ButtonTabComponent(final JTabbedPane pane) { super(new BorderLayout(0, 0)); if (pane == null) { throw new NullPointerException("TabbedPane is null"); } this.pane = pane; setOpaque(false); this.label = new TabLabel(); // { label.setHorizontalAlignment(SwingConstants.CENTER); label.setVerticalAlignment(SwingConstants.CENTER); add(label, BorderLayout.CENTER); // add more space between the label and the button label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); // tab button JButton button = new TabButton(); button.setHorizontalAlignment(SwingConstants.TRAILING); add(button, BorderLayout.EAST); // add more space to the top of the component setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); pane.addPropertyChangeListener(new PropertyChangeListener() { // triggers repaint, so size is recalculated, when title text changes @Override public void propertyChange(PropertyChangeEvent evt) { if ("indexForTitle".equals(evt.getPropertyName())) { label.revalidate(); label.repaint(); } } }); } @Override public void onSessionChanged(SessionChangeEvent changeEvent) { if (changeEvent.getState() == TN5250jConstants.STATE_CONNECTED) { this.label.setEnabled(true); this.label.setToolTipText(LangTool.getString("ss.state.connected")); this.setToolTipText(LangTool.getString("ss.state.connected")); } else { this.label.setEnabled(false); this.label.setToolTipText(LangTool.getString("ss.state.disconnected")); this.setToolTipText(LangTool.getString("ss.state.disconnected")); } } /** * Add a TabClosedListener to the listener list. * * @param listener The TabClosedListener to be added */ public synchronized void addTabCloseListener(TabClosedListener listener) { if (closeListeners == null) { closeListeners = new ArrayList<TabClosedListener>(3); } closeListeners.add(listener); } /** * Remove a TabClosedListener from the listener list. * * @param listener The TabClosedListener to be removed */ public synchronized void removeTabCloseListener(TabClosedListener listener) { if (closeListeners == null) { return; } closeListeners.remove(listener); } /** * Notify all the tab listeners that this specific tab was selected to close. * * @param tabToClose */ protected void fireTabClosed(int tabToClose) { if (closeListeners != null) { int size = closeListeners.size(); for (int i = 0; i < size; i++) { TabClosedListener target = closeListeners.get(i); target.onTabClosed(tabToClose); } } } // ======================================================================= /** * Label delegating icon and text to the corresponding tab. * Implementing MouseListener is a workaround, cause when applying * a tool tip to the JLabel, clicking the tabs doesn't work * (tested on Tn5250j0.6.2; WinXP+WinVista+Win7; JRE 1.6.0_20+). */ private final class TabLabel extends JLabel implements MouseListener { private static final long serialVersionUID = 1L; public TabLabel() { addMouseListener(this); } public String getText() { final int i = pane.indexOfTabComponent(ButtonTabComponent.this); if (i != -1) { return pane.getTitleAt(i); } return null; } public Icon getIcon() { final int i = pane.indexOfTabComponent(ButtonTabComponent.this); if (i != -1) { return pane.getIconAt(i); } return null; } /* (non-Javadoc) * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent) */ @Override public void mouseClicked(MouseEvent e) { actionSelectTab(); } /* (non-Javadoc) * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent) */ @Override public void mousePressed(MouseEvent e) { // not needed } /* (non-Javadoc) * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent) */ @Override public void mouseReleased(MouseEvent e) { actionSelectTab(); } /* (non-Javadoc) * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent) */ @Override public void mouseEntered(MouseEvent e) { // not needed } /* (non-Javadoc) * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent) */ @Override public void mouseExited(MouseEvent e) { // not needed } private void actionSelectTab() { final int i = pane.indexOfTabComponent(ButtonTabComponent.this); if (i != -1) { pane.setSelectedIndex(i); } } } /** * Special button displaying an X as close icon. */ private final class TabButton extends JButton implements ActionListener { private static final long serialVersionUID = 1L; public TabButton() { int size = 17; setPreferredSize(new Dimension(size, size)); setToolTipText(LangTool.getString("popup.close")); // Make the button looks the same for all Laf's setUI(new BasicButtonUI()); // Make it transparent setContentAreaFilled(false); // No need to be focusable setFocusable(false); setBorder(BorderFactory.createEtchedBorder()); setBorderPainted(false); // Making nice rollover effect // we use the same listener for all buttons addMouseListener(buttonMouseListener); setRolloverEnabled(true); // Close the proper tab by clicking the button addActionListener(this); } public void actionPerformed(ActionEvent e) { int i = pane.indexOfTabComponent(ButtonTabComponent.this); if (i != -1) { fireTabClosed(i); // hint: the actual close will be done within the TabbedPane Container } } // we don't want to update UI for this button public void updateUI() { } // paint the cross protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); // shift the image for pressed buttons if (getModel().isPressed()) { g2.translate(1, 1); } g2.setStroke(new BasicStroke(2)); g2.setColor(Color.BLACK); if (getModel().isRollover()) { g2.setColor(Color.MAGENTA); } int delta = 6; g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1); g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1); g2.dispose(); } } private final static MouseListener buttonMouseListener = new MouseAdapter() { public void mouseEntered(MouseEvent e) { Component component = e.getComponent(); if (component instanceof AbstractButton) { AbstractButton button = (AbstractButton) component; button.setBorderPainted(true); } } public void mouseExited(MouseEvent e) { Component component = e.getComponent(); if (component instanceof AbstractButton) { AbstractButton button = (AbstractButton) component; button.setBorderPainted(false); } } }; }
gpl-2.0
jgfntu/ijkplayer
android/ijkmediawidget/src/tv/danmaku/ijk/media/widget/VideoView.java
25159
/* * Copyright (C) 2006 The Android Open Source Project * Copyright (C) 2012 YIXIA.COM * Copyright (C) 2013 Zhang Rui <bbcallen@gmail.com> * 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 tv.danmaku.ijk.media.widget; import java.io.IOException; import java.util.List; import tv.danmaku.ijk.media.player.IMediaPlayer; import tv.danmaku.ijk.media.player.IMediaPlayer.OnBufferingUpdateListener; import tv.danmaku.ijk.media.player.IMediaPlayer.OnCompletionListener; import tv.danmaku.ijk.media.player.IMediaPlayer.OnErrorListener; import tv.danmaku.ijk.media.player.IMediaPlayer.OnInfoListener; import tv.danmaku.ijk.media.player.IMediaPlayer.OnPreparedListener; import tv.danmaku.ijk.media.player.IMediaPlayer.OnSeekCompleteListener; import tv.danmaku.ijk.media.player.IMediaPlayer.OnVideoSizeChangedListener; import tv.danmaku.ijk.media.player.IjkMediaPlayer; import tv.danmaku.ijk.media.player.option.AvFourCC; import tv.danmaku.ijk.media.player.option.format.AvFormatOption_HttpDetectRangeSupport; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.media.AudioManager; import android.net.Uri; import android.util.AttributeSet; import android.util.Pair; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup.LayoutParams; /** * Displays a video file. The VideoView class can load images from various * sources (such as resources or content providers), takes care of computing its * measurement from the video so that it can be used in any layout manager, and * provides various display options such as scaling and tinting. * * VideoView also provide many wrapper methods for * {@link io.vov.vitamio.MediaPlayer}, such as {@link #getVideoWidth()}, * {@link #setSubShown(boolean)} */ public class VideoView extends SurfaceView implements MediaController.MediaPlayerControl { private static final String TAG = VideoView.class.getName(); private Uri mUri; private long mDuration; private static final int STATE_ERROR = -1; private static final int STATE_IDLE = 0; private static final int STATE_PREPARING = 1; private static final int STATE_PREPARED = 2; private static final int STATE_PLAYING = 3; private static final int STATE_PAUSED = 4; private static final int STATE_PLAYBACK_COMPLETED = 5; private static final int STATE_SUSPEND = 6; private static final int STATE_RESUME = 7; private static final int STATE_SUSPEND_UNSUPPORTED = 8; private int mCurrentState = STATE_IDLE; private int mTargetState = STATE_IDLE; private int mVideoLayout = VIDEO_LAYOUT_SCALE; public static final int VIDEO_LAYOUT_ORIGIN = 0; public static final int VIDEO_LAYOUT_SCALE = 1; public static final int VIDEO_LAYOUT_STRETCH = 2; public static final int VIDEO_LAYOUT_ZOOM = 3; private SurfaceHolder mSurfaceHolder = null; private IMediaPlayer mMediaPlayer = null; private int mVideoWidth; private int mVideoHeight; private int mVideoSarNum; private int mVideoSarDen; private int mSurfaceWidth; private int mSurfaceHeight; private MediaController mMediaController; private View mMediaBufferingIndicator; private OnCompletionListener mOnCompletionListener; private OnPreparedListener mOnPreparedListener; private OnErrorListener mOnErrorListener; private OnSeekCompleteListener mOnSeekCompleteListener; private OnInfoListener mOnInfoListener; private OnBufferingUpdateListener mOnBufferingUpdateListener; private int mCurrentBufferPercentage; private long mSeekWhenPrepared; private boolean mCanPause = true; private boolean mCanSeekBack = true; private boolean mCanSeekForward = true; private Context mContext; public VideoView(Context context) { super(context); initVideoView(context); } public VideoView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VideoView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initVideoView(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = getDefaultSize(mVideoWidth, widthMeasureSpec); int height = getDefaultSize(mVideoHeight, heightMeasureSpec); setMeasuredDimension(width, height); } /** * Set the display options * * @param layout * <ul> * <li>{@link #VIDEO_LAYOUT_ORIGIN} * <li>{@link #VIDEO_LAYOUT_SCALE} * <li>{@link #VIDEO_LAYOUT_STRETCH} * <li>{@link #VIDEO_LAYOUT_ZOOM} * </ul> * @param aspectRatio * video aspect ratio, will audo detect if 0. */ public void setVideoLayout(int layout) { LayoutParams lp = getLayoutParams(); Pair<Integer, Integer> res = ScreenResolution.getResolution(mContext); int windowWidth = res.first.intValue(), windowHeight = res.second.intValue(); float windowRatio = windowWidth / (float) windowHeight; int sarNum = mVideoSarNum; int sarDen = mVideoSarDen; if (mVideoHeight > 0 && mVideoWidth > 0) { float videoRatio = ((float) (mVideoWidth)) / mVideoHeight; if (sarNum > 0 && sarDen > 0) videoRatio = videoRatio * sarNum / sarDen; mSurfaceHeight = mVideoHeight; mSurfaceWidth = mVideoWidth; if (VIDEO_LAYOUT_ORIGIN == layout && mSurfaceWidth < windowWidth && mSurfaceHeight < windowHeight) { lp.width = (int) (mSurfaceHeight * videoRatio); lp.height = mSurfaceHeight; } else if (layout == VIDEO_LAYOUT_ZOOM) { lp.width = windowRatio > videoRatio ? windowWidth : (int) (videoRatio * windowHeight); lp.height = windowRatio < videoRatio ? windowHeight : (int) (windowWidth / videoRatio); } else { boolean full = layout == VIDEO_LAYOUT_STRETCH; lp.width = (full || windowRatio < videoRatio) ? windowWidth : (int) (videoRatio * windowHeight); lp.height = (full || windowRatio > videoRatio) ? windowHeight : (int) (windowWidth / videoRatio); } setLayoutParams(lp); getHolder().setFixedSize(mSurfaceWidth, mSurfaceHeight); DebugLog.dfmt( TAG, "VIDEO: %dx%dx%f[SAR:%d:%d], Surface: %dx%d, LP: %dx%d, Window: %dx%dx%f", mVideoWidth, mVideoHeight, videoRatio, mVideoSarNum, mVideoSarDen, mSurfaceWidth, mSurfaceHeight, lp.width, lp.height, windowWidth, windowHeight, windowRatio); } mVideoLayout = layout; } private void initVideoView(Context ctx) { mContext = ctx; mVideoWidth = 0; mVideoHeight = 0; mVideoSarNum = 0; mVideoSarDen = 0; getHolder().addCallback(mSHCallback); setFocusable(true); setFocusableInTouchMode(true); requestFocus(); mCurrentState = STATE_IDLE; mTargetState = STATE_IDLE; if (ctx instanceof Activity) ((Activity) ctx).setVolumeControlStream(AudioManager.STREAM_MUSIC); } public boolean isValid() { return (mSurfaceHolder != null && mSurfaceHolder.getSurface().isValid()); } public void setVideoPath(String path) { setVideoURI(Uri.parse(path)); } public void setVideoURI(Uri uri) { mUri = uri; mSeekWhenPrepared = 0; openVideo(); requestLayout(); invalidate(); } public void stopPlayback() { if (mMediaPlayer != null) { mMediaPlayer.stop(); mMediaPlayer.release(); mMediaPlayer = null; mCurrentState = STATE_IDLE; mTargetState = STATE_IDLE; } } private void openVideo() { if (mUri == null || mSurfaceHolder == null) return; Intent i = new Intent("com.android.music.musicservicecommand"); i.putExtra("command", "pause"); mContext.sendBroadcast(i); release(false); try { mDuration = -1; mCurrentBufferPercentage = 0; // mMediaPlayer = new AndroidMediaPlayer(); IjkMediaPlayer ijkMediaPlayer = null; if (mUri != null) { ijkMediaPlayer = new IjkMediaPlayer(); ijkMediaPlayer.setAvOption(AvFormatOption_HttpDetectRangeSupport.Disable); ijkMediaPlayer.setOverlayFormat(AvFourCC.SDL_FCC_RV32); ijkMediaPlayer.setAvCodecOption("skip_loop_filter", "48"); ijkMediaPlayer.setFrameDrop(12); } mMediaPlayer = ijkMediaPlayer; mMediaPlayer.setOnPreparedListener(mPreparedListener); mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener); mMediaPlayer.setOnCompletionListener(mCompletionListener); mMediaPlayer.setOnErrorListener(mErrorListener); mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener); mMediaPlayer.setOnInfoListener(mInfoListener); mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener); if (mUri != null) mMediaPlayer.setDataSource(mUri.toString()); mMediaPlayer.setDisplay(mSurfaceHolder); mMediaPlayer.setScreenOnWhilePlaying(true); mMediaPlayer.prepareAsync(); mCurrentState = STATE_PREPARING; attachMediaController(); } catch (IOException ex) { DebugLog.e(TAG, "Unable to open content: " + mUri, ex); mCurrentState = STATE_ERROR; mTargetState = STATE_ERROR; mErrorListener.onError(mMediaPlayer, IMediaPlayer.MEDIA_ERROR_UNKNOWN, 0); return; } catch (IllegalArgumentException ex) { DebugLog.e(TAG, "Unable to open content: " + mUri, ex); mCurrentState = STATE_ERROR; mTargetState = STATE_ERROR; mErrorListener.onError(mMediaPlayer, IMediaPlayer.MEDIA_ERROR_UNKNOWN, 0); return; } } public void setMediaController(MediaController controller) { if (mMediaController != null) mMediaController.hide(); mMediaController = controller; attachMediaController(); } public void setMediaBufferingIndicator(View mediaBufferingIndicator) { if (mMediaBufferingIndicator != null) mMediaBufferingIndicator.setVisibility(View.GONE); mMediaBufferingIndicator = mediaBufferingIndicator; } private void attachMediaController() { if (mMediaPlayer != null && mMediaController != null) { mMediaController.setMediaPlayer(this); View anchorView = this.getParent() instanceof View ? (View) this .getParent() : this; mMediaController.setAnchorView(anchorView); mMediaController.setEnabled(isInPlaybackState()); if (mUri != null) { List<String> paths = mUri.getPathSegments(); String name = paths == null || paths.isEmpty() ? "null" : paths .get(paths.size() - 1); mMediaController.setFileName(name); } } } OnVideoSizeChangedListener mSizeChangedListener = new OnVideoSizeChangedListener() { public void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sarNum, int sarDen) { DebugLog.dfmt(TAG, "onVideoSizeChanged: (%dx%d)", width, height); mVideoWidth = mp.getVideoWidth(); mVideoHeight = mp.getVideoHeight(); mVideoSarNum = sarNum; mVideoSarDen = sarDen; if (mVideoWidth != 0 && mVideoHeight != 0) setVideoLayout(mVideoLayout); } }; OnPreparedListener mPreparedListener = new OnPreparedListener() { public void onPrepared(IMediaPlayer mp) { DebugLog.d(TAG, "onPrepared"); mCurrentState = STATE_PREPARED; mTargetState = STATE_PLAYING; if (mOnPreparedListener != null) mOnPreparedListener.onPrepared(mMediaPlayer); if (mMediaController != null) mMediaController.setEnabled(true); mVideoWidth = mp.getVideoWidth(); mVideoHeight = mp.getVideoHeight(); long seekToPosition = mSeekWhenPrepared; if (seekToPosition != 0) seekTo(seekToPosition); if (mVideoWidth != 0 && mVideoHeight != 0) { setVideoLayout(mVideoLayout); if (mSurfaceWidth == mVideoWidth && mSurfaceHeight == mVideoHeight) { if (mTargetState == STATE_PLAYING) { start(); if (mMediaController != null) mMediaController.show(); } else if (!isPlaying() && (seekToPosition != 0 || getCurrentPosition() > 0)) { if (mMediaController != null) mMediaController.show(0); } } } else if (mTargetState == STATE_PLAYING) { start(); } } }; private OnCompletionListener mCompletionListener = new OnCompletionListener() { public void onCompletion(IMediaPlayer mp) { DebugLog.d(TAG, "onCompletion"); mCurrentState = STATE_PLAYBACK_COMPLETED; mTargetState = STATE_PLAYBACK_COMPLETED; if (mMediaController != null) mMediaController.hide(); if (mOnCompletionListener != null) mOnCompletionListener.onCompletion(mMediaPlayer); } }; private OnErrorListener mErrorListener = new OnErrorListener() { public boolean onError(IMediaPlayer mp, int framework_err, int impl_err) { DebugLog.dfmt(TAG, "Error: %d, %d", framework_err, impl_err); mCurrentState = STATE_ERROR; mTargetState = STATE_ERROR; if (mMediaController != null) mMediaController.hide(); if (mOnErrorListener != null) { if (mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err)) return true; } if (getWindowToken() != null) { int message = framework_err == IMediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK ? R.string.vitamio_videoview_error_text_invalid_progressive_playback : R.string.vitamio_videoview_error_text_unknown; new AlertDialog.Builder(mContext) .setTitle(R.string.vitamio_videoview_error_title) .setMessage(message) .setPositiveButton( R.string.vitamio_videoview_error_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (mOnCompletionListener != null) mOnCompletionListener .onCompletion(mMediaPlayer); } }).setCancelable(false).show(); } return true; } }; private OnBufferingUpdateListener mBufferingUpdateListener = new OnBufferingUpdateListener() { public void onBufferingUpdate(IMediaPlayer mp, int percent) { mCurrentBufferPercentage = percent; if (mOnBufferingUpdateListener != null) mOnBufferingUpdateListener.onBufferingUpdate(mp, percent); } }; private OnInfoListener mInfoListener = new OnInfoListener() { @Override public boolean onInfo(IMediaPlayer mp, int what, int extra) { DebugLog.dfmt(TAG, "onInfo: (%d, %d)", what, extra); if (mOnInfoListener != null) { mOnInfoListener.onInfo(mp, what, extra); } else if (mMediaPlayer != null) { if (what == IMediaPlayer.MEDIA_INFO_BUFFERING_START) { DebugLog.dfmt(TAG, "onInfo: (MEDIA_INFO_BUFFERING_START)"); if (mMediaBufferingIndicator != null) mMediaBufferingIndicator.setVisibility(View.VISIBLE); } else if (what == IMediaPlayer.MEDIA_INFO_BUFFERING_END) { DebugLog.dfmt(TAG, "onInfo: (MEDIA_INFO_BUFFERING_END)"); if (mMediaBufferingIndicator != null) mMediaBufferingIndicator.setVisibility(View.GONE); } } return true; } }; private OnSeekCompleteListener mSeekCompleteListener = new OnSeekCompleteListener() { @Override public void onSeekComplete(IMediaPlayer mp) { DebugLog.d(TAG, "onSeekComplete"); if (mOnSeekCompleteListener != null) mOnSeekCompleteListener.onSeekComplete(mp); } }; public void setOnPreparedListener(OnPreparedListener l) { mOnPreparedListener = l; } public void setOnCompletionListener(OnCompletionListener l) { mOnCompletionListener = l; } public void setOnErrorListener(OnErrorListener l) { mOnErrorListener = l; } public void setOnBufferingUpdateListener(OnBufferingUpdateListener l) { mOnBufferingUpdateListener = l; } public void setOnSeekCompleteListener(OnSeekCompleteListener l) { mOnSeekCompleteListener = l; } public void setOnInfoListener(OnInfoListener l) { mOnInfoListener = l; } SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback() { public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { mSurfaceHolder = holder; if (mMediaPlayer != null) { mMediaPlayer.setDisplay(mSurfaceHolder); } mSurfaceWidth = w; mSurfaceHeight = h; boolean isValidState = (mTargetState == STATE_PLAYING); boolean hasValidSize = (mVideoWidth == w && mVideoHeight == h); if (mMediaPlayer != null && isValidState && hasValidSize) { if (mSeekWhenPrepared != 0) seekTo(mSeekWhenPrepared); start(); if (mMediaController != null) { if (mMediaController.isShowing()) mMediaController.hide(); mMediaController.show(); } } } public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; if (mMediaPlayer != null && mCurrentState == STATE_SUSPEND && mTargetState == STATE_RESUME) { mMediaPlayer.setDisplay(mSurfaceHolder); resume(); } else { openVideo(); } } public void surfaceDestroyed(SurfaceHolder holder) { mSurfaceHolder = null; if (mMediaController != null) mMediaController.hide(); if (mCurrentState != STATE_SUSPEND) release(true); } }; private void release(boolean cleartargetstate) { if (mMediaPlayer != null) { mMediaPlayer.reset(); mMediaPlayer.release(); mMediaPlayer = null; mCurrentState = STATE_IDLE; if (cleartargetstate) mTargetState = STATE_IDLE; } } @Override public boolean onTouchEvent(MotionEvent ev) { if (isInPlaybackState() && mMediaController != null) toggleMediaControlsVisiblity(); return false; } @Override public boolean onTrackballEvent(MotionEvent ev) { if (isInPlaybackState() && mMediaController != null) toggleMediaControlsVisiblity(); return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean isKeyCodeSupported = keyCode != KeyEvent.KEYCODE_BACK && keyCode != KeyEvent.KEYCODE_VOLUME_UP && keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_MENU && keyCode != KeyEvent.KEYCODE_CALL && keyCode != KeyEvent.KEYCODE_ENDCALL; if (isInPlaybackState() && isKeyCodeSupported && mMediaController != null) { if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keyCode == KeyEvent.KEYCODE_SPACE) { if (mMediaPlayer.isPlaying()) { pause(); mMediaController.show(); } else { start(); mMediaController.hide(); } return true; } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP && mMediaPlayer.isPlaying()) { pause(); mMediaController.show(); } else { toggleMediaControlsVisiblity(); } } return super.onKeyDown(keyCode, event); } private void toggleMediaControlsVisiblity() { if (mMediaController.isShowing()) { mMediaController.hide(); } else { mMediaController.show(); } } @Override public void start() { if (isInPlaybackState()) { mMediaPlayer.start(); mCurrentState = STATE_PLAYING; } mTargetState = STATE_PLAYING; } @Override public void pause() { if (isInPlaybackState()) { if (mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); mCurrentState = STATE_PAUSED; } } mTargetState = STATE_PAUSED; } public void resume() { if (mSurfaceHolder == null && mCurrentState == STATE_SUSPEND) { mTargetState = STATE_RESUME; } else if (mCurrentState == STATE_SUSPEND_UNSUPPORTED) { openVideo(); } } @Override public int getDuration() { if (isInPlaybackState()) { if (mDuration > 0) return (int) mDuration; mDuration = mMediaPlayer.getDuration(); return (int) mDuration; } mDuration = -1; return (int) mDuration; } @Override public int getCurrentPosition() { if (isInPlaybackState()) { long position = mMediaPlayer.getCurrentPosition(); return (int) position; } return 0; } @Override public void seekTo(long msec) { if (isInPlaybackState()) { mMediaPlayer.seekTo(msec); mSeekWhenPrepared = 0; } else { mSeekWhenPrepared = msec; } } @Override public boolean isPlaying() { return isInPlaybackState() && mMediaPlayer.isPlaying(); } @Override public int getBufferPercentage() { if (mMediaPlayer != null) return mCurrentBufferPercentage; return 0; } public int getVideoWidth() { return mVideoWidth; } public int getVideoHeight() { return mVideoHeight; } protected boolean isInPlaybackState() { return (mMediaPlayer != null && mCurrentState != STATE_ERROR && mCurrentState != STATE_IDLE && mCurrentState != STATE_PREPARING); } public boolean canPause() { return mCanPause; } public boolean canSeekBackward() { return mCanSeekBack; } public boolean canSeekForward() { return mCanSeekForward; } }
gpl-2.0
longqzh/chronOS_test
libjchronos/source/java/edu/vt/realtime/ChronosUtil.java
3005
/*************************************************************************** * Copyright (C) 2011-2012 by Virginia Tech Real-Time Systems Lab * * * * Author(s): * * - Aaron Lindsay (aaron.lindsay@vt.edu) * * * * 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 edu.vt.realtime; public class ChronosUtil{ /* Make sure libjchronos is loaded so we can access the native methods */ static{ System.loadLibrary("jchronos"); } public static native void burnCpu(long exec_usec, double slope); public static native void usleep(long usec); public static final native void printAbortTime(int tid); public static final native int gettid(); public static native int getPriority(); /* These set/get the "nice" values */ public static native boolean setPriority(int priority); public static boolean setLinuxScheduler(LinuxSchedulerType sched, int priority){ return ChronosUtil.setLinuxScheduler(sched.getNativeId(), priority); } public static boolean setLinuxScheduler(LinuxSchedulerType sched){ return ChronosUtil.setLinuxScheduler(sched.getNativeId(), sched==LinuxSchedulerType.SCHED_NORMAL?1:0); } private static native boolean setLinuxScheduler(int sched, int priority); public static LinuxSchedulerType getLinuxScheduler() { return LinuxSchedulerType.typeFromInt(ChronosUtil.chronos_getLinuxScheduler()); } private static native int chronos_getLinuxScheduler(); public static native boolean setAffinity(int pid, long mask); public static boolean setAffinity(long mask) {return ChronosUtil.setAffinity(0, mask); } public static native boolean memoryLock(); public static native boolean memoryUnlock(); }
gpl-2.0
icesphere/star-realms-simulator
src/starrealmssimulator/cards/ships/machinecult/PatrolBot.java
1098
package starrealmssimulator.cards.ships.machinecult; import starrealmssimulator.model.*; public class PatrolBot extends Ship implements AlliableCard { public PatrolBot() { name = "Patrol Bot"; faction = Faction.MACHINE_CULT; cost = 2; set = CardSet.CRISIS_FLEETS_AND_FORTRESSES; text = "Add 2 Trade OR Add 4 Combat; Ally: You may scrap a card in your hand or discard pile"; } @Override public void cardPlayed(Player player) { Choice choice1 = new Choice(1, "Add 2 Trade"); Choice choice2 = new Choice(2, "Add 4 Combat"); player.makeChoice(this, choice1, choice2); } @Override public void choiceMade(int choice, Player player) { player.getGame().gameLog("Chose Add 2 Trade"); if (choice == 1) { player.addTrade(2); } else if (choice == 2) { player.getGame().gameLog("Chose Add 4 Combat"); player.addCombat(4); } } @Override public void cardAllied(Player player) { player.scrapCardFromHandOrDiscard(); } }
gpl-2.0
javiergarciaescobedo/AddressBookDroid
app/src/main/java/es/javiergarciaescobedo/addressbookdroid/models/Persons.java
2252
package es.javiergarciaescobedo.addressbookdroid.models; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Persons { public static List<Person> personList = new ArrayList(); public static Map<String, Person> ITEM_MAP = new HashMap<String, Person>(); /** * Load a little number of persons in the list, with only a few properties filled */ public static void loadSimpleSamples() { Person person = new Person(); person = new Person(); person.setId(1); person.setName("EVA MARIA"); person.setSurnames("HURTADO REQUENA"); person.setAlias("EVA"); person.setPhoneNumber("956290949"); person.setFavorite(true); person.setEmail("eva.hurtado@server.com"); person.setAddress("CLAVILEÑO , CALLE"); person.setPostCode("11659"); person.setCity("PUERTO SERRANO"); person.setProvince("CÁDIZ"); personList.add(person); ITEM_MAP.put(String.valueOf(person.getId()), person); person = new Person(); person.setId(2); person.setName("CARLOS DOMINGO DE GUZMAN"); person.setSurnames("BLANCO PEREZ"); person.setAlias("CARLOS"); person.setPhoneNumber("956125889"); person.setFavorite(false); person.setEmail("carlos.blanco@server.com"); person.setAddress("PERU , CALLE"); person.setPostCode("11611"); person.setCity("VILLALUENGA DEL ROSARIO"); person.setProvince("CÁDIZ"); personList.add(person); ITEM_MAP.put(String.valueOf(person.getId()), person); person = new Person(); person.setId(3); person.setName("ANTONIO ENRIQUE"); person.setSurnames("FUENTE DE LA SANDE\n"); person.setAlias("ANTONIO"); person.setPhoneNumber("956222472"); person.setFavorite(true); person.setEmail("antonio.fuente@server.com"); person.setAddress("PORTERIA DE STO.DOMINGO , CALLE"); person.setPostCode("11600"); person.setCity("UBRIQUE"); person.setProvince("CÁDIZ"); personList.add(person); ITEM_MAP.put(String.valueOf(person.getId()), person); } }
gpl-2.0
perlawsn/language
src/test/java/org/dei/perla/lang/executor/NoopQueryHandler.java
367
package org.dei.perla.lang.executor; import org.dei.perla.lang.executor.statement.QueryHandler; /** * @author Guido Rota 13/04/15. */ public class NoopQueryHandler implements QueryHandler<Object, Object[]> { @Override public void error(Object source, Throwable error) { } @Override public void data(Object source, Object[] value) { } }
gpl-2.0
aelliott2000/tuxcourser
src/main/java/net/ovres/tuxcourser/itemtypes/Finish.java
991
/* * TuxCourser * Copyright (C) 2003-2004 Adam Elliott * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package net.ovres.tuxcourser.itemtypes; public class Finish extends ItemType { public Finish( String baseObj ) { this.initialize( "finish", baseObj, 255, 255, 0 ); this.setScale( 1.2 ); } }
gpl-2.0
as-ideas/crowdsource
crowdsource-core/src/main/java/de/asideas/crowdsource/controller/DateTimeController.java
697
package de.asideas.crowdsource.controller; import de.asideas.crowdsource.presentation.DateTimeWrapper; import de.asideas.crowdsource.security.Roles; import org.joda.time.DateTime; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/datetime") public class DateTimeController { @Secured({Roles.ROLE_USER}) @RequestMapping(method = RequestMethod.GET) public DateTimeWrapper getDatetime() { return new DateTimeWrapper(DateTime.now()); } }
gpl-2.0
SampleSizeShop/WebServiceCommon
src/edu/ucdenver/bios/webservice/common/domain/BetaScaleList.java
3456
/* * Web service utility functions for managing hibernate, json, etc. * * Copyright (C) 2010 Regents of the University of Colorado. * * 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 edu.ucdenver.bios.webservice.common.domain; import java.util.ArrayList; import java.util.List; // TODO: Auto-generated Javadoc // TO-DO: Auto-generated Javadoc /** * List of beta scale objects to work around Jackson serializaiton issues. * * @author Uttara Sakhadeo * */ public class BetaScaleList { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The uuid. */ private byte[] uuid = null; /** The beta scale list. */ private List<BetaScale> betaScaleList = null; /*-------------------- * Constructors *--------------------*/ /** * Instantiates a new beta scale list. */ public BetaScaleList() { } /** * Instantiates a new beta scale list. * * @param uuid * the uuid */ public BetaScaleList(final byte[] uuid) { this.uuid = uuid; } /** * Instantiates a new beta scale list. * * @param uuid the uuid * @param list the list */ public BetaScaleList(final byte[] uuid, final List<BetaScale> list) { this.betaScaleList = list; this.uuid = uuid; } /** * Instantiates a new beta scale list. * * @param list * the list */ public BetaScaleList(final List<BetaScale> list) { this.betaScaleList = list; } /** * Instantiates a new beta scale list. * * @param size * the size */ public BetaScaleList(final int size) { this.betaScaleList = new ArrayList<BetaScale>(size); } /*-------------------- * Getter/Setter Methods *--------------------*/ /** * Gets the uuid. * * @return the uuid */ public final byte[] getUuid() { return uuid; } /** * Sets the uuid. * * @param uuid * the new uuid */ public final void setUuid(final byte[] uuid) { this.uuid = uuid; } /** * Gets the beta scale list. * * @return the beta scale list */ public final List<BetaScale> getBetaScaleList() { return betaScaleList; } /** * Sets the beta scale list. * * @param betaScaleList * the new beta scale list */ public void setBetaScaleList(final List<BetaScale> betaScaleList) { this.betaScaleList = betaScaleList; } }
gpl-2.0
medavox/distribackup
src/main/java/com/medavox/distribackup/connections/Listener.java
1383
package com.medavox.distribackup.connections; import java.io.*; import java.net.*; import com.medavox.distribackup.peers.Peer; /**Assigns new Sockets to incoming connections. The first point of contact for new connections. * Further new connection set up is handled via a callback: Peer.setupNewSocket(Socket)*/ public class Listener extends Thread { static PrintStream o = System.out; Peer owner; private int port = 1210;//default value private final int MAX_BACKLOG = 50; public Listener(int port, Peer owner) { this.port = port; this.owner = owner; } public void run() { ServerSocket svr; //get open port to listen on while(true) { try { System.out.println("Opening listening port: "+port+"..."); svr = new ServerSocket(port, MAX_BACKLOG); break; } catch(BindException be) { System.err.println(be.getMessage()); port++; continue; } catch(IOException ioe) { ioe.printStackTrace(); System.exit(1); } } while(owner.threadsEnabled) {//on a new socket connection: try { Socket s = svr.accept(); owner.setupNewSocket(s);//callback: pass new Socket back to main thread } catch(Exception e) { System.err.println("CRASHED on connection NODATA"); e.printStackTrace(); System.exit(1); } //o.println("connection "+connectionNumber+" established"); } } }
gpl-2.0
tkaviya/streets
src/main/java/net/blaklizt/streets/android/location/navigation/Legs.java
1464
package net.blaklizt.streets.android.location.navigation; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * User: tkaviya * Date: 7/1/14 * Time: 7:49 PM */ public class Legs { private ArrayList<Steps> steps; private String totalDistance; private String totalDuration; public Legs(JSONObject leg){ steps = new ArrayList<Steps>(); parseSteps(leg); } public ArrayList<Steps> getSteps(){ return steps; } private void parseSteps(JSONObject leg){ try{ if(!leg.isNull("steps")){ JSONArray step = leg.getJSONArray("steps"); for(int i=0; i<step.length();i++){ JSONObject obj = step.getJSONObject(i); steps.add(new Steps(obj)); } } if(!leg.isNull("distance")){ JSONObject obj = leg.getJSONObject("distance"); totalDistance = obj.getString("text"); } if(!leg.isNull("duration")){ JSONObject obj = leg.getJSONObject("duration"); totalDuration = obj.getString("text"); } }catch (JSONException e) { e.printStackTrace(); } } public String getLegDistance(){ return totalDistance; } public String getLegDuration(){ return totalDuration; } }
gpl-2.0
mobile-event-processing/Asper
source/test/com/espertech/esper/support/xml/SupportXPathFunctionResolver.java
1106
/* * ************************************************************************************* * 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.support.xml; import javax.xml.xpath.XPathVariableResolver; import javax.xml.xpath.XPathFunctionResolver; import javax.xml.xpath.XPathFunction; import javax.xml.namespace.QName; public class SupportXPathFunctionResolver implements XPathFunctionResolver { public XPathFunction resolveFunction(QName functionName, int arity) { return null; } }
gpl-2.0
kartoFlane/FTL-ErrorChecker
src/com/kartoflane/ftl/errorchecker/core/CheckerConfig.java
7408
package com.kartoflane.ftl.errorchecker.core; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Properties; import java.util.concurrent.TimeUnit; import javax.swing.UIManager; @SuppressWarnings("serial") public class CheckerConfig extends Properties { // @formatter:off public static final String USE_NATIVE_GUI = "use_native_gui"; public static final String FTL_DAT_PATH = "ftl_dats_path"; public static final String REM_GEOMETRY = "remember_geometry"; public static final String GEOMETRY = "geometry"; public static final String UPDATE_DATABASE = "update_db"; public static final String UPDATE_APPLICATION = "update_app"; public static final String HIDE_EMPTY_FILES = "hide_empty_files"; public static final String LOGGING_LEVEL = "log_level"; public static final String VIEWER_FONT_STYLE = "viewer_font_style"; public static final String VIEWER_FONT_SIZE = "viewer_font_size"; public static final String VIEWER_TAB_SIZE = "viewer_tab_size"; public static final String VIEWER_WRAP_TEXT = "viewer_wrap"; public static final String PARSER_MAX_THREADS = "parser_max_threads"; public static final String PARSER_TIMEOUT_VAL = "parser_timeout_val"; public static final String PARSER_TIMEOUT_UNIT = "parser_timeout_unit"; public static final String VALIDATE_MAX_THREADS = "validate_max_threads"; public static final String VALIDATE_TIMEOUT_VAL = "validate_timeout_val"; public static final String VALIDATE_TIMEOUT_UNIT = "validate_timeout_unit"; public static final String FONT_STYLE_DEFAULT = "System Default"; // @formatter:on private final File configFile; public CheckerConfig(File configFile) { this.configFile = configFile; } /** * Returns a copy of an existing CheckerConfig object. */ public CheckerConfig(CheckerConfig srcConfig) { this.configFile = srcConfig.getConfigFile(); putAll(srcConfig); } public File getConfigFile() { return configFile; } public int getPropertyAsInt(String key) { String s = super.getProperty(key); if (s != null && s.matches("^\\d+$")) return Integer.parseInt(s); else return getPropertyDefaultValueInteger(key); } public boolean getPropertyAsBoolean(String key) { String s = super.getProperty(key); if (s == null) return getPropertyDefaultValueBoolean(key); try { return Boolean.parseBoolean(s); } catch (Exception e) { return getPropertyDefaultValueBoolean(key); } } @Override public String getProperty(String key, String defaultValue) { return getProperty(key); } @Override public String getProperty(String key) { String s = super.getProperty(key); if (s == null) { return getPropertyDefaultValueString(key); } return s; } public void writeConfig() throws IOException { OutputStream out = null; try { out = new FileOutputStream(configFile); String configComments = ""; configComments += "\n"; configComments += String.format(" %-20s- If true, the program will try to resemble the native GUI. Default: %s.%n", USE_NATIVE_GUI, getPropertyDefaultValueBoolean(USE_NATIVE_GUI)); configComments += String.format(" %-20s- The path to FTL's resources folder. If invalid, you'll be prompted.%n", FTL_DAT_PATH); configComments += String.format(" %-20s- If true, window geometry will be saved on exit and restored on startup. Default: %s.%n", REM_GEOMETRY, getPropertyDefaultValueBoolean(REM_GEOMETRY)); configComments += String.format(" %-20s- If a number greater than 0, check for new database every N days. Default: %s.%n", UPDATE_DATABASE, getPropertyDefaultValueInteger(UPDATE_DATABASE)); configComments += String.format(" %-20s- If a number greater than 0, check for newer app versions every N days. Default: %s.%n", UPDATE_APPLICATION, getPropertyDefaultValueInteger(UPDATE_APPLICATION)); configComments += String.format(" %-20s- If true, files that don't have any problems will not be shown in the tree. Default: %s.%n", HIDE_EMPTY_FILES, getPropertyDefaultValueBoolean(HIDE_EMPTY_FILES)); configComments += String.format(" %-20s- The name of the logical font used in the text viewer.%n", VIEWER_FONT_STYLE); configComments += String.format(" %-20s- Size of the font used in the viewer.%n", VIEWER_FONT_SIZE); configComments += String.format(" %-20s- Indentation level of a single tab character. Default: %s.%n", VIEWER_TAB_SIZE, getPropertyDefaultValueInteger(VIEWER_TAB_SIZE)); configComments += String.format(" %-20s- If true, text in the viewer will be wrapped. Default: %s.%n", VIEWER_WRAP_TEXT, getPropertyDefaultValueBoolean(VIEWER_WRAP_TEXT)); configComments += String.format(" %-20s- Amount of time the parser has to finish parsing all files. Default: %s.%n", PARSER_TIMEOUT_VAL, getPropertyDefaultValueInteger(PARSER_TIMEOUT_VAL)); configComments += String.format(" %-20s- The unit of time used for the above value. Default: %s.%n", PARSER_TIMEOUT_UNIT, getPropertyDefaultValueString(PARSER_TIMEOUT_UNIT)); configComments += String.format(" %-20s- Amount of time the program has to finish validating all files. Default: %s.%n", PARSER_TIMEOUT_VAL, getPropertyDefaultValueInteger(VALIDATE_TIMEOUT_VAL)); configComments += String.format(" %-20s- The unit of time used for the above value. Default: %s.%n", PARSER_TIMEOUT_UNIT, getPropertyDefaultValueString(VALIDATE_TIMEOUT_UNIT)); configComments += "\n"; configComments += String.format(" %-20s- Last saved position/size/etc of the main window.%n", GEOMETRY); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); store(writer, configComments); writer.flush(); } finally { try { if (out != null) out.close(); } catch (IOException e) { } } } public static int getPropertyDefaultValueInteger(String key) { if (UPDATE_DATABASE.equals(key)) { return 7; } else if (UPDATE_APPLICATION.equals(key)) { return 7; } else if (VIEWER_FONT_SIZE.equals(key)) { return UIManager.getFont("Label.font").getSize(); } else if (VIEWER_TAB_SIZE.equals(key)) { return 4; } else if (PARSER_MAX_THREADS.equals(key)) { return 2; } else if (VALIDATE_MAX_THREADS.equals(key)) { return 2; } else if (PARSER_TIMEOUT_VAL.equals(key)) { return 30; } else if (VALIDATE_TIMEOUT_VAL.equals(key)) { return 30; } throw new IllegalArgumentException("Not an integer property: " + key); } public static boolean getPropertyDefaultValueBoolean(String key) { if (USE_NATIVE_GUI.equals(key) || REM_GEOMETRY.equals(key)) { return true; } else if (HIDE_EMPTY_FILES.equals(key) || VIEWER_WRAP_TEXT.equals(key)) { return false; } throw new IllegalArgumentException("Not a boolean property: " + key); } public static String getPropertyDefaultValueString(String key) { if (FTL_DAT_PATH.equals(key)) { return ""; } else if (VIEWER_FONT_STYLE.equals(key)) { return FONT_STYLE_DEFAULT; } else if (PARSER_TIMEOUT_UNIT.equals(key)) { return TimeUnit.SECONDS.toString(); } else if (VALIDATE_TIMEOUT_UNIT.equals(key)) { return TimeUnit.SECONDS.toString(); } else if (GEOMETRY.equals(key)) { return null; } else if (LOGGING_LEVEL.equals(key)) { return "INFO"; } throw new IllegalArgumentException("Not a string property: " + key); } }
gpl-2.0
hkaj/CoFITS
server/src/utils/projectNameEncoder.java
1231
package utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import Constants.DataBaseConstants; public class projectNameEncoder { public Connection createConnection() throws SQLException { Connection conn = null; conn = DriverManager.getConnection( "jdbc:postgresql://" + DataBaseConstants.host + "/" + DataBaseConstants.databaseName, DataBaseConstants.userName, DataBaseConstants.password ); return conn; } public String encode(String projectName) { String projectId = projectName.replace(" ", "_"); String requestStr = "SELECT count(*) as c FROM projects p where p.name = '" + projectName + "';"; int count = 0; try { Statement s = this.createConnection().createStatement(); final ResultSet res = s.executeQuery(requestStr); if (res.next()) { count = res.getInt("c"); } } catch (SQLException e) { e.printStackTrace(); } projectId = projectId.concat("_" + count); return projectId; } public void main(String[] args) { System.out.println("Trying to encode 'SR03 project'..."); System.out.println("The encoded id is: " + encode("SR03 project")); } }
gpl-2.0
gulimran/hackerdetector
detector/src/test/java/com/imrang/detector/domain/ActivityLogTest.java
1077
package com.imrang.detector.domain; import com.imrang.detector.convert.ActivityLogConverter; import com.imrang.detector.convert.Converter; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.junit.Test; public class ActivityLogTest { private static Converter<ActivityLog, String> converter = new ActivityLogConverter(); @Test public void shouldFulfillEqualsHashCodeContract() { ActivityLog activityLog = new ActivityLog("80.238.9.179", 133612947, Action.SIGNIN_SUCCESS,"Dave.Branning"); EqualsVerifier.forClass(ActivityLog.class) .withPrefabValues(ActivityLog.class, activityLog, new ActivityLog()) .suppress(Warning.NONFINAL_FIELDS, Warning.NULL_FIELDS) .verify(); } public static ActivityLog buildActivityLog(String ip, Long time, Action action, String userName) { return new ActivityLog(ip, time, action,userName); } public static ActivityLog buildActivityLog(String line) { return converter.convert(line); } }
gpl-2.0
saces/fred
src/freenet/node/updater/UpdateDeployContext.java
11514
package freenet.node.updater; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Properties; import org.tanukisoftware.wrapper.WrapperManager; import freenet.l10n.NodeL10n; import freenet.node.NodeInitException; import freenet.node.updater.UpdateDeployContext.CHANGED; import freenet.support.io.Closer; /** * Handles the wrapper.conf, essentially. */ public class UpdateDeployContext { public static class UpdateCatastropheException extends Exception { private static final long serialVersionUID = 1L; File oldConfig; File newConfig; UpdateCatastropheException(File oldConfig, File newConfig) { super(l10n("updateCatastrophe", new String[] { "old", "new" }, new String[] { oldConfig.toString(), newConfig.toString() })); this.oldConfig = oldConfig; this.newConfig = newConfig; } } File mainJar; File extJar; int mainClasspathNo; int extClasspathNo; File newMainJar; File newExtJar; boolean mainJarAbsolute; boolean extJarAbsolute; boolean currentExtJarHasNewExtension; boolean currentExtJarHasNewExtension() { return currentExtJarHasNewExtension; } UpdateDeployContext() throws UpdaterParserException { Properties p = WrapperManager.getProperties(); for(int propNo=1;true;propNo++) { String prop = p.getProperty("wrapper.java.classpath."+propNo); if(prop == null) break; File f = new File(prop); boolean isAbsolute = f.isAbsolute(); String name = f.getName().toLowerCase(); if(extJar == null) { if(name.equals("freenet-ext.jar.new")) { extJar = f; newExtJar = new File(extJar.getParent(), "freenet-ext.jar"); extJarAbsolute = isAbsolute; extClasspathNo = propNo; currentExtJarHasNewExtension = true; continue; } else if(name.equals("freenet-ext.jar")) { extJar = f; newExtJar = new File(extJar.getParent(), "freenet-ext.jar.new"); extClasspathNo = propNo; continue; } } if(mainJar == null) { // Try to match it if((name.startsWith("freenet") && (name.endsWith(".jar")))) { mainJar = f; newMainJar = new File(mainJar.getParent(), "freenet.jar.new"); mainJarAbsolute = isAbsolute; mainClasspathNo = propNo; continue; } else if((name.startsWith("freenet") && (name.endsWith(".jar.new")))) { mainJar = f; newMainJar = new File(mainJar.getParent(), "freenet.jar"); mainJarAbsolute = isAbsolute; mainClasspathNo = propNo; continue; } } } if(mainJar == null && extJar == null) throw new UpdaterParserException(l10n("cannotUpdateNoJars")); if(mainJar == null) throw new UpdaterParserException(l10n("cannotUpdateNoMainJar", "extFilename", extJar.toString())); if(extJar == null) throw new UpdaterParserException(l10n("cannotUpdateNoExtJar", "mainFilename", mainJar.toString())); } private String l10n(String key) { return NodeL10n.getBase().getString("UpdateDeployContext."+key); } public static String l10n(String key, String[] patterns, String[] values) { return NodeL10n.getBase().getString("UpdateDeployContext."+key, patterns, values); } public static String l10n(String key, String pattern, String value) { return NodeL10n.getBase().getString("UpdateDeployContext."+key, pattern, value); } File getMainJar() { return mainJar; } File getNewMainJar() { return newMainJar; } File getExtJar() { return extJar; } File getNewExtJar() { return newExtJar; } void rewriteWrapperConf(boolean writtenNewJar, boolean writtenNewExt) throws IOException, UpdateCatastropheException, UpdaterParserException { // Rewrite wrapper.conf // Don't just write it out from properties; we want to keep it as close to what it was as possible. File oldConfig = new File("wrapper.conf"); File newConfig = new File("wrapper.conf.new"); if(!oldConfig.exists()) { File wrapperDir = new File("wrapper"); if(wrapperDir.exists() && wrapperDir.isDirectory()) { File o = new File(wrapperDir, "wrapper.conf"); if(o.exists()) { oldConfig = o; newConfig = new File(wrapperDir, "wrapper.conf.new"); } } } FileInputStream fis = new FileInputStream(oldConfig); BufferedInputStream bis = new BufferedInputStream(fis); InputStreamReader isr = new InputStreamReader(bis); BufferedReader br = new BufferedReader(isr); FileOutputStream fos = new FileOutputStream(newConfig); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); String line; boolean writtenReload = false; String newMain = mainJarAbsolute ? newMainJar.getAbsolutePath() : newMainJar.getPath(); String newExt = extJarAbsolute ? newExtJar.getAbsolutePath() : newExtJar.getPath(); String extRHS = null; String mainRHS = null; ArrayList<String> otherLines = new ArrayList<String>(); ArrayList<String> classpath = new ArrayList<String>(); // We MUST put the ext before the main jar, or auto-update of freenet-ext.jar on Windows won't work. // The main jar refers to freenet-ext.jar so that java -jar freenet.jar works. // Therefore, on Windows, if we update freenet-ext.jar, it will use freenet.jar and freenet-ext.jar // and freenet-ext.jar.new as well. The old freenet-ext.jar will take precedence, and we won't be // able to overwrite either of them, so we'll just restart every 5 minutes forever! while((line = br.readLine()) != null) { // The classpath numbers are not reliable. // We have to check the content. boolean dontWrite = false; if(line.startsWith("wrapper.java.classpath.")) { line = line.substring("wrapper.java.classpath.".length()); int idx = line.indexOf('='); if(idx != -1) { try { int number = Integer.parseInt(line.substring(0, idx)); // Don't go by the numbers. String rhs = line.substring(idx+1); System.out.println("RHS is: "+rhs); if(rhs.equals("freenet-ext.jar") || rhs.equals("freenet-ext.jar.new")) { if(writtenNewExt) extRHS = newExt; else extRHS = rhs; dontWrite = true; } else if(rhs.equals("freenet.jar") || rhs.equals("freenet.jar.new") || rhs.equals("freenet-stable-latest.jar") || rhs.equals("freenet-stable-latest.jar.new") || rhs.equals("freenet-testing-latest.jar") || rhs.equals("freenet-testing-latest.jar.new")) { if(writtenNewJar) mainRHS = newMain; else mainRHS = rhs; dontWrite = true; } else { classpath.add(rhs); dontWrite = true; } } catch (NumberFormatException e) { // Argh! System.out.println("Don't understand line in wrapper.conf - should be numeric?:\n"+line); } } } else if(line.equalsIgnoreCase("wrapper.restart.reload_configuration=TRUE")) { writtenReload = true; } if(!dontWrite) otherLines.add(line); } br.close(); // Write classpath first if(mainRHS == null || extRHS == null) { throw new UpdaterParserException(l10n("updateFailedNonStandardConfig", new String[] { "main", "ext" }, new String[] { Boolean.toString(mainRHS != null), Boolean.toString(extRHS != null) } )); } // Write ext first bw.write("wrapper.java.classpath.1="+extRHS+'\n'); bw.write("wrapper.java.classpath.2="+mainRHS+'\n'); int count = 3; for(String s : classpath) { bw.write("wrapper.java.classpath."+count+"="+s+'\n'); count++; } for(String s : otherLines) bw.write(s+'\n'); if(!writtenReload) { // Add it. bw.write("wrapper.restart.reload_configuration=TRUE\n"); } bw.close(); if(!newConfig.renameTo(oldConfig)) { if(!oldConfig.delete()) { throw new UpdaterParserException(l10n("updateFailedCannotDeleteOldConfig", "old", oldConfig.toString())); } if(!newConfig.renameTo(oldConfig)) { throw new UpdateCatastropheException(oldConfig, newConfig); } } // New config installed. System.err.println("Rewritten wrapper.conf for"+(writtenNewJar ? (" new main jar: "+newMainJar) : "")+(writtenNewExt ? (" new ext jar: "+newExtJar): "")); } public enum CHANGED { ALREADY, // Found the comment, so it has already been changed SUCCESS, // Succeeded FAIL // Failed e.g. due to unable to write wrapper.conf. } public static CHANGED tryIncreaseMemoryLimit(int extraMemoryMB, String markerComment) { // Rewrite wrapper.conf // Don't just write it out from properties; we want to keep it as close to what it was as possible. File oldConfig = new File("wrapper.conf"); File newConfig = new File("wrapper.conf.new"); if(!oldConfig.exists()) { File wrapperDir = new File("wrapper"); if(wrapperDir.exists() && wrapperDir.isDirectory()) { File o = new File(wrapperDir, "wrapper.conf"); if(o.exists()) { oldConfig = o; newConfig = new File(wrapperDir, "wrapper.conf.new"); } } } FileInputStream fis = null; BufferedInputStream bis = null; InputStreamReader isr = null; BufferedReader br = null; FileOutputStream fos = null; OutputStreamWriter osw = null; BufferedWriter bw = null; boolean success = false; try { fis = new FileInputStream(oldConfig); bis = new BufferedInputStream(fis); isr = new InputStreamReader(bis); br = new BufferedReader(isr); fos = new FileOutputStream(newConfig); osw = new OutputStreamWriter(fos); bw = new BufferedWriter(osw); String line; while((line = br.readLine()) != null) { if(line.equals("#" + markerComment)) return CHANGED.ALREADY; if(line.startsWith("wrapper.java.maxmemory=")) { try { int memoryLimit = Integer.parseInt(line.substring("wrapper.java.maxmemory=".length())); int newMemoryLimit = memoryLimit + extraMemoryMB; // There have been some cases where really high limits have caused the JVM to do bad things. if(newMemoryLimit > 2048) newMemoryLimit = 2048; bw.write('#' + markerComment + '\n'); bw.write("wrapper.java.maxmemory="+newMemoryLimit+'\n'); success = true; continue; } catch (NumberFormatException e) { // Grrrrr! } } bw.write(line+'\n'); } br.close(); } catch (IOException e) { newConfig.delete(); System.err.println("Unable to rewrite wrapper.conf with new memory limit."); return CHANGED.FAIL; } finally { Closer.close(br); Closer.close(isr); Closer.close(bis); Closer.close(fis); Closer.close(bw); Closer.close(osw); Closer.close(fos); } if(success) { if(!newConfig.renameTo(oldConfig)) { if(!oldConfig.delete()) { System.err.println("Unable to move rewritten wrapper.conf with new memory limit "+newConfig+" over old config "+oldConfig+" : unable to delete old config"); return CHANGED.FAIL; } if(!newConfig.renameTo(oldConfig)) { System.err.println("Old wrapper.conf deleted but new wrapper.conf cannot be renamed!"); System.err.println("FREENET WILL NOT START UNTIL YOU RENAME "+newConfig+" to "+oldConfig); System.exit(NodeInitException.EXIT_BROKE_WRAPPER_CONF); } } System.err.println("Rewritten wrapper.conf for new memory limit"); return CHANGED.SUCCESS; } else { newConfig.delete(); return CHANGED.FAIL; } } }
gpl-2.0
waqasraz/Compiler-J--
jmm/src/AST/Blockstatements.java
1140
package AST; public abstract class Blockstatements implements SyntaxNode { private SyntaxNode parent; public Blockstatements getBlockstatements() { throw new ClassCastException("tried to call abstract method"); } public void setBlockstatements(Blockstatements blockstatements) { throw new ClassCastException("tried to call abstract method"); } public Blockstatement getBlockstatement() { throw new ClassCastException("tried to call abstract method"); } public void setBlockstatement(Blockstatement blockstatement) { throw new ClassCastException("tried to call abstract method"); } public SyntaxNode getParent() { return parent; } public void setParent(SyntaxNode parent) { this.parent=parent; } public abstract void accept(Visitor visitor); public abstract void childrenAccept(Visitor visitor); public abstract void traverseTopDown(Visitor visitor); public abstract void traverseBottomUp(Visitor visitor); public String toString() { return toString(""); } public abstract String toString(String tab); }
gpl-2.0
Urinx/SomeCodes
Android/sms/gen/com/eular/sms/BuildConfig.java
155
/** Automatically generated file. DO NOT MODIFY */ package com.eular.sms; public final class BuildConfig { public final static boolean DEBUG = true; }
gpl-2.0
austinv11/CollectiveFramework
src/main/java/com/austinv11/collectiveframework/utils/TimeProfiler.java
640
package com.austinv11.collectiveframework.utils; /** * Simple class for figuring out how long things take to be done */ public class TimeProfiler { private long startTime; /** * Starts a profiler at the current instant */ public TimeProfiler() { startTime = System.currentTimeMillis(); } /** * Gets the amount of time lapsed from instantiation to the method call * @return The time (in ms) */ public long getTime() { return System.currentTimeMillis()-startTime; } /** * Gets the time this object was instantiated at * @return The time (in ms) */ public long getStartTime() { return startTime; } }
gpl-2.0
craigcabrey/swen-343-base-patterns-examples
gateway/ComplexPricingStrategy.java
509
// Complex API code public class ComplexPricingStrategy { int calculateAirlinePricing(String source, String destination) { return source.length() + destination.length(); } int calculateProprtyValuation(String location) { return (location.length() * 150 % 40 + 12345 - 50) >> 1; } int calculateOilValuation(String location) { int arbitrary_oil_weight = 87; int complex_oil_expression = (arbitrary_oil_weight * 13) * 321; return (complex_oil_expression * location.length()) << 2; } }
gpl-2.0
SampleSizeShop/GlimmpseWeb
src/edu/ucdenver/bios/glimmpseweb/client/shared/GlimmpseLogoPanel.java
644
package edu.ucdenver.bios.glimmpseweb.client.shared; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.VerticalPanel; import edu.ucdenver.bios.glimmpseweb.client.GlimmpseConstants; public class GlimmpseLogoPanel extends Composite { private static final String STYLE = "glimmpseLogo"; public GlimmpseLogoPanel() { VerticalPanel panel = new VerticalPanel(); HTML name = new HTML(""); // layout panel.add(name); // set style name.setStyleName(STYLE); initWidget(panel); } }
gpl-2.0
supermavp/avisoft
appAvisoft/src/Modelo/Insumo.java
8936
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Modelo; import java.util.ArrayList; import java.util.HashMap; import javax.swing.table.AbstractTableModel; /** * * @author zirex */ public class Insumo { private Conexion con; private String id; private String nombre; private int cantidad; private String medida; private String estado; private String nombre_tipo; public Insumo(String id, String nombre, int cantidad, String medida, String nombre_tipo) { this.con= new Conexion(); ArrayList<HashMap> res= this.con.query("SELECT * FROM insumo WHERE id='"+id+"';"); if(res.isEmpty()){ this.con.query("INSERT INTO insumo (id, nombre, cantidad, medida, nombre_tipo) VALUES('"+id+"', '"+nombre+"', "+cantidad+", '"+medida+"', '"+nombre_tipo+"');"); this.id = id; this.nombre = nombre; this.cantidad = cantidad; this.medida = medida; this.estado= "1"; this.nombre_tipo = nombre_tipo; } else{ this.id= res.get(0).get("id")+""; this.nombre= res.get(0).get("nombre").toString(); this.cantidad= Integer.valueOf(res.get(0).get("cantidad")+""); this.medida= res.get(0).get("medida").toString(); this.estado= res.get(0).get("estado").toString(); this.nombre_tipo= res.get(0).get("nombre_tipo")+""; } } public Insumo(String id, String nombre, int cantidad, String medida, String estado, String nombre_tipo) { this.con=new Conexion(); this.id = id; this.nombre = nombre; this.cantidad = cantidad; this.medida = medida; this.estado= estado; this.nombre_tipo= nombre_tipo; } public static boolean addTipo(String tipo){ Conexion con = new Conexion(); ArrayList<HashMap> res= con.query("SELECT * FROM tipo WHERE nombre_tipo= '"+tipo+"';"); if(res.isEmpty()){ con.query("INSERT INTO tipo VALUES ('"+tipo+"');"); return true; } else{ return false; } } public static ArrayList<String> consulTipo(){ Conexion con= new Conexion(); ArrayList<String> tipos= new ArrayList<String>(); ArrayList<HashMap> res= con.query("SELECT * FROM tipo"); for (HashMap tipo : res) { tipos.add(tipo.get("nombre_tipo").toString()); } return tipos; } public static ArrayList<String[]> getInsumos() { Conexion con = new Conexion(); ArrayList<String[]> ins = new ArrayList<String[]>(); ArrayList<HashMap> inms = con.query("SELECT * FROM insumo WHERE estado= 1"); for (HashMap inm: inms) { String m[] = {inm.get("id").toString(), inm.get("nombre").toString(), inm.get("nombre_tipo").toString(), inm.get("cantidad").toString(), inm.get("medida").toString()}; ins.add(m); } return ins; } public static AbstractTableModel tablaIns(){ AbstractTableModel tabla= new AbstractTableModel() { private Conexion con; private String[] ColumnName= {"Id", "Nombre", "Tipo", "Cant.", "Medida", "Estado"}; private Object [][] cons= this.contenido(); private Object[][] contenido(){ boolean activo= true; boolean inactivo= false; this.con= new Conexion(); Object [][] datos; ArrayList<HashMap> res= con.query("SELECT * FROM insumo"); datos= new Object[res.size()][ColumnName.length]; int i=0; for (HashMap fila : res) { String [] col= {fila.get("id").toString(), fila.get("nombre").toString(), fila.get("nombre_tipo").toString(), fila.get("cantidad").toString(), fila.get("medida").toString(), fila.get("estado").toString()}; for(int j=0; j<ColumnName.length; j++){ if(j !=5){ datos[i][j]= col[j]; } else{ if(Integer.parseInt(col[j]+"") == 1){ datos[i][j]= activo; } else{ datos[i][j]= inactivo; } } } i++; } return datos; } @Override public int getRowCount() { return this.cons.length; } @Override public int getColumnCount() { return this.ColumnName.length; } @Override public Object getValueAt(int i, int i1) { return this.cons[i][i1]; } @Override public String getColumnName(int columnIndex){ return this.ColumnName[columnIndex]; } @Override public Class<?> getColumnClass(int c){ return this.cons[0][c].getClass(); } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex){ if(columnIndex == 5){ boolean value= Boolean.parseBoolean(aValue.toString()); String estado= "0"; if(value == true){ estado= "1"; } Insumo i= Insumo.existe(this.cons[rowIndex][0].toString()); i.setEstado(estado); this.cons[rowIndex][columnIndex]= value; // Disparamos el Evento TableDataChanged (La tabla ha cambiado) //fireTableCellUpdated(rowIndex, columnIndex); } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex==5; } }; return tabla; } public String getEstado() { return estado; } public int getCantidad() { return cantidad; } public String getId() { return id; } public String getMedida() { return medida; } public String getNombre() { return nombre; } public String getTipo() { return nombre_tipo; } public void setEstado(String estado) { this.con.query("UPDATE insumo SET estado='"+estado+"' WHERE id='"+this.id+"';"); this.estado = estado; } public void setMedida(String medida) { this.con.query("UPDATE insumo SET medida='"+medida+"' WHERE id='"+this.id+"';"); this.medida = medida; } public void setTipo(String nombre_tipo) { this.con.query("UPDATE insumo SET nombre_tipo='"+nombre_tipo+"' WHERE id='"+this.id+"';"); this.nombre_tipo = nombre_tipo; } public void setCantidad(int cantidad, int opc) { if(opc==1){ this.con.query("UPDATE insumo SET cantidad= cantidad +"+cantidad+" WHERE id='"+this.id+"';"); this.cantidad+=cantidad; } else{ this.con.query("UPDATE insumo SET cantidad= cantidad -"+cantidad+" WHERE id='"+this.id+"';"); this.cantidad-=cantidad; } } public void setNombre(String nombre) { this.con.query("UPDATE insumo SET nombre= '"+nombre+"' WHERE id= '"+this.id+"';"); this.nombre = nombre; } public static Insumo existe(String id){ Conexion c= new Conexion(); ArrayList<HashMap> res= c.query("SELECT nombre, nombre_tipo, cantidad, medida, estado FROM insumo WHERE id= '"+id+"';"); if(!res.isEmpty()){ return new Insumo(id, res.get(0).get("nombre")+"", Integer.parseInt(res.get(0).get("cantidad")+""), res.get(0).get("medida").toString(), res.get(0).get("estado")+"", res.get(0).get("nombre_tipo").toString()); } return null; } public static boolean update(String valores, String id) { Conexion conn= new Conexion(); boolean res = false; String q = " UPDATE insumo SET " + valores + " WHERE id= " + id; ArrayList<HashMap> oper= conn.query(q); if(oper==null) res=true; return res; } @Override public String toString() { return "Insumo{" + "id=" + id + ", nombre=" + nombre + ", tipo=" + nombre_tipo + ", cantidad=" + cantidad + ", medida=" + medida + ", estado=" + estado + '}'; } }
gpl-2.0
Lotusun/OfficeHelper
src/main/java/com/charlesdream/office/word/objects/SeriesCollection.java
314
package com.charlesdream.office.word.objects; import com.charlesdream.office.BaseObject; import com.jacob.com.Dispatch; /** * @author Charles Cui on 3/5/2016. * @since 1.0 */ public class SeriesCollection extends BaseObject { public SeriesCollection(Dispatch dispatch) { super(dispatch); } }
gpl-2.0
TachoMex/Progsis
Practica 1/Clasificador.java
8653
/** *@author Gilberto Vargas Hernández *Clase que nos ayuda a clasificar los tipos de token que puede procesar un ensamblador */ import java.util.*; import java.util.regex.*; public class Clasificador{ /** *Funcion que clasifica una string en sus 3 tipos de componentes *@param String s, la cadena a clasificar *@return una arreglo de String, si es de tamaño 1 con el error, tamaño 3 si todo salio bien */ public static String[] procesar(String s){ //Retorna un arreglo de cadenas separando las instrucciones de tamaño 3. Si la linea no es correcta retorna un arreglo de tamaño 1 con el error //Divide la cadena en 2, la parte que pertenece a un comentario y la parte de la instrucción String comentario = Clasificador.obtenerComentario(s); String instruccion = Clasificador.removerComentario(s); //Crea la variable que vamos a retornar al ginal String[] ret=null; //En una lista se van a guardar los tokens que hay en la cadena recibida. List<String> tokens = new ArrayList<String>(); StringTokenizer tok = new StringTokenizer(instruccion, "\t "); //Extrae los tokens while(tok.hasMoreTokens()){ tokens.add(tok.nextToken()); } //Dependiendo de la cantidad de tokens extraidos, se evalua la forma de la cadena switch(tokens.size()){ case 1: //Para el caso 1, solo podría ser un CODOP y debe iniciar con espacio o tabulador if(Clasificador.esCodop(tokens.get(0))){ if(s.charAt(0)==' ' || s.charAt(0)=='\t'){ ret = new String[3]; ret[0] = "NULL"; ret[1] = tokens.get(0); ret[2] = "NULL"; }else{ ret = new String[1]; if(Clasificador.esEtiqueta(tokens.get(0))){ ret[0] = "Se esperaba un codop al final de la linea"; }else{ ret[0] = "La linea debe comenzar con un espacio"; } } }else{ ret = new String[1]; if(s.charAt(0)==' ' || s.charAt(0)=='\t'){ ret[0] = Clasificador.errorCodop(tokens.get(0)); }else if(Clasificador.esEtiqueta(tokens.get(0))){ ret[0] = "Se esperaba un codop al final de la linea"; }else{ ret[0] = "La linea debe comenzar con un espacio"; } } break; case 2: //Cuando hay 2 operandos, en caso de que el primero sea una etiqueta, el segundo debe ser un CODOP //Pero si el primero es un CODOP el segundo debe ser un operando //Si no se cumple cualquier cosa, significa que hay un error if(Clasificador.esEtiqueta(tokens.get(0)) && s.charAt(0)!=' ' && s.charAt(0)!='\t' && Clasificador.esCodop(tokens.get(1))){ ret = new String[3]; ret[0] = tokens.get(0); ret[1] = tokens.get(1); ret[2] = "NULL"; }else if(Clasificador.esCodop(tokens.get(0)) && Clasificador.esOperando(tokens.get(1)) && (s.charAt(0)==' ' || s.charAt(0)=='\t')){ ret = new String[3]; ret[0] = "NULL"; ret[1] = tokens.get(0); ret[2] = tokens.get(1); }else if(Clasificador.esEtiqueta(tokens.get(0)) && s.charAt(0)!=' ' && s.charAt(0)!='\t'){ ret = new String[1]; ret[0] = Clasificador.errorCodop(tokens.get(1)); return ret; }else if(s.charAt(0)==' ' || s.charAt(0)=='\t'){ ret = new String[1]; ret[0] = Clasificador.errorCodop(tokens.get(1)); return ret; }else if(Clasificador.esCodop(tokens.get(0)) && (s.charAt(0)==' ' || s.charAt(0)=='\t')){ ret = new String[1]; ret[0] = Clasificador.errorOperando(tokens.get(1)); return ret; }else{ ret = new String[1]; ret[0] = Clasificador.errorEtiqueta(tokens.get(0)); return ret; } break; case 3: //Si la linea tiene 3 instrucciones, el unico orden en que pueden ir debe ser //Etiqueta - CODOP - OPERANDO if(Clasificador.esEtiqueta(tokens.get(0))){ if(!Character.isLetter(s.charAt(0))){ ret = new String[1]; ret[0] = "Las etiqutaes deben aparecer al inicio de la linea"; } if(Clasificador.esCodop(tokens.get(1))){ if(Clasificador.esOperando(tokens.get(2))){ ret = new String[3]; ret[0]=tokens.get(0); ret[1]=tokens.get(1); ret[2]=tokens.get(2); }else{ ret = new String[1]; ret[0] = Clasificador.errorOperando(tokens.get(2));; } }else{ ret = new String[1]; ret[0] = Clasificador.errorCodop(tokens.get(1));; } }else{ ret = new String[1]; ret[0] = Clasificador.errorEtiqueta(tokens.get(0));; } break; case 0: //Si la linea no tiene ninguna instruccion significa que esta vacia ret = new String[1]; ret[0] = "LV"; break; default: //Si la linea tiene demasiadas instrucciones significa que no hay como evaluar la cadena ret = new String[1]; ret[0]="Error en la cantidad de tokens"; } return ret; } /** *Toma el comentario de una cadena *@param String s, la cadena de la cual tomará el comentario *@return Una cadena con el comentario dentro de la cadena, cadena vacia en caso contrario */ public static String obtenerComentario(String s){ //El comentario inicia en la primer incidencia de un ';', por lo que una subcadena de donde se encuentra el primer ';' al final es el comentario int idx = s.indexOf(';'); return (idx>=0?s.substring(idx+1):""); } /** *Retorna la cadena de entrada quitandole el comentario *@param String s, la cadena a ser procesada *@return la cadena pero sin el comentario */ public static String removerComentario(String s){ //Se busca un ';' y se extrae la subcadena hasta la posicion de ';', sino se retorna la cadena completa int idx = s.indexOf(';'); return (idx>=0?s.substring(0,idx):s); } /** *Comprueba si la cadena es una etiqueta 1 *@param String s, la cadena a ser verificada *@return true si la cadena es una etiqueta, falso en caso contrario */ public static boolean esEtiqueta(String s){ //La cadena debe ser de longitud 8 como maximo //Debe comenzar con una letra //Y el resto deben ser letras, numeros o '_' Pattern p = Pattern.compile("[a-zA-Z]{1}[a-zA-Z_0-9]{"+(s.length()-1)+"}"); Matcher m = p.matcher(s); return m.find() && s.length()<=8; } /** *Comprueba si la cadena es un codigo de operación *@param String s, la cadena a ser verificada *@return true si la cadena es un codigo de operacion, falso en caso contrario */ public static boolean esCodop(String s){ //La cadena debe ser de longitud 5 como maximo //Debe comenzar con una letra //El resto de la letra pueden ser letras, numeros o '_' //Puede contener un '.' como maximo, la bandera controla la cantidad de '.' que se han encontrado int puntos = s.length() - s.replace(".", "").length(); if(puntos>1){ return false; } Pattern p = Pattern.compile("[a-zA-Z]{1}[a-zA-Z_0-9.]{"+(s.length()-1)+"}"); Matcher m = p.matcher(s); return m.find()&&s.length()<=5; } /** *Comprueba si la cadena es un operando *@param String s, la cadena a ser verificada *@return true si la cadena es un operando, falso en caso contrario */ public static boolean esOperando(String s){ //Para esta practica no hay una regla de operandos return true; } /** *Calcula el error que tiene la cadena al ser evaluada como etiqueta *@param String s, la cadena a ser verificada *@return Una cadena con la descripción del errot */ public static String errorEtiqueta(String s){ if(s.length()>8){ return "El tamaño de la etiqueta exede el limite (8)"; } if(!Character.isLetter(s.charAt(0))){ return "La etiqueta no comienza con letra"; } Pattern p = Pattern.compile("[^a-zA-Z_0-9]"); Matcher m = p.matcher(s); if(m.find()){ return "La etiqueta contiene simbolos no permitidos"; } return "Error desconocido"; } /** *Calcula el error que tiene la cadena al ser evaluada como codop *@param String s, la cadena a ser verificada *@return Una cadena con la descripción del errot */ public static String errorCodop(String s){ if(s.length()>5){ return "El tamaño del codop exede el limite (5)"; } int puntos = s.length() - s.replace(".", "").length(); if(puntos>1){ return "El codop tiene mas de un '.'"; } if(!Character.isLetter(s.charAt(0))){ return "El codop no comienza con letra"; } Pattern p = Pattern.compile("[^a-zA-Z._0-9]"); Matcher m = p.matcher(s); if(m.find()){ return "El codop contiene simbolos no permitidos"; } return "Error desconocido"; } /** *Calcula el error que tiene la cadena al ser evaluada como operando *@param String s, la cadena a ser verificada *@return Una cadena con la descripción del errot */ public static String errorOperando(String s){ //Al no haber ninguna restriccion aun nunca caera aqui. return ""; } }
gpl-2.0
paco30amigos/sieni
SIENI/rio/tag/src/main/java/org/primefaces/rio/service/CarService.java
2580
/* * Copyright 2009-2014 PrimeTek. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.primefaces.rio.service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import javax.faces.bean.ApplicationScoped; import javax.faces.bean.ManagedBean; import org.primefaces.rio.domain.Car; @ManagedBean(name = "carService") @ApplicationScoped public class CarService { private final static String[] colors; private final static String[] brands; static { colors = new String[10]; colors[0] = "Black"; colors[1] = "White"; colors[2] = "Green"; colors[3] = "Red"; colors[4] = "Blue"; colors[5] = "Orange"; colors[6] = "Silver"; colors[7] = "Yellow"; colors[8] = "Brown"; colors[9] = "Maroon"; brands = new String[10]; brands[0] = "BMW"; brands[1] = "Mercedes"; brands[2] = "Volvo"; brands[3] = "Audi"; brands[4] = "Renault"; brands[5] = "Fiat"; brands[6] = "Volkswagen"; brands[7] = "Honda"; brands[8] = "Jaguar"; brands[9] = "Ford"; } public List<Car> createCars(int size) { List<Car> list = new ArrayList<Car>(); for(int i = 0 ; i < size ; i++) { list.add(new Car(getRandomId(), getRandomBrand(), getRandomYear(), getRandomColor(), getRandomPrice(), getRandomSoldState())); } return list; } private String getRandomId() { return UUID.randomUUID().toString().substring(0, 8); } private int getRandomYear() { return (int) (Math.random() * 50 + 1960); } private String getRandomColor() { return colors[(int) (Math.random() * 10)]; } private String getRandomBrand() { return brands[(int) (Math.random() * 10)]; } private int getRandomPrice() { return (int) (Math.random() * 100000); } private boolean getRandomSoldState() { return (Math.random() > 0.5) ? true: false; } public List<String> getColors() { return Arrays.asList(colors); } public List<String> getBrands() { return Arrays.asList(brands); } }
gpl-2.0
deyami/dbstorm
dbstorm-zookeeper/src/main/java/com/reform/dbstorm/zookeeper/StateListener.java
285
package com.reform.dbstorm.zookeeper; /** * 状态监听器. * * @author huaiyu.du@opi-corp.com 2012-1-29 下午4:45:03 */ public interface StateListener { /** * 新连接建立或重连. */ void onNewSession(); /** * 状态发生改变. */ void onStateChange(); }
gpl-2.0
wells369/Rubato
java/src/org/rubato/logeo/reform/RecursiveLimitReformer.java
3764
/* * Copyright (C) 2006 Gérard Milmeister * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License 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., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * */ package org.rubato.logeo.reform; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.rubato.base.RubatoException; import org.rubato.math.module.Module; import org.rubato.math.yoneda.*; class RecursiveLimitReformer extends LimitReformer { public static RecursiveLimitReformer make(LimitForm from, LimitForm to) { RecursiveLimitReformer reformer = null; List<Form> fromForms = new LinkedList<Form>(); collectForms(from, fromForms); List<Form> toForms = new LinkedList<Form>(); collectForms(to, toForms); if (fromForms.size() == toForms.size()) { Reformer[] reformers = new Reformer[fromForms.size()]; Iterator<Form> from_iter = fromForms.iterator(); Iterator<Form> to_iter = toForms.iterator(); for (int i = 0; i < reformers.length; i++) { reformers[i] = Reformer._make(from_iter.next(), to_iter.next()); if (reformers[i] == null) { return null; } } reformer = new RecursiveLimitReformer(to, reformers); } return reformer; } private static void collectForms(LimitForm form, List<Form> forms) { for (Form f : form.getForms()) { if (f instanceof LimitForm) { collectForms((LimitForm)f, forms); } else { forms.add(f); } } } public Denotator reform(Denotator d) throws RubatoException { LimitDenotator ld = (LimitDenotator)d; List<Denotator> fromList = new LinkedList<Denotator>(); collectDenotators(ld, fromList); List<Denotator> toList = new LinkedList<Denotator>(); int i = 0; for (Denotator from : fromList) { toList.add(reformers[i++].reform(from)); } return distributeDenotators(toList, d.getAddress(), to); } private void collectDenotators(LimitDenotator deno, List<Denotator> denos) { for (Denotator d : deno.getFactors()) { if (d instanceof LimitDenotator) { collectDenotators((LimitDenotator)d, denos); } else { denos.add(d); } } } private Denotator distributeDenotators(List<Denotator> denos, Module address, LimitForm toForm) { List<Denotator> list = new LinkedList<Denotator>(); for (Form f : toForm.getForms()) { if (f instanceof LimitForm) { list.add(distributeDenotators(denos, address, (LimitForm)f)); } else { list.add(denos.remove(0)); } } return LimitDenotator._make_unsafe(null, address, toForm, list); } private RecursiveLimitReformer(LimitForm to, Reformer[] reformers) { this.to = to; this.reformers = reformers; } private LimitForm to; private Reformer[] reformers; }
gpl-2.0
philipwhiuk/j3d-core
src/classes/share/javax/media/j3d/ShaderAttributeBindingRetained.java
2911
/* * $RCSfile$ * * Copyright 2005-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. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun 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 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. * * $Revision: 892 $ * $Date: 2008-02-28 20:18:01 +0000 (Thu, 28 Feb 2008) $ * $State$ */ package javax.media.j3d; import javax.vecmath.*; /** * The ShaderAttributeBinding object encapsulates a uniform attribute * whose value is bound to a Java&nbsp;3D system attribute. The * shader variable <code>attrName</code> is implicitly set to the * value of the corresponding Java&nbsp;3D system attribute * <code>j3dAttrName</code> during rendering. <code>attrName</code> * must be the name of a valid uniform attribute in the shader in * which it is used. Otherwise, the attribute name will be ignored and * a runtime error may be generated. <code>j3dAttrName</code> must be * the name of a predefined Java&nbsp;3D system attribute. An * IllegalArgumentException will be thrown if the specified * <code>j3dAttrName</code> is not one of the predefined system * attributes. Further, the type of the <code>j3dAttrName</code> * attribute must match the type of the corresponding * <code>attrName</code> variable in the shader in which it is * used. Otherwise, the shader will not be able to use the attribute * and a runtime error may be generated. */ class ShaderAttributeBindingRetained extends ShaderAttributeRetained { String j3dAttrName; ShaderAttributeBindingRetained() { } void initJ3dAttrName(String j3dAttrName) { this.j3dAttrName = j3dAttrName; } /** * Retrieves the name of the Java 3D system attribute that is bound to this * shader attribute. * * @return the name of the Java 3D system attribute that is bound to this * shader attribute */ String getJ3DAttributeName() { return j3dAttrName; } }
gpl-2.0
identityxx/penrose-server
core/src/java/org/safehaus/penrose/jdbc/StatementSource.java
719
package org.safehaus.penrose.jdbc; /** * @author Endi Sukma Dewata */ public class StatementSource { private String alias; private String partitionName; private String sourceName; public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getPartitionName() { return partitionName; } public void setPartitionName(String partitionName) { this.partitionName = partitionName; } public String getSourceName() { return sourceName; } public void setSourceName(String sourceName) { this.sourceName = sourceName; } }
gpl-2.0
SCADA-LTS/Scada-LTS
src/com/serotonin/mango/rt/event/detectors/BinaryStateDetectorRT.java
3230
/* Mango - Open Source M2M - http://mango.serotoninsoftware.com Copyright (C) 2006-2011 Serotonin Software Technologies Inc. @author Matthew Lohbihler This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.serotonin.mango.rt.event.detectors; import com.serotonin.mango.rt.dataImage.PointValueTime; import com.serotonin.mango.util.PointEventDetectorUtils; import com.serotonin.mango.view.event.NoneEventRenderer; import com.serotonin.mango.view.text.TextRenderer; import com.serotonin.mango.vo.event.PointEventDetectorVO; import com.serotonin.web.i18n.LocalizableMessage; public class BinaryStateDetectorRT extends StateDetectorRT { public BinaryStateDetectorRT(PointEventDetectorVO vo) { this.vo = vo; } @Override public LocalizableMessage getMessage() { String name = vo.njbGetDataPoint().getName(); String prettyText = vo.njbGetDataPoint().getTextRenderer().getText(vo.isBinaryState(), TextRenderer.HINT_SPECIFIC); LocalizableMessage durationDescription = getDurationDescription(); String description = PointEventDetectorUtils.getDescription(vo); String eventRendererText = (vo.njbGetDataPoint().getEventTextRenderer() == null) ? "" : vo.njbGetDataPoint().getEventTextRenderer().getText(vo.isBinaryState()); if (durationDescription == null) return new LocalizableMessage("event.detector.state", name, prettyText, description, eventRendererText); return new LocalizableMessage("event.detector.periodState", name, prettyText, durationDescription, description, eventRendererText); } @Override protected LocalizableMessage getShortMessage() { if (vo.njbGetDataPoint().getEventTextRenderer() != null && !vo.njbGetDataPoint().getEventTextRenderer().getTypeName().equals(NoneEventRenderer.TYPE_NAME) && vo.njbGetDataPoint().getEventTextRenderer().getText(vo.isBinaryState()) != null && (!vo.njbGetDataPoint().getEventTextRenderer().getText(vo.isBinaryState()).equals(""))) { String eventRendererText = vo.njbGetDataPoint().getEventTextRenderer().getText(vo.isBinaryState()); return new LocalizableMessage("event.detector.shortMessage", vo.njbGetDataPoint().getName(), eventRendererText); } else { return getMessage(); } } @Override protected boolean stateDetected(PointValueTime newValue) { boolean newBinary = newValue.getBooleanValue(); return newBinary == vo.isBinaryState(); } }
gpl-2.0
stelfrich/openmicroscopy
components/insight/SRC/org/openmicroscopy/shoola/env/data/views/calls/FileAnnotationCheckLoader.java
3769
/* * Copyright (C) 2014 University of Dundee & Open Microscopy Environment. * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * *------------------------------------------------------------------------------ */ package org.openmicroscopy.shoola.env.data.views.calls; import java.util.List; import org.openmicroscopy.shoola.agents.metadata.FileAnnotationCheckResult; import org.openmicroscopy.shoola.env.data.OmeroMetadataService; import omero.gateway.SecurityContext; import org.openmicroscopy.shoola.env.data.views.BatchCall; import org.openmicroscopy.shoola.env.data.views.BatchCallTree; import pojos.DataObject; import pojos.FileAnnotationData; /** * Loads the parents ({@link DataObject}) of the specified {@link FileAnnotationData} objects, * wrapped in a {@link FileAnnotationCheckResult} * * @author Dominik Lindner &nbsp;&nbsp;&nbsp;&nbsp; <a * href="mailto:d.lindner@dundee.ac.uk">d.lindner@dundee.ac.uk</a> * @since 5.0 */ public class FileAnnotationCheckLoader extends BatchCallTree { /** The result of the call. */ private FileAnnotationCheckResult result; /** The call */ private BatchCall loadCall; /** * Creates a {@link BatchCall} to load the parents of the annotations. * * @param ctx The security context. * @param annotations The @link FileAnnotationData} objects * @param referenceObjects The DataObjects from which the FileAnnotation should be removed * @return The {@link BatchCall}. */ private BatchCall makeCall(final SecurityContext ctx, final List<FileAnnotationData> annotations, final List<DataObject> referenceObjects) { return new BatchCall("Load Parents of annotations") { public void doCall() throws Exception { result = new FileAnnotationCheckResult(referenceObjects); for(FileAnnotationData fd : annotations) { OmeroMetadataService svc = context.getMetadataService(); List<DataObject> parents = svc.loadParentsOfAnnotations(ctx, fd.getId(), -1); result.addLinks(fd, parents); } } }; } /** * Adds the {@link #loadCall} to the computation tree. * * @see BatchCallTree#buildTree() */ protected void buildTree() { add(loadCall); } /** * Returns {@link FileAnnotationCheckResult}, which holds a <code>Map</code> * of {@link FileAnnotationData} objects mapped to {@link DataObject}s * * @see BatchCallTree#getResult() */ protected Object getResult() { return result; } /** * Creates a new instance. * * @param ctx The security context. * @param annotations The {@link FileAnnotationData} objects */ public FileAnnotationCheckLoader(SecurityContext ctx, List<FileAnnotationData> annotations, List<DataObject> referenceObjects) { loadCall = makeCall(ctx, annotations, referenceObjects); } }
gpl-2.0
cybershare/elseweb-v2
harvester/src/main/java/edu/utep/cybershare/elseweb/build/edac/services/source/edac/fgdc/theme/Themes.java
2344
package edu.utep.cybershare.elseweb.build.edac.services.source.edac.fgdc.theme; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Themes { private static final String THEMEKT_ISO_19115_Topic_Categories = "ISO 19115 Topic Categories"; private static final String THEMEKY_GCMD_Science = "GCMD Science"; private static final String THEMEKY_EDAC = "None"; private static final String THEME_CF = "CF"; private Theme theme_ISO_19115_Topic_Categories; private Theme theme_GCMD_Science; private Theme theme_EDAC_Prism; private Theme theme_EDAC_MODIS; private Theme theme_CF; public Themes(Document fgdcDoc){ NodeList themes = fgdcDoc.getElementsByTagName("theme"); for(int i = 0; i < themes.getLength(); i ++) setTheme(getTheme(themes.item(i))); } private Theme getTheme(Node aThemeNode){ NodeList themeParts = aThemeNode.getChildNodes(); Node themePart; String tagName; String tagValue; Theme aTheme = new Theme(); for(int i = 0; i < themeParts.getLength(); i ++){ themePart = themeParts.item(i); tagName = themePart.getNodeName(); tagValue = themePart.getTextContent(); if(tagName.equals("themekt")) aTheme.setThemekt(tagValue); else if(tagName.equals("themekey")) aTheme.addThemekey(tagValue); } return aTheme; } private void setTheme(Theme aTheme){ if(aTheme.getThemekt().equals(Themes.THEMEKT_ISO_19115_Topic_Categories)) this.theme_ISO_19115_Topic_Categories = aTheme; else if(aTheme.getThemekt().equals(Themes.THEMEKY_GCMD_Science)) this.theme_GCMD_Science = aTheme; else if(aTheme.getThemekt().equals(Themes.THEMEKY_EDAC)) setSourceTheme(aTheme); else if(aTheme.getThemekt().equals(Themes.THEME_CF)) this.theme_CF = aTheme; } private void setSourceTheme(Theme sourceTheme){ if(sourceTheme.getNumberOfThemeKeys() == 2) this.theme_EDAC_Prism = sourceTheme; else this.theme_EDAC_MODIS = sourceTheme; } public Theme getTheme_ISO_19115_Topic_Categories(){ return this.theme_ISO_19115_Topic_Categories; } public Theme getTheme_GCMD_Science(){ return this.theme_GCMD_Science; } public Theme getTheme_CF(){ return this.theme_CF; } public Theme getTheme_EDAC_Prism(){ return this.theme_EDAC_Prism; } public Theme getTheme_EDAC_MODIS(){ return this.theme_EDAC_MODIS; } }
gpl-2.0
Fernando-Marquardt/mcarchitect
MCArchitect/src/klaue/mcschematictool/blocktypes/Farmland.java
1419
package klaue.mcschematictool.blocktypes; /** * A farmland block with wetness * * @author klaue * */ public class Farmland extends Block { /** * initializes the farmland block * * @param wetness 0-8 */ public Farmland(byte wetness) { super((short) 60, wetness); this.type = Type.FARMLAND; if (wetness < 0 || wetness > 8) { throw new IllegalArgumentException("wetness " + wetness + "outside boundaries"); } } /** * Get the wetness value of the farmland. 0 is dry, 8 is the wettest. This is ingame set by the distance to the next * water block * * @return the wetness */ public byte getWetness() { return this.data; } /** * Get the wetness value of the farmland. 0 is dry, 8 is the wettest. This is ingame set by the distance to the next * water block, so it may not be a good idea to set this. * * @param wetness the wetness to set */ public void setWetness(byte wetness) { if (wetness < 0 || wetness > 8) { throw new IllegalArgumentException("wetness " + wetness + "outside boundaries"); } this.data = wetness; } @Override public String toString() { return super.toString() + ", wetness: " + this.data; } @Override public void setData(byte data) { setWetness(data); } }
gpl-2.0
mdaniel/svn-caucho-com-resin
modules/quercus/src/com/caucho/quercus/lib/curl/UrlEncodedBody.java
2002
/* * Copyright (c) 1998-2012 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 Nam Nguyen */ package com.caucho.quercus.lib.curl; import java.io.IOException; import java.io.OutputStream; import com.caucho.quercus.env.Callable; import com.caucho.quercus.env.Callback; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.StringValue; import com.caucho.quercus.env.Value; public class UrlEncodedBody extends PostBody { private StringValue _body; private int _length; private String _contentType = "application/x-www-form-urlencoded"; public UrlEncodedBody (Env env, Value body) { _body = body.toStringValue(env); _length = _body.length(); } public String getContentType() { return _contentType; } public void setContentType(String type) { _contentType = type; } @Override public long getContentLength() { return (long) _length; } public void writeTo(Env env, OutputStream os) throws IOException { for (int i = 0; i < _length; i++) { os.write(_body.charAt(i)); } } }
gpl-2.0
christianchristensen/resin
modules/servlet16/src/javax/el/PropertyNotFoundException.java
1449
/* * Copyright (c) 1998-2010 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 javax.el; /** * EL exceptions */ public class PropertyNotFoundException extends ELException { public PropertyNotFoundException() { } public PropertyNotFoundException(String message) { super(message); } public PropertyNotFoundException(String message, Throwable cause) { super(message, cause); } public PropertyNotFoundException(Throwable cause) { super(cause); } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01682.java
2526
/** * 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("/BenchmarkTest01682") public class BenchmarkTest01682 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 = ""; java.util.Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames.hasMoreElements()) { param = headerNames.nextElement(); // just grab first element } StringBuilder sbxyz1736 = new StringBuilder(param); String bar = sbxyz1736.append("_SafeStuff").toString(); // FILE URIs are tricky because they are different between Mac and Windows because of lack of standardization. // Mac requires an extra slash for some reason. String startURIslashes = ""; if (System.getProperty("os.name").indexOf("Windows") != -1) if (System.getProperty("os.name").indexOf("Windows") != -1) startURIslashes = "/"; else startURIslashes = "//"; try { java.net.URI fileURI = new java.net.URI("file:" + startURIslashes + org.owasp.benchmark.helpers.Utils.testfileDir.replace('\\', '/').replace(' ', '_') + bar); new java.io.File(fileURI); } catch (java.net.URISyntaxException e) { throw new ServletException(e); } } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jaxws/drop_included/jaxws_src/src/com/sun/xml/internal/bind/v2/runtime/NameList.java
2634
/* * Copyright 2005-2006 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. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun 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 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 com.sun.xml.internal.bind.v2.runtime; /** * Namespace URIs and local names sorted by their indices. * Number of Names used for EIIs and AIIs * * @author Kohsuke Kawaguchi */ public final class NameList { /** * Namespace URIs by their indices. No nulls in this array. * Read-only. */ public final String[] namespaceURIs; /** * For each entry in {@link #namespaceURIs}, whether the namespace URI * can be declared as the default. If namespace URI is used in attributes, * we always need a prefix, so we can't. * * True if this URI has to have a prefix. */ public final boolean[] nsUriCannotBeDefaulted; /** * Local names by their indices. No nulls in this array. * Read-only. */ public final String[] localNames; /** * Number of Names for elements */ public final int numberOfElementNames; /** * Number of Names for attributes */ public final int numberOfAttributeNames; public NameList(String[] namespaceURIs, boolean[] nsUriCannotBeDefaulted, String[] localNames, int numberElementNames, int numberAttributeNames) { this.namespaceURIs = namespaceURIs; this.nsUriCannotBeDefaulted = nsUriCannotBeDefaulted; this.localNames = localNames; this.numberOfElementNames = numberElementNames; this.numberOfAttributeNames = numberAttributeNames; } }
gpl-2.0
johnzzc/JFExchangemarket
ExchangeMarket/src/com/jon/exchangemarket/interceptor/LoginInterceptor.java
373
package com.jon.exchangemarket.interceptor; import com.jfinal.aop.Interceptor; import com.jfinal.core.ActionInvocation; public class LoginInterceptor implements Interceptor{ @Override public void intercept(ActionInvocation ai) { System.out.println("Before action invoking"); ai.invoke(); ai.getViewPath(); System.out.println("After action invoking"); } }
gpl-2.0
barta3/ch.bfh.bti7321thesis.mqttSemantics
ch.bfh.bti7321thesis.description/src/test/java/ch/bfh/bti7321thesis/description/MqttTopicTest.java
406
package ch.bfh.bti7321thesis.description; import static org.junit.Assert.assertEquals; import org.junit.Test; import ch.bfh.bti7321thesis.app.MqttTopic; public class MqttTopicTest { @Test public void testMqttTopicString() { MqttTopic topic = new MqttTopic("a/b/c/d/"); assertEquals(4, topic.getNumberofElements()); topic.append("e"); assertEquals("a/b/c/d/e", topic.toString()); } }
gpl-2.0
h3xstream/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01093.java
3101
/** * OWASP Benchmark Project v1.2 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>. * * The OWASP 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 OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Dave Wichers * @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(value="/sqli-02/BenchmarkTest01093") public class BenchmarkTest01093 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 { response.setContentType("text/html;charset=UTF-8"); String param = ""; if (request.getHeader("BenchmarkTest01093") != null) { param = request.getHeader("BenchmarkTest01093"); } // URL Decode the header value since req.getHeader() doesn't. Unlike req.getParameter(). param = java.net.URLDecoder.decode(param, "UTF-8"); String bar = new Test().doSomething(request, param); String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'"; try { java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement(); statement.execute( sql, new int[] { 1, 2 } ); org.owasp.benchmark.helpers.DatabaseHelper.printResults(statement, sql, response); } catch (java.sql.SQLException e) { if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) { response.getWriter().println( "Error processing request." ); return; } else throw new ServletException(e); } } // end doPost private class Test { public String doSomething(HttpServletRequest request, String param) throws ServletException, IOException { String bar = "safe!"; java.util.HashMap<String,Object> map18142 = new java.util.HashMap<String,Object>(); map18142.put("keyA-18142", "a-Value"); // put some stuff in the collection map18142.put("keyB-18142", param); // put it in a collection map18142.put("keyC", "another-Value"); // put some stuff in the collection bar = (String)map18142.get("keyB-18142"); // get it back out return bar; } } // end innerclass Test } // end DataflowThruInnerClass
gpl-2.0
azurro/kafka-group-monitor
src/test/java/pl/azurro/kafka/groupmonitor/GroupMonitorTest.java
3275
package pl.azurro.kafka.groupmonitor; import static java.util.Collections.singletonList; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import kafka.cluster.Broker; import kafka.javaapi.OffsetRequest; import kafka.javaapi.OffsetResponse; import kafka.javaapi.PartitionMetadata; import kafka.javaapi.TopicMetadata; import kafka.javaapi.TopicMetadataRequest; import kafka.javaapi.TopicMetadataResponse; import kafka.javaapi.consumer.SimpleConsumer; import org.I0Itec.zkclient.ZkClient; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import pl.azurro.kafka.groupmonitor.model.GroupInfo; import pl.azurro.kafka.zookeeper.ZookeeperUtils; @RunWith(MockitoJUnitRunner.class) public class GroupMonitorTest { private static final String TOPIC_NAME = "topicName"; private static final String GROUP_ID = "testGroup"; private static final String zkServers = "host1:2181,host2:2181,host3:2181/mychroot"; @Mock private SimpleConsumer consumer; @Mock private ZookeeperUtils zookeeperUtils; @Mock private ZkClient zkClient; @Mock private Broker broker; private GroupMonitor monitor = new GroupMonitor(zkServers) { @Override SimpleConsumer createSimpleConsumerFor(Broker broker) { return consumer; } @Override ZookeeperUtils createZookeeperUtils() { return zookeeperUtils; } }; @Before public void setUp() { when(zookeeperUtils.getZkClient(zkServers)).thenReturn(zkClient); when(zookeeperUtils.getBrokers(zkClient)).thenReturn(singletonList(broker)); when(broker.getConnectionString()).thenReturn("host1:9092"); } @Test public void shouldReturnGroupInfo() throws Exception { OffsetResponse offsetResponse = mock(OffsetResponse.class); TopicMetadataResponse response = mock(TopicMetadataResponse.class); TopicMetadata topicMetadata = mock(TopicMetadata.class); PartitionMetadata partitionMetadata = mock(PartitionMetadata.class); when(topicMetadata.partitionsMetadata()).thenReturn(singletonList(partitionMetadata)); when(response.topicsMetadata()).thenReturn(singletonList(topicMetadata)); when(consumer.send(any(TopicMetadataRequest.class))).thenReturn(response); when(topicMetadata.topic()).thenReturn(TOPIC_NAME); when(partitionMetadata.leader()).thenReturn(broker); when(partitionMetadata.partitionId()).thenReturn(0); when(zookeeperUtils.getLastConsumedOffset(zkClient, GROUP_ID, TOPIC_NAME, 0)).thenReturn(90L); when(consumer.getOffsetsBefore(any(OffsetRequest.class))).thenReturn(offsetResponse); when(offsetResponse.hasError()).thenReturn(false); when(offsetResponse.offsets(TOPIC_NAME, 0)).thenReturn(new long[] { 1112 }); GroupInfo info = monitor.getGroupInfo(GROUP_ID); GroupInfo expectedInfo = new GroupInfo(GROUP_ID); expectedInfo.addInfoFor(TOPIC_NAME, 0, 1112, 90); assertThat(info).isEqualTo(expectedInfo); } }
gpl-2.0
qoswork/opennmszh
opennms-model/src/main/java/org/opennms/netmgt/model/OnmsMonitoredServiceDetail.java
4276
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.model; import static org.opennms.core.utils.InetAddressUtils.toInteger; import java.io.Serializable; import java.math.BigInteger; import java.net.InetAddress; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.opennms.core.xml.bind.InetAddressXmlAdapter; @SuppressWarnings("serial") @XmlRootElement(name = "monitored-service") public class OnmsMonitoredServiceDetail implements Serializable, Comparable<OnmsMonitoredServiceDetail> { private String m_statusCode; private String m_status; private String m_nodeLabel; private String m_serviceName; private InetAddress m_ipAddress; private boolean m_isMonitored; private boolean m_isDown; public OnmsMonitoredServiceDetail() { } public OnmsMonitoredServiceDetail(OnmsMonitoredService service) { m_nodeLabel = service.getIpInterface().getNode().getLabel(); m_ipAddress = service.getIpAddress(); m_serviceName = service.getServiceName(); m_isMonitored = service.getStatus().equals("A"); m_isDown = service.isDown(); m_statusCode = service.getStatus(); m_status = service.getStatusLong(); } @XmlElement(name="status") public String getStatus() { return m_status; } public void setStatus(String status) { this.m_status = status; } @XmlAttribute(name="statusCode") public String getStatusCode() { return m_statusCode; } public void setStatusCode(String statusCode) { this.m_statusCode = statusCode; } @XmlElement(name="node") public String getNodeLabel() { return m_nodeLabel; } public void setNodeLabel(String nodeLabel) { this.m_nodeLabel = nodeLabel; } @XmlElement(name="serviceName") public String getServiceName() { return m_serviceName; } public void setServiceName(String serviceName) { this.m_serviceName = serviceName; } @XmlElement(name="ipAddress") @XmlJavaTypeAdapter(InetAddressXmlAdapter.class) public InetAddress getIpAddress() { return m_ipAddress; } public void setIpAddress(InetAddress ipAddress) { this.m_ipAddress = ipAddress; } @XmlAttribute(name="isMonitored") public boolean isMonitored() { return m_isMonitored; } @XmlAttribute(name="isDown") public boolean isDown() { return m_isDown; } @Override public int compareTo(OnmsMonitoredServiceDetail o) { int diff; diff = getNodeLabel().compareToIgnoreCase(o.getNodeLabel()); if (diff != 0) { return diff; } BigInteger a = toInteger(getIpAddress()); BigInteger b = toInteger(o.getIpAddress()); diff = a.compareTo(b); if (diff != 0) { return diff; } return getServiceName().compareToIgnoreCase(o.getServiceName()); } }
gpl-2.0
sungsoo/esper
examples/stockticker/src/test/java/com/espertech/esper/example/stockticker/TestStockTickerMultithreaded.java
4900
/************************************************************************************** * 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.example.stockticker; import java.util.LinkedList; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.LinkedBlockingQueue; import junit.framework.TestCase; import com.espertech.esper.example.stockticker.monitor.StockTickerResultListener; import com.espertech.esper.example.stockticker.monitor.StockTickerMonitor; import com.espertech.esper.example.stockticker.eventbean.PriceLimit; import com.espertech.esper.example.stockticker.eventbean.StockTick; import com.espertech.esper.client.EPServiceProvider; import com.espertech.esper.client.EPServiceProviderManager; import com.espertech.esper.client.Configuration; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; public class TestStockTickerMultithreaded extends TestCase implements StockTickerRegressionConstants { StockTickerResultListener listener; private EPServiceProvider epService; protected void setUp() throws Exception { listener = new StockTickerResultListener(); Configuration configuration = new Configuration(); configuration.addEventType("PriceLimit", PriceLimit.class.getName()); configuration.addEventType("StockTick", StockTick.class.getName()); epService = EPServiceProviderManager.getProvider("TestStockTickerMultithreaded", configuration); epService.initialize(); new StockTickerMonitor(epService, listener); } public void testMultithreaded() { //performTest(3, 1000000, 100000, 60); // on fast systems performTest(3, 50000, 10000, 15); // for unit tests on slow machines } public void performTest(int numberOfThreads, int numberOfTicksToSend, int ratioPriceOutOfLimit, int numberOfSecondsWaitForCompletion) { final int totalNumTicks = numberOfTicksToSend + 2 * TestStockTickerGenerator.NUM_STOCK_NAMES; log.info(".performTest Generating data, numberOfTicksToSend=" + numberOfTicksToSend + " ratioPriceOutOfLimit=" + ratioPriceOutOfLimit); StockTickerEventGenerator generator = new StockTickerEventGenerator(); LinkedList stream = generator.makeEventStream(numberOfTicksToSend, ratioPriceOutOfLimit, TestStockTickerGenerator.NUM_STOCK_NAMES, StockTickerRegressionConstants.PRICE_LIMIT_PCT_LOWER_LIMIT, StockTickerRegressionConstants.PRICE_LIMIT_PCT_UPPER_LIMIT, StockTickerRegressionConstants.PRICE_LOWER_LIMIT, StockTickerRegressionConstants.PRICE_UPPER_LIMIT, true); log.info(".performTest Send limit and initial tick events - singlethreaded"); for (int i = 0; i < TestStockTickerGenerator.NUM_STOCK_NAMES * 2; i++) { Object theEvent = stream.removeFirst(); epService.getEPRuntime().sendEvent(theEvent); } log.info(".performTest Loading thread pool work queue, numberOfRunnables=" + stream.size()); ThreadPoolExecutor pool = new ThreadPoolExecutor(0, numberOfThreads, 99999, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); for (Object theEvent : stream) { SendEventRunnable runnable = new SendEventRunnable(epService, theEvent); pool.execute(runnable); } log.info(".performTest Starting thread pool, threads=" + numberOfThreads); pool.setCorePoolSize(numberOfThreads); log.info(".performTest Listening for completion"); EPRuntimeUtil.awaitCompletion(epService.getEPRuntime(), totalNumTicks, numberOfSecondsWaitForCompletion, 1, 10); pool.shutdown(); // Check results : make sure the given ratio of out-of-limit stock prices was reported int expectedNumEmitted = (numberOfTicksToSend / ratioPriceOutOfLimit) + 1; assertTrue(listener.getSize() == expectedNumEmitted); log.info(".performTest Done test"); } private static final Log log = LogFactory.getLog(TestStockTickerMultithreaded.class); }
gpl-2.0