repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
joaobiriba/Camera4DummiesAndroidApp
camera4dummiesandroid/src/main/java/ora/camera4dummies/camera4dummiesandroid/MapFragment.java
475
package ora.camera4dummies.camera4dummiesandroid; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * Created by joaobiriba on 17/05/14. */ public class MapFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.mapfragment, null); } }
mit
datanets/kanjoto
kanjoto-android/src/summea/kanjoto/data/ApprenticesDataSource.java
7603
package summea.kanjoto.data; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import summea.kanjoto.model.Apprentice; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; public class ApprenticesDataSource { private SQLiteDatabase database; private KanjotoDatabaseHelper dbHelper; // database table columns private String[] allColumns = { KanjotoDatabaseHelper.COLUMN_ID, KanjotoDatabaseHelper.COLUMN_NAME, KanjotoDatabaseHelper.COLUMN_LEARNING_STYLE_ID, }; /** * ApprenticesDataSource constructor. * * @param context Current state. */ public ApprenticesDataSource(Context context) { dbHelper = new KanjotoDatabaseHelper(context); } /** * ApprenticesDataSource constructor. * * @param context Current state. * @param databaseName Database to use. */ public ApprenticesDataSource(Context context, String databaseName) { dbHelper = new KanjotoDatabaseHelper(context, databaseName); } /** * Open database. * * @throws SQLException */ public void open() throws SQLException { setDatabase(dbHelper.getWritableDatabase()); } /** * Close database. */ public void close() { dbHelper.close(); } /** * Create apprentice row in database. * * @param apprenticevalues String of apprentice values to insert. * @return Apprentice of newly-created apprentice data. */ public Apprentice createApprentice(Apprentice apprentice) { ContentValues contentValues = new ContentValues(); contentValues.put(KanjotoDatabaseHelper.COLUMN_NAME, apprentice.getName()); contentValues.put(KanjotoDatabaseHelper.COLUMN_LEARNING_STYLE_ID, apprentice.getLearningStyleId()); // create database handle SQLiteDatabase db = dbHelper.getWritableDatabase(); long insertId = db.insert(KanjotoDatabaseHelper.TABLE_APPRENTICES, null, contentValues); Cursor cursor = db.query( KanjotoDatabaseHelper.TABLE_APPRENTICES, allColumns, KanjotoDatabaseHelper.COLUMN_ID + " = " + insertId, null, null, null, null); cursor.moveToFirst(); Apprentice newApprentice = cursorToApprentice(cursor); cursor.close(); db.close(); return newApprentice; } /** * Delete apprentice row from database. * * @param apprentice Apprentice to delete. */ public void deleteApprentice(Apprentice apprentice) { long id = apprentice.getId(); // create database handle SQLiteDatabase db = dbHelper.getWritableDatabase(); // delete apprentice db.delete(KanjotoDatabaseHelper.TABLE_APPRENTICES, KanjotoDatabaseHelper.COLUMN_ID + " = " + id, null); db.close(); } /** * Get all apprentices from database table. * * @return List of Apprentices. */ public List<Apprentice> getAllApprentices() { List<Apprentice> apprentices = new ArrayList<Apprentice>(); String query = "SELECT * FROM " + KanjotoDatabaseHelper.TABLE_APPRENTICES; // create database handle SQLiteDatabase db = dbHelper.getWritableDatabase(); // select all notes from database Cursor cursor = db.rawQuery(query, null); Apprentice apprentice = null; if (cursor.moveToFirst()) { do { // create note objects based on note data from database apprentice = new Apprentice(); apprentice.setId(cursor.getLong(0)); apprentice.setName(cursor.getString(1)); apprentice.setLearningStyleId(cursor.getLong(2)); // add note string to list of strings apprentices.add(apprentice); } while (cursor.moveToNext()); } db.close(); return apprentices; } /** * Access column data at current position of result. * * @param cursor Current cursor location. * @return Apprentice */ private Apprentice cursorToApprentice(Cursor cursor) { Apprentice apprentice = new Apprentice(); apprentice.setId(cursor.getLong(0)); apprentice.setName(cursor.getString(1)); apprentice.setLearningStyleId(cursor.getLong(2)); return apprentice; } /** * Get a list of all apprentices ids. * * @return List of Apprentice ids. */ public List<Long> getAllApprenticeListDBTableIds() { List<Long> apprentices = new LinkedList<Long>(); String query = "SELECT " + KanjotoDatabaseHelper.COLUMN_ID + " FROM " + KanjotoDatabaseHelper.TABLE_APPRENTICES; // create database handle SQLiteDatabase db = dbHelper.getWritableDatabase(); // select all apprentices from database Cursor cursor = db.rawQuery(query, null); Apprentice apprentice = null; if (cursor.moveToFirst()) { do { // create apprentice objects based on apprentice data from database apprentice = new Apprentice(); apprentice.setId(Long.parseLong(cursor.getString(0))); // add apprentice to apprentices list apprentices.add(apprentice.getId()); } while (cursor.moveToNext()); } db.close(); return apprentices; } public Apprentice getApprentice(long apprenticeId) { Apprentice apprentice = new Apprentice(); String query = "SELECT * FROM " + KanjotoDatabaseHelper.TABLE_APPRENTICES + " WHERE " + KanjotoDatabaseHelper.COLUMN_ID + "=?"; // create database handle SQLiteDatabase db = dbHelper.getWritableDatabase(); // select all apprentices from database Cursor cursor = db.rawQuery(query, new String[] { String.valueOf(apprenticeId) }); if (cursor.moveToFirst()) { do { // create apprentice objects based on apprentice data from database apprentice = new Apprentice(); apprentice.setId(cursor.getLong(0)); apprentice.setName(cursor.getString(1)); apprentice.setLearningStyleId(cursor.getLong(2)); } while (cursor.moveToNext()); } db.close(); return apprentice; } public Apprentice updateApprentice(Apprentice apprentice) { // create database handle SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(KanjotoDatabaseHelper.COLUMN_ID, apprentice.getId()); contentValues.put(KanjotoDatabaseHelper.COLUMN_NAME, apprentice.getName()); contentValues.put(KanjotoDatabaseHelper.COLUMN_LEARNING_STYLE_ID, apprentice.getLearningStyleId()); db.update(KanjotoDatabaseHelper.TABLE_APPRENTICES, contentValues, KanjotoDatabaseHelper.COLUMN_ID + "=" + apprentice.getId(), null); db.close(); return apprentice; } public SQLiteDatabase getDatabase() { return database; } public void setDatabase(SQLiteDatabase database) { this.database = database; } }
mit
ria-ee/X-Road
src/common-messagelog/src/main/java/ee/ria/xroad/common/messagelog/AbstractLogRecord.java
1753
/** * The MIT License * Copyright (c) 2015 Estonian Information System Authority (RIA), Population Register Centre (VRK) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package ee.ria.xroad.common.messagelog; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * Encapsulates information about a log record. */ @ToString @EqualsAndHashCode public abstract class AbstractLogRecord implements LogRecord { @Getter @Setter private Long id; // log record id @Getter @Setter private Long time; // time of the creation of the log record @Getter @Setter private boolean archived; // indicates, whether this log record is archived }
mit
YagneshShah/SeleniumLearnExploreContribute
seleniumWebdriverLearningSnippets/src/utils/MobileCommonMethods.java
13093
/* * Date: September 1st 2014 * Author: Adil Imroz * Twitter handle: @adilimroz * Organization: Moolya Software Testing Pvt Ltd * License Type: MIT */ package utils; import io.appium.java_client.AppiumDriver; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.concurrent.TimeUnit; import jxl.Cell; import jxl.LabelCell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import utils.WebCommonMethods; // //import mobilePageObjects.SigninElements; //Update this as per your context import org.openqa.selenium.By; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.Assert; public class MobileCommonMethods { public static AppiumDriver driver; public static int sleepTimeMin; public static int sleepTimeMin2; public static int sleepTimeAverage; public static int sleepTimeAverage2; public static int sleepTimeMax; public static int sleepTimeMax2; public static int Btn1; public static int Btn2; public static int Btn3; public static int Btn4; public static int Btn5; public static int Btn6; public static int Btn7; public static int Btn8; public static int Btn9; public static int Btn10; public static int key1; public static int key2; public static int key3; public static int key4; public static int key5; public static int key6; public static int key7; public static int key8; public static int key9; public static int key10; static Workbook wrk1; static Sheet sheet1; //Method to dynamically retrieve any 1 specific record from any mobile excel sheet public static Cell[] mobileReadExcel(String sheetName, String uniqueValue) throws BiffException, IOException { wrk1 = Workbook.getWorkbook(new File("../seleniumWebdriverLearningSnippets/testdata/mobileTestData.xls")); // Connecting to excel workbook. sheet1 = wrk1.getSheet(sheetName); // Connecting to the sheet LabelCell cell=sheet1.findLabelCell(uniqueValue); int row=cell.getRow(); Cell[] record = sheet1.getRow(row); return record; } //Method to dynamically retrieve any 1 specific record which is just below the uniqueValue specified public static Cell[] mobileReadExcelNextRowOfUniqueValue(String sheetName, String uniqueValue) throws BiffException, IOException { wrk1 = Workbook.getWorkbook(new File("../seleniumWebdriverLearningSnippets/testdata/mobileTestData.xls")); // Connecting to excel workbook. sheet1 = wrk1.getSheet(sheetName); // Connecting to the sheet LabelCell cell=sheet1.findLabelCell(uniqueValue); int row=cell.getRow(); Cell[] record = sheet1.getRow(row+1); return record; } public static void initializeSleepTimings() throws IOException { FileReader reader = new FileReader("../seleniumWebdriverLearningSnippets/config.properties"); //Reading configuration file Properties prop = new Properties(); prop.load(reader); sleepTimeMin = Integer.parseInt(prop.getProperty("sleepTimeMin")); //System.out.println("sleepTimeMin:" + sleepTimeMin); sleepTimeMin2 = Integer.parseInt(prop.getProperty("sleepTimeMin2")); //System.out.println("sleepTimeMin2:" + sleepTimeMin2); sleepTimeAverage = Integer.parseInt(prop.getProperty("sleepTimeAverage")); //System.out.println("sleepTimeAverage:" + sleepTimeAverage); sleepTimeAverage2 = Integer.parseInt(prop.getProperty("sleepTimeAverage2")); sleepTimeMax = Integer.parseInt(prop.getProperty("sleepTimeMax")); //System.out.println("sleepTimeMax:" + sleepTimeMax); sleepTimeMax2 = Integer.parseInt(prop.getProperty("sleepTimeMax2")); } public static int mobileNumberKeyEventsEntry(int buttonValue){ if (buttonValue == 0) { buttonValue = 7; } if (buttonValue == 1) { buttonValue = 8; } if (buttonValue == 2) { buttonValue = 9; } if (buttonValue == 3) { buttonValue = 10; } if (buttonValue == 4) { buttonValue = 11; } if (buttonValue == 5) { buttonValue = 12; } if (buttonValue == 6) { buttonValue = 13; } if (buttonValue == 7) { buttonValue = 14; } if (buttonValue == 8) { buttonValue = 15; } if (buttonValue == 9) { buttonValue = 16; } return buttonValue; } public static void keyEventsForMobileNumber(String UserData) throws BiffException, IOException{ Cell[] cashInDetails = MobileCommonMethods.mobileReadExcel("cashInData",UserData); String mobileNumber_btn1 = cashInDetails[2].getContents().substring(0, 1); Btn1 = Integer.parseInt(mobileNumber_btn1); key1 = MobileCommonMethods.mobileNumberKeyEventsEntry(Btn1); String mobileNumber_btn2 = cashInDetails[2].getContents().substring(1, 2); Btn2 = Integer.parseInt(mobileNumber_btn2); key2 = MobileCommonMethods.mobileNumberKeyEventsEntry(Btn2); String mobileNumber_btn3 = cashInDetails[2].getContents().substring(2, 3); Btn3 = Integer.parseInt(mobileNumber_btn3); key3 = MobileCommonMethods.mobileNumberKeyEventsEntry(Btn3); String mobileNumber_btn4 = cashInDetails[2].getContents().substring(3, 4); Btn4 = Integer.parseInt(mobileNumber_btn4); key4 = MobileCommonMethods.mobileNumberKeyEventsEntry(Btn4); String mobileNumber_btn5 = cashInDetails[2].getContents().substring(4, 5); Btn5 = Integer.parseInt(mobileNumber_btn5); key5 = MobileCommonMethods.mobileNumberKeyEventsEntry(Btn5); String mobileNumber_btn6 = cashInDetails[2].getContents().substring(5, 6); Btn6 = Integer.parseInt(mobileNumber_btn6); key6 = MobileCommonMethods.mobileNumberKeyEventsEntry(Btn6); String mobileNumber_btn7 = cashInDetails[2].getContents().substring(6, 7); Btn7 = Integer.parseInt(mobileNumber_btn7); key7 = MobileCommonMethods.mobileNumberKeyEventsEntry(Btn7); String mobileNumber_btn8 = cashInDetails[2].getContents().substring(7, 8); Btn8 = Integer.parseInt(mobileNumber_btn8); key8 = MobileCommonMethods.mobileNumberKeyEventsEntry(Btn8); String mobileNumber_btn9 = cashInDetails[2].getContents().substring(8, 9); Btn9 = Integer.parseInt(mobileNumber_btn9); key9 = MobileCommonMethods.mobileNumberKeyEventsEntry(Btn9); String mobileNumber_btn10 = cashInDetails[2].getContents().substring(9, 10); Btn10 = Integer.parseInt(mobileNumber_btn10); key10 = MobileCommonMethods.mobileNumberKeyEventsEntry(Btn10); } // public static void sendMobileNumberKeyEvents(){ // // driver.findElementByName(ObjectsCashIn.TextField_ConfirmMobileNumber).click(); // driver.sendKeyEvent(MobileCommonMethods.key1); // driver.sendKeyEvent(MobileCommonMethods.key2); // driver.sendKeyEvent(MobileCommonMethods.key3); // driver.sendKeyEvent(MobileCommonMethods.key4); // driver.sendKeyEvent(MobileCommonMethods.key5); // driver.sendKeyEvent(MobileCommonMethods.key6); // driver.sendKeyEvent(MobileCommonMethods.key7); // driver.sendKeyEvent(MobileCommonMethods.key8); // driver.sendKeyEvent(MobileCommonMethods.key9); // driver.sendKeyEvent(MobileCommonMethods.key10); // } // Method to launch the Application while it does not get uninstalled during script execution public static void launchApp1() throws BiffException, IOException { //Update this method based on your app context. This is just for code reference System.out.println("*****Launching the app*****"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("deviceName", "Android"); capabilities.setCapability("appPackage","com.moolya.boi"); capabilities.setCapability("appActivity","com.moolya.boi.ShellAppBOIMPay"); driver = new AppiumDriver(new URL("http://0.0.0.0:4723/wd/hub"), capabilities); // initializing the driver driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); } // Method for Agent sigin public static void appSignin(String username) throws InterruptedException, BiffException, IOException {//Update this method based on your app context. This is just for code reference // Text with signin button :: Sign in Cell[] record = MobileCommonMethods.mobileReadExcel("validLogin",username); // read from excel String mobileNumber = record[1].getContents(); //remove following 3 comments below and update the snippet based on your context to make this method workable... // driver.findElementByName(SigninElements.textField_projectNameSignIn).sendKeys(mobileNumber); // driver.findElementByName(SigninElements.button_textField_projectNameSignIn).click(); // MobileCommonMethods.mPinEntry(username); // method to enter the mpin // driver.findElementByName(SigninElements.button_TermsOfServiceAccept).click();//No content desc for this button driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); } public static void mPinEntry(String username) throws BiffException, IOException{//Update this method based on your app context. This is just for code reference // Fetching the mPin of the mentioned user from the excel Cell[] record = MobileCommonMethods.mobileReadExcel("validLogin",username); String mPin_btn1 = record[2].getContents().substring(0, 1); String mPin_btn2 = record[2].getContents().substring(1, 2); String mPin_btn3 = record[2].getContents().substring(2, 3); String mPin_btn4 = record[2].getContents().substring(3, 4); driver.findElementByName("layout_mpin_entry_btnNum"+mPin_btn1).click(); //testing server password driver.findElementByName("layout_mpin_entry_btnNum"+mPin_btn2).click(); //testing server password driver.findElementByName("layout_mpin_entry_btnNum"+mPin_btn3).click(); //testing server password driver.findElementByName("layout_mpin_entry_btnNum"+mPin_btn4).click(); //testing server password driver.findElementByName("layout_mpin_entry_btnDone").click();//tap on tick button } // public static void signout1() { // // driver.sendKeyEvent(4); // if (driver.findElementByName("Do you wish to go back and retry?").isDisplayed()) // { // driver.findElementByName("Retry").click(); // driver.sendKeyEvent(4); // driver.findElementByName("Go Back").click(); // driver.sendKeyEvent(4); // driver.findElementByName("Stop").click(); // driver.sendKeyEvent(4); // driver.sendKeyEvent(4); // driver.findElementByName("Sign Out").click(); // System.out.println("Signed Out Successfully"); // } // // else if (driver.findElementByName("Do you wish to stop this transaction?").isDisplayed()) // { // driver.findElementByName("Stop").click(); // driver.sendKeyEvent(4); // driver.sendKeyEvent(4); // driver.findElementByName("Sign Out").click(); // System.out.println("Signed Out Successfully"); // } // else if (driver.findElementByName("Do you wish to go back to the previous step?").isDisplayed()) // { // driver.findElementByName("Go Back").click(); // driver.sendKeyEvent(4); // driver.findElementByName("Stop").click(); // driver.sendKeyEvent(4); // driver.sendKeyEvent(4); // driver.findElementByName("Sign Out").click(); // System.out.println("Signed Out Successfully"); // } // else // { // driver.findElementByName(ObjectsGeneral.Button_NavigateUp).click(); // driver.findElementByName("Stop").click(); // driver.sendKeyEvent(4); // driver.sendKeyEvent(4); // driver.findElementByName("Sign Out").click(); // System.out.println("Signed Out Successfully"); //// } // } //Method to signout from app public static void signout() throws InterruptedException { //Update this method based on your app context. This is just for code reference try{ driver.navigate().back(); //back from boi app page driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.navigate().back(); //back from select partner page driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.findElementByName("Sign Out").isDisplayed(); driver.findElementByName("Sign Out").click();// signout btn } catch(Exception e) { System.out.println("Caught exception during signout process..."); boolean present; boolean namaskaar; try { driver.findElement(By.name("Dismiss")); present = true; } catch (org.openqa.selenium.NoSuchElementException e1) { present = false; } try { driver.findElement(By.name("namaskaar")); namaskaar = true; } catch (org.openqa.selenium.NoSuchElementException e1) { namaskaar = false; } if(present == true) { driver.findElementByName("Dismiss").click(); driver.findElementByName("Navigate up").click(); driver.findElementByName("Stop").click(); // click on Stop button driver.navigate().back(); driver.findElementByName("Sign Out").click();// signout } else if(namaskaar == true) { driver.navigate().back(); driver.findElementByName("Sign Out").click();// signout } else { driver.findElementByName("Cancel").click(); driver.findElementByName("Navigate up").click(); driver.findElementByName("Stop").click(); // click on Stop button driver.navigate().back(); driver.findElementByName("Sign Out").click();// signout } // btn } finally { driver.quit(); } } }
mit
zaoying/EChartsAnnotation
src/cn/edu/gdut/zaoying/Option/series/bar/markLine/SymbolSizeArray.java
318
package cn.edu.gdut.zaoying.Option.series.bar.markLine; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface SymbolSizeArray { }
mit
facebook/infer
infer/tests/codetoanalyze/java/nullsafe/ModePromotions.java
3135
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * A test ensuring that we correctly analyze mode promotions possibility. All classes in this file * should be free of nullability issues (w.r.t to their mode). The goal of the test is to ensure * that mode to promote to is correct for each class. */ package codetoanalyze.java.nullsafe; import com.facebook.infer.annotation.Nullsafe; // Zero issues and no dependencies - can strictify class Default_NoDeps_CanBePromotedToStrict { static String f() { return ""; } } @Nullsafe(Nullsafe.Mode.LOCAL) class Local_NoDeps_CanBePromotedToStrict { static String f() { return ""; } } // Nothing to promote to @Nullsafe(Nullsafe.Mode.STRICT) class Strict_NoDeps_NoPromos { static String f() { return ""; } } class Default_UsesDefault_CanBePromotedToTrustAll { static String f() { // We use unknown default function. Since we don't support trust some in promotions, // the possible promotion is trust all. return Default_NoDeps_CanBePromotedToStrict.f(); } } class Default_UsesItself_CanBePromotedToStrict { static String f() { // We use only the function from its own class. The class can be promoted to strict staight // ahead. return g(); } static String g() { return ""; } } class Default_UsesLocal_CanBePromotedToTrustNone { static String f() { // We depend only on a nullsafe method. // Hence the class can be promoted to "trust none" (but not to strict). return Local_NoDeps_CanBePromotedToStrict.f(); } } class Default_UsesStrict_CanBePromotedToStrict { static String f() { // We depend only on a strict class. // Hence the class can be promoted to "trust none" (but not to strict). return Strict_NoDeps_NoPromos.f(); } } @Nullsafe( value = Nullsafe.Mode.LOCAL, trustOnly = @Nullsafe.TrustList({Default_NoDeps_CanBePromotedToStrict.class})) class TrustSome_DoesNotUseTrusted_CanBePromotedToTrustNone { static String f() { return Local_NoDeps_CanBePromotedToStrict.f(); } } @Nullsafe( value = Nullsafe.Mode.LOCAL, trustOnly = @Nullsafe.TrustList({Default_NoDeps_CanBePromotedToStrict.class})) class TrustSome_UsesTrusted_NoPromo { static String f() { return Default_NoDeps_CanBePromotedToStrict.f(); } } @Nullsafe( value = Nullsafe.Mode.LOCAL, trustOnly = @Nullsafe.TrustList({Local_NoDeps_CanBePromotedToStrict.class})) class TrustSome_TrustToLocalIsNotNeeded_CanBePromotedToTrustNone { static String f() { return Local_NoDeps_CanBePromotedToStrict.f(); } } @Nullsafe( value = Nullsafe.Mode.LOCAL, trustOnly = @Nullsafe.TrustList({Strict_NoDeps_NoPromos.class})) class TrustSome_TrustStrictIsNotNeeded_CanBePromotedToStrict { static String f() { return Strict_NoDeps_NoPromos.f(); } } @Nullsafe(value = Nullsafe.Mode.LOCAL, trustOnly = @Nullsafe.TrustList({})) class TrustNone_CanBePromotedToStrict { static String f() { return Strict_NoDeps_NoPromos.f(); } }
mit
jaquadro/StorageDrawers
api/thaumcraft/api/research/ScanEntity.java
1656
package thaumcraft.api.research; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import thaumcraft.api.ThaumcraftApi.EntityTagsNBT; import thaumcraft.api.ThaumcraftApiHelper; public class ScanEntity implements IScanThing { String research; Class entityClass; EntityTagsNBT[] NBTData; /** * false if the specific entity class should be used, or true if anything the inherits from that class is also allowed. */ boolean inheritedClasses=false; public ScanEntity(String research, Class entityClass, boolean inheritedClasses) { this.research = research; this.entityClass = entityClass; this.inheritedClasses = inheritedClasses; } public ScanEntity(String research, Class entityClass, boolean inheritedClasses, EntityTagsNBT... nbt) { this.research = research; this.entityClass = entityClass; this.inheritedClasses = inheritedClasses; this.NBTData = nbt; } @Override public boolean checkThing(EntityPlayer player, Object obj) { if (obj!=null && ((!inheritedClasses && entityClass==obj.getClass()) || (inheritedClasses && entityClass.isInstance(obj)))) { if (NBTData!=null && NBTData.length>0) { boolean b = true; NBTTagCompound tc = new NBTTagCompound(); ((Entity)obj).writeToNBT(tc); for (EntityTagsNBT nbt:NBTData) { if (!tc.hasKey(nbt.name) || !ThaumcraftApiHelper.getNBTDataFromId(tc, tc.getTagId(nbt.name), nbt.name).equals(nbt.value)) { return false; } } } return true; } return false; } @Override public String getResearchKey() { return research; } }
mit
herveyw/azure-sdk-for-java
azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/VirtualMachineScaleSetVMExtensionsSummary.java
1158
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.compute; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * Extensions summary for virtual machines of a virtual machine scale set. */ public class VirtualMachineScaleSetVMExtensionsSummary { /** * the extension name. */ @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private String name; /** * the extensions information. */ @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private List<VirtualMachineStatusCodeCount> statusesSummary; /** * Get the name value. * * @return the name value */ public String name() { return this.name; } /** * Get the statusesSummary value. * * @return the statusesSummary value */ public List<VirtualMachineStatusCodeCount> statusesSummary() { return this.statusesSummary; } }
mit
utluiz/spring-examples
agenda-dao-spring/src/main/java/br/com/starcode/agenda/dao/mysqltemplate/UsuarioDaoMySqlJdbcTemplateImpl.java
1212
package br.com.starcode.agenda.dao.mysqltemplate; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Primary; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import br.com.starcode.agenda.dao.UsuarioDao; import br.com.starcode.agenda.dao.mapper.UsuarioRowMapper; import br.com.starcode.agenda.domain.Usuario; @Repository @Qualifier("template") @Primary public class UsuarioDaoMySqlJdbcTemplateImpl implements UsuarioDao { @Autowired private JdbcTemplate jdbcTemplate; public Usuario findByNomeUsuario(String nomeUsuario) { try { return jdbcTemplate.queryForObject( "select * from usuario where nome_usuario = ?", new UsuarioRowMapper(), nomeUsuario); } catch (EmptyResultDataAccessException e) { return null; } } public void atualizarUltimoAcesso(Integer id, Date data) { jdbcTemplate.update( "update usuario set ultimo_acesso = ? where id = ?", data, id); } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2019_07_01/src/main/java/com/microsoft/azure/management/network/v2019_07_01/implementation/PageImpl1.java
1752
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_07_01.implementation; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.azure.Page; import java.util.List; /** * An instance of this class defines a page of Azure resources and a link to * get the next page of resources, if any. * * @param <T> type of Azure resource */ public class PageImpl1<T> implements Page<T> { /** * The link to the next page. */ @JsonProperty("") private String nextPageLink; /** * The list of items. */ @JsonProperty("value") private List<T> items; /** * Gets the link to the next page. * * @return the link to the next page. */ @Override public String nextPageLink() { return this.nextPageLink; } /** * Gets the list of items. * * @return the list of items in {@link List}. */ @Override public List<T> items() { return items; } /** * Sets the link to the next page. * * @param nextPageLink the link to the next page. * @return this Page object itself. */ public PageImpl1<T> setNextPageLink(String nextPageLink) { this.nextPageLink = nextPageLink; return this; } /** * Sets the list of items. * * @param items the list of items in {@link List}. * @return this Page object itself. */ public PageImpl1<T> setItems(List<T> items) { this.items = items; return this; } }
mit
gsotoridd/resp
src/com/app/net/ClientListenerFinalRunnable.java
2377
package com.app.net; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import com.app.resp.StudentRoomActivity; /** * El listener para el cliente no es mas que un servidor que esta siempre * esperando por conexiones entrantes. */ public class ClientListenerFinalRunnable implements Runnable{ protected int serverPort; protected ServerSocket serverSocket = null; protected boolean isStopped = false; protected Thread runningThread= null; protected StudentRoomActivity activity; public ClientListenerFinalRunnable(int port,StudentRoomActivity act){ this.serverPort = port; activity=act; } public void run(){ synchronized(this){ this.runningThread = Thread.currentThread(); } openServerSocket(); while(! isStopped()){ // clientSocket es el socket en que se acepta la conexion entrante Socket clientSocket = null; try { clientSocket = this.serverSocket.accept(); // Establecemos un timeout de 10 segs clientSocket.setSoTimeout(10000); } catch (IOException e) { if(isStopped()) { System.out.println("Server Stopped.") ; return; } throw new RuntimeException( "Error accepting client connection", e); } // leemos que es lo que viene por el socket new Thread( new ClientWorkerRunnable( clientSocket, "Client Listener Server",this, this.activity) ).start(); } System.out.println("Server Stopped.") ; } private synchronized boolean isStopped() { return this.isStopped; } public boolean isRunning() { return !this.isStopped; } public synchronized void stop(){ this.isStopped = true; try { this.serverSocket.close(); } catch (IOException e) { throw new RuntimeException("Error closing server", e); } } private void openServerSocket() { try { this.serverSocket = new ServerSocket(this.serverPort); } catch (IOException e) { throw new RuntimeException("Cannot open port " + this.serverPort, e); } } }
mit
mmohan01/ReFactory
data/jhotdraw/jhotdraw-6.0b1/org/jhotdraw/figures/FontSizeHandle.java
3483
/* * @(#)FontSizeHandle.java * * Project: JHotdraw - a GUI framework for technical drawings * http://www.jhotdraw.org * http://jhotdraw.sourceforge.net * Copyright: © by the original author(s) and all contributors * License: Lesser GNU Public License (LGPL) * http://www.opensource.org/licenses/lgpl-license.html */ package org.jhotdraw.figures; import org.jhotdraw.framework.*; import org.jhotdraw.standard.*; import org.jhotdraw.util.Undoable; import org.jhotdraw.util.UndoableAdapter; import java.awt.*; /** * A Handle to change the font size by direct manipulation. * * @version <$CURRENT_VERSION$> */ public class FontSizeHandle extends LocatorHandle { public FontSizeHandle(Figure owner, Locator l) { super(owner, l); } public void invokeStart(int x, int y, DrawingView view) { setUndoActivity(createUndoActivity(view)); getUndoActivity().setAffectedFigures(new SingleFigureEnumerator(owner())); } public void invokeStep (int x, int y, int anchorX, int anchorY, DrawingView view) { TextFigure textOwner = (TextFigure) owner(); FontSizeHandle.UndoActivity activity = (FontSizeHandle.UndoActivity)getUndoActivity(); int newSize = activity.getFont().getSize() + y-anchorY; textOwner.setFont(new Font(activity.getFont().getName(), activity.getFont().getStyle(), newSize)); } public void invokeEnd(int x, int y, int anchorX, int anchorY, DrawingView view) { TextFigure textOwner = (TextFigure) owner(); FontSizeHandle.UndoActivity activity = (FontSizeHandle.UndoActivity)getUndoActivity(); // there has been no change so there is nothing to undo if (textOwner.getFont().getSize() == activity.getOldFontSize()) { setUndoActivity(null); } else { activity.setFont(textOwner.getFont()); } } public void draw(Graphics g) { Rectangle r = displayBox(); g.setColor(Color.yellow); g.fillOval(r.x, r.y, r.width, r.height); g.setColor(Color.black); g.drawOval(r.x, r.y, r.width, r.height); } /** * Factory method for undo activity */ protected Undoable createUndoActivity(DrawingView newView) { TextFigure textOwner = (TextFigure)owner(); return new FontSizeHandle.UndoActivity(newView, textOwner.getFont()); } public static class UndoActivity extends UndoableAdapter { private Font myFont; private int myOldFontSize; public UndoActivity(DrawingView newView, Font newFont) { super(newView); setFont(newFont); setOldFontSize(getFont().getSize()); setUndoable(true); setRedoable(true); } public boolean undo() { if (!super.undo()) { return false; } swapFont(); return true; } public boolean redo() { // do not call execute directly as the selection might has changed if (!isRedoable()) { return false; } swapFont(); return true; } protected void swapFont() { setOldFontSize(replaceFontSize()); FigureEnumeration fe = getAffectedFigures(); while (fe.hasNextFigure()) { ((TextFigure)fe.nextFigure()).setFont(getFont()); } } private int replaceFontSize() { int tempFontSize = getFont().getSize(); setFont(new Font(getFont().getName(), getFont().getStyle(), getOldFontSize())); return tempFontSize; } protected void setFont(Font newFont) { myFont = newFont; } public Font getFont() { return myFont; } protected void setOldFontSize(int newOldFontSize) { myOldFontSize = newOldFontSize; } public int getOldFontSize() { return myOldFontSize; } } }
mit
marnig/Programing-Memories
Programing_Contest/Spoj/AddRev/AddRev.java
985
package addrev; /** * * @author BBW Latino */ import java.util.Scanner; public class AddRev { static public long invertir(long num1){ long aux1; long aux2 = -1; String aux3 = ""; while(aux2 != 0){ aux1 = num1 % 10; aux2 = num1 / 10; num1 = aux2; aux3 += Long.toString(aux1); } num1 = Long.parseLong(aux3); return num1; } static public void Ejercicio42() { Scanner sc = new Scanner(System.in); System.out.println("Casos"); int cases = sc.nextInt(); long num1; long num2; long inver; for(int i = 0; i < cases; i++){ num1 = sc.nextLong(); num2 = sc.nextLong(); inver = invertir(invertir(num1) + invertir(num2)); System.out.println(inver); } } public static void main(String[] args) { Ejercicio42(); } }
mit
dcendents/sysdeotomcat
src/com/sysdeo/eclipse/tomcat/WebClassPathEntries.java
6163
package com.sysdeo.eclipse.tomcat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * container for managing a number of WebClassPathEntry objects * * @version 1.0 * @author Martin Kahr */ public class WebClassPathEntries { public static final String TAG_NAME = "webClassPathEntries"; private static final String ENTRY_TAG_NAME = "webClassPathEntry"; private List entries; public WebClassPathEntries() { entries = new ArrayList(); } public WebClassPathEntries(List values) { entries = values; } /** returns the number of webclasspath-entries */ public int size() { return entries.size(); } /** return the WebClassPathEntry value at the index provided */ public String getWebClassPathEntry(int index) { if (index >= entries.size()) return null; String entry = (String) entries.get(index); return entry; } /** add a WebClassPathEntry value */ public void addWebClassPathEntry(String value) { if (entries.contains(value)) return; entries.add(value); } public List getList() { return entries; } /** * transfer the state of this object to an XML string */ public String xmlMarshal() { return xmlMarshal(0); } public String xmlMarshal(int spacesToIntend) { String spaces = ""; for(int i=0; i < spacesToIntend; i++) { spaces = spaces+" "; } String xml = spaces + startTag() + "\n"; for (Iterator it = entries.iterator(); it.hasNext();) { String entry = (String) it.next(); xml += spaces + spaces + startEntryTag() + entry + endEntryTag() + "\n"; } xml += spaces + endTag() + "\n"; return xml; } /** * instantiate a WebClassPathEntries object and intialize * it with the xml data provided * @return the object if unmarshaling had no errors. returns null * if the marshaling was unsuccessfully. */ public static WebClassPathEntries xmlUnmarshal(String xmlString) { if (xmlString == null || xmlString.trim().length() == 0) { return null; } int start = xmlString.indexOf(startTag()); int end = xmlString.indexOf(endTag()); if (start < 0 || end <= start) return null; String value = xmlString.substring(start+startTag().length(), end); value = value.trim(); WebClassPathEntries webEntries = new WebClassPathEntries(); while(value != null && value.length() > 0) { start = value.indexOf(startEntryTag()); end = value.indexOf(endEntryTag()); if (start >= 0 || end > start) { String entryValue = value.substring(start+startEntryTag().length(), end); if (entryValue.trim().length() > 0) { webEntries.addWebClassPathEntry(entryValue); } value = value.substring(end + endEntryTag().length()); } else { value = null; } } return webEntries; } private static String startTag() { return "<" + TAG_NAME + ">"; } private static String endTag() { return "</" + TAG_NAME + ">"; } private static String startEntryTag() { return "<" + ENTRY_TAG_NAME + ">"; } private static String endEntryTag() { return "</" + ENTRY_TAG_NAME + ">"; } /** * main method yust for some simple tests - should be in a Junit Testclass * but I don't want to add the junit reference to this project */ public static void main(String[] arguments) { String xml = ""; WebClassPathEntries entries = xmlUnmarshal(xml); if (entries != null) { System.err.println("invalid xml must result in null object !"); System.exit(1); } xml = "<webClassPathEntries></webClassPathEntries>"; entries = xmlUnmarshal(xml); if (entries == null) { System.err.println("valid xml must result in an object !"); System.exit(1); } if (entries.size() != 0) { System.err.println("expected size 0 but was " + entries.size()); System.exit(1); } xml = "<root><webClassPathEntries>\n</webClassPathEntries>\n</root>"; entries = xmlUnmarshal(xml); if (entries == null) { System.err.println("valid xml must result in an object !"); System.exit(1); } if (entries.size() != 0) { System.err.println("expected size 0 but was " + entries.size()); System.exit(1); } xml = "<webClassPathEntries><webClassPathEntry>abc</webClassPathEntry></webClassPathEntries>"; entries = xmlUnmarshal(xml); if (entries == null) { System.err.println("valid xml must result in an object !"); System.exit(1); } if (entries.size() != 1) { System.err.println("expected size 1 but was " + entries.size()); System.exit(1); } if (!entries.getWebClassPathEntry(0).equals("abc")) { System.err.println("expected 'abc' but was '" + entries.getWebClassPathEntry(0) + "'"); System.exit(1); } xml = "<webClassPathEntries>\n<webClassPathEntry>abc</webClassPathEntry>\n<webClassPathEntry>def</webClassPathEntry>\n<webClassPathEntry>123</webClassPathEntry>\nxxxxx</webClassPathEntries>\n"; entries = xmlUnmarshal(xml); if (entries == null) { System.err.println("valid xml must result in an object !"); System.exit(1); } if (entries.size() != 3) { System.err.println("expected size 1 but was " + entries.size()); System.exit(1); } if (!entries.getWebClassPathEntry(0).equals("abc")) { System.err.println("expected 'abc' but was '" + entries.getWebClassPathEntry(0) + "'"); System.exit(1); } if (!entries.getWebClassPathEntry(1).equals("def")) { System.err.println("expected 'def' but was '" + entries.getWebClassPathEntry(1) + "'"); System.exit(1); } if (!entries.getWebClassPathEntry(2).equals("123")) { System.err.println("expected '123' but was '" + entries.getWebClassPathEntry(2) + "'"); System.exit(1); } xml = "<webClassPathEntries>\n<webClassPathEntry>abc</webClassPathEntry>\n<webClassPathEntry>def</webClassPathEntry>\n<webClassPathEntry>123</webClassPathEntry>\n</webClassPathEntries>\n"; String gen = entries.xmlMarshal(); if (gen.equals(xml) == false) { System.err.println("generated xml is incorrect:\n!" + gen + "!"); System.err.println("expected xml is :\n!" + xml + "!"); System.exit(1); } System.out.println("All okay !"); } }
mit
tsdl2013/ApplicationInsights-Android
applicationinsights-android/src/androidTest/java/com/microsoft/applicationinsights/contracts/CrashDataTests.java
2442
package com.microsoft.applicationinsights.contracts; import junit.framework.Assert; import junit.framework.TestCase; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; /// <summary> /// Data contract test class CrashDataTests. /// </summary> public class CrashDataTests extends TestCase { public void testVerPropertyWorksAsExpected() { int expected = 42; CrashData item = new CrashData(); item.setVer(expected); int actual = item.getVer(); Assert.assertEquals(expected, actual); expected = 13; item.setVer(expected); actual = item.getVer(); Assert.assertEquals(expected, actual); } public void testHeadersPropertyWorksAsExpected() { CrashDataHeaders expected = new CrashDataHeaders(); CrashData item = new CrashData(); item.setHeaders(expected); CrashDataHeaders actual = item.getHeaders(); Assert.assertEquals(expected, actual); expected = new CrashDataHeaders(); item.setHeaders(expected); actual = item.getHeaders(); Assert.assertEquals(expected, actual); } public void testThreadsPropertyWorksAsExpected() { CrashData item = new CrashData(); ArrayList<CrashDataThread> actual = (ArrayList<CrashDataThread>)item.getThreads(); Assert.assertNotNull(actual); } public void testBinariesPropertyWorksAsExpected() { CrashData item = new CrashData(); ArrayList<CrashDataBinary> actual = (ArrayList<CrashDataBinary>)item.getBinaries(); Assert.assertNotNull(actual); } public void testSerialize() throws IOException { CrashData item = new CrashData(); item.setVer(42); item.setHeaders(new CrashDataHeaders()); for (CrashDataThread entry : new ArrayList<CrashDataThread>() {{add(new CrashDataThread());}}) { item.getThreads().add(entry); } for (CrashDataBinary entry : new ArrayList<CrashDataBinary>() {{add(new CrashDataBinary());}}) { item.getBinaries().add(entry); } StringWriter writer = new StringWriter(); item.serialize(writer); String expected = "{\"ver\":42,\"headers\":{\"id\":null},\"threads\":[{\"id\":0}],\"binaries\":[{}]}"; Assert.assertEquals(expected, writer.toString()); } }
mit
P0T4T0x/AKGBensheim
app/src/main/java/de/tobiaserthal/akgbensheim/base/toolbar/ToolbarFragment.java
12939
package de.tobiaserthal.akgbensheim.base.toolbar; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewCompat; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.github.ksoichiro.android.observablescrollview.ScrollUtils; import java.lang.ref.WeakReference; import de.tobiaserthal.akgbensheim.R; import de.tobiaserthal.akgbensheim.backend.utils.Log; import de.tobiaserthal.akgbensheim.utils.ContextHelper; /** * A simple fragment wrapper that helps you to create fragments with the ability to manage the * parent activity's toolbar by adding a header view or animating it. */ // FIXME: header sometimes not animating in position public abstract class ToolbarFragment extends Fragment { private static final int INTERNAL_CONTENT_VIEW_ID = 0x000000; private static final int INTERNAL_HEADER_VIEW_ID = 0x000001; private static final String TAG = "TabbedFragment"; /* private pointer */ private ValueAnimator toolbarAnimator; private WeakReference<Toolbar> toolbar; private View headerView; private View contentView; private int toolbarAnimMillis = 200; public ToolbarActivity getParent() { try { return (ToolbarActivity) getActivity(); } catch (ClassCastException e) { throw new IllegalStateException("Parent activity must extend ToolbarActivity!"); } } @SuppressWarnings("ResourceType") @Override public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final Context context = getActivity(); FrameLayout root = new FrameLayout(context); /* Add content view */ View contentFrame = onCreateContentView(inflater, root, savedInstanceState); if(contentFrame != null) { contentFrame.setId(INTERNAL_CONTENT_VIEW_ID); root.addView(contentFrame); } /* Create header layout */ LinearLayout headerFrame = new LinearLayout(context); headerFrame.setId(INTERNAL_HEADER_VIEW_ID); headerFrame.setOrientation(LinearLayout.VERTICAL); View toolBarPadding = new View(context); int toolBarPaddingSize = ContextHelper.getPixelSize(context, R.attr.actionBarSize); toolBarPadding.setMinimumHeight(toolBarPaddingSize); headerFrame.addView(toolBarPadding, new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, toolBarPaddingSize )); /* Add header content */ View headerContent = onCreateHeaderView(inflater, headerFrame, savedInstanceState); /* Add toolbar shadow */ if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { View toolBarShadow = new View(context); int toolBarShadowSize = getResources().getDimensionPixelSize(R.dimen.toolbar_shadow_size); toolBarShadow.setMinimumHeight(toolBarShadowSize); toolBarShadow.setBackgroundResource(R.drawable.toolbar_shadow); FrameLayout headerContentWrapper = new FrameLayout(getContext()); headerContentWrapper.setBackgroundColor(ContextHelper.getColor(context, R.attr.colorPrimary)); if(headerContent != null) { headerContentWrapper.addView(headerContent); } headerFrame.setBackgroundColor(Color.TRANSPARENT); headerFrame.addView(headerContentWrapper, new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); headerFrame.addView(toolBarShadow, new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, toolBarShadowSize)); } else { if(headerContent != null) { headerFrame.addView(headerContent); } headerFrame.setBackgroundColor(ContextHelper.getColor(context, R.attr.colorPrimary)); ViewCompat.setElevation(headerFrame, getResources().getDimension(R.dimen.toolbar_default_elevation)); } /* Add header view*/ root.addView(headerFrame, new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT )); /* Add root view */ root.setLayoutParams(new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); return root; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ensureToolbar(); ensureHeader(); ensureContent(); if(savedInstanceState == null) { showToolbar(false); } } @Override public void onDestroyView() { toolbar.clear(); headerView = null; contentView = null; super.onDestroyView(); } public void setToolbarAnimMillis(int millis) { this.toolbarAnimMillis = millis; } public int getToolbarAnimMillis() { return toolbarAnimMillis; } public abstract View onCreateContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState); public abstract View onCreateHeaderView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState); /** * Returns the header view. Don't get confused with {@link #getHeaderContent()} * @return The header view containing the toolbar wrapper, the content view and if pre-lollipop * a shadow layer with 5dp height at */ @SuppressWarnings("ResourceType") public View getHeaderView() { ensureHeader(); return headerView; } /** * Returns the content of the header view you created in {@link #onCreateHeaderView(LayoutInflater, ViewGroup, Bundle)} * @return The header content view */ public View getHeaderContent() { LinearLayout headerView = (LinearLayout) getHeaderView(); if(headerView == null) return null; if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { if (headerView.getChildCount() == 3) return ((ViewGroup) headerView.getChildAt(1)).getChildAt(0); else return null; } else { if (headerView.getChildCount() == 2) return headerView.getChildAt(1); else return null; } } /** * Returns the content view you created in {@link #onCreateContentView(LayoutInflater, ViewGroup, Bundle)} * @return The content view */ public View getContentView() { ensureContent(); return contentView; } /** * Get the toolbar of the parent Activity * @return The toolbar view of the parent activity */ public final Toolbar getToolbar() { ensureToolbar(); return toolbar.get(); } private void ensureToolbar() { if(toolbar != null && toolbar.get() != null) return; if(getActivity() != null) toolbar = new WeakReference<>(getParent().getToolbar()); } @SuppressWarnings("ResourceType") private void ensureHeader() { if(headerView != null) { return; } if (getView() != null) { headerView = getView().findViewById(INTERNAL_HEADER_VIEW_ID); } else { throw new IllegalStateException("getHeaderView called without a header being created!"); } } private void ensureContent() { if(contentView != null) { return; } if(getView() != null) { contentView = getView().findViewById(INTERNAL_CONTENT_VIEW_ID); } else { throw new IllegalStateException("getContentView called without a content being created!"); } } public float getToolbarTranslation() { return getToolbar().getTranslationY(); } public int getToolbarHeight() { return getToolbar().getHeight(); } /** * Move the toolbar and the header view by the specified amount of pixels * @param byTranslation the pixels to move the toolbar up */ public void moveToolbar(float byTranslation) { float oldTrans = getToolbarTranslation(); setToolbarTranslation(oldTrans + byTranslation); } /** * Set the toolbar and header view translation * @param translation The view translation in pixels */ public void setToolbarTranslation(float translation) { float transY = ScrollUtils.getFloat(translation, -getToolbar().getHeight(), 0); onToolbarMoved(transY); prepareAnimator(); getHeaderView().setTranslationY(transY); getToolbar().setTranslationY(transY); } /** * Move the toolbar and header back into the visible view area * @param animated whether this operation should be animated or not */ public void showToolbar(boolean animated) { if(!animated) { float headerTranslationY = getToolbarTranslation(); if(headerTranslationY != 0) { onToolbarMoved(0); prepareAnimator(); getHeaderView().setTranslationY(0); getToolbar().setTranslationY(0); } return; } showToolbar(); } /** * Move the toolbar and header out of the visible view area * @param animated whether this operation should be animated or not */ public void hideToolbar(boolean animated) { if(!animated) { float headerTranslationY = getToolbarTranslation(); int toolbarHeight = getToolbar().getHeight(); if (headerTranslationY != -toolbarHeight) { onToolbarMoved(-toolbarHeight); prepareAnimator(); getToolbar().setTranslationY(-toolbarHeight); getToolbar().setTranslationY(-toolbarHeight); } return; } hideToolbar(); } /** * Animate the toolbar and header back into the visible view area */ public void showToolbar() { Log.d(TAG, "showToolbar()"); float headerTranslationY = getToolbarTranslation(); if(headerTranslationY != 0) { prepareAnimator(); toolbarAnimator.setFloatValues(headerTranslationY, 0); toolbarAnimator.start(); } } /** * Animate the toolbar and header out of the visible view area */ public void hideToolbar() { Log.d(TAG, "hideToolbar()"); float headerTranslationY = getToolbarTranslation(); int toolbarHeight = getToolbar().getHeight(); if(headerTranslationY != -toolbarHeight) { prepareAnimator(); toolbarAnimator.setFloatValues(headerTranslationY, -toolbarHeight); toolbarAnimator.start(); } } public void toggleToolbar() { toggleToolbar(true); } public void toggleToolbar(boolean animated) { if(toolbarIsShown()) { hideToolbar(animated); } else { showToolbar(animated); } } /** * Get whether the toolbar is fully visible or not * @return the visibility as a boolean */ public boolean toolbarIsShown() { return getToolbarTranslation() >= 0; } /** * Get whether the toolbar is completely invisible or not * @return the visibility as a boolean */ public boolean toolbarIsHidden() { return getToolbarTranslation() <= -getToolbar().getHeight(); } private void prepareAnimator() { if(toolbarAnimator == null) { toolbarAnimator = new ValueAnimator(); toolbarAnimator.setDuration(toolbarAnimMillis); toolbarAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float translationY = (float) animation.getAnimatedValue(); getHeaderView().setTranslationY(translationY); getToolbar().setTranslationY(translationY); onToolbarMoved(translationY); } }); } else { toolbarAnimator.cancel(); } } public void onToolbarMoved(float translationY) { // empty } }
mit
telbot/reefminder-microservices
auth-server/src/main/java/org/reefminder/microservice/auth/mongo/MongoUserDetailsManager.java
5303
package org.reefminder.microservice.auth.mongo; import com.google.common.collect.Sets; import org.reefminder.microservice.auth.mongo.domain.User; import org.reefminder.microservice.auth.mongo.repositories.UserRepository; import org.reefminder.microservice.auth.services.SecurityContextService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.util.Collection; @Component public class MongoUserDetailsManager implements UserDetailsManager { protected final Logger logger = LoggerFactory.getLogger(getClass()); private final UserRepository userRepository; private AuthenticationManager authenticationManager; private SecurityContextService securityContextService; @Autowired public MongoUserDetailsManager(final UserRepository userRepository, final SecurityContextService securityContextService, final AuthenticationManager authenticationManager) { this.userRepository = userRepository; this.securityContextService = securityContextService; this.authenticationManager = authenticationManager; } @Override public void createUser(final UserDetails user) { validateUserDetails(user); userRepository.save(getUser(user)); } private User getUser(UserDetails userDetails) { final User user = (User) userDetails; return new User(user.getPassword(), user.getUsername(), user.getUserUUID(), Sets.newConcurrentHashSet(user.getAuthorities()), user.isAccountNonExpired(), user.isAccountNonLocked(),user.isCredentialsNonExpired(), user.isEnabled()); } @Override public void updateUser(final UserDetails user) { validateUserDetails(user); userRepository.save(getUser(user)); } @Override public void deleteUser(final String username) { final User user = userRepository.findOne(username); userRepository.delete(user); } @Override public void changePassword(final String oldPassword, final String newPassword) { final Authentication currentUser = securityContextService.getAuthentication(); if (currentUser == null) { // This would indicate bad coding somewhere throw new AccessDeniedException("Can't change password as no Authentication object found in context " + "for current user."); } final String username = currentUser.getName(); // If an authentication manager has been set, re-authenticate the user with the supplied password. if (authenticationManager != null) { logger.debug("Reauthenticating user '"+ username + "' for password change request."); authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, oldPassword)); } else { logger.debug("No authentication manager set. Password won't be re-checked."); } logger.debug("Changing password for user '"+ username + "'"); userRepository.changePassword(oldPassword, newPassword, username); securityContextService.setAuthentication(createNewAuthentication(currentUser)); } @Override public boolean userExists(final String username) { final User user = userRepository.findOne(username); return user != null; } @Override public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { return userRepository.findOne(username); } protected Authentication createNewAuthentication(final Authentication currentAuth) { final UserDetails user = loadUserByUsername(currentAuth.getName()); final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); newAuthentication.setDetails(currentAuth.getDetails()); return newAuthentication; } private void validateUserDetails(UserDetails user) { Assert.hasText(user.getUsername(), "Username may not be empty or null"); validateAuthorities(user.getAuthorities()); } private void validateAuthorities(Collection<? extends GrantedAuthority> authorities) { Assert.notNull(authorities, "Authorities list must not be null"); for (GrantedAuthority authority : authorities) { Assert.notNull(authority, "Authorities list contains a null entry"); Assert.hasText(authority.getAuthority(), "getAuthority() method must return a non-empty string"); } } }
mit
nh13/picard
src/test/java/picard/sam/util/ReadNameParserTests.java
7114
package picard.sam.util; import htsjdk.samtools.util.CollectionUtil; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.List; /** * Tests for the ReadNameParser class. */ public class ReadNameParserTests { /** Tests rapidParseInt for positive and negative numbers, as well as non-digit suffixes */ @Test public void testRapidParseInt() { for (int i = -100; i < 100; i++) { Assert.assertEquals(ReadNameParser.rapidParseInt(Integer.toString(i)), i); // trailing characters Assert.assertEquals(ReadNameParser.rapidParseInt(Integer.toString(i)+"A"), i); Assert.assertEquals(ReadNameParser.rapidParseInt(Integer.toString(i)+"ACGT"), i); Assert.assertEquals(ReadNameParser.rapidParseInt(Integer.toString(i)+".1"), i); } } /** Tests rapidParseInt for positive and negative numbers, as well as non-digit suffixes */ @Test public void testRapidParseIntFails() { List<String> values = CollectionUtil.makeList("foo", "bar", "abc123", "-foo", "f00", "-f00"); for (String s : values) { try { ReadNameParser.rapidParseInt(s); Assert.fail("Should have failed to rapid-parse " + s + " as an int."); } catch (NumberFormatException nfe) { /* expected */ } } } /** Helper for testGetRapidDefaultReadNameRegexSplit */ private void doTestGetRapidDefaultReadNameRegexSplit(int numFields) { final int[] inputFields = new int[3]; final int[] expectedFields = new int[3]; String readName = ""; for (int i = 0; i < numFields; i++) { if (0 < i) readName += ":"; readName += Integer.toString(i); } inputFields[0] = inputFields[1] = inputFields[2] = -1; if (numFields < 3) { Assert.assertEquals(ReadNameParser.getLastThreeFields(readName, ':', inputFields), -1); } else { Assert.assertEquals(ReadNameParser.getLastThreeFields(readName, ':', inputFields), numFields); expectedFields[0] = expectedFields[1] = expectedFields[2] = -1; if (0 < numFields) expectedFields[0] = numFields-3; if (1 < numFields) expectedFields[1] = numFields-2; if (2 < numFields) expectedFields[2] = numFields-1; for (int i = 0; i < inputFields.length; i++) { Assert.assertEquals(inputFields[i], expectedFields[i]); } } } /** Tests that we split the string with the correct # of fields, and modified values */ @Test public void testGetRapidDefaultReadNameRegexSplit() { for (int i = 1; i < 10; i++) { doTestGetRapidDefaultReadNameRegexSplit(i); } } @DataProvider(name = "testParseReadNameDataProvider") public Object[][] testParseReadNameDataProvider() { return new Object[][]{ {"RUNID:7:1203:2886:82292", 1203, 2886, 82292}, {"RUNID:7:1203:2884:16834", 1203, 2884, 16834} }; } // NB: these test fail s due to overflow in the duplicate finder test. This has been the behavior previously, so keep it for now. @Test(dataProvider = "testParseReadNameDataProvider", enabled = true) public void testParseReadNameOverflow(final String readName, final int tile, final int x, final int y) { ReadNameParser parser = new ReadNameParser(); PhysicalLocation loc = new PhysicalLocationShort(); Assert.assertTrue(parser.addLocationInformation(readName, loc)); Assert.assertEquals(loc.getTile(), tile); Assert.assertEquals(loc.getX(), (short)x); // casting to short for the overflow Assert.assertEquals(loc.getY(), (short)y); // casting to short for the overflow } // NB: this test the case where we do not overflow in the duplicate finder test. @Test(dataProvider = "testParseReadNameDataProvider", enabled = true) public void testParseReadNameOK(final String readName, final int tile, final int x, final int y) { ReadNameParser parser = new ReadNameParser(); PhysicalLocation loc = new PhysicalLocationInt(); Assert.assertTrue(parser.addLocationInformation(readName, loc)); Assert.assertEquals(loc.getTile(), tile); Assert.assertEquals(loc.getX(), x); // we store ints, so we should not overflow Assert.assertEquals(loc.getY(), y); // we store ints, so we should not overflow } @DataProvider(name = "testReadNameParsing") public Object[][] testReadNameParsingDataProvider() { final String lastThreeFieldsRegex = "(?:.*:)?([0-9]+)[^:]*:([0-9]+)[^:]*:([0-9]+)[^:]*$"; return new Object[][]{ {lastThreeFieldsRegex, "RUNID:123:000000000-ZZZZZ:1:1105:17981:23325", 1105, 17981, 23325, true}, {lastThreeFieldsRegex, "RUNID:123:000000000-ZZZZZ:1:1109:22981:17995", 1109, 22981, 17995, true}, {lastThreeFieldsRegex, "1109:22981:17995", 1109, 22981, 17995, true}, {lastThreeFieldsRegex, "RUNID:7:1203:2886:82292", 1203, 2886, 82292, true}, {lastThreeFieldsRegex, "RUNID:7:1203:2884:16834", 1203, 2884, 16834, true}, {lastThreeFieldsRegex, "1109ABC:22981DEF:17995GHI", 1109, 22981, 17995, true}, {ReadNameParser.DEFAULT_READ_NAME_REGEX, "RUNID:123:000000000-ZZZZZ:1:1105:17981:23325", 1105, 17981, 23325, true}, {ReadNameParser.DEFAULT_READ_NAME_REGEX, "RUNID:123:000000000-ZZZZZ:1:1109:22981:17995", 1109, 22981, 17995, true}, {ReadNameParser.DEFAULT_READ_NAME_REGEX, "1109:22981:17995", 1109, 22981, 17995, false}, {ReadNameParser.DEFAULT_READ_NAME_REGEX, "RUNID:7:1203:2886:82292", 1203, 2886, 82292, true}, {ReadNameParser.DEFAULT_READ_NAME_REGEX, "RUNID:7:1203:2884:16834", 1203, 2884, 16834, true} }; } @Test(dataProvider = "testReadNameParsing") public void testReadNameParsing(final String readNameRegex, final String readName, final int tile, final int x, final int y, final boolean addLocationInformationSucceeds) { final ReadNameParser parser = new ReadNameParser(readNameRegex); final PhysicalLocationInt loc = new PhysicalLocationInt(); Assert.assertEquals(parser.addLocationInformation(readName, loc), addLocationInformationSucceeds); if (addLocationInformationSucceeds) { // just check the location Assert.assertEquals(loc.getTile(), tile); Assert.assertEquals(loc.getX(), x); Assert.assertEquals(loc.getY(), y); } else if (readNameRegex == ReadNameParser.DEFAULT_READ_NAME_REGEX) { // additional testing on the default regex int[] tokens = new int[3]; ReadNameParser.getLastThreeFields(readName, ':', tokens); Assert.assertEquals(tokens[0], tile); Assert.assertEquals(tokens[1], x); Assert.assertEquals(tokens[2], y); } } }
mit
aspose-cells/Aspose.Cells-for-Cloud
Examples/Java/SDK/src/main/java/com/aspose/cells/cloud/examples/cells/UnmergeCellsWorksheet.java
1834
package com.aspose.cells.cloud.examples.cells; import com.aspose.cells.api.CellsApi; import com.aspose.cells.cloud.examples.Configuration; import com.aspose.cells.cloud.examples.Utils; import com.aspose.storage.api.StorageApi; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; public class UnmergeCellsWorksheet { public static void main(String... args) throws IOException { // ExStart: unmerge-cells-in-worksheet try { // Instantiate Aspose Storage API SDK StorageApi storageApi = new StorageApi(Configuration.apiKey, Configuration.appSID, true); // Instantiate Aspose Words API SDK CellsApi cellsApi = new CellsApi(Configuration.apiKey, Configuration.appSID, true); String input = "sample1.xlsx"; Path inputFile = Utils.getPath(UnmergeCellsWorksheet.class, input); String output = "sample2.xlsx"; Path outputFile = Utils.getPath(UnmergeCellsWorksheet.class, output); String sheetName = "Sheet1"; Integer startRow = 1; Integer startColumn = 0; Integer totalRows = 1; Integer totalColumns = 5; storageApi.PutCreate(input, null, Utils.STORAGE, inputFile.toFile()); cellsApi.PostWorksheetUnmerge(input, sheetName, startRow, startColumn, totalRows, totalColumns, Utils.STORAGE, Utils.FOLDER); com.aspose.storage.model.ResponseMessage sr = storageApi.GetDownload(input, null, Utils.STORAGE); Files.copy(sr.getInputStream(), outputFile, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { e.printStackTrace(); } // ExEnd: unmerge-cells-in-worksheet } }
mit
darshanhs90/Java-InterviewPrep
src/Jan2021Leetcode/_0938RangeSumOfBST.java
1373
package Jan2021Leetcode; public class _0938RangeSumOfBST { static public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } public static void main(String[] args) { TreeNode tn = new TreeNode(10); tn.left = new TreeNode(5); tn.right = new TreeNode(15); tn.left.left = new TreeNode(3); tn.left.right = new TreeNode(7); tn.right.right = new TreeNode(18); System.out.println(rangeSumBST(tn, 7, 15)); tn = new TreeNode(10); tn.left = new TreeNode(5); tn.right = new TreeNode(15); tn.left.left = new TreeNode(3); tn.left.right = new TreeNode(7); tn.left.left.left = new TreeNode(1); tn.left.right.left = new TreeNode(6); tn.right.left = new TreeNode(13); tn.right.right = new TreeNode(18); System.out.println(rangeSumBST(tn, 6, 10)); } static int sum; public static int rangeSumBST(TreeNode root, int low, int high) { sum = 0; rangeSumBST(low, root, high); return sum; } public static void rangeSumBST(int low, TreeNode root, int high) { if (root == null) return; if (root.val >= low && root.val <= high) { sum += root.val; } rangeSumBST(low, root.left, high); rangeSumBST(low, root.right, high); } }
mit
zoopaper/design-pattern
src/main/java/com/pattern/factorymethod/ChartEnum.java
162
package com.pattern.factorymethod; /** * User: krisjin * Date: 2016/9/20 */ public enum ChartEnum { NewsQuantityTrendsChart, PositiveNegativeChart }
mit
StarFruitBrasil/Brino
Br++/src/main/java/cc/brino/SerialMonitor/SerialMonitor.java
6740
package cc.brino.SerialMonitor; /* * Copyright (c) 2016 StarFruitBrasil * * Permission is hereby granted, free of charge, to any * person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the * Software without restriction, including without * limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice * shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.util.TooManyListenersException; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.Border; import javax.swing.border.LineBorder; import cc.brino.Brpp.IDEui.BubbleBorder; import cc.brino.Brpp.IDEui.SouthPanel; import cc.brino.Brpp.IDEui.ScrollBar.ScrollLeanUI; import cc.brino.Brpp.Utils.CommPortUtils; @SuppressWarnings("serial") public class SerialMonitor extends JFrame { public static boolean isOpen = false, connected = true; private final Color cinza = new Color(46, 46, 46), cinzaEscuro = new Color(30, 30, 30), verde = new Color( 72, 155, 0); private final Border roundedBorder = new LineBorder(cinzaEscuro, 15, true), translucidBorder = BorderFactory.createEmptyBorder(2, 5, 5, 5), emptyBorder = BorderFactory.createEmptyBorder(); private BorderLayout main = new BorderLayout(); private JTextPane Jp; private static JTextArea OUT = new JTextArea(600, 500); private JScrollPane out = new JScrollPane(OUT); private JPanel NorthPanel; private static JCheckBox autorolagem = new JCheckBox("Auto-rolagem"); private JButton Enviar = new JButton("Enviar"); static String messageString = "Hello, world!\n"; private CommPortUtils PortUtils; public SerialMonitor(String com) throws TooManyListenersException { // TODO Auto-generated constructor stub super("Monitor Serial"); PortUtils = new CommPortUtils(); isOpen = true; connected = true; if (!PortUtils.openPort(com)) { SouthPanel.getLOG() .append("A porta selecionada não está disponível!\r\n"); dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); setVisible(false); dispose(); connected = false; isOpen = false; } this.setLayout(main); setBackground(cinza); main.setHgap(10); try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } OUT.setBackground(cinzaEscuro); OUT.setForeground(Color.WHITE); OUT.setBorder(emptyBorder); OUT.setText(""); OUT.setEditable(false); Action enviaAction = new AbstractAction("Enviar") { private static final long serialVersionUID = -1528090166842624429L; @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated // method stub String msg = Jp.getText(); PortUtils.send(msg); Jp.setText(""); } }; enviaAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK)); Enviar.setAction(enviaAction); Enviar.setBorder(new BubbleBorder(verde)); Enviar.setBackground(verde); Enviar.setForeground(Color.WHITE); Enviar.setOpaque(true); Jp = new JTextPane(); Jp.setBorder(new BubbleBorder(cinzaEscuro)); Jp.setEditable(true); Jp.setOpaque(true); Jp.setBackground(cinzaEscuro); Jp.setForeground(Color.WHITE); Jp.setCaretColor(Color.WHITE); JScrollBar sb = out.getVerticalScrollBar(); sb.setPreferredSize(new Dimension(6, sb.getHeight())); sb.setUI(new ScrollLeanUI()); sb.setBackground(cinza); sb.setBorder(emptyBorder); JPanel centerPanel = new JPanel(new BorderLayout()); out.setBorder(roundedBorder); out.setBackground(cinza); out.setForeground(cinzaEscuro); out.setViewportBorder(emptyBorder); out.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); out.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); centerPanel.add(out, BorderLayout.CENTER); centerPanel.setBorder(translucidBorder); centerPanel.setBackground(cinza); add(centerPanel, BorderLayout.CENTER); autorolagem.setBackground(cinza); autorolagem.setForeground(Color.WHITE); add(autorolagem, BorderLayout.SOUTH); BorderLayout NLayout = new BorderLayout(); NLayout.setHgap(5); NorthPanel = new JPanel(); NorthPanel.setLayout(NLayout); NorthPanel.setBackground(cinza); NorthPanel.add(Jp, BorderLayout.CENTER); NorthPanel.add(Enviar, BorderLayout.EAST); NorthPanel.setBorder(translucidBorder); NorthPanel.setSize(getWidth(), 10); add(NorthPanel, BorderLayout.NORTH); this.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { try { CommPortUtils.closePort(); } catch (NullPointerException e) { e.printStackTrace(); } finally { isOpen = false; } } }); } public static void display(String string) { OUT.append(string); if (autorolagem.isSelected()) { OUT.setCaretPosition(OUT.getDocument().getLength()); } } public boolean getConnected() { return connected; } }
mit
aspose-email/Aspose.Email-for-Java
Examples/src/main/java/com/aspose/email/examples/email/ReadAllMessagesFromZimbraTgzStorage.java
746
package com.aspose.email.examples.email; import com.aspose.email.*; import com.aspose.email.examples.Utils; public class ReadAllMessagesFromZimbraTgzStorage { public static void main(String[] args) { // ExStart:1 // The path to the resource directory. String dataDir = Utils.getSharedDataDir(ReadAllMessagesFromZimbraTgzStorage.class) + "email/"; TgzReader reader = new TgzReader(dataDir + "ZimbraSample.tgz"); try { while (reader.readNextMessage()) { String directoryName = reader.getCurrentDirectory(); System.out.println(directoryName); MailMessage eml = reader.getCurrentMessage(); System.out.println(eml.getSubject()); } } finally { reader.dispose(); } // ExEnd:1 } }
mit
arminnh/Telecom-Distr.Systems-Project
distributed-systems/chat-app/src/controlsocket/ControlSocket.java
25635
package controlsocket; /* -*- c-basic-offset: 4 -*- * ControlSocket.java -- class for manipulating ControlSockets * Douglas S. J. De Couto, Eddie Kohler * * Copyright (c) 2000 Massachusetts Institute of Technology. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ import java.net.*; import java.io.*; import java.util.Vector; /** * Manage a user-level click Router via its TCP ControlSocket. * * @author Douglas S. J. De Couto, Eddie Kohler */ public class ControlSocket { private InetAddress _host; private int _port; private Socket _sock; private BufferedReader _in; private BufferedWriter _out; private int _protocolMinorVersion; private static final int CODE_OK = 200; private static final int CODE_OK_WARN = 220; private static final int CODE_SYNTAX_ERR = 500; private static final int CODE_UNIMPLEMENTED = 501; private static final int CODE_NO_ELEMENT = 510; private static final int CODE_NO_HANDLER = 511; private static final int CODE_HANDLER_ERR = 520; private static final int CODE_PERMISSION = 530; private static final int CODE_NO_ROUTER = 540; public static final int PROTOCOL_MAJOR_VERSION = 1; public static final int PROTOCOL_MINOR_VERSION = 0; /* XXX not sure timeout is a good idea; if we do timeout, we should reset the connection (close and re-open) to get rid of all old data... */ public static final int _sock_timeout = 0; // 1500; // msecs /** * Constructs a new ControlSocket. * * @param host Machine that the user-level click is running on. * @param port Port the Click ControlSocket is listening on. * @exception IOException If there was a problem setting up the * socket and streams, or if the ControlSocket version is wrong, or * if the ControlSocket returned a bad response. * @see java.net.InetAddress */ public ControlSocket(InetAddress host, int port) throws IOException { _host = host; _port = port; /* * setup connection to the node's click ControlSocket */ _sock = new Socket(_host, _port); _sock.setSoTimeout(_sock_timeout); InputStream is = _sock.getInputStream(); OutputStream os = _sock.getOutputStream(); _in = new BufferedReader(new InputStreamReader(is)); _out = new BufferedWriter(new OutputStreamWriter(os)); /* * check version */ try { String banner = _in.readLine(); if (banner == null) throw new IOException("ControlSocket stream closed unexpectedly"); int slash = banner.indexOf('/'); int dot = (slash >= 0 ? banner.indexOf('.', slash + 1) : -1); if (slash < 0 || dot < 0) { _sock.close(); throw new IOException("Unexpected greeting from ControlSocket"); } int majorVersion = Integer.parseInt(banner.substring(slash + 1, dot)); int minorVersion = Integer.parseInt(banner.substring(dot + 1)); if (majorVersion != PROTOCOL_MAJOR_VERSION || minorVersion < PROTOCOL_MINOR_VERSION) { _sock.close(); throw new IOException("Wrong ControlSocket version"); } _protocolMinorVersion = minorVersion; } catch (InterruptedIOException e) { // read timed out throw e; } catch (NumberFormatException e) { throw new IOException("Unexpected greeting from ControlSocket"); } } /** * Returns a String describing the socket's destination address and port. * * @return Socket description. */ public String socketName() { return _sock.getInetAddress().toString() + ":" + _sock.getPort(); } /** * Returns the same String as socketName * * @return Socket description * @see #socketName */ public String toString() { return _host + ":" + _port; } /** * Gets a String containing the router's configuration. * * @return Router configuration. * @exception NoSuchHandlerException If there is no configuration read handler. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing * the handler (e.g., there was a stream or socket error, the * ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). * @see #getRouterFlatConfig * @see #getConfigElementNames */ public String getRouterConfig() throws ClickException, IOException { return readString(null, "config"); } /** * Gets a String containing the router's flattened configuration. * * @return Flattened router configuration. * @exception NoSuchHandlerException If there is no flattened configuration read handler. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing * the handler (e.g., there was a stream or socket error, the * ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). * @see #getRouterConfig * @see #getConfigElementNames */ public String getRouterFlatConfig() throws ClickException, IOException { return readString(null, "flatconfig"); } /** * Gets a String containing the router's version. * * @return Version string. * @exception NoSuchHandlerException If there is no version read handler. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing * the handler (e.g., there was a stream or socket error, the * ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). * @see java.lang.String */ public String getRouterVersion() throws ClickException, IOException { return readString(null, "version").trim(); } /** * Gets the names of elements in the current router configuration. * * @return Vector of Strings of the element names. * @exception NoSuchHandlerException If there is no element list read handler. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing * the handler (e.g., there was a stream or socket error, the * ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). * @see #getElementHandlers * @see #getRouterConfig * @see #getRouterFlatConfig */ public Vector getConfigElementNames() throws ClickException, IOException { char[] buf = read(null, "list"); // how many elements? int i; for (i = 0; i < buf.length && buf[i] != '\n'; i++) ; // do it int numElements = 0; try { numElements = Integer.parseInt(new String(buf, 0, i)); } catch (NumberFormatException ex) { throw new ClickException.HandlerFormatException("element list"); } Vector v = StringUtils.split(buf, i + 1, '\n'); if (v.size() != numElements) throw new ClickException.HandlerFormatException("element list"); return v; } /** * Gets the names of element types that the router knows about. * * @return Vector of Strings of the element names. * @exception NoSuchHandlerException If there is no element list read handler. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing * the handler (e.g., there was a stream or socket error, the * ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). */ public Vector getRouterClasses() throws ClickException, IOException { char[] buf = read(null, "classes"); return StringUtils.split(buf, 0, '\n'); } /** * Gets the names of packages that the router knows about. * * @return Vector of Strings of the package names. * @exception NoSuchHandlerException If there is no element list read handler. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing * the handler (e.g., there was a stream or socket error, the * ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). */ public Vector getRouterPackages() throws ClickException, IOException { char[] buf = read(null, "packages"); return StringUtils.split(buf, 0, '\n'); } /** * Gets the names of the current router configuration requirements. * * @return Vector of Strings of the package names. * @exception NoSuchHandlerException If there is no element list read handler. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing * the handler (e.g., there was a stream or socket error, the * ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). * @see #getRouterConfig * @see #getRouterFlatConfig */ public Vector getConfigRequirements() throws ClickException, IOException { char[] buf = read(null, "requirements"); return StringUtils.split(buf, 0, '\n'); } public static class HandlerInfo { String elementName; String handlerName; boolean canRead; boolean canWrite; HandlerInfo() { this(null, null); } HandlerInfo(String el) { this(el, null); } HandlerInfo(String el, String handler) { elementName = el; handlerName = handler; canRead = canWrite = false; } public String getDescription() { if (elementName == null) return handlerName; else return elementName + "." + handlerName; } public String toString() { return handlerName; } } /** * Gets the information about an element's handlers in the current * router configuration. * * @param el The element name. * @return Vector of HandlerInfo structures. * @exception NoSuchElementException If there is no such element in the current configuration. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing * the handler (e.g., there was a stream or socket error, the * ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). * @see #HandlerInfo * @see #getConfigElementNames * @see #getRouterConfig * @see #getRouterFlatConfig */ public Vector getElementHandlers(String elementName) throws ClickException, IOException { Vector v = new Vector(); Vector vh; try { char[] buf = read(elementName, "handlers"); vh = StringUtils.split(buf, 0, '\n'); } catch (ClickException.NoSuchHandlerException e) { return v; } for (int i = 0; i < vh.size(); i++) { String s = (String) vh.elementAt(i); int j; for (j = 0; j < s.length() && !Character.isWhitespace(s.charAt(j)); j++) ; // find record split if (j == s.length()) throw new ClickException.HandlerFormatException(elementName + ".handlers"); HandlerInfo hi = new HandlerInfo(elementName, s.substring(0, j).trim()); while (j < s.length() && Character.isWhitespace(s.charAt(j))) j++; for ( ; j < s.length(); j++) { char c = s.charAt(j); if (Character.toLowerCase(c) == 'r') hi.canRead = true; else if (Character.toLowerCase(c) == 'w') hi.canWrite = true; else if (Character.isWhitespace(c)) break; } v.addElement(hi); } return v; } /** * Checks whether a read/write handler exists. * * @param elementName The element name. * @param handlerName The handler name. * @param writeHandler True to check write handler, otherwise false. * @return True if handler exists, otherwise false. * @exception IOException If there was a stream or socket error. * @exception ClickException If there was some other error * accessing the handler (e.g., the ControlSocket returned an unknown * unknown error code, or the response could otherwise not be understood). * @see #read * @see #write * @see #getConfigElementNames * @see #getElementHandlers */ public boolean checkHandler(String elementName, String handlerName, boolean writeHandler) throws ClickException, IOException { String handler = handlerName; if (elementName != null) handler = elementName + "." + handlerName; _out.write((writeHandler ? "CHECKWRITE " : "CHECKREAD ") + handler + "\n"); _out.flush(); // make sure we read all the response lines... String response = ""; String lastLine = null; do { lastLine = _in.readLine(); if (lastLine == null) throw new IOException("ControlSocket stream closed unexpectedly"); if (lastLine.length() < 4) throw new ClickException("Bad response line from ControlSocket"); response = response + lastLine.substring(4); } while (lastLine.charAt(3) == '-'); int code = getResponseCode(lastLine); switch (getResponseCode(lastLine)) { case CODE_OK: case CODE_OK_WARN: return true; case CODE_NO_ELEMENT: case CODE_NO_HANDLER: case CODE_HANDLER_ERR: case CODE_PERMISSION: return false; case CODE_UNIMPLEMENTED: if (elementName == null) handleErrCode(code, elementName, handlerName, response); return checkHandlerWorkaround(elementName, handlerName, writeHandler); default: handleErrCode(code, elementName, handlerName, response); return false; } } private boolean checkHandlerWorkaround(String elementName, String handlerName, boolean writeHandler) throws ClickException, IOException { // If talking to an old ControlSocket, try the "handlers" handler // instead. String s = readString(elementName, "handlers"); int pos = 0; // Find handler with same name. while (true) { pos = s.indexOf(handlerName, pos); if (pos < 0) // no such handler return false; if ((pos == 0 || s.charAt(pos - 1) == '\n') && Character.isWhitespace(s.charAt(pos + handlerName.length()))) break; pos++; } // we have a matching handler: will it be read/write suitable? char wantType = (writeHandler ? 'w' : 'r'); for (pos += handlerName.length(); pos < s.length() && Character.isWhitespace(s.charAt(pos)); pos++) /* nada */; for (; pos < s.length(); pos++) { char c = s.charAt(pos); if (Character.toLowerCase(c) == wantType) return true; else if (Character.isWhitespace(c)) break; } return false; } /** * Returns the result of reading an element's handler. * * @param elementName The element name. * @param handlerName The handler name. * @return Char array containing the data. * @exception NoSuchHandlerException If there is no such read handler. * @exception NoSuchElementException If there is no such element in the current configuration. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was a stream or socket error. * @exception ClickException If there was some other error * accessing the handler (e.g., the ControlSocket returned an unknown * unknown error code, or the response could otherwise not be understood). * @see #checkHandler * @see #write * @see #getConfigElementNames * @see #getElementHandlers */ public char[] read(String elementName, String handlerName) throws ClickException, IOException { String handler = handlerName; if (elementName != null) handler = elementName + "." + handlerName; _out.write("READ " + handler + "\n"); _out.flush(); // make sure we read all the response lines... String response = ""; String lastLine = null; do { lastLine = _in.readLine(); if (lastLine == null) throw new IOException("ControlSocket stream closed unexpectedly"); if (lastLine.length() < 4) throw new ClickException("Bad response line from ControlSocket"); response = response + lastLine.substring(4); } while (lastLine.charAt(3) == '-'); int code = getResponseCode(lastLine); if (code != CODE_OK && code != CODE_OK_WARN) handleErrCode(code, elementName, handlerName, response); response = _in.readLine(); if (response == null) throw new IOException("ControlSocket stream closed unexpectedly"); int num_bytes = getDataLength(response); if (num_bytes < 0) throw new ClickException("Bad length returned from ControlSocket"); if (num_bytes == 0) return new char[0]; // sometimes, read will return without completely filling the // buffer (e.g. on win32 JDK) char data[] = new char[num_bytes]; int bytes_left = num_bytes; while (bytes_left > 0) { int bytes_read = _in.read(data, num_bytes - bytes_left, bytes_left); bytes_left -= bytes_read; } return data; } public String readString(String el, String handler) throws ClickException, IOException { return new String(read(el, handler)); } public String readString(HandlerInfo hinfo) throws ClickException, IOException { return new String(read(hinfo.elementName, hinfo.handlerName)); } private void handleWriteResponse(String elementName, String handlerName) throws ClickException, IOException { String response = ""; String lastLine = null; do { lastLine = _in.readLine(); if (lastLine == null) throw new IOException("ControlSocket stream closed unexpectedly"); if (lastLine.length() < 4) throw new ClickException("Bad response line from ControlSocket"); response = response + lastLine.substring(4) + "\n"; } while (lastLine.charAt(3) == '-'); int code = getResponseCode(lastLine); if (code != CODE_OK && code != CODE_OK_WARN) handleErrCode(code, elementName, handlerName, response); } /** * Writes data to an element's handler. * * @param elementName The element name. * @param handlerName The handler name. * @param data Char array containing the data. * @exception NoSuchHandlerException If there is no such write handler. * @exception NoSuchElementException If there is no such element in the current configuration. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was a stream or socket error. * @exception ClickException If there was some other error * accessing the handler (e.g., the ControlSocket returned an unknown * unknown error code, or the response could otherwise not be understood). * @see #checkHandler * @see #write * @see #getConfigElementNames * @see #getElementHandlers */ public void write(String elementName, String handlerName, char[] data) throws ClickException, IOException { String handler = handlerName; if (elementName != null) handler = elementName + "." + handlerName; _out.write("WRITEDATA " + handler + " " + data.length + "\n"); _out.write(data, 0, data.length); _out.flush(); handleWriteResponse(elementName, handlerName); } public void write(String elementName, String handlerName, String data) throws ClickException, IOException { String handler = handlerName; if (elementName != null) handler = elementName + "." + handlerName; _out.write("WRITEDATA " + handler + " " + data.length() + "\n"); _out.write(data); _out.flush(); handleWriteResponse(elementName, handlerName); } public void write(HandlerInfo info, char[] data) throws ClickException, IOException { write(info.elementName, info.handlerName, data); } public void write(HandlerInfo info, String data) throws ClickException, IOException { write(info.elementName, info.handlerName, data); } /** * Close the ControlSocket. */ public void close() { try { _sock.close(); } catch (IOException ex) { } } private int getResponseCode(String s) { String code_str = s.substring(0, 3); try { return Integer.parseInt(code_str); } catch (NumberFormatException ex) { return -1; } } private int getDataLength(String s) { int i; for (i = 0; i < s.length() && !Character.isDigit(s.charAt(i)); i++) ; // do it if (i == s.length()) return -1; String len_str = s.substring(i); try { return Integer.parseInt(len_str); } catch (NumberFormatException ex) { return -1; } } private void handleErrCode(int code, String elementName, String handlerName, String response) throws ClickException { String hid = handlerName; if (elementName != null) hid = elementName + "." + handlerName; switch (code) { case CODE_SYNTAX_ERR: throw new ClickException("Syntax error calling handler `" + hid + "'"); case CODE_UNIMPLEMENTED: throw new ClickException("Unimplemented ControlSocket command"); case CODE_NO_ELEMENT: throw new ClickException.NoSuchElementException(elementName); case CODE_NO_HANDLER: throw new ClickException.NoSuchHandlerException(hid); case CODE_HANDLER_ERR: throw new ClickException.HandlerErrorException(hid, response); case CODE_PERMISSION: throw new ClickException.PermissionDeniedException(hid); default: throw new ClickException("Unknown ControlSocket error code " + code); } } /* * test driver */ public static void main(String args[]) { if (args.length == 0 || args.length > 3) { System.out.println("to list router info, `java ControlSocket'"); System.out.println("to list handlers, `java ControlSocket <element>'"); System.out.println("to read, `java ControlSocket <element> <handler>'"); System.out.println("to write, `java ControlSocket <element> <handler> <data>'"); System.out.println("router info follows"); } InetAddress localhost = null; try { // localhost = InetAddress.getLocalHost(); localhost = InetAddress.getByName("bermuda.lcs.mit.edu"); } catch (UnknownHostException ex) { System.out.println("Can't get localhost address"); System.exit(-1); } try { ControlSocket cs = new ControlSocket(localhost, 7777); if (args.length == 2) { char data[] = cs.read(args[0], args[1]); System.out.println(data); } else if (args.length == 3) { cs.write(args[0], args[1], args[2].toCharArray()); } else if (args.length == 1) { // dump element handler info Vector v = cs.getElementHandlers(args[0]); for (int i = 0; i < v.size(); i++) { ControlSocket.HandlerInfo hi = (ControlSocket.HandlerInfo) v.elementAt(i); System.out.print(hi.handlerName + "\t"); if (hi.canRead) System.out.print("r"); if (hi.canWrite) System.out.print("w"); System.out.println(); } } else { // dump router info System.out.println("Click version: " + cs.getRouterVersion().trim()); System.out.print("Router classes: "); Vector v = cs.getRouterClasses(); for (int i = 0; i < v.size(); i++) System.out.print(v.elementAt(i) + " "); System.out.println(); System.out.println("Router config:"); System.out.print(cs.getRouterConfig()); System.out.print("Config element names: "); v = cs.getConfigElementNames(); for (int i = 0; i < v.size(); i++) System.out.print(v.elementAt(i) + " "); System.out.println(); System.out.print("Router packages: "); v = cs.getRouterPackages(); for (int i = 0; i < v.size(); i++) System.out.print(v.elementAt(i) + " "); System.out.println(); System.out.print("Config requirements: "); v = cs.getConfigRequirements(); for (int i = 0; i < v.size(); i++) System.out.print(v.elementAt(i) + " "); System.out.println(); } } catch (IOException ex) { System.out.println("I/O error calling ControlSocket: " + ex.getMessage()); System.exit(1); } catch (ClickException ex) { System.out.println(ex.getMessage()); System.exit(1); } } }
mit
plumer/codana
tomcat_files/7.0.0/ResourceBundleELResolver.java
3945
/* * 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 javax.el; import java.beans.FeatureDescriptor; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; public class ResourceBundleELResolver extends ELResolver { public ResourceBundleELResolver() { super(); } @Override public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { if (property != null) { try { Object result = ((ResourceBundle) base).getObject(property .toString()); context.setPropertyResolved(true); return result; } catch (MissingResourceException mre) { return "???" + property.toString() + "???"; } } } return null; } @Override public Class<?> getType(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return null; } @Override public void setValue(ELContext context, Object base, Object property, Object value) throws NullPointerException, PropertyNotFoundException, PropertyNotWritableException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); throw new PropertyNotWritableException(message(context, "resolverNotWriteable", new Object[] { base.getClass() .getName() })); } } @Override public boolean isReadOnly(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ResourceBundle) { context.setPropertyResolved(true); } return true; } @Override // Can't use Iterator<FeatureDescriptor> because API needs to match specification public @SuppressWarnings("unchecked") Iterator getFeatureDescriptors( ELContext context, Object base) { if (base instanceof ResourceBundle) { List<FeatureDescriptor> feats = new ArrayList<FeatureDescriptor>(); Enumeration<String> e = ((ResourceBundle) base).getKeys(); FeatureDescriptor feat; String key; while (e.hasMoreElements()) { key = e.nextElement(); feat = new FeatureDescriptor(); feat.setDisplayName(key); feat.setExpert(false); feat.setHidden(false); feat.setName(key); feat.setPreferred(true); feat.setValue(RESOLVABLE_AT_DESIGN_TIME, Boolean.TRUE); feat.setValue(TYPE, String.class); feats.add(feat); } return feats.iterator(); } return null; } @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { if (base instanceof ResourceBundle) { return String.class; } return null; } }
mit
plattformbrandenburg/ldadmin
src/main/java/de/piratenpartei/berlin/ldadmin/dbaccess/generated/udt/records/DelegationInfoTypeRecord.java
13064
/** * This class is generated by jOOQ */ package de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.records; /** * This class is generated by jOOQ. */ @javax.annotation.Generated(value = { "http://www.jooq.org", "3.4.4" }, comments = "This class is generated by jOOQ") @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class DelegationInfoTypeRecord extends org.jooq.impl.UDTRecordImpl<de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.records.DelegationInfoTypeRecord> implements org.jooq.Record10<java.lang.Boolean, de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationScope, java.lang.Integer, java.lang.Boolean, java.lang.Boolean, java.lang.Integer, java.lang.Boolean, java.lang.Boolean, de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationInfoLoopType, java.lang.Integer>, de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.interfaces.IDelegationInfoType { private static final long serialVersionUID = 701528767; /** * Setter for <code>delegation_info_type.own_participation</code>. */ public void setOwnParticipation(java.lang.Boolean value) { setValue(0, value); } /** * Getter for <code>delegation_info_type.own_participation</code>. */ @Override public java.lang.Boolean getOwnParticipation() { return (java.lang.Boolean) getValue(0); } /** * Setter for <code>delegation_info_type.own_delegation_scope</code>. */ public void setOwnDelegationScope(de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationScope value) { setValue(1, value); } /** * Getter for <code>delegation_info_type.own_delegation_scope</code>. */ @Override public de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationScope getOwnDelegationScope() { return (de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationScope) getValue(1); } /** * Setter for <code>delegation_info_type.first_trustee_id</code>. */ public void setFirstTrusteeId(java.lang.Integer value) { setValue(2, value); } /** * Getter for <code>delegation_info_type.first_trustee_id</code>. */ @Override public java.lang.Integer getFirstTrusteeId() { return (java.lang.Integer) getValue(2); } /** * Setter for <code>delegation_info_type.first_trustee_participation</code>. */ public void setFirstTrusteeParticipation(java.lang.Boolean value) { setValue(3, value); } /** * Getter for <code>delegation_info_type.first_trustee_participation</code>. */ @Override public java.lang.Boolean getFirstTrusteeParticipation() { return (java.lang.Boolean) getValue(3); } /** * Setter for <code>delegation_info_type.first_trustee_ellipsis</code>. */ public void setFirstTrusteeEllipsis(java.lang.Boolean value) { setValue(4, value); } /** * Getter for <code>delegation_info_type.first_trustee_ellipsis</code>. */ @Override public java.lang.Boolean getFirstTrusteeEllipsis() { return (java.lang.Boolean) getValue(4); } /** * Setter for <code>delegation_info_type.other_trustee_id</code>. */ public void setOtherTrusteeId(java.lang.Integer value) { setValue(5, value); } /** * Getter for <code>delegation_info_type.other_trustee_id</code>. */ @Override public java.lang.Integer getOtherTrusteeId() { return (java.lang.Integer) getValue(5); } /** * Setter for <code>delegation_info_type.other_trustee_participation</code>. */ public void setOtherTrusteeParticipation(java.lang.Boolean value) { setValue(6, value); } /** * Getter for <code>delegation_info_type.other_trustee_participation</code>. */ @Override public java.lang.Boolean getOtherTrusteeParticipation() { return (java.lang.Boolean) getValue(6); } /** * Setter for <code>delegation_info_type.other_trustee_ellipsis</code>. */ public void setOtherTrusteeEllipsis(java.lang.Boolean value) { setValue(7, value); } /** * Getter for <code>delegation_info_type.other_trustee_ellipsis</code>. */ @Override public java.lang.Boolean getOtherTrusteeEllipsis() { return (java.lang.Boolean) getValue(7); } /** * Setter for <code>delegation_info_type.delegation_loop</code>. */ public void setDelegationLoop(de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationInfoLoopType value) { setValue(8, value); } /** * Getter for <code>delegation_info_type.delegation_loop</code>. */ @Override public de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationInfoLoopType getDelegationLoop() { return (de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationInfoLoopType) getValue(8); } /** * Setter for <code>delegation_info_type.participating_member_id</code>. */ public void setParticipatingMemberId(java.lang.Integer value) { setValue(9, value); } /** * Getter for <code>delegation_info_type.participating_member_id</code>. */ @Override public java.lang.Integer getParticipatingMemberId() { return (java.lang.Integer) getValue(9); } // ------------------------------------------------------------------------- // Record10 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public org.jooq.Row10<java.lang.Boolean, de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationScope, java.lang.Integer, java.lang.Boolean, java.lang.Boolean, java.lang.Integer, java.lang.Boolean, java.lang.Boolean, de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationInfoLoopType, java.lang.Integer> fieldsRow() { return (org.jooq.Row10) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public org.jooq.Row10<java.lang.Boolean, de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationScope, java.lang.Integer, java.lang.Boolean, java.lang.Boolean, java.lang.Integer, java.lang.Boolean, java.lang.Boolean, de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationInfoLoopType, java.lang.Integer> valuesRow() { return (org.jooq.Row10) super.valuesRow(); } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Boolean> field1() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.OWN_PARTICIPATION; } /** * {@inheritDoc} */ @Override public org.jooq.Field<de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationScope> field2() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.OWN_DELEGATION_SCOPE; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Integer> field3() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.FIRST_TRUSTEE_ID; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Boolean> field4() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.FIRST_TRUSTEE_PARTICIPATION; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Boolean> field5() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.FIRST_TRUSTEE_ELLIPSIS; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Integer> field6() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.OTHER_TRUSTEE_ID; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Boolean> field7() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.OTHER_TRUSTEE_PARTICIPATION; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Boolean> field8() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.OTHER_TRUSTEE_ELLIPSIS; } /** * {@inheritDoc} */ @Override public org.jooq.Field<de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationInfoLoopType> field9() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.DELEGATION_LOOP; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Integer> field10() { return de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.PARTICIPATING_MEMBER_ID; } /** * {@inheritDoc} */ @Override public java.lang.Boolean value1() { return getOwnParticipation(); } /** * {@inheritDoc} */ @Override public de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationScope value2() { return getOwnDelegationScope(); } /** * {@inheritDoc} */ @Override public java.lang.Integer value3() { return getFirstTrusteeId(); } /** * {@inheritDoc} */ @Override public java.lang.Boolean value4() { return getFirstTrusteeParticipation(); } /** * {@inheritDoc} */ @Override public java.lang.Boolean value5() { return getFirstTrusteeEllipsis(); } /** * {@inheritDoc} */ @Override public java.lang.Integer value6() { return getOtherTrusteeId(); } /** * {@inheritDoc} */ @Override public java.lang.Boolean value7() { return getOtherTrusteeParticipation(); } /** * {@inheritDoc} */ @Override public java.lang.Boolean value8() { return getOtherTrusteeEllipsis(); } /** * {@inheritDoc} */ @Override public de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationInfoLoopType value9() { return getDelegationLoop(); } /** * {@inheritDoc} */ @Override public java.lang.Integer value10() { return getParticipatingMemberId(); } /** * {@inheritDoc} */ @Override public DelegationInfoTypeRecord value1(java.lang.Boolean value) { setOwnParticipation(value); return this; } /** * {@inheritDoc} */ @Override public DelegationInfoTypeRecord value2(de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationScope value) { setOwnDelegationScope(value); return this; } /** * {@inheritDoc} */ @Override public DelegationInfoTypeRecord value3(java.lang.Integer value) { setFirstTrusteeId(value); return this; } /** * {@inheritDoc} */ @Override public DelegationInfoTypeRecord value4(java.lang.Boolean value) { setFirstTrusteeParticipation(value); return this; } /** * {@inheritDoc} */ @Override public DelegationInfoTypeRecord value5(java.lang.Boolean value) { setFirstTrusteeEllipsis(value); return this; } /** * {@inheritDoc} */ @Override public DelegationInfoTypeRecord value6(java.lang.Integer value) { setOtherTrusteeId(value); return this; } /** * {@inheritDoc} */ @Override public DelegationInfoTypeRecord value7(java.lang.Boolean value) { setOtherTrusteeParticipation(value); return this; } /** * {@inheritDoc} */ @Override public DelegationInfoTypeRecord value8(java.lang.Boolean value) { setOtherTrusteeEllipsis(value); return this; } /** * {@inheritDoc} */ @Override public DelegationInfoTypeRecord value9(de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationInfoLoopType value) { setDelegationLoop(value); return this; } /** * {@inheritDoc} */ @Override public DelegationInfoTypeRecord value10(java.lang.Integer value) { setParticipatingMemberId(value); return this; } /** * {@inheritDoc} */ @Override public DelegationInfoTypeRecord values(java.lang.Boolean value1, de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationScope value2, java.lang.Integer value3, java.lang.Boolean value4, java.lang.Boolean value5, java.lang.Integer value6, java.lang.Boolean value7, java.lang.Boolean value8, de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationInfoLoopType value9, java.lang.Integer value10) { return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached DelegationInfoTypeRecord */ public DelegationInfoTypeRecord() { super(de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.DELEGATION_INFO_TYPE); } /** * Create a detached, initialised DelegationInfoTypeRecord */ public DelegationInfoTypeRecord(java.lang.Boolean ownParticipation, de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationScope ownDelegationScope, java.lang.Integer firstTrusteeId, java.lang.Boolean firstTrusteeParticipation, java.lang.Boolean firstTrusteeEllipsis, java.lang.Integer otherTrusteeId, java.lang.Boolean otherTrusteeParticipation, java.lang.Boolean otherTrusteeEllipsis, de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DelegationInfoLoopType delegationLoop, java.lang.Integer participatingMemberId) { super(de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationInfoType.DELEGATION_INFO_TYPE); setValue(0, ownParticipation); setValue(1, ownDelegationScope); setValue(2, firstTrusteeId); setValue(3, firstTrusteeParticipation); setValue(4, firstTrusteeEllipsis); setValue(5, otherTrusteeId); setValue(6, otherTrusteeParticipation); setValue(7, otherTrusteeEllipsis); setValue(8, delegationLoop); setValue(9, participatingMemberId); } }
mit
testmycode/tmc-intellij
tmc-plugin-intellij/src/main/java/fi/helsinki/cs/tmc/intellij/ui/submissionresult/feedback/TextQuestionPanel.java
4677
package fi.helsinki.cs.tmc.intellij.ui.submissionresult.feedback; import fi.helsinki.cs.tmc.core.domain.submission.FeedbackAnswer; import fi.helsinki.cs.tmc.core.domain.submission.FeedbackQuestion; import com.intellij.ui.components.JBScrollPane; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TextQuestionPanel extends FeedbackQuestionPanel { private static final Logger logger = LoggerFactory.getLogger(TextQuestionPanel.class); private final FeedbackQuestion question; public TextQuestionPanel(FeedbackQuestion question) { logger.info( "Creating text question panel for submission feedback window " + "@TextQuestionPanel"); this.question = question; initComponents(); this.questionLabel.setText(question.getQuestion()); } @Override public FeedbackAnswer getAnswer() { logger.info("Getting feedback answer. @TextQuestionPanel"); String text = answerTextArea.getText().trim(); if (text.isEmpty()) { return null; } return new FeedbackAnswer(question, text); } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT * modify this code. The content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") private void initComponents() { logger.info("Initializing components for TextQuestionPanel " + "@TextQuestionPanel"); questionLabel = new javax.swing.JLabel(); //textAreaScrollPane = new javax.swing.JScrollPane(); textAreaScrollPane = new JBScrollPane(); answerTextArea = new javax.swing.JTextArea(); //questionLabel.setText(org.openide.util.NbBundle.getMessage(TextQuestionPanel.class, "TextQuestionPanel.questionLabel.text")); // NOI18N questionLabel.setText("Teting testing TextQuestionPanle"); // NOI18N answerTextArea.setColumns(20); answerTextArea.setLineWrap(true); answerTextArea.setRows(5); answerTextArea.setWrapStyleWord(true); textAreaScrollPane.setViewportView(answerTextArea); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addContainerGap() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment .LEADING) .addComponent( textAreaScrollPane, javax.swing.GroupLayout .DEFAULT_SIZE, 362, Short.MAX_VALUE) .addComponent(questionLabel)) .addContainerGap())); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addContainerGap() .addComponent(questionLabel) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( textAreaScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE) .addContainerGap())); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextArea answerTextArea; private javax.swing.JLabel questionLabel; private javax.swing.JScrollPane textAreaScrollPane; // End of variables declaration//GEN-END:variables }
mit
ldebello/java-advanced
JavaEE/JavaWebServices/FacadeAPI/ProductAPI/src/main/java/ar/com/javacuriosities/facade/api/controllers/ProductController.java
849
package ar.com.javacuriosities.facade.api.controllers; import ar.com.javacuriosities.facade.api.model.ProductDTO; import ar.com.javacuriosities.facade.api.services.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("products") public class ProductController { @Autowired private ProductService productService; @GetMapping(produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, "application/x-yaml"}) public List<ProductDTO> getProducts() { return productService.getProducts(); } }
mit
nevercast/OpenModsLib
src/main/java/openmods/proxy/OpenServerProxy.java
1598
package openmods.proxy; import java.io.File; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.INetHandler; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import openmods.gui.CommonGuiHandler; import cpw.mods.fml.common.network.IGuiHandler; public final class OpenServerProxy implements IOpenModsProxy { @Override public EntityPlayer getThePlayer() { return null; } @Override public boolean isClientPlayer(Entity player) { return false; } @Override public long getTicks(World worldObj) { return worldObj.getTotalWorldTime(); } @Override public World getClientWorld() { return null; } @Override public World getServerWorld(int id) { return DimensionManager.getWorld(id); } @Override public File getMinecraftDir() { return MinecraftServer.getServer().getFile(""); } @Override public String getLogFileName() { return "ForgeModLoader-server-0.log"; } @Override public IGuiHandler wrapHandler(IGuiHandler modSpecificHandler) { return new CommonGuiHandler(modSpecificHandler); } @Override public void preInit() {} @Override public void init() {} @Override public void postInit() {} @Override public void setNowPlayingTitle(String nowPlaying) {} @Override public EntityPlayer getPlayerFromHandler(INetHandler handler) { if (handler instanceof NetHandlerPlayServer) return ((NetHandlerPlayServer)handler).playerEntity; return null; } }
mit
aima-java/aima-java
aimax-osm/src/main/java/aimax/osm/data/impl/AbstractEntityFinder.java
3580
package aimax.osm.data.impl; import java.util.ArrayList; import java.util.List; import aimax.osm.data.EntityFinder; import aimax.osm.data.OsmMap; import aimax.osm.data.MapWayFilter; import aimax.osm.data.Position; import aimax.osm.data.entities.MapEntity; /** * Base class suitable to implement different entity finders. Just the method * {@link #find(boolean)} has to be overridden. * * @author Ruediger Lunde */ public abstract class AbstractEntityFinder implements EntityFinder { protected enum Mode { ENTITY, NODE, WAY, ADDRESS } private final OsmMap storage; private int minRadius; private int maxRadius; protected int nextRadius; protected Mode mode; protected String pattern; protected Position position; protected MapWayFilter wayFilter; private final List<MapEntity> intermediateResults; private final List<MapEntity> results; /** Creates a new entity finder for the given map data storage. */ public AbstractEntityFinder(OsmMap storage) { this.storage = storage; minRadius = 2; maxRadius = 16; nextRadius = -1; intermediateResults = new ArrayList<>(); results = new ArrayList<>(); } protected OsmMap getStorage() { return storage; } /** {@inheritDoc} */ @Override public int getMinRadius() { return minRadius; } /** {@inheritDoc} */ @Override public void setMinRadius(int km) { minRadius = km; } /** {@inheritDoc} */ @Override public int getMaxRadius() { return maxRadius; } /** {@inheritDoc} */ @Override public void setMaxRadius(int km) { maxRadius = km; } /** {@inheritDoc} */ @Override public void findEntity(String pattern, Position pos) { mode = Mode.ENTITY; this.pattern = pattern; position = pos; wayFilter = null; nextRadius = minRadius; clearResults(); find(false); } /** {@inheritDoc} */ @Override public void findNode(String pattern, Position pos) { mode = Mode.NODE; this.pattern = pattern; position = pos; nextRadius = minRadius; clearResults(); find(false); } /** {@inheritDoc} */ @Override public void findWay(String pattern, Position pos, MapWayFilter filter) { mode = Mode.WAY; this.pattern = pattern; position = pos; wayFilter = filter; nextRadius = minRadius; clearResults(); find(false); } /** {@inheritDoc} */ @Override public void findAddress(String pattern, Position pos) { mode = Mode.ADDRESS; this.pattern = pattern; position = pos; wayFilter = null; nextRadius = minRadius; clearResults(); find(false); } /** {@inheritDoc} */ @Override public boolean canFindMore() { return nextRadius != -1 || intermediateResults.size() == 1; } /** {@inheritDoc} */ @Override public void findMore() { find(true); } /** Abstract operation which makes the interesting work. */ protected abstract void find(boolean findMore); public Position getRefPosition() { return position; } /** {@inheritDoc} */ @Override public List<MapEntity> getIntermediateResults() { return intermediateResults; } /** {@inheritDoc} */ @Override public List<MapEntity> getResults() { return results; } /** {@inheritDoc} */ @Override public void selectIntermediateResult(MapEntity entity) { intermediateResults.clear(); intermediateResults.add(entity); } /** Clears results and sets the next search radius to the minimum radius. */ private void clearResults() { intermediateResults.clear(); results.clear(); } }
mit
hou80houzhu/brooderServer
src/main/java/com/bright/contenter/template/TemplaterException.java
619
package com.bright.contenter.template; import freemarker.core.Environment; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import java.io.Writer; public class TemplaterException implements TemplateExceptionHandler { @Override public void handleTemplateException(TemplateException te, Environment e, Writer writer) throws TemplateException { try { writer.write("[NODATA]"); } catch (Exception ez) { throw new TemplateException("Failed to print error message. Cause: " + writer, e); } } }
mit
JPAT-ROSEMARY/SCUBA
org.jpat.scuba.external.slf4j/logback-1.2.3/logback-classic/src/test/java/org/dummy/DummyLBAppender.java
1274
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package org.dummy; import java.util.ArrayList; import java.util.List; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; public class DummyLBAppender extends AppenderBase<ILoggingEvent> { public List<ILoggingEvent> list = new ArrayList<ILoggingEvent>(); public List<String> stringList = new ArrayList<String>(); PatternLayout layout; DummyLBAppender() { this(null); } DummyLBAppender(PatternLayout layout) { this.layout = layout; } protected void append(ILoggingEvent e) { list.add(e); if (layout != null) { String s = layout.doLayout(e); stringList.add(s); } } }
mit
GlowstonePlusPlus/GlowstonePlusPlus
src/main/java/net/glowstone/net/handler/login/LoginStartHandler.java
2883
package net.glowstone.net.handler.login; import com.flowpowered.network.MessageHandler; import net.glowstone.EventFactory; import net.glowstone.GlowServer; import net.glowstone.entity.meta.profile.GlowPlayerProfile; import net.glowstone.net.GlowSession; import net.glowstone.net.ProxyData; import net.glowstone.net.message.login.EncryptionKeyRequestMessage; import net.glowstone.net.message.login.LoginStartMessage; import net.glowstone.util.SecurityUtils; import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result; import java.nio.charset.StandardCharsets; import java.util.UUID; import java.util.regex.Pattern; public final class LoginStartHandler implements MessageHandler<GlowSession, LoginStartMessage> { private static final Pattern usernamePattern = Pattern.compile("[a-zA-Z0-9_]+"); @Override public void handle(GlowSession session, LoginStartMessage message) { String name = message.getUsername(); int length = name.length(); if (length > 16 || !usernamePattern.matcher(name).find()) { session.disconnect("Invalid username provided.", true); } GlowServer server = session.getServer(); if (server.getOnlineMode()) { // Get necessary information to create our request message String sessionId = session.getSessionId(); byte[] publicKey = SecurityUtils .generateX509Key(server.getKeyPair().getPublic()) .getEncoded(); //Convert to X509 format byte[] verifyToken = SecurityUtils.generateVerifyToken(); // Set verify data on session for use in the response handler session.setVerifyToken(verifyToken); session.setVerifyUsername(name); // Send created request message and wait for the response session.send(new EncryptionKeyRequestMessage(sessionId, publicKey, verifyToken)); } else { GlowPlayerProfile profile; ProxyData proxy = session.getProxyData(); if (proxy == null) { UUID uuid = UUID .nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8)); profile = new GlowPlayerProfile(name, uuid, true); } else { profile = proxy.getProfile(name); } AsyncPlayerPreLoginEvent event = EventFactory.getInstance() .onPlayerPreLogin(profile.getName(), session.getAddress(), profile.getId()); if (event.getLoginResult() != Result.ALLOWED) { session.disconnect(event.getKickMessage(), true); return; } GlowPlayerProfile finalProfile = profile; server.getScheduler().runTask(null, () -> session.setPlayer(finalProfile)); } } }
mit
quchunguang/test
testjava/TIJ4-code/innerclasses/Destination.java
147
//: innerclasses/Destination.java package innerclasses; /* Added by Eclipse.py */ public interface Destination { String readLabel(); } ///:~
mit
kaituo/sedge
trunk/test-kaituo/edu/umass/cs/pig/test/TestExGen4Foreach.java
5660
package edu.umass.cs.pig.test; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; import java.util.Properties; import java.util.Random; import org.apache.pig.ExecType; import org.apache.pig.PigServer; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; import org.apache.pig.impl.PigContext; import org.apache.pig.newplan.Operator; import org.apache.pig.test.SessionIdentifierGenerator; import org.junit.BeforeClass; import org.junit.Test; public class TestExGen4Foreach { static PigContext pigContext = new PigContext(ExecType.LOCAL, new Properties()); static int MAX = 100; static String A, B, C; static File fileA, fileB, fileC; { try { pigContext.connect(); } catch (ExecException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @BeforeClass public static void oneTimeSetup() throws Exception { fileA = File.createTempFile("dataA", ".dat"); fileB = File.createTempFile("dataB", ".dat"); fileC = File.createTempFile("dataC", ".dat"); writeData(fileA); writeData(fileB); writeData2(fileC); fileA.deleteOnExit(); fileB.deleteOnExit(); fileC.deleteOnExit(); A = "'" + fileA.getPath() + "'"; B = "'" + fileB.getPath() + "'"; C = "'" + fileC.getPath() + "'"; System.out.println("A : " + A + "\n" + "B : " + B + "\n" + "C : " + C); System.out.println("Test data created."); } private static void writeData(File dataFile) throws Exception { // File dataFile = File.createTempFile(name, ".dat"); FileOutputStream dat = new FileOutputStream(dataFile); Random rand = new Random(); for (int i = 0; i < MAX; i++) dat.write((rand.nextInt(10) + "\t" + rand.nextInt(10) + "\n") .getBytes()); dat.close(); } private static void writeData2(File dataFile) throws Exception { // File dataFile = File.createTempFile(name, ".dat"); FileOutputStream dat = new FileOutputStream(dataFile); SessionIdentifierGenerator rand = new SessionIdentifierGenerator(); Random rand2 = new Random(); for (int i = 0; i < MAX; i++) dat.write((rand.nextSessionId() + "\t" + rand2.nextInt(10) + "\n") .getBytes()); dat.close(); } @Test public void testForeach() throws Exception { PigServer pigserver = new PigServer(pigContext); String query = "A = load " + A + " using PigStorage() as (x : int, y : int);\n"; pigserver.registerQuery(query); query = "B = filter A by x * y > 200;"; pigserver.registerQuery(query); query = "C = FOREACH B GENERATE (x+1) as x1, (y+1) as y1;"; pigserver.registerQuery(query); query = "D = FOREACH C GENERATE (x1+1) as x2, (y1+1) as y2;"; pigserver.registerQuery(query); query = "E = DISTINCT D;"; pigserver.registerQuery(query); Map<Operator, DataBag> derivedData = pigserver.getExamples2("E"); assertTrue(derivedData != null); } @Test public void testForeach2() throws ExecException, IOException { PigServer pigServer = new PigServer(pigContext); pigServer.registerQuery("A = load " + A + " using PigStorage() as (x : int, y : int);"); pigServer.registerQuery("B = foreach A generate x + y as sum;"); Map<Operator, DataBag> derivedData = pigServer.getExamples2("B"); assertTrue(derivedData != null); } @Test public void testForeachBinCondWithBooleanExp() throws ExecException, IOException { PigServer pigServer = new PigServer(pigContext); pigServer.registerQuery("A = load " + A + " using PigStorage() as (x : int, y : int);"); pigServer.registerQuery("B = foreach A generate (x + 1 > y ? 0 : 1);"); Map<Operator, DataBag> derivedData = pigServer.getExamples2("B"); assertTrue(derivedData != null); } @Test public void testForeachWithTypeCastCounter() throws ExecException, IOException { PigServer pigServer = new PigServer(pigContext); //cast error results in counter being incremented and was resulting // in a NPE exception in illustrate pigServer.registerQuery("A = load " + A + " using PigStorage() as (x : int, y : int);"); pigServer.registerQuery("B = foreach A generate x, (int)'InvalidInt';"); Map<Operator, DataBag> derivedData = pigServer.getExamples("B"); assertTrue(derivedData != null); } @Test public void testForeach3() throws Exception { PigServer pigserver = new PigServer(pigContext); String query = "A = load " + A + " using PigStorage() as (x : int, y : int);\n"; pigserver.registerQuery(query); query = "B = FOREACH A GENERATE (x+1) as x1, (y+1) as y1;"; pigserver.registerQuery(query); query = "C = filter B by x1 * y1 > 200;"; pigserver.registerQuery(query); query = "D = FOREACH C GENERATE (x1+1) as x2, (y1+1) as y2;"; pigserver.registerQuery(query); query = "E = DISTINCT D;"; pigserver.registerQuery(query); Map<Operator, DataBag> derivedData = pigserver.getExamples2("E"); assertTrue(derivedData != null); } }
mit
mollstam/UnrealPy
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/db-4.7.25.0/java/src/com/sleepycat/bind/tuple/IntegerBinding.java
2297
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2000,2008 Oracle. All rights reserved. * * $Id: IntegerBinding.java 63573 2008-05-23 21:43:21Z trent.nelson $ */ package com.sleepycat.bind.tuple; import com.sleepycat.db.DatabaseEntry; /** * A concrete <code>TupleBinding</code> for a <code>Integer</code> primitive * wrapper or an <code>int</code> primitive. * * <p>There are two ways to use this class:</p> * <ol> * <li>When using the {@link com.sleepycat.db} package directly, the static * methods in this class can be used to convert between primitive values and * {@link DatabaseEntry} objects.</li> * <li>When using the {@link com.sleepycat.collections} package, an instance of * this class can be used with any stored collection. The easiest way to * obtain a binding instance is with the {@link * TupleBinding#getPrimitiveBinding} method.</li> * </ol> */ public class IntegerBinding extends TupleBinding { private static final int INT_SIZE = 4; // javadoc is inherited public Object entryToObject(TupleInput input) { return new Integer(input.readInt()); } // javadoc is inherited public void objectToEntry(Object object, TupleOutput output) { output.writeInt(((Number) object).intValue()); } // javadoc is inherited protected TupleOutput getTupleOutput(Object object) { return sizedOutput(); } /** * Converts an entry buffer into a simple <code>int</code> value. * * @param entry is the source entry buffer. * * @return the resulting value. */ public static int entryToInt(DatabaseEntry entry) { return entryToInput(entry).readInt(); } /** * Converts a simple <code>int</code> value into an entry buffer. * * @param val is the source value. * * @param entry is the destination entry buffer. */ public static void intToEntry(int val, DatabaseEntry entry) { outputToEntry(sizedOutput().writeInt(val), entry); } /** * Returns a tuple output object of the exact size needed, to avoid * wasting space when a single primitive is output. */ private static TupleOutput sizedOutput() { return new TupleOutput(new byte[INT_SIZE]); } }
mit
DevOpsDistilled/OpERP
OpERP/src/main/java/devopsdistilled/operp/client/context/account/MvcControllerContext.java
898
package devopsdistilled.operp.client.context.account; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import devopsdistilled.operp.client.account.panes.controllers.PaidTransactionPaneController; import devopsdistilled.operp.client.account.panes.controllers.ReceivedTransactionPaneController; import devopsdistilled.operp.client.account.panes.controllers.impl.PaidTransactionPaneControllerImpl; import devopsdistilled.operp.client.account.panes.controllers.impl.ReceivedTransactionPaneControllerImpl; @Configuration public class MvcControllerContext { @Bean public ReceivedTransactionPaneController receivedTransactionPaneController() { return new ReceivedTransactionPaneControllerImpl(); } @Bean public PaidTransactionPaneController paidTransactionPaneController() { return new PaidTransactionPaneControllerImpl(); } }
mit
Bernardo-MG/spring-soap-ws-security-example
src/test/java/com/bernardomg/example/swss/test/unit/client/password/digest/xwss/TestEntityClientPasswordDigestXwss.java
2281
/** * The MIT License (MIT) * <p> * Copyright (c) 2015-2017 the original author or authors. * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * 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 com.bernardomg.example.swss.test.unit.client.password.digest.xwss; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import com.bernardomg.example.swss.test.util.config.context.ClientXwssContextPaths; import com.bernardomg.example.swss.test.util.config.properties.SoapPropertiesPaths; import com.bernardomg.example.swss.test.util.config.properties.TestPropertiesPaths; import com.bernardomg.example.swss.test.util.test.unit.client.AbstractTestEntityClientHeader; /** * Unit test for a XWSS digested password protected client. * * @author Bernardo Mart&iacute;nez Garrido */ @ContextConfiguration(locations = { ClientXwssContextPaths.PASSWORD_DIGEST }) @TestPropertySource({ SoapPropertiesPaths.PASSWORD_DIGEST, TestPropertiesPaths.USER }) public final class TestEntityClientPasswordDigestXwss extends AbstractTestEntityClientHeader { /** * Constructs a {@code TestEntityClientPasswordDigestXWSS}. */ public TestEntityClientPasswordDigestXwss() { super(); } }
mit
zik43/java-design-patterns
marker/src/test/java/ThiefTest.java
1406
/* * The MIT License * Copyright © 2014-2019 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; /** * Thief test */ public class ThiefTest { @Test public void testThief() { Thief thief = new Thief(); assertFalse(thief instanceof Permission); } }
mit
blackbbc/Tucao
DanmakuFlameMaster/src/main/java/master/flame/danmaku/danmaku/model/IDrawingCache.java
466
package master.flame.danmaku.danmaku.model; public interface IDrawingCache<T> { public void build(int w, int h, int density, boolean checkSizeEquals, int bitsPerPixel); public void erase(); public T get(); public void destroy(); public int size(); public int width(); public int height(); public boolean hasReferences(); public void increaseReference(); public void decreaseReference(); }
mit
zaoying/EChartsAnnotation
src/cn/edu/gdut/zaoying/Option/series/effectScatter/markPoint/label/emphasis/textStyle/FontSizeNumber.java
383
package cn.edu.gdut.zaoying.Option.series.effectScatter.markPoint.label.emphasis.textStyle; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FontSizeNumber { double value() default 0; }
mit
mollstam/UnrealPy
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/db-4.7.25.0/java/src/com/sleepycat/persist/impl/RawSingleInput.java
988
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002,2008 Oracle. All rights reserved. * * $Id: RawSingleInput.java 63573 2008-05-23 21:43:21Z trent.nelson $ */ package com.sleepycat.persist.impl; import java.util.IdentityHashMap; /** * Extends RawAbstractInput to convert array (ObjectArrayFormat and * PrimitiveArrayteKeyFormat) RawObject instances. * * @author Mark Hayes */ class RawSingleInput extends RawAbstractInput { private Object singleValue; private Format declaredFormat; RawSingleInput(Catalog catalog, boolean rawAccess, IdentityHashMap converted, Object singleValue, Format declaredFormat) { super(catalog, rawAccess, converted); this.singleValue = singleValue; this.declaredFormat = declaredFormat; } @Override Object readNext() { return checkAndConvert(singleValue, declaredFormat); } }
mit
ex3ndr/telegram
app/src/main/java/org/telegram/android/core/audio/OpusEncoderActor.java
2772
package org.telegram.android.core.audio; import org.telegram.opus.OpusLib; import org.telegram.actors.*; import java.nio.ByteBuffer; /** * Created by ex3ndr on 18.03.14. */ public class OpusEncoderActor extends ReflectedActor { private static final int STATE_NONE = 0; private static final int STATE_STARTED = 1; private static final int STATE_COMPLETED = 2; private int state = STATE_NONE; private OpusLib opusLib = new OpusLib(); private ByteBuffer fileBuffer = ByteBuffer.allocateDirect(1920); public OpusEncoderActor(ActorSystem system) { super(system,"opus_encoder", "encoding"); } protected void onStartMessage(String fileName) { if (state != STATE_NONE) { return; } int result = opusLib.startRecord(fileName); state = STATE_STARTED; } protected void onWriteMessage(byte[] buffer, int size) { if (state != STATE_STARTED) { return; } ByteBuffer finalBuffer = ByteBuffer.allocateDirect(size); finalBuffer.put(buffer, 0, size); finalBuffer.rewind(); boolean flush = false; while (finalBuffer.hasRemaining()) { int oldLimit = -1; if (finalBuffer.remaining() > fileBuffer.remaining()) { oldLimit = finalBuffer.limit(); finalBuffer.limit(fileBuffer.remaining() + finalBuffer.position()); } fileBuffer.put(finalBuffer); if (fileBuffer.position() == fileBuffer.limit() || flush) { int length = !flush ? fileBuffer.limit() : finalBuffer.position(); if (opusLib.writeFrame(fileBuffer, length) != 0) { fileBuffer.rewind(); } } if (oldLimit != -1) { finalBuffer.limit(oldLimit); } } } protected void onStopMessage() { if (state != STATE_STARTED) { return; } opusLib.stopRecord(); state = STATE_COMPLETED; } @Override public void onException(Exception e) { e.printStackTrace(); } public static class Messenger extends ActorMessenger { public Messenger(ActorReference reference, ActorReference sender) { super(reference, sender); } public void start(String fileName) { talkRaw("start", fileName); } public void write(byte[] buffer, int size) { talkRaw("write", buffer, size); } public void stop() { talkRaw("stop"); } @Override public ActorMessenger cloneForSender(ActorReference sender) { return new Messenger(reference, sender); } } }
mit
hecklerm/TRIPwire
src/main/java/org/thehecklers/DataHandler.java
2000
package org.thehecklers; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.socket.*; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by markheckler on 1/19/2016. */ @Component public class DataHandler extends TextWebSocketHandler { private List<WebSocketSession> sessionList = new ArrayList<>(); @Autowired private ReadingRepository repo; @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessionList.add(session); System.out.println("Data connection established from " + session.toString() + ", TIME: " + new Date().toString()); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { try { ObjectMapper mapper = new ObjectMapper(); Reading reading = mapper.readValue(message.getPayload(), Reading.class); repo.save(reading); System.out.println("New reading: " + reading.toString()); sessionList.stream().filter(s -> s != session).forEach(s -> { try { s.sendMessage(message); } catch (IOException e) { System.out.println("Exception re-sending data message: " + e.getLocalizedMessage()); } }); } catch (Exception e) { System.out.println("Exception: " + e.getLocalizedMessage()); } } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessionList.remove(session); System.out.println("Data connection closed by " + session.toString() + ", TIME: " + new Date().toString()); } }
mit
forge/core
projects/tests/src/main/java/org/jboss/forge/addon/projects/mock/MockProjectTypeNoRequiredFacets.java
1036
/** * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.addon.projects.mock; import java.util.Collections; import org.jboss.forge.addon.projects.AbstractProjectType; import org.jboss.forge.addon.projects.ProjectFacet; import org.jboss.forge.addon.ui.wizard.UIWizardStep; /** * @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> */ public class MockProjectTypeNoRequiredFacets extends AbstractProjectType { @Override public String getType() { return "norequirements"; } @Override public Class<? extends UIWizardStep> getSetupFlow() { return null; } @Override public Iterable<Class<? extends ProjectFacet>> getRequiredFacets() { return Collections.emptySet(); } @Override public String toString() { return getType(); } @Override public int priority() { return 0; } }
epl-1.0
luhaoaimama1/AndroidZone
JavaTest_Zone/src/算法/MinStack.java
1084
package 算法; import java.util.Stack; /** * Created by fuzhipeng on 2018/4/27. * * 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。 */ public class MinStack { Stack<Integer> stack = new Stack<Integer>(); Stack<Integer> minStack = new Stack<Integer>(); /** * 当推入的元素 大于 minstack站的值的话就不用存, 为什么呢? * 因为pop这个元素的 最小值还是是不变的。 所以不需要压入 * * @param item * @return */ public Integer push(Integer item) { stack.push(item); if (minStack.isEmpty()) minStack.push(item); else { if (item < minStack.peek()) minStack.push(item); } return item; } public Integer pop() { if (stack.peek() == minStack.peek()) minStack.pop(); return stack.pop(); } public Integer peek() { return stack.peek(); } public Integer minPeek() { return minStack.peek(); } }
epl-1.0
kevinott/crypto
org.jcryptool.analysis.transpositionanalysis/src/org/jcryptool/analysis/transpositionanalysis/calc/transpositionanalysis/model/PolledTranspositionKey.java
12408
//-----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2010 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ //-----END DISCLAIMER----- package org.jcryptool.analysis.transpositionanalysis.calc.transpositionanalysis.model; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.jcryptool.analysis.transpositionanalysis.calc.PolledPositiveInteger; import org.jcryptool.analysis.transpositionanalysis.calc.PolledValue; import org.jcryptool.crypto.classic.transposition.algorithm.TranspositionKey; /** * A Transposition key (with set length), which positions can be polled. * * @author Simon L * */ public class PolledTranspositionKey { /** * Creates a standard entry for a key position with given length * * @param positionCount * the number of positions in the key ("key length") * @return a PolledPositiveInteger of the specified length and standard * values */ private static final PolledPositiveInteger NOVALUE(int positionCount) { PolledPositiveInteger result = new PolledPositiveInteger(); for (int i = 0; i < positionCount; i++) result.addChoice(i); return result; } private HashMap<Integer, PolledPositiveInteger> internalRepresentation; /** * Creates an empty PolledTranspositionKey */ public PolledTranspositionKey() { internalRepresentation = new HashMap<Integer, PolledPositiveInteger>(0); } /** * Creates a PolledTranspositionKey from an array. Format: see * {@link #fromArray(double[][])} * * @param arrayRepresentation * the array */ public PolledTranspositionKey(double[][] arrayRepresentation) { this(); this.fromArray(arrayRepresentation); } /** * Clears all content. */ public void clear() { internalRepresentation.clear(); } /** * Specifies the possibility for a value at the given position of the key. <br /> * Basically, if a value a is on the position b in the key, that means, that * in every column of a plaintext, the character at position b will be * placed in position a in the ciphertext. Specifying a high possibility for * a value at a given position means, that it is very likely that the polled * key will have this value on the said position in the end. <br /> * <br /> * If one of the parameters (position, or value) have a higher value than * the actual size of the key, the key will be resized to it. * * @param position * the position in the key * @param value * the value that has to stand at this position. * @param possibility * the possibility vot the value to be actually in the given * position (use constants from {@link PolledValue} for example). */ public void setPossibility(int position, int value, double possibility) { setLength(Math.max(Math.max(position + 1, value + 1), getLength())); internalRepresentation.get(position).addChoice(value, possibility); } /** * Combines the possibility for a value at the given position of the key * with a given one. <br /> * See also: {@link #setPossibility(int, int, double)}<br /> * If one of the parameters (position, or value) have a higher value than * the actual size of the key, the key will be resized to it. * * @param position * the position in the key * @param value * the value that has to stand at this position. * @param possibility * the possibility the existing possibility will be combined with * (you can use constants from {@link PolledValue} for example). */ public void combinePossibility(int position, int value, double possibility) { setLength(Math.max(Math.max(position + 1, value + 1), getLength())); internalRepresentation.get(position).combinePossibility(value, possibility); } /** * Sets the key to a specified length. All values in the key that are bigger * than this new length, will be removed. In the end, there will be n polls * for key positions, when n is the new length, and the method * {@link #toArray()} will return a n x n array. * * @param length * the new length */ public void setLength(int length) { // remove all entries with key greater than length Set<Integer> removelist = new HashSet<Integer>(0); for (Integer k : internalRepresentation.keySet()) { if (k >= length) { removelist.add(k); } } for (Integer i : removelist) { internalRepresentation.remove(i); } for (int i = 0; i < length; i++) { // make sure that every key from 0 to length is contained once. if (!internalRepresentation.containsKey(i)) { internalRepresentation.put(i, NOVALUE(length)); } // remove all entries from a poll for a position, that are greater // than the length removelist.clear(); for (Integer choice : internalRepresentation.get(i).getPollSubjects()) { if (choice >= length) removelist.add(choice); } for (Integer removeChoice : removelist) { internalRepresentation.get(i).removeChoice(removeChoice); } // make sure, that in all Polls for positions are only the values // between 0 and length for (int k = 0; k < length; k++) { if (!internalRepresentation.get(i).hasChoice(k)) { internalRepresentation.get(i).addChoice(k); } } } } private double valueOfChoice(int[] choice, double[][] pollArray) { double[] choiceArray = new double[choice.length]; for (int i = 0; i < choiceArray.length; i++) { choiceArray[i] = pollArray[i][choice[i]]; } return valueOfChoiceAsDoublerow(choiceArray); } private double valueOfChoiceAsDoublerow(double[] choiceValues) { double result = PolledValue.POSSIBILITY_DEFAULT; for (int i = 0; i < choiceValues.length; i++) { result *= choiceValues[i]; } return result; } private int[] combineRecursiveChoices(int thisDepthChoice, int[] nextDepthChoice) { int[] result = new int[nextDepthChoice.length + 1]; result[0] = thisDepthChoice; for (int i = 1; i < nextDepthChoice.length + 1; i++) { result[i] = nextDepthChoice[i - 1] >= thisDepthChoice ? nextDepthChoice[i - 1] + 1 : nextDepthChoice[i - 1]; } return result; } private double[][] makeSubPollArray(int choiceIndexOfRowZero, double[][] pollArray) { if (!(pollArray.length > 1 && pollArray[0].length > 1)) throw new IllegalArgumentException( "Can't crate sub - Poll-array from 1-element-array."); if (choiceIndexOfRowZero >= pollArray.length) throw new IllegalArgumentException( "choiceIndex is greater than poll array dimensions. cannot create sub - poll-array."); double[][] result = new double[pollArray.length - 1][pollArray[0].length - 1]; for (int i = 1; i < pollArray.length; i++) { for (int k = 0; k < pollArray[i].length - 1; k++) { result[i - 1][k] = pollArray[i][(k >= choiceIndexOfRowZero) ? k + 1 : k]; } } return result; } private int[] getBestChoice(double[][] pollArray) { if (pollArray.length < 1) throw new IllegalArgumentException("there is no best choice for a void array"); if (pollArray.length == 1) return new int[] { 0 }; // take the remaining // piece // not-trivial cases int[] bestChoice = null; double bestChoiceValue = Double.MIN_VALUE; for (int i = 0; i < pollArray.length; i++) { double[][] subArray = makeSubPollArray(i, pollArray); // heuristic cost is the biggest cost that could possibly reached // with choice i (estimated) double heuristicCost = calcHeuristicCostForChoiceAndFollowingSubarray(pollArray[0][i], subArray); if (heuristicCost > bestChoiceValue) { int[] currentChoice = combineRecursiveChoices(i, getBestChoice(subArray)); double subValue = valueOfChoice(currentChoice, pollArray); if (subValue > bestChoiceValue) { bestChoiceValue = subValue; bestChoice = currentChoice; } } } return bestChoice; } private double calcHeuristicCostForChoiceAndFollowingSubarray(double choiceValue, double[][] subArray) { double[] valueArray = new double[subArray.length + 1]; double[] subArrayOverestimation = calcBestValuePerPosList(subArray); valueArray[0] = choiceValue; for (int i = 1; i < subArray.length + 1; i++) { valueArray[i] = subArrayOverestimation[i - 1]; } return valueOfChoiceAsDoublerow(valueArray); } /** * Calculates the best TranspositionKey that would match the given * possibility data. * * @return a TranspositionKey which is the best match for this * PolledTranspositionKey. */ public TranspositionKey getBestChoice() { double[][] array = toArray(); if (!(array.length > 0 && array[0].length > 0)) throw new IllegalArgumentException( "polled key has no content - cannot calculate best choice"); int[] bestChoice = getBestChoice(array); return new TranspositionKey(bestChoice); } private double[] calcBestValuePerPosList(double[][] array) { List<Double> maxValues = new LinkedList<Double>(); for (int i = 0; i < array.length; i++) { double minVal = Double.MIN_VALUE; for (int k = 0; k < array[i].length; k++) { minVal = Math.max(minVal, array[i][k]); } maxValues.add(minVal); } double[] valueListAsArray = new double[maxValues.size()]; for (int i = 0; i < valueListAsArray.length; i++) valueListAsArray[i] = maxValues.get(i); return valueListAsArray; } /** * Read an array of integer values into the polled key, as follows: * <code>arrayRepresentation[2][4] = 6</code> means, that in the key on * position 2 (zero-relative), the value "4" has a possibility that is one * relatively high one*. Such, a polled key of length n is always * represented by a double array with dimensions n x n.<br /> * <br /> * * * because a possibility of 1 means 50%, and 6 is normally a value that * specifies "Very high possibility". see possibility constants in * {@link PolledValue}, e. g. {@link PolledValue#POSSIBILITY_VERY_LIKELY} * * @param arrayRepresentation * a representation of the polled key that shall be loaded, as * described above (length x length - array) */ public void fromArray(double[][] arrayRepresentation) { this.clear(); int length = arrayRepresentation.length; this.clear(); this.setLength(length); for (int i = 0; i < length; i++) { for (int k = 0; k < length; k++) { this.setPossibility(i, k, arrayRepresentation[i][k]); } } } /** * See {@link #fromArray()} (inverse-compatible method) * * @return an length x length-array of possibilities. */ public double[][] toArray() { TreeSet<Integer> sortedKeySet = new TreeSet<Integer>(internalRepresentation.keySet()); Integer[] sortedKeyArray = new Integer[] {}; sortedKeyArray = sortedKeySet.toArray(sortedKeyArray); double[][] result = new double[sortedKeyArray.length][sortedKeyArray.length]; for (int i = 0; i < sortedKeyArray.length; i++) { PolledPositiveInteger pollAtPos = internalRepresentation.get(i); for (int k = 0; k < pollAtPos.getChoiceCount(); k++) { result[i][k] = pollAtPos.getPossibility(k); } } return result; } @Override public String toString() { String result = ""; double[][] array = this.toArray(); for (int i = 0; i < array.length; i++) { result += (i == 0 ? "" : "\n") + "Position " + i + ": "; for (int k = 0; k < array[i].length; k++) { result += (k == 0 ? "" : " ") + array[i][k]; } } return result; } /** * Returns the length of the key (speaking: the number of positions in the * key). * * @return the length */ public int getLength() { return internalRepresentation.keySet().size(); } }
epl-1.0
Cooperate-Project/Cooperate
bundles/de.cooperateproject.modeling.textual.component.ui/src-gen/de/cooperateproject/modeling/textual/component/ui/ComponentExecutableExtensionFactory.java
833
/* * generated by Xtext 2.12.0 */ package de.cooperateproject.modeling.textual.component.ui; import com.google.inject.Injector; import de.cooperateproject.modeling.textual.component.ui.internal.ComponentActivator; import org.eclipse.xtext.ui.guice.AbstractGuiceAwareExecutableExtensionFactory; import org.osgi.framework.Bundle; /** * This class was generated. Customizations should only happen in a newly * introduced subclass. */ public class ComponentExecutableExtensionFactory extends AbstractGuiceAwareExecutableExtensionFactory { @Override protected Bundle getBundle() { return ComponentActivator.getInstance().getBundle(); } @Override protected Injector getInjector() { return ComponentActivator.getInstance().getInjector(ComponentActivator.DE_COOPERATEPROJECT_MODELING_TEXTUAL_COMPONENT_COMPONENT); } }
epl-1.0
ChristophSonnberger/crypto
org.jcryptool.analysis.textmodify/src/org/jcryptool/analysis/textmodify/commands/Messages.java
1042
// -----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2010 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.analysis.textmodify.commands; import org.eclipse.osgi.util.NLS; public class Messages extends NLS { private static final String BUNDLE_NAME = "org.jcryptool.analysis.textmodify.commands.messages"; //$NON-NLS-1$ public static String TransformAction_errorTransformMenuBtn; public static String TransformAction_tooltip1; public static String TransformAction_tooltip2; static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); } private Messages() { } }
epl-1.0
sguan-actuate/birt
testsuites/org.eclipse.birt.report.tests.model/src/org/eclipse/birt/report/tests/model/regression/Regression_134954.java
3192
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. All rights reserved. This program and * the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: Actuate Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.birt.report.tests.model.regression; import java.io.IOException; import org.eclipse.birt.report.model.api.DesignConfig; import org.eclipse.birt.report.model.api.DesignEngine; import org.eclipse.birt.report.model.api.DesignFileException; import org.eclipse.birt.report.model.api.LibraryHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.SessionHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.tests.model.BaseTestCase; import com.ibm.icu.util.ULocale; /** * Regression description: * </p> * Library can't be removed. * <p> * Steps to reproduce: * <ol> * <li>New a report "a.rptdesign" * <li>New a library which is not in the same fold with report, saying * "../test/lib.rptlibrary" * <li>Report includes the library * <li>Remove the library * </ol> * <b>Expected result:</b> * <p> * The library is removed * <p> * <b>Actual result:</b> * <p> * Open XMLSource, the included library structure is still there. * </p> * Test description: * <p> * Report include a library from a relative folder "lib/***", remove the library * from report, save and reopen the report, make sure the included library * structure is cleared. * </p> */ public class Regression_134954 extends BaseTestCase { private final static String INPUT = "regression_134954.xml"; //$NON-NLS-1$ private final static String OUTPUT = "regression_134954_out"; //$NON-NLS-1$ protected void setUp( ) throws Exception { super.setUp( ); removeResource( ); // retrieve two input files from tests-model.jar file copyInputToFile ( INPUT_FOLDER + "/" + INPUT ); } /** * @throws DesignFileException * @throws SemanticException * @throws IOException */ public void test_regression_134954( ) throws DesignFileException, SemanticException, IOException { openDesign( INPUT ); LibraryHandle lib = designHandle.getLibrary( "regression_134954" ); //$NON-NLS-1$ designHandle.dropLibrary( lib ); // save the design and reopen it, make sure the included structure is // cleared. designHandle.saveAs( OUTPUT ); DesignEngine engine = new DesignEngine( new DesignConfig( ) ); SessionHandle session = engine.newSessionHandle( ULocale.ENGLISH ); //ReportDesignHandle designHandle = session.openDesign(getTempFolder()+File.separator+ OUTPUT_FOLDER+ File.separator+OUTPUT ); //ReportDesignHandle designHandle = session.openDesign(OUTPUT ); ReportDesignHandle designHandle = session.openDesign(OUTPUT ); assertNull( designHandle .getListProperty( ReportDesignHandle.LIBRARIES_PROP ) ); } }
epl-1.0
tavalin/openhab2-addons
addons/binding/org.openhab.binding.neeo/src/main/java/org/openhab/binding/neeo/internal/discovery/NeeoRoomDiscoveryService.java
4842
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.neeo.internal.discovery; import java.io.IOException; import java.util.Collections; import java.util.Objects; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.config.discovery.AbstractDiscoveryService; import org.eclipse.smarthome.config.discovery.DiscoveryResult; import org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder; import org.eclipse.smarthome.core.thing.Bridge; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.ThingUID; import org.openhab.binding.neeo.internal.NeeoBrainApi; import org.openhab.binding.neeo.internal.NeeoBrainConfig; import org.openhab.binding.neeo.internal.NeeoConstants; import org.openhab.binding.neeo.internal.handler.NeeoBrainHandler; import org.openhab.binding.neeo.internal.models.NeeoBrain; import org.openhab.binding.neeo.internal.models.NeeoRoom; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of {@link AbstractDiscoveryService} that will discover the rooms in a NEEO brain; * * @author Tim Roberts - Initial contribution */ @NonNullByDefault public class NeeoRoomDiscoveryService extends AbstractDiscoveryService { /** The logger */ private final Logger logger = LoggerFactory.getLogger(NeeoRoomDiscoveryService.class); /** The room bridge type we support */ private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Collections .singleton(NeeoConstants.BRIDGE_TYPE_ROOM); /** The timeout (in seconds) for searching the brain */ private static final int SEARCH_TIME = 10; /** The brain handler that we will use */ private final NeeoBrainHandler brainHandler; /** * Constructs the discover service from the brain handler * * @param brainHandler a non-null brain handler */ public NeeoRoomDiscoveryService(NeeoBrainHandler brainHandler) { super(DISCOVERABLE_THING_TYPES_UIDS, SEARCH_TIME); Objects.requireNonNull(brainHandler, "brainHandler cannot be null"); this.brainHandler = brainHandler; } @Override protected void startScan() { final String brainId = brainHandler.getNeeoBrainId(); final Bridge brainBridge = brainHandler.getThing(); final ThingUID brainUid = brainBridge.getUID(); final NeeoBrainApi api = brainHandler.getNeeoBrainApi(); if (api == null) { logger.debug("Brain API was not available for {} - skipping", brainId); return; } try { final NeeoBrain brain = api.getBrain(); final NeeoBrainConfig config = brainBridge.getConfiguration().as(NeeoBrainConfig.class); final NeeoRoom[] rooms = brain.getRooms().getRooms(); if (rooms.length == 0) { logger.debug("Brain {} ({}) found - but there were no rooms - skipping", brain.getName(), brainId); return; } logger.debug("Brain {} ({}) found, scanning {} rooms in it", brain.getName(), brainId, rooms.length); for (NeeoRoom room : rooms) { final String roomKey = room.getKey(); if (roomKey == null || StringUtils.isEmpty(roomKey)) { logger.debug("Room didn't have a room key: {}", room); continue; } if (room.getDevices().getDevices().length == 0 && room.getRecipes().getRecipes().length == 0 && !config.isDiscoverEmptyRooms()) { logger.debug("Room {} ({}) found but has no devices or recipes, ignoring - {}", room.getKey(), brainId, room.getName()); continue; } final ThingUID thingUID = new ThingUID(NeeoConstants.BRIDGE_TYPE_ROOM, brainUid, room.getKey()); final DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) .withProperty(NeeoConstants.CONFIG_ROOMKEY, roomKey) .withProperty(NeeoConstants.CONFIG_EXCLUDE_THINGS, true).withBridge(brainUid) .withLabel(room.getName() + " (NEEO " + brainId + ")").build(); thingDiscovered(discoveryResult); } } catch (IOException e) { logger.debug("IOException occurred getting brain info ({}): {}", brainId, e.getMessage(), e); } } }
epl-1.0
OpenLiberty/open-liberty
dev/build.depScanner/src/io/openliberty/depScanner/Repository.java
2291
/******************************************************************************* * Copyright (c) 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package io.openliberty.depScanner; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.JarInputStream; import java.util.stream.Stream; import java.util.zip.ZipEntry; public class Repository { private final Map<String, List<Module>> moduleMap = new HashMap<>(); public Repository(File repoDir) { Module.setRoot(repoDir.getAbsolutePath()); for (File f : Utils.findJars(repoDir)) { try { Module m = new Module(f); List<Module> modules = moduleMap.computeIfAbsent(m.getModuleId(), k -> new ArrayList<>()); modules.add(m); JarInputStream jarIn = new JarInputStream(new FileInputStream(f)); ZipEntry entry = jarIn.getNextEntry(); if (entry != null) { do { if (entry.getName().endsWith(".class") && !entry.getName().equals("module-info.class")) { String className = entry.getName(); className = className.replaceAll("/", "."); className = className.substring(0, className.length() - 6); byte[] hash = Utils.computeHash(jarIn); m.addClass(className, hash); } } while ((entry = jarIn.getNextEntry()) != null); } } catch (IOException e) { e.printStackTrace(); } } } public Stream<Map.Entry<String, List<Module>>> stream() { return moduleMap.entrySet().stream(); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.msgstore/src/com/ibm/ws/sib/msgstore/persistence/objectManager/BatchingContextImpl.java
38416
package com.ibm.ws.sib.msgstore.persistence.objectManager; /******************************************************************************* * Copyright (c) 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ import com.ibm.ws.objectManager.LogFileFullException; import com.ibm.ws.objectManager.ObjectManager; import com.ibm.ws.objectManager.ObjectManagerException; import com.ibm.ws.objectManager.ObjectStore; import com.ibm.ws.objectManager.ObjectStoreFullException; import com.ibm.ws.objectManager.Transaction; import com.ibm.ws.sib.msgstore.MessageStoreConstants; import com.ibm.ws.sib.msgstore.PersistenceException; import com.ibm.ws.sib.msgstore.PersistenceFullException; import com.ibm.ws.sib.msgstore.SevereMessageStoreException; import com.ibm.ws.sib.msgstore.persistence.BatchingContext; import com.ibm.ws.sib.msgstore.persistence.Persistable; import com.ibm.ws.sib.msgstore.persistence.impl.CachedPersistableImpl; import com.ibm.ws.sib.msgstore.transactions.impl.PersistentTransaction; import com.ibm.ws.sib.transactions.PersistentTranId; import com.ibm.websphere.ras.TraceComponent; import com.ibm.ws.sib.utils.ras.SibTr; public class BatchingContextImpl implements BatchingContext { private static TraceComponent tc = SibTr.register(BatchingContextImpl.class, MessageStoreConstants.MSG_GROUP, MessageStoreConstants.MSG_BUNDLE); private ObjectManager _objectManager; private ObjectStore _objectStore; private Transaction _tran; private PersistenceException _deferredException; private int _capacity = 10; // Flags used to determine if this batching context // is being used to service two-phase work. These // flags will be dependant on the calling of the // addIndoubtXid(), updateXIDXXX() and deleteXID() // methods during the lifetime of this object. private static final int STATE_ACTIVE = 0; private static final int STATE_PREPARING = 1; private static final int STATE_PREPARED = 2; private static final int STATE_COMMITTING = 3; private static final int STATE_COMMITTED = 4; private static final int STATE_ROLLINGBACK = 5; private static final int STATE_ROLLEDBACK = 6; private static final String[] _stateToString = {"STATE_ACTIVE", "STATE_PREPARING", "STATE_PREPARED", "STATE_COMMITTING", "STATE_COMMITTED", "STATE_ROLLINGBACK", "STATE_ROLLEDBACK"}; private int _state = STATE_ACTIVE; private byte[] _xid; /** * one-phase constructor * * @param objectManager * @param objectStore */ public BatchingContextImpl(ObjectManager objectManager, ObjectStore objectStore) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "<init>", new Object[] {"ObjectManager="+objectManager,"ObjectStore="+objectStore}); _objectManager = objectManager; _objectStore = objectStore; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "<init>"); } /** * two-phase constructor * * @param objectManager * @param objectStore * @param transaction * * @exception PersistenceException */ public BatchingContextImpl(ObjectManager objectManager, ObjectStore objectStore, PersistentTransaction transaction) throws PersistenceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "<init>", new Object[] {"ObjectManager="+objectManager,"ObjectStore="+objectStore,"Transaction="+transaction}); _objectManager = objectManager; _objectStore = objectStore; if (transaction != null) { _xid = transaction.getPersistentTranId().toByteArray(); try { _tran = _objectManager.getTransaction(); _tran.setXID(_xid); } catch (ObjectManagerException ome) { com.ibm.ws.ffdc.FFDCFilter.processException(ome, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.<init>", "1:132:1.18", this); PersistenceException pe = new PersistenceException("Exception caught starting object manager transaction: "+ome.getMessage(), ome); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Exception caught starting object manager transaction!"); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "<init>"); throw pe; } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "<init>"); } /** * recovery constructor * * @param objectManager * @param objectStore * @param transaction * * @exception PersistenceException */ public BatchingContextImpl(ObjectManager objectManager, ObjectStore objectStore, Transaction transaction) throws PersistenceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "<init>", new Object[] {"ObjectManager="+objectManager,"ObjectStore="+objectStore,"Transaction="+transaction}); _objectManager = objectManager; _objectStore = objectStore; if (transaction != null) { _tran = transaction; _state = STATE_PREPARED; } else { PersistenceException pe = new PersistenceException("Recovered transaction is null!"); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Recovered transaction is null!"); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "<init>"); throw pe; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "<init>"); } public void insert(Persistable persistable) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "insert", "Persistable="+persistable); if (_deferredException == null) { // Creation of a new item try { _startTransaction(); PersistableImpl thePersistable = null; CachedPersistableImpl cachedPersistable = null; if (persistable instanceof PersistableImpl) { // We are working directly on the persistable // so we can just call it directly. thePersistable = (PersistableImpl)persistable; thePersistable.addToStore(_tran, _objectStore); } else if (persistable instanceof CachedPersistableImpl) { // We are using a cached version of the persistables // data so we need to pass that to the original // persistable object. cachedPersistable = (CachedPersistableImpl)persistable; thePersistable = (PersistableImpl)cachedPersistable.getPersistable(); thePersistable.addToStore(_tran, _objectStore, persistable); } } catch (LogFileFullException lffe) { com.ibm.ws.ffdc.FFDCFilter.processException(lffe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.insert", "1:210:1.18", this); SibTr.error(tc, "FILE_STORE_LOG_FULL_SIMS1573E"); _deferredException = new PersistenceFullException("FILE_STORE_LOG_FULL_SIMS1573E", lffe); } catch (ObjectStoreFullException osfe) { com.ibm.ws.ffdc.FFDCFilter.processException(osfe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.insert", "1:216:1.18", this); if (_objectStore.getStoreStrategy() == ObjectStore.STRATEGY_KEEP_ALWAYS) { SibTr.error(tc, "FILE_STORE_PERMANENT_STORE_FULL_SIMS1574E"); _deferredException = new PersistenceFullException("FILE_STORE_PERMANENT_STORE_FULL_SIMS1574E", osfe); } else { SibTr.error(tc, "FILE_STORE_TEMPORARY_STORE_FULL_SIMS1575E"); _deferredException = new PersistenceFullException("FILE_STORE_TEMPORARY_STORE_FULL_SIMS1575E", osfe); } } catch (ObjectManagerException ome) { com.ibm.ws.ffdc.FFDCFilter.processException(ome, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.insert", "1:230:1.18", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Exception caught inserting item into object store!", ome); _deferredException = new PersistenceException("Exception caught inserting item into object store: "+ome.getMessage(), ome); } catch (PersistenceException pe) { com.ibm.ws.ffdc.FFDCFilter.processException(pe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.insert", "1:236:1.18", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "PersistenceException caught inserting item into object store!", pe); _deferredException = pe; } catch (SevereMessageStoreException smse) { com.ibm.ws.ffdc.FFDCFilter.processException(smse, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.insert", "1:242:1.18", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Severe exception caught inserting item into object store!", smse); _deferredException = new PersistenceException("Exception caught inserting item into object store: "+smse.getMessage(), smse);; } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "No work attempted as an exception has already been thrown during this batch!"); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "insert"); } public void updateDataAndSize(Persistable persistable) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "updateDataAndSize", "Persistable="+persistable); if (_deferredException == null) { try { _startTransaction(); PersistableImpl thePersistable = null; CachedPersistableImpl cachedPersistable = null; if (persistable instanceof PersistableImpl) { // We are working directly on the persistable // so we can just call it directly. thePersistable = (PersistableImpl)persistable; thePersistable.updateDataOnly(_tran, _objectStore); } else if (persistable instanceof CachedPersistableImpl) { // We are using a cached version of the persistables // data so we need to pass that to the original // persistable object. cachedPersistable = (CachedPersistableImpl)persistable; thePersistable = (PersistableImpl)cachedPersistable.getPersistable(); thePersistable.updateDataOnly(_tran, _objectStore, persistable); } } catch (LogFileFullException lffe) { com.ibm.ws.ffdc.FFDCFilter.processException(lffe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateDataAndSize", "1:289:1.18", this); SibTr.error(tc, "FILE_STORE_LOG_FULL_SIMS1573E"); _deferredException = new PersistenceFullException("FILE_STORE_LOG_FULL_SIMS1573E", lffe); } catch (ObjectStoreFullException osfe) { com.ibm.ws.ffdc.FFDCFilter.processException(osfe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateDataAndSize", "1:295:1.18", this); if (_objectStore.getStoreStrategy() == ObjectStore.STRATEGY_KEEP_ALWAYS) { SibTr.error(tc, "FILE_STORE_PERMANENT_STORE_FULL_SIMS1574E"); _deferredException = new PersistenceFullException("FILE_STORE_PERMANENT_STORE_FULL_SIMS1574E", osfe); } else { SibTr.error(tc, "FILE_STORE_TEMPORARY_STORE_FULL_SIMS1575E"); _deferredException = new PersistenceFullException("FILE_STORE_TEMPORARY_STORE_FULL_SIMS1575E", osfe); } } catch (ObjectManagerException ome) { com.ibm.ws.ffdc.FFDCFilter.processException(ome, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateDataAndSize", "1:309:1.18", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Exception caught updating data in object store!", ome); _deferredException = new PersistenceException("Exception caught updating data in object store: "+ome.getMessage(), ome); } catch (PersistenceException pe) { com.ibm.ws.ffdc.FFDCFilter.processException(pe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateDataAndSize", "1:315:1.18", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Persistence exception caught updating data in object store!", pe); _deferredException = pe; } catch (SevereMessageStoreException smse) { com.ibm.ws.ffdc.FFDCFilter.processException(smse, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateDataAndSize", "1:321:1.18", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Severe exception caught updating data in object store!", smse); _deferredException = new PersistenceException("Exception caught inserting item into object store: "+smse.getMessage(), smse);; } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "No work attempted as an exception has already been thrown during this batch!"); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateDataAndSize"); } public void updateLockIDOnly(Persistable persistable) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "updateLockIDOnly", "Persistable="+persistable); if (_deferredException == null) { try { _startTransaction(); PersistableImpl thePersistable = null; CachedPersistableImpl cachedPersistable = null; if (persistable instanceof PersistableImpl) { // We are working directly on the persistable // so we can just call it directly. thePersistable = (PersistableImpl)persistable; thePersistable.updateMetaDataOnly(_tran); } else if (persistable instanceof CachedPersistableImpl) { // We are using a cached version of the persistables // data so we need to pass that to the original // persistable object. cachedPersistable = (CachedPersistableImpl)persistable; thePersistable = (PersistableImpl)cachedPersistable.getPersistable(); thePersistable.updateMetaDataOnly(_tran, persistable); } } catch (LogFileFullException lffe) { com.ibm.ws.ffdc.FFDCFilter.processException(lffe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateLockIDOnly", "1:368:1.18", this); SibTr.error(tc, "FILE_STORE_LOG_FULL_SIMS1573E"); _deferredException = new PersistenceFullException("FILE_STORE_LOG_FULL_SIMS1573E", lffe); } catch (ObjectStoreFullException osfe) { com.ibm.ws.ffdc.FFDCFilter.processException(osfe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateLockIDOnly", "1:374:1.18", this); if (_objectStore.getStoreStrategy() == ObjectStore.STRATEGY_KEEP_ALWAYS) { SibTr.error(tc, "FILE_STORE_PERMANENT_STORE_FULL_SIMS1574E"); _deferredException = new PersistenceFullException("FILE_STORE_PERMANENT_STORE_FULL_SIMS1574E", osfe); } else { SibTr.error(tc, "FILE_STORE_TEMPORARY_STORE_FULL_SIMS1575E"); _deferredException = new PersistenceFullException("FILE_STORE_TEMPORARY_STORE_FULL_SIMS1575E", osfe); } } catch (ObjectManagerException ome) { com.ibm.ws.ffdc.FFDCFilter.processException(ome, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateLockIDOnly", "1:388:1.18", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Exception caught updating metadata in object store!", ome); _deferredException = new PersistenceException("Exception caught updating metadata in object store: "+ome.getMessage(), ome); } catch (PersistenceException pe) { com.ibm.ws.ffdc.FFDCFilter.processException(pe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateLockIDOnly", "1:394:1.18", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Persistence exception caught updating metadata in object store!", pe); _deferredException = pe; } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "No work attempted as an exception has already been thrown during this batch!"); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateLockIDOnly"); } public void updateRedeliveredCountOnly(Persistable persistable) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "updateRedeliveredCountOnly", "Persistable="+persistable); if (_deferredException == null) { try { _startTransaction(); PersistableImpl thePersistable = null; CachedPersistableImpl cachedPersistable = null; if (persistable instanceof PersistableImpl) { // We are working directly on the persistable // so we can just call it directly. thePersistable = (PersistableImpl)persistable; thePersistable.updateMetaDataOnly(_tran); } else if (persistable instanceof CachedPersistableImpl) { // We are using a cached version of the persistables // data so we need to pass that to the original // persistable object. cachedPersistable = (CachedPersistableImpl)persistable; thePersistable = (PersistableImpl)cachedPersistable.getPersistable(); thePersistable.updateMetaDataOnly(_tran, persistable); } } catch (LogFileFullException lffe) { com.ibm.ws.ffdc.FFDCFilter.processException(lffe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateRedeliveredCountOnly", "1:368:1.17", this); SibTr.error(tc, "FILE_STORE_LOG_FULL_SIMS1573E"); _deferredException = new PersistenceFullException("FILE_STORE_LOG_FULL_SIMS1573E", lffe); } catch (ObjectStoreFullException osfe) { com.ibm.ws.ffdc.FFDCFilter.processException(osfe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateRedeliveredCountOnly", "1:374:1.17", this); if (_objectStore.getStoreStrategy() == ObjectStore.STRATEGY_KEEP_ALWAYS) { SibTr.error(tc, "FILE_STORE_PERMANENT_STORE_FULL_SIMS1574E"); _deferredException = new PersistenceFullException("FILE_STORE_PERMANENT_STORE_FULL_SIMS1574E", osfe); } else { SibTr.error(tc, "FILE_STORE_TEMPORARY_STORE_FULL_SIMS1575E"); _deferredException = new PersistenceFullException("FILE_STORE_TEMPORARY_STORE_FULL_SIMS1575E", osfe); } } catch (ObjectManagerException ome) { com.ibm.ws.ffdc.FFDCFilter.processException(ome, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateRedeliveredCountOnly", "1:388:1.17", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Exception caught updating metadata in object store!", ome); _deferredException = new PersistenceException("Exception caught updating metadata in object store: "+ome.getMessage(), ome); } catch (PersistenceException pe) { com.ibm.ws.ffdc.FFDCFilter.processException(pe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.updateRedeliveredCountOnly", "1:394:1.17", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Persistence exception caught updating metadata in object store!", pe); _deferredException = pe; } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "No work attempted as an exception has already been thrown during this batch!"); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateRedeliveredCountOnly"); } public void updateLogicalDeleteAndXID(Persistable persistable) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "updateLogicalDeleteAndXID", "Persistable="+persistable); if (_deferredException == null) { PersistableImpl thePersistable = (PersistableImpl)persistable; if (thePersistable.isLogicallyDeleted()) { // Task level prepare time remove processing. internalDelete(persistable); } else { // Task level rollback time remove processing. At // the moment we don't have anything to do here as // we simply backout the changes in the object // store at executeBatch time. } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "No work attempted as an exception has already been thrown during this batch!"); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateLogicalDeleteAndXID"); } public void delete(Persistable persistable) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "delete", "Persistable="+persistable); if (_deferredException == null) { // Task level rollback time add processing. At the moment // we don't need to do anything as we simply backout the // change in the object store at executeBatch time. // Task level two-phase commit time remove processing. // At the moment we don't need to do anything as we // simply commit the first phase changes in the object // store at executeBatch time. // Task level one-phase commit time remove processing. // If our state is not STATE_ACTIVE then we have carried // out first phase processing previously. if (_state == STATE_ACTIVE) { internalDelete(persistable); } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "No work attempted as an exception has already been thrown during this batch!"); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "delete"); } private void internalDelete(Persistable persistable) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "internalDelete", "Persistable="+persistable); PersistableImpl thePersistable = (PersistableImpl)persistable; // Deletion of an item try { _startTransaction(); thePersistable.removeFromStore(_tran); } catch (LogFileFullException lffe) { com.ibm.ws.ffdc.FFDCFilter.processException(lffe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.internalDelete", "1:557:1.18", this); SibTr.error(tc, "FILE_STORE_LOG_FULL_SIMS1573E"); _deferredException = new PersistenceFullException("FILE_STORE_LOG_FULL_SIMS1573E", lffe); } catch (ObjectStoreFullException osfe) { com.ibm.ws.ffdc.FFDCFilter.processException(osfe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.internalDelete", "1:563:1.18", this); if (_objectStore.getStoreStrategy() == ObjectStore.STRATEGY_KEEP_ALWAYS) { SibTr.error(tc, "FILE_STORE_PERMANENT_STORE_FULL_SIMS1574E"); _deferredException = new PersistenceFullException("FILE_STORE_PERMANENT_STORE_FULL_SIMS1574E", osfe); } else { SibTr.error(tc, "FILE_STORE_TEMPORARY_STORE_FULL_SIMS1575E"); _deferredException = new PersistenceFullException("FILE_STORE_TEMPORARY_STORE_FULL_SIMS1575E", osfe); } } catch (ObjectManagerException ome) { com.ibm.ws.ffdc.FFDCFilter.processException(ome, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.internalDelete", "1:577:1.18", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Exception caught deleting from object store!", ome); _deferredException = new PersistenceException("Exception caught deleting from object store: "+ome.getMessage(), ome); } catch (PersistenceException pe) { com.ibm.ws.ffdc.FFDCFilter.processException(pe, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.internalDelete", "1:583:1.18", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Persistence exception caught deleting from object store!", pe); _deferredException = pe; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "internalDelete"); } public void addIndoubtXID(PersistentTranId xid) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "addIndoubtXID", "XID="+xid); if (_deferredException == null) { // We are going indoubt which basically translates // to preparing the object manager transaction so // we can just update our state here and carry out // the proper action at executeBatch() time. if (_state == STATE_ACTIVE) { _state = STATE_PREPARING; } else { _deferredException = new PersistenceException("Cannot PREPARE batch as it not in the correct state! State="+_stateToString[_state]); } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "No work attempted as an exception has already been thrown during this batch!"); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "addIndoubtXID"); } /** * In the OM implementation this method is used to flag the batching * context so that upon the next call to executeBatch the OM transaction * being used is committed. * * @param xid */ public void updateXIDToCommitted(PersistentTranId xid) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "updateXIDToCommitted", "XID="+xid); if (_deferredException == null) { // We are committing a transaction. The transaction can // be either one-phase or two-phase so we need to check // our state and then update it so that commit is called // at executeBatch() time. if (_state == STATE_ACTIVE || _state == STATE_PREPARED) { _state = STATE_COMMITTING; } else { _deferredException = new PersistenceException("Cannot COMMIT batch as it not in the correct state! State="+_stateToString[_state]); } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "No work attempted as an exception has already been thrown during this batch!"); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateXIDToCommitted"); } /** * In the OM implementation this method is used to flag the batching * context so that upon the next call to executeBatch the OM transaction * being used is rolled back. This call is only valid after an * addIndoubtXid/executeBatch pair have been called i.e. a prepare * has occurred. * * @param xid */ public void updateXIDToRolledback(PersistentTranId xid) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "updateXIDToRolledback", "XID="+xid); if (_deferredException == null) { // We are rolling back a transaction. This should only be // applied to prepared transactions as single-phase rollbacks // should not get as far as the persistence layer. if (_state == STATE_PREPARED) { _state = STATE_ROLLINGBACK; } else { _deferredException = new PersistenceException("Cannot ROLLBACK batch as it not in the correct state! State="+_stateToString[_state]); } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "No work attempted as an exception has already been thrown during this batch!"); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateXIDToRolledback"); } public void executeBatch() throws PersistenceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "executeBatch"); // If we have a deferred exception, throw it now if (_deferredException != null) { // If we have an existing OM tran then we need // to roll it back before we throw any exception. if (_tran != null) { try { Transaction t = _tran; _xid = null; _tran = null; t.backout(false); _state = STATE_ROLLEDBACK; } catch (ObjectManagerException ome) { com.ibm.ws.ffdc.FFDCFilter.processException(ome, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.executeBatch", "1:714:1.18", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Unexpected exception caught cleaning up transaction!", ome); // Don't throw here as we are going to throw a deferred // exception anyway and that may have more information // about the root cause of our problems. } } PersistenceException e = _deferredException; _deferredException = null; if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Deferred exception being thrown during executeBatch!", e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "executeBatch"); throw e; } // Complete the work in this batch. Dependant // upon the state of this batch object we have // to choose to prepare, commit or rollback // the object manager transaction. try { if (_tran != null) { Transaction t = _tran; switch (_state) { case STATE_PREPARING: if (t.getXID() == null) { PersistenceException pe = new PersistenceException("No XID associated at prepare time!"); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "No XID associated at prepare time!"); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "executeBatch"); throw pe; } t.prepare(); _state = STATE_PREPARED; break; case STATE_ACTIVE: // Spill 1PC case STATE_COMMITTING: _xid = null; _tran = null; t.commit(false); _state = STATE_COMMITTED; break; case STATE_ROLLINGBACK: _xid = null; _tran = null; t.backout(false); _state = STATE_ROLLEDBACK; break; default: PersistenceException pe = new PersistenceException("BatchingContext not in correct state to executeUpdate! State="+_stateToString[_state]); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "BatchingContext not in correct state to executeUpdate! State="+_stateToString[_state]); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "executeBatch"); throw pe; } } } catch (ObjectManagerException ome) { com.ibm.ws.ffdc.FFDCFilter.processException(ome, "com.ibm.ws.sib.msgstore.persistence.objectManager.BatchingContextImpl.executeBatch", "1:775:1.18", this); PersistenceException pe = new PersistenceException("Unexpected exception caught completing transaction: "+ome.getMessage(), ome); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(tc, "Exception caught completing transaction!", ome); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "executeBatch"); throw pe; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "executeBatch"); } public void clear() { // We are probably going to be re-used so we need // to reset all of our current state variables. _state = STATE_ACTIVE; _deferredException = null; } private void _startTransaction() throws ObjectManagerException { if (_tran == null) { _tran = _objectManager.getTransaction(); } } public void setCapacity(int capacity) { _capacity = capacity; } public int getCapacity() { return _capacity; } public void updateTickValueOnly(Persistable persistable) {/* NO-OP within file store implementation.*/} public void deleteXID(PersistentTranId xid) {/* NO-OP within file store implementation.*/} public void setUseEnlistedConnections(boolean useEnlistedConnections) {/* NO-OP within file store implementation.*/} }
epl-1.0
unverbraucht/kura
kura/org.eclipse.kura.api/src/main/java/org/eclipse/kura/net/NetRouterMode.java
819
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.net; /** * Used to specify the route mode of each interface. * * @author eurotech * */ public enum NetRouterMode { /** DHCP and NAT **/ netRouterDchpNat, /** DHCP only **/ netRouterDchp, /** NAT only **/ netRouterNat, /** OFF **/ netRouterOff; }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxws.common/src/com/ibm/ws/jaxws/client/JaxWsHandlerChainInstanceInterceptor.java
3090
/******************************************************************************* * Copyright (c) 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.jaxws.client; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.ws.handler.Handler; import org.apache.cxf.Bus; import org.apache.cxf.common.injection.ResourceInjector; import org.apache.cxf.jaxws.handler.InitParamResourceResolver; import org.apache.cxf.resource.ResourceManager; import org.apache.cxf.resource.ResourceResolver; import com.ibm.ws.jaxws.metadata.HandlerInfo; import com.ibm.ws.jaxws.metadata.ParamValueInfo; import com.ibm.ws.jaxws.support.JaxWsInstanceManager.InstanceInterceptor; import com.ibm.ws.jaxws.support.JaxWsInstanceManager.InterceptException; import com.ibm.ws.jaxws.support.JaxWsInstanceManager.InterceptorContext; /** * */ public class JaxWsHandlerChainInstanceInterceptor implements InstanceInterceptor { private final Bus bus; private final HandlerInfo handlerInfo; public JaxWsHandlerChainInstanceInterceptor(Bus bus, HandlerInfo handlerInfo) { this.bus = bus; this.handlerInfo = handlerInfo; } @Override public void postNewInstance(InterceptorContext ctx) throws InterceptException { configureHandler((Handler<?>) ctx.getInstance()); } @Override public void postInjectInstance(InterceptorContext ctx) { } @Override public void preDestroyInstance(InterceptorContext ctx) throws InterceptException { } private void configureHandler(Handler<?> handler) { if (handlerInfo.getInitParam().size() == 0) { return; } Map<String, String> params = new HashMap<String, String>(); for (ParamValueInfo param : handlerInfo.getInitParam()) { params.put(trimString(param.getParamName() == null ? null : param.getParamName()), trimString(param.getParamValue() == null ? null : param.getParamValue())); } initializeViaInjection(handler, params); } private void initializeViaInjection(Handler<?> handler, final Map<String, String> params) { if (bus != null) { ResourceManager resMgr = bus.getExtension(ResourceManager.class); List<ResourceResolver> resolvers = new ArrayList<ResourceResolver>(resMgr.getResourceResolvers()); resolvers.add(new InitParamResourceResolver(params)); ResourceInjector resInj = new ResourceInjector(resMgr, resolvers); resInj.inject(handler); } } private String trimString(String str) { return str != null ? str.trim() : null; } }
epl-1.0
paulianttila/openhab2
bundles/org.openhab.binding.telegram/src/main/java/org/openhab/binding/telegram/internal/TelegramBindingConstants.java
1672
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.telegram.internal; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.core.thing.ThingTypeUID; /** * The {@link TelegramBindingConstants} class defines common constants, which are * used across the whole binding. * * @author Jens Runge - Initial contribution */ @NonNullByDefault public class TelegramBindingConstants { private static final String BINDING_ID = "telegram"; public static final Set<String> PHOTO_EXTENSIONS = Set.of(".jpg", ".jpeg", ".png", ".gif", ".jpe", ".jif", ".jfif", ".jfi", ".webp"); // List of all Thing Type UIDs public static final ThingTypeUID TELEGRAM_THING = new ThingTypeUID(BINDING_ID, "telegramBot"); // List of all Channel ids public static final String LASTMESSAGETEXT = "lastMessageText"; public static final String LASTMESSAGEURL = "lastMessageURL"; public static final String LASTMESSAGEDATE = "lastMessageDate"; public static final String LASTMESSAGENAME = "lastMessageName"; public static final String LASTMESSAGEUSERNAME = "lastMessageUsername"; public static final String CHATID = "chatId"; public static final String REPLYID = "replyId"; public static final String LONGPOLLINGTIME = "longPollingTime"; }
epl-1.0
bartlomiej-laczkowski/che
ide/commons-gwt/src/main/java/org/eclipse/che/ide/websocket/impl/WebSocketConnectionManager.java
4238
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.websocket.impl; import com.google.inject.Inject; import org.eclipse.che.ide.util.loging.Log; import javax.inject.Singleton; import java.util.HashMap; import java.util.Map; /** * Manages all connection related high level processes. Acts as a facade to low level web socket * components. * * @author Dmitry Kuleshov */ @Singleton public class WebSocketConnectionManager { private final WebSocketFactory webSocketFactory; private final Map<String, WebSocketConnection> connectionsRegistry = new HashMap<>(); @Inject public WebSocketConnectionManager(WebSocketFactory webSocketFactory) { this.webSocketFactory = webSocketFactory; } /** * Initialize a connection. Performs all necessary preparations except for properties management. Must be called before * any interactions with a web socket connection. * * @param url * url of a web socket connection that is to be initialized */ public void initializeConnection(String url) { connectionsRegistry.put(url, webSocketFactory.create(url)); } /** * Establishes a web socket connection to an endpoint defined by a URL parameter * * @param url * url of a web socket connection that is to be established */ public void establishConnection(String url) { final WebSocketConnection webSocketConnection = connectionsRegistry.get(url); if (webSocketConnection == null) { final String error = "No connection with url: " + url + "is initialized. Run 'initializedConnection' first."; Log.error(getClass(), error); throw new IllegalStateException(error); } webSocketConnection.open(); Log.debug(getClass(), "Opening connection. Url: " + url); } /** * Close a web socket connection to an endpoint defined by a URL parameter * * @param url * url of a connection to be closed */ public void closeConnection(String url) { final WebSocketConnection webSocketConnection = connectionsRegistry.get(url); if (webSocketConnection == null) { final String warning = "Closing connection that is not registered and seem like does not exist"; Log.warn(getClass(), warning); throw new IllegalStateException(warning); } webSocketConnection.close(); Log.debug(WebSocketConnectionManager.class, "Closing connection."); } /** * Sends a message to a specified endpoint over web socket connection. * * @param url * url of an endpoint the message is adressed to * @param message * plain text message */ public void sendMessage(String url, String message) { final WebSocketConnection webSocketConnection = connectionsRegistry.get(url); if (webSocketConnection == null) { final String error = "No connection with url: " + url + "is initialized. Run 'initializedConnection' first."; Log.error(getClass(), error); throw new IllegalStateException(error); } webSocketConnection.send(message); Log.debug(getClass(), "Sending message: " + message); } /** * Checks if a connection is opened at the moment * * @param url * url of a web socket connection to be checked * * @return connection status: true if opened, false if else */ public boolean isConnectionOpen(String url) { final WebSocketConnection webSocketConnection = connectionsRegistry.get(url); return webSocketConnection != null && webSocketConnection.isOpen(); } }
epl-1.0
jhon0010/sirius-blog
tree-layout/fr.obeo.dsl.houseofcard.metamodel/src/houseofcards/util/HouseofcardsSwitch.java
3891
/** */ package houseofcards.util; import houseofcards.*; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see houseofcards.HouseofcardsPackage * @generated */ public class HouseofcardsSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static HouseofcardsPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public HouseofcardsSwitch() { if (modelPackage == null) { modelPackage = HouseofcardsPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @parameter ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case HouseofcardsPackage.HOUSE: { House house = (House)theEObject; T result = caseHouse(house); if (result == null) result = defaultCase(theEObject); return result; } case HouseofcardsPackage.PERSON: { Person person = (Person)theEObject; T result = casePerson(person); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>House</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>House</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseHouse(House object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Person</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Person</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casePerson(Person object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //HouseofcardsSwitch
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.jca_fat/test-resourceadapters/adapter.regr/src/com/ibm/adapter/FVTAdapterVerifyImpl.java
1922
/******************************************************************************* * Copyright (c) 2004, 2020 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.adapter; public class FVTAdapterVerifyImpl { static String adapterName; static String propertyD; static String propertyW; static String propertyX; static String propertyI; /** * @return */ public static String getAdapterName() { return adapterName; } /** * @return */ public static String getPropertyD() { return propertyD; } /** * @return */ public static String getPropertyI() { return propertyI; } /** * @return */ public static String getPropertyW() { return propertyW; } /** * @return */ public static String getPropertyX() { return propertyX; } /** * @param string */ public static void setAdapterName(String string) { adapterName = string; } /** * @param string */ public static void setPropertyD(String string) { propertyD = string; } /** * @param string */ public static void setPropertyI(String string) { propertyI = string; } /** * @param string */ public static void setPropertyW(String string) { propertyW = string; } /** * @param string */ public static void setPropertyX(String string) { propertyX = string; } }
epl-1.0
eclipse/hawkbit
hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java
4314
/** * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.hawkbit.repository.jpa.rsql; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields; import org.eclipse.hawkbit.repository.builder.SoftwareModuleMetadataCreate; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.test.util.TestdataFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import com.google.common.collect.Lists; import io.qameta.allure.Description; import io.qameta.allure.Feature; import io.qameta.allure.Story; @Feature("Component Tests - Repository") @Story("RSQL filter software module metadata") public class RSQLSoftwareModuleMetadataFieldsTest extends AbstractJpaIntegrationTest { private Long softwareModuleId; @BeforeEach public void setupBeforeTest() { final SoftwareModule softwareModule = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_APP); softwareModuleId = softwareModule.getId(); final List<SoftwareModuleMetadataCreate> metadata = Lists.newArrayListWithExpectedSize(5); for (int i = 0; i < 5; i++) { metadata.add( entityFactory.softwareModuleMetadata().create(softwareModule.getId()).key("" + i).value("" + i)); } metadata.add(entityFactory.softwareModuleMetadata().create(softwareModule.getId()).key("targetVisible") .value("targetVisible").targetVisible(true)); metadata.add(entityFactory.softwareModuleMetadata().create(softwareModule.getId()).key("emptyMd") .targetVisible(true)); softwareModuleManagement.createMetaData(metadata); } @Test @Description("Test filter software module metadata by key") public void testFilterByParameterKey() { assertRSQLQuery(SoftwareModuleMetadataFields.KEY.name() + "==1", 1); assertRSQLQuery(SoftwareModuleMetadataFields.KEY.name() + "!=1", 6); assertRSQLQuery(SoftwareModuleMetadataFields.KEY.name() + "=in=(1,2)", 2); assertRSQLQuery(SoftwareModuleMetadataFields.KEY.name() + "=out=(1,2)", 5); } @Test @Description("Test fitler software module metadata by value") public void testFilterByParameterValue() { assertRSQLQuery(SoftwareModuleMetadataFields.VALUE.name() + "==''", 1); assertRSQLQuery(SoftwareModuleMetadataFields.VALUE.name() + "!=''", 6); assertRSQLQuery(SoftwareModuleMetadataFields.VALUE.name() + "==1", 1); assertRSQLQuery(SoftwareModuleMetadataFields.VALUE.name() + "!=1", 6); assertRSQLQuery(SoftwareModuleMetadataFields.VALUE.name() + "=in=(1,2)", 2); assertRSQLQuery(SoftwareModuleMetadataFields.VALUE.name() + "=out=(1,2)", 5); } @Test @Description("Test fitler software module metadata by target visible") public void testFilterByParameterTargetVisible() { assertRSQLQuery(SoftwareModuleMetadataFields.TARGETVISIBLE.name() + "==true", 2); assertRSQLQuery(SoftwareModuleMetadataFields.TARGETVISIBLE.name() + "==false", 5); assertRSQLQuery(SoftwareModuleMetadataFields.TARGETVISIBLE.name() + "!=false", 2); assertRSQLQuery(SoftwareModuleMetadataFields.TARGETVISIBLE.name() + "!=true", 5); } private void assertRSQLQuery(final String rsqlParam, final long expectedEntities) { final Page<SoftwareModuleMetadata> findEnitity = softwareModuleManagement .findMetaDataByRsql(PageRequest.of(0, 100), softwareModuleId, rsqlParam); final long countAllEntities = findEnitity.getTotalElements(); assertThat(findEnitity).isNotNull(); assertThat(countAllEntities).isEqualTo(expectedEntities); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/servletcoexist3/src/com/ibm/ws/jaxrs/fat/servletcoexist4/DemoApplication.java
1138
/******************************************************************************* * Copyright (c) 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.jaxrs.fat.servletcoexist4; import java.util.HashSet; import java.util.Set; import javax.ws.rs.ApplicationPath; @ApplicationPath("/servletcoexist4") public class DemoApplication extends javax.ws.rs.core.Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<Class<?>>(); classes.add(UserRestService4.class); return classes; } @Override public Set<Object> getSingletons() { Set<Object> objs = new HashSet<Object>(); objs.add(new GroupRestService4()); return objs; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.wsat.concurrent_fat/test-applications/threadedClient/src/com/ibm/ws/wsat/threadedclient/client/threaded/MultiThreaded.java
2078
/******************************************************************************* * Copyright (c) 2019, 2020 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.wsat.threadedclient.client.threaded; import javax.jws.WebMethod; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; @WebService(name = "MultiThreaded", targetNamespace = "http://server.threadedserver.wsat.ws.ibm.com/") @XmlSeeAlso({ ObjectFactory.class }) public interface MultiThreaded { /** * * @return * returns java.lang.String */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "invoke", targetNamespace = "http://server.threadedserver.wsat.ws.ibm.com/", className = "com.ibm.ws.wsat.threadedclient.client.threaded.Invoke") @ResponseWrapper(localName = "invokeResponse", targetNamespace = "http://server.threadedserver.wsat.ws.ibm.com/", className = "com.ibm.ws.wsat.threadedclient.client.threaded.InvokeResponse") public String invoke(); /** * * @return * returns boolean */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "clearXAResource", targetNamespace = "http://server.threadedserver.wsat.ws.ibm.com/", className = "com.ibm.ws.wsat.threadedclient.client.threaded.ClearXAResource") @ResponseWrapper(localName = "clearXAResourceResponse", targetNamespace = "http://server.threadedserver.wsat.ws.ibm.com/", className = "com.ibm.ws.wsat.threadedclient.client.threaded.ClearXAResourceResponse") public boolean clearXAResource(); }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.microprofile.metrics.2.3/src/com/ibm/ws/microprofile/metrics23/impl/package-info.java
803
/******************************************************************************* * Copyright (c) 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ /** * */ @org.osgi.annotation.versioning.Version("1.0") @TraceOptions(traceGroup = "METRICS", messageBundle = "com.ibm.ws.microprofile.metrics.resources.Metrics") package com.ibm.ws.microprofile.metrics23.impl; import com.ibm.websphere.ras.annotation.TraceOptions;
epl-1.0
kevinott/crypto
org.jcryptool.analysis.substitution/src/org/jcryptool/analysis/substitution/ui/modules/utils/StatisticsSelector.java
13761
package org.jcryptool.analysis.substitution.ui.modules.utils; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Observable; import java.util.Observer; import java.util.Set; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.jcryptool.analysis.substitution.Activator; import org.jcryptool.analysis.substitution.calc.DynamicPredefinedStatisticsProvider; import org.jcryptool.analysis.substitution.calc.TextStatistic; import org.jcryptool.analysis.substitution.ui.modules.Messages; import org.jcryptool.analysis.substitution.ui.modules.SubstitutionAnalysisConfigPanel; import org.jcryptool.core.operations.algorithm.classic.textmodify.TransformData; import org.jcryptool.core.operations.alphabets.AbstractAlphabet; import org.jcryptool.core.operations.alphabets.AlphabetsManager; import org.jcryptool.crypto.ui.textloader.ui.ControlHatcher; import org.jcryptool.crypto.ui.textloader.ui.wizard.TextLoadController; import org.jcryptool.crypto.ui.textsource.TextInputWithSource; import org.jcryptool.crypto.ui.util.NestedEnableDisableSwitcher; public class StatisticsSelector extends Composite { private static final String NOCONTENT_COMBO_STRING = Messages.StatisticsSelector_0; private AbstractAlphabet alpha; private List<Observer> observers; private Composite layoutRoot; private TextLoadController referenceTextSelector; private TextStatistic analyzedReferenceText; private boolean isPredefinedStatistic; private TextStatistic selectedStatistic; private Combo comboPredefined; private LinkedList<TextStatistic> predefinedStatistics; private Button btnCustom; private Button btnPredefined; private NestedEnableDisableSwitcher customControlsEnabler; private NestedEnableDisableSwitcher predefinedControlsEnabler; /** * Create the composite. * @param parent * @param style */ public StatisticsSelector(Composite parent, Composite layoutRoot, int style) { super(parent, style); this.layoutRoot = layoutRoot; this.observers = new LinkedList<Observer>(); this.alpha = getDefaultAlphabetInitialization(); setLayout(new GridLayout(2, false)); btnPredefined = new Button(this, SWT.RADIO); btnPredefined.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if(btnPredefined.getSelection()) { setPredefinedControlsEnabled(true); setPredefinedStatistics(comboPredefined.getSelectionIndex(), true); } } }); btnPredefined.setText(Messages.StatisticsSelector_1); comboPredefined = new Combo(this, SWT.NONE); GridData comboLData = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); comboPredefined.setText(NOCONTENT_COMBO_STRING); comboLData.widthHint = comboPredefined.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; comboPredefined.setLayoutData(comboLData); comboPredefined.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if(btnPredefined.getSelection()) { setPredefinedStatistics(comboPredefined.getSelectionIndex(), true); } } }); btnCustom = new Button(this, SWT.RADIO); btnCustom.setText(Messages.StatisticsSelector_2); btnCustom.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if(btnCustom.getSelection()) { setCustomControlsEnabled(true); setCustomStatistics(analyzedReferenceText, referenceTextSelector.getText(), referenceTextSelector.getTransformData(), true); } } }); referenceTextSelector = new TextLoadController(this, layoutRoot, SWT.NONE, false, true); referenceTextSelector.setControlHatcherAfterWizText(new ControlHatcher.LabelHatcher( SubstitutionAnalysisConfigPanel.TEXTTRANSFORM_HINT+"\n\n"+ //$NON-NLS-1$ Messages.StatisticsSelector_4 + Messages.StatisticsSelector_5 )); referenceTextSelector.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, true, false)); referenceTextSelector.addObserver(new Observer() { @Override public void update(Observable o, Object arg) { TextInputWithSource text = referenceTextSelector.getText(); if(text != null) { TextStatistic newCustomStatistic = analyzeCustomText(text, referenceTextSelector.getTransformData()); setCustomStatistics(newCustomStatistic, text, referenceTextSelector.getTransformData(), true); } } }); customControlsEnabler = new NestedEnableDisableSwitcher(referenceTextSelector); customControlsEnabler.alwaysRefresh = true; predefinedControlsEnabler = new NestedEnableDisableSwitcher(comboPredefined); predefinedControlsEnabler.alwaysRefresh = true; setInitialState(); } private void setInitialState() { initializePredefinedStatistics(getAlphabet()); if(this.predefinedStatistics.size() != 0) { setPredefinedStatistics(0, false); } else { setCustomStatistics(null, null, null, false); } } public void addObserver(Observer o) { this.observers.add(o); } protected TextStatistic analyzeCustomText(TextInputWithSource text, TransformData transformData) { // TODO maybe show progress? // TODO: write identification information (origin e.g.) // TODO: maybe saving of statistics? // TODO: hint, that the statistics will be filtered by the selected alphabet String textToAnalyze; textToAnalyze = text.getText(); textToAnalyze = prepareCustomTextForAnalysis(transformData, textToAnalyze); return new TextStatistic(textToAnalyze); } private String prepareCustomTextForAnalysis(TransformData selectedTransformData, String textToAnalyze) { return DynamicPredefinedStatisticsProvider.prepareFileTextForAnalysis(textToAnalyze, selectedTransformData, getAlphabet()); } private void initializePredefinedStatistics(AbstractAlphabet alphabet) { PredefinedStatisticsProvider statisticsProvider = getDefaultStatisticsProvider(); List<TextStatistic> statistics = getSuitableStatistics(alphabet, statisticsProvider); setPredefinedStatisticsNoRefresh(statistics); } private void reinitializePredefinedStatistics(AbstractAlphabet oldAlpha, AbstractAlphabet newAlpha, TextStatistic previousSelection, boolean previousSelectionWasPredefined ) { PredefinedStatisticsProvider statisticsProvider = getDefaultStatisticsProvider(); List<TextStatistic> statistics = getSuitableStatistics(newAlpha, statisticsProvider); TextStatistic newSelection = null; boolean newSelectionIsPredefined = previousSelectionWasPredefined; boolean prevExistsInNewPredefined = statistics.contains(previousSelection); if(previousSelectionWasPredefined) { if(statistics.size()==0) { newSelectionIsPredefined = false; newSelection = analyzedReferenceText; } else { if(prevExistsInNewPredefined) { newSelectionIsPredefined = true; newSelection = previousSelection; } else { newSelection = statistics.get(0); newSelectionIsPredefined = true; } } } else { if(previousSelection != null) { TextInputWithSource previousSource = referenceTextSelector.getText(); TransformData previousTransformData = referenceTextSelector.getTransformData(); //re-analyze with new alphabet newSelection = analyzeCustomText(previousSource, previousTransformData); newSelectionIsPredefined = false; } else { newSelection = null; newSelectionIsPredefined = false; } } setPredefinedStatisticsNoRefresh(statistics); if(newSelectionIsPredefined) { setPredefinedStatistics(statistics.indexOf(newSelection), true); } else { setCustomStatistics(newSelection, referenceTextSelector.getText(), referenceTextSelector.getTransformData(), true); } } private void setPredefinedStatisticsNoRefresh(List<TextStatistic> statistics) { this.predefinedStatistics = new LinkedList<TextStatistic>(statistics); this.comboPredefined.setItems(new String[]{}); setPredefinedSectionEnabled(statistics.size()>0); if(statistics.size()>0) { for (int i = 0; i < statistics.size(); i++) { TextStatistic s = statistics.get(i); comboPredefined.add(generateComboStringItemFor(s, i)); } } } public void setCustomStatistics(TextStatistic selectedCustomStatistics, TextInputWithSource source, TransformData transformData, boolean notifyObservers) { //TODO: transform text this.selectedStatistic = selectedCustomStatistics; if(selectedCustomStatistics != null) { analyzedReferenceText = selectedCustomStatistics; if(referenceTextSelector.getText() != source || referenceTextSelector.getTransformData() != transformData) { referenceTextSelector.setTextData(source, transformData, false); } } else { analyzedReferenceText = null; referenceTextSelector.setTextData(null, null, false); } if(!btnCustom.getSelection()) { btnCustom.setSelection(true); } btnPredefined.setSelection(false); this.isPredefinedStatistic = false; setPredefinedControlsEnabled(false); setCustomControlsEnabled(true); if(notifyObservers) notifyObservers(); } public void setPredefinedStatistics(TextStatistic statistic, boolean notifyObservers) { int index = predefinedStatistics.indexOf(statistic); if(index > -1) { setPredefinedStatistics(index, notifyObservers); } else { setCustomStatistics(null, null, null, notifyObservers); } } public void setPredefinedStatistics(int indexOfPredefinedStatistic, boolean notifyObservers) { if(indexOfPredefinedStatistic > -1) { this.selectedStatistic = predefinedStatistics.get(indexOfPredefinedStatistic); if(! (comboPredefined.getSelectionIndex() == indexOfPredefinedStatistic)) { comboPredefined.select(indexOfPredefinedStatistic); } } else { this.selectedStatistic = null; comboPredefined.select(-1); } if(!btnPredefined.getSelection()) { btnPredefined.setSelection(true); } btnCustom.setSelection(false); this.isPredefinedStatistic = true; setCustomControlsEnabled(false); setPredefinedControlsEnabled(true); if(notifyObservers) notifyObservers(); } private void setCustomControlsEnabled(boolean b) { customControlsEnabler.setEnabled(b); } private void setPredefinedControlsEnabled(boolean b) { predefinedControlsEnabler.setEnabled(b); } private String generateComboStringItemFor(TextStatistic s, int i) { return String.format(Messages.StatisticsSelector_6, s.getLanguage(), s.getName()); } private void setPredefinedSectionEnabled(boolean b) { //TODO: set flags for whole component enabling/disabling predefinedControlsEnabler.setEnabled(b); btnPredefined.setEnabled(b); if(!b) { comboPredefined.setText(NOCONTENT_COMBO_STRING); } else { comboPredefined.setText(""); //$NON-NLS-1$ } } private static List<Character> alphaContentAsList(AbstractAlphabet alpha) { LinkedList<Character> result = new LinkedList<Character>(); for(char c: alpha.getCharacterSet()) result.add(c); return result; } public static List<TextStatistic> getSuitableStatistics(AbstractAlphabet newAlpha, PredefinedStatisticsProvider statisticsProvider) { List<TextStatistic> suitableStatistics = new LinkedList<TextStatistic>(); List<TextStatistic> allStatistics = statisticsProvider.getPredefinedStatistics(); Set<String> names = new LinkedHashSet<String>(); LinkedHashMap<TextStatistic, Double> scoreMap = new LinkedHashMap<TextStatistic, Double>(); for(TextStatistic statistic: allStatistics) { double score = TextStatistic.compareTwoAlphabets(alphaContentAsList(newAlpha), statistic.getTextCharacters()); scoreMap.put(statistic, score); names.add(statistic.getName()); } for(String name: names) { Double maxVal = Double.MIN_VALUE; TextStatistic best = null; for(Entry<TextStatistic, Double> entry: scoreMap.entrySet()) { if(entry.getKey().getName().equals(name) && entry.getValue()>maxVal) { best = entry.getKey(); maxVal = entry.getValue(); } } if(best != null) { suitableStatistics.add(best); } } return suitableStatistics; } private void notifyObservers() { for(Observer o: this.observers) { o.update(null, null); } } private static List<TextStatistic> myStats; static{ myStats = new LinkedList<TextStatistic>(); myStats.add(TextStatistic.getDummyStatistic()); myStats.add(new TextStatistic("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")); //$NON-NLS-1$ myStats.add(new TextStatistic("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ")); //$NON-NLS-1$ } private PredefinedStatisticsProvider getDefaultStatisticsProvider() { return Activator.getPredefinedStatisticsProvider(); } private AbstractAlphabet getDefaultAlphabetInitialization() { return AlphabetsManager.getInstance().getDefaultAlphabet(); } public void setAlphabet(AbstractAlphabet newAlpha) { AbstractAlphabet oldAlpha = getAlphabet(); this.alpha = newAlpha; reinitializePredefinedStatistics(oldAlpha, newAlpha, getSelectedStatistic(), isPredefinedStatistic()); } public AbstractAlphabet getAlphabet() { return alpha; } public boolean isPredefinedStatistic() { return this.isPredefinedStatistic; } public TextStatistic getSelectedStatistic() { return this.selectedStatistic; } @Override protected void checkSubclass() { // Disable the check that prevents subclassing of SWT components } public boolean hasPredefinedStatistics() { return !predefinedStatistics.isEmpty(); } }
epl-1.0
khatchad/Migrate-Skeletal-Implementation-to-Interface-Refactoring
edu.cuny.citytech.defaultrefactoring.tests/resources/MigrateSkeletalImplementationToInterface/testMethodContainedInTypeWithTypeParameters2/out/A.java
103
package p; interface I { default void m() { E e = null; } } abstract class A<E> implements I { }
epl-1.0
kgibm/open-liberty
dev/com.ibm.ws.wssecurity_fat.wsscxf.1/fat/src/test/libertyfat/x509mig/contract/FatBAX11Service.java
2879
/******************************************************************************* * Copyright (c) 2020 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package test.libertyfat.x509mig.contract; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceFeature; /** * This class was generated by Apache CXF 2.6.2 * 2012-12-19T14:55:09.165-06:00 * Generated source version: 2.6.2 * */ @WebServiceClient(name = "FatBAX11Service", wsdlLocation = "x509migtoken.wsdl", targetNamespace = "http://x509mig.libertyfat.test/contract") public class FatBAX11Service extends Service { public final static URL WSDL_LOCATION; public final static QName SERVICE = new QName("http://x509mig.libertyfat.test/contract", "FatBAX11Service"); public final static QName UrnX509Token11 = new QName("http://x509mig.libertyfat.test/contract", "UrnX509Token11"); static { URL url = FatBAX11Service.class.getResource("x509migtoken.wsdl"); if (url == null) { java.util.logging.Logger.getLogger(FatBAX11Service.class.getName()).log(java.util.logging.Level.INFO, "Can not initialize the default wsdl from {0}", "x509migtoken.wsdl"); } WSDL_LOCATION = url; } public FatBAX11Service(URL wsdlLocation) { super(wsdlLocation, SERVICE); } public FatBAX11Service(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } public FatBAX11Service() { super(WSDL_LOCATION, SERVICE); } /** * * @return * returns FVTVersionBAX */ @WebEndpoint(name = "UrnX509Token11") public FVTVersionBAX getUrnX509Token11() { return super.getPort(UrnX509Token11, FVTVersionBAX.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their * default values. * @return * returns FVTVersionBAX */ @WebEndpoint(name = "UrnX509Token11") public FVTVersionBAX getUrnX509Token11(WebServiceFeature... features) { return super.getPort(UrnX509Token11, FVTVersionBAX.class, features); } }
epl-1.0
eclipse/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupGrid.java
9616
/** * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.hawkbit.ui.rollout.rolloutgroup; import java.util.Collection; import java.util.Optional; import org.eclipse.hawkbit.repository.RolloutGroupManagement; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupStatus; import org.eclipse.hawkbit.ui.common.CommonUiDependencies; import org.eclipse.hawkbit.ui.common.builder.GridComponentBuilder; import org.eclipse.hawkbit.ui.common.builder.StatusIconBuilder.RolloutGroupStatusIconSupplier; import org.eclipse.hawkbit.ui.common.data.mappers.RolloutGroupToProxyRolloutGroupMapper; import org.eclipse.hawkbit.ui.common.data.providers.RolloutGroupDataProvider; import org.eclipse.hawkbit.ui.common.data.proxies.ProxyRollout; import org.eclipse.hawkbit.ui.common.data.proxies.ProxyRolloutGroup; import org.eclipse.hawkbit.ui.common.event.CommandTopics; import org.eclipse.hawkbit.ui.common.event.EventLayout; import org.eclipse.hawkbit.ui.common.event.EventView; import org.eclipse.hawkbit.ui.common.event.FilterType; import org.eclipse.hawkbit.ui.common.event.LayoutVisibilityEventPayload; import org.eclipse.hawkbit.ui.common.event.LayoutVisibilityEventPayload.VisibilityType; import org.eclipse.hawkbit.ui.common.event.SelectionChangedEventPayload.SelectionChangedEventType; import org.eclipse.hawkbit.ui.common.grid.AbstractGrid; import org.eclipse.hawkbit.ui.common.grid.support.FilterSupport; import org.eclipse.hawkbit.ui.common.grid.support.MasterEntitySupport; import org.eclipse.hawkbit.ui.common.grid.support.SelectionSupport; import org.eclipse.hawkbit.ui.rollout.DistributionBarHelper; import org.eclipse.hawkbit.ui.rollout.RolloutManagementUIState; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider; import com.google.common.base.Predicates; import com.vaadin.shared.ui.ContentMode; import com.vaadin.ui.Button; import com.vaadin.ui.renderers.HtmlRenderer; /** * Rollout group list grid component. */ public class RolloutGroupGrid extends AbstractGrid<ProxyRolloutGroup, Long> { private static final long serialVersionUID = 1L; private static final String ROLLOUT_GROUP_LINK_ID = "rolloutGroup"; private final RolloutManagementUIState rolloutManagementUIState; private final transient RolloutGroupManagement rolloutGroupManagement; private final transient RolloutGroupToProxyRolloutGroupMapper rolloutGroupMapper; private final RolloutGroupStatusIconSupplier<ProxyRolloutGroup> rolloutGroupStatusIconSupplier; private final transient MasterEntitySupport<ProxyRollout> masterEntitySupport; RolloutGroupGrid(final CommonUiDependencies uiDependencies, final RolloutGroupManagement rolloutGroupManagement, final RolloutManagementUIState rolloutManagementUIState) { super(uiDependencies.getI18n(), uiDependencies.getEventBus(), uiDependencies.getPermChecker()); this.rolloutManagementUIState = rolloutManagementUIState; this.rolloutGroupManagement = rolloutGroupManagement; this.rolloutGroupMapper = new RolloutGroupToProxyRolloutGroupMapper(); setSelectionSupport(new SelectionSupport<>(this, eventBus, EventLayout.ROLLOUT_GROUP_LIST, EventView.ROLLOUT, this::mapIdToProxyEntity, this::getSelectedEntityIdFromUiState, this::setSelectedEntityIdToUiState)); getSelectionSupport().disableSelection(); setFilterSupport(new FilterSupport<>(new RolloutGroupDataProvider(rolloutGroupManagement, rolloutGroupMapper))); initFilterMappings(); this.masterEntitySupport = new MasterEntitySupport<>(getFilterSupport()); rolloutGroupStatusIconSupplier = new RolloutGroupStatusIconSupplier<>(i18n, ProxyRolloutGroup::getStatus, UIComponentIdProvider.ROLLOUT_GROUP_STATUS_LABEL_ID); init(); } /** * Map id to rollout group * * @param entityId * Entity id * * @return Rollout group */ public Optional<ProxyRolloutGroup> mapIdToProxyEntity(final long entityId) { return rolloutGroupManagement.get(entityId).map(rolloutGroupMapper::map); } private Long getSelectedEntityIdFromUiState() { return rolloutManagementUIState.getSelectedRolloutGroupId(); } private void setSelectedEntityIdToUiState(final Long entityId) { rolloutManagementUIState.setSelectedRolloutGroupId(entityId); } private void initFilterMappings() { getFilterSupport().<Long> addMapping(FilterType.MASTER, (filter, masterFilter) -> getFilterSupport().setFilter(masterFilter)); } @Override public String getGridId() { return UIComponentIdProvider.ROLLOUT_GROUP_LIST_GRID_ID; } @Override public void addColumns() { GridComponentBuilder.addComponentColumn(this, this::buildRolloutGroupLink).setId(ROLLOUT_GROUP_LINK_ID) .setCaption(i18n.getMessage("header.name")).setHidable(false).setExpandRatio(3); GridComponentBuilder.addDescriptionColumn(this, i18n, SPUILabelDefinitions.VAR_DESC).setHidable(true) .setHidden(true); GridComponentBuilder.addIconColumn(this, rolloutGroupStatusIconSupplier::getLabel, SPUILabelDefinitions.VAR_STATUS, i18n.getMessage("header.status")).setHidable(true); addColumn(rolloutGroup -> DistributionBarHelper .getDistributionBarAsHTMLString(rolloutGroup.getTotalTargetCountStatus().getStatusTotalCountMap()), new HtmlRenderer()).setId(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS) .setCaption(i18n.getMessage("header.detail.status")) .setDescriptionGenerator( rolloutGroup -> DistributionBarHelper.getTooltip( rolloutGroup.getTotalTargetCountStatus().getStatusTotalCountMap(), i18n), ContentMode.HTML) .setExpandRatio(5).setHidable(true); GridComponentBuilder.addColumn(this, ProxyRolloutGroup::getTotalTargetsCount) .setId(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setCaption(i18n.getMessage("header.total.targets")) .setHidable(true); GridComponentBuilder.addColumn(this, group -> group.getFinishedPercentage() + "%") .setId(SPUILabelDefinitions.ROLLOUT_GROUP_INSTALLED_PERCENTAGE) .setCaption(i18n.getMessage("header.rolloutgroup.installed.percentage")).setHidable(true); GridComponentBuilder.addColumn(this, group -> group.getErrorConditionExp() + "%") .setId(SPUILabelDefinitions.ROLLOUT_GROUP_ERROR_THRESHOLD) .setCaption(i18n.getMessage("header.rolloutgroup.threshold.error")).setHidable(true); GridComponentBuilder.addColumn(this, group -> group.getSuccessConditionExp() + "%") .setId(SPUILabelDefinitions.ROLLOUT_GROUP_THRESHOLD) .setCaption(i18n.getMessage("header.rolloutgroup.threshold")).setHidable(true); GridComponentBuilder.addCreatedAndModifiedColumns(this, i18n) .forEach(col -> col.setHidable(true).setHidden(true)); } private Button buildRolloutGroupLink(final ProxyRolloutGroup rolloutGroup) { final boolean enableButton = RolloutGroupStatus.CREATING != rolloutGroup.getStatus() && permissionChecker.hasRolloutTargetsReadPermission(); return GridComponentBuilder.buildLink(rolloutGroup, "rolloutgroup.link.", rolloutGroup.getName(), enableButton, clickEvent -> onClickOfRolloutGroupName(rolloutGroup)); } private void onClickOfRolloutGroupName(final ProxyRolloutGroup rolloutGroup) { getSelectionSupport().sendSelectionChangedEvent(SelectionChangedEventType.ENTITY_SELECTED, rolloutGroup); rolloutManagementUIState.setSelectedRolloutGroupName(rolloutGroup.getName()); showRolloutGroupTargetsListLayout(); } private void showRolloutGroupTargetsListLayout() { eventBus.publish(CommandTopics.CHANGE_LAYOUT_VISIBILITY, this, new LayoutVisibilityEventPayload( VisibilityType.SHOW, EventLayout.ROLLOUT_GROUP_TARGET_LIST, EventView.ROLLOUT)); } /** * Update items in rollout group grid * * @param ids * List of Rollout group id */ public void updateGridItems(final Collection<Long> ids) { ids.stream().filter(Predicates.notNull()).map(rolloutGroupManagement::getWithDetailedStatus) .forEach(rolloutGroup -> rolloutGroup.ifPresent(this::updateGridItem)); } private void updateGridItem(final RolloutGroup rolloutGroup) { getDataProvider().refreshItem(rolloutGroupMapper.map(rolloutGroup)); } @Override public void restoreState() { final Long masterEntityId = rolloutManagementUIState.getSelectedRolloutId(); if (masterEntityId != null) { getMasterEntitySupport().masterEntityChanged(new ProxyRollout(masterEntityId)); } } /** * @return Rollout master entity support */ public MasterEntitySupport<ProxyRollout> getMasterEntitySupport() { return masterEntitySupport; } }
epl-1.0
jcryptool/crypto
org.jcryptool.visual.zeroknowledge/src/org/jcryptool/visual/zeroknowledge/ui/graphenisomorphie/GFlow.java
11525
// -----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2021 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.visual.zeroknowledge.ui.graphenisomorphie; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.jcryptool.core.util.fonts.FontService; import org.jcryptool.visual.zeroknowledge.algorithm.graphenisomorphie.GAlice; import org.jcryptool.visual.zeroknowledge.algorithm.graphenisomorphie.GBeweiser; import org.jcryptool.visual.zeroknowledge.algorithm.graphenisomorphie.GBob; import org.jcryptool.visual.zeroknowledge.algorithm.graphenisomorphie.GCarol; import org.jcryptool.visual.zeroknowledge.views.GraphenisomorphieView; /** * Repräsentiert eine Klasse, die ein Group-Objekt erstellt, das die Erklärung * zum behandelten Fall enthält. * * @author Mareike Paul * @version 1.0.0 */ public class GFlow { private GAlice alice; private GBob bob; private GCarol carol; private Label erklaerung01; private Label erklaerung02; private Label erklaerung03; private Label erklaerung04; private Button generateB; private Button generateH; private GraphenisomorphieView graphiso; private Composite group; private boolean secretKnown; private Button sendSigma; private Button verify; /** * Konstruktor, der das Group-Objekt erstellt * * @param graphiso * Graphenisomorphie-Objekt, das die Modelle enthält * @param parent * Parent für die graphische Oberfläche */ public GFlow(GraphenisomorphieView graphiso, Composite parent) { this.graphiso = graphiso; alice = graphiso.getAlice(); bob = graphiso.getBob(); carol = graphiso.getCarol(); secretKnown = true; group = new Composite(parent, SWT.NONE); GridLayout gl_group = new GridLayout(4, false); gl_group.horizontalSpacing = 50; gl_group.verticalSpacing = 20; group.setLayout(gl_group); group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); generateButtons(group); setFont(); setFirstCase(true); } /** * schaltet nur den ersten Button frei, deaktiviert alle folgenden */ public void disableAll() { generateH.setEnabled(false); generateB.setEnabled(false); sendSigma.setEnabled(false); verify.setEnabled(false); erklaerung04.setVisible(true); } /** * schaltet den genRandom Button frei, deaktiviert alle folgenden */ public void enableFirst() { generateH.setEnabled(true); generateH.setFocus(); generateB.setEnabled(false); sendSigma.setEnabled(false); verify.setEnabled(false); erklaerung01.setVisible(false); erklaerung02.setVisible(false); erklaerung03.setVisible(false); erklaerung04.setVisible(false); } /** * schaltet den vierten Button frei */ public void enableForth() { verify.setEnabled(true); verify.setFocus(); erklaerung03.setVisible(true); } /** * schaltet den dritten Button frei, deaktiviert alle folgenden */ public void enableSecond() { generateB.setEnabled(true); generateB.setFocus(); sendSigma.setEnabled(false); verify.setEnabled(false); erklaerung01.setVisible(true); } /** * schaltet den calcY Button frei, deaktiviert alle folgenden */ public void enableThird() { sendSigma.setEnabled(true); sendSigma.setFocus(); verify.setEnabled(false); erklaerung02.setVisible(true); } /** * Methode, die die Buttons anlegt * @param parent */ private void generateButtons(Composite parent) { new Label(parent, SWT.NONE).setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); // Button, um die Zufallszahl zu erstellen generateH = new Button(parent, SWT.PUSH); generateH.setText(Messages.GFlow_8); generateH.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); generateH.addSelectionListener( /** * SelectionAdapter, der darauf achtet, ob der Button "Graph H erstellen" * betätigt wurde */ new SelectionAdapter() { /** * Die Person, die gerade betrachtet wird, erstellt einen Graphen H und reicht * diesen an Bob. Der erläuternde Text wird fett gedruckt, der zweite Schritt * des Protokolls wird ermöglicht. */ @Override public void widgetSelected(SelectionEvent arg0) { GBeweiser p; if (secretKnown) { p = alice; } else { p = carol; } bob.setG0(p.getG0()); bob.setG1(p.getG1()); p.generateA(); bob.setH(p.getGraphH()); graphiso.setH(p.getGraphH()); setStep(1); enableSecond(); } }); generateH.setEnabled(false); erklaerung01 = new Label(parent, SWT.WRAP); erklaerung01.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); new Label(parent, SWT.NONE).setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); // Button, um das Zufallsbit zu erstellen generateB = new Button(parent, SWT.PUSH); generateB.setText(Messages.GFlow_9); generateB.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); generateB.addSelectionListener( /** * SelectionAdapter, der darauf achtet, ob der Button "b wählen" betätigt wurde */ new SelectionAdapter() { /** * Bob generiert b. Der erläuternde Text wird fett gedruckt, der dritte Schritt * des Protokolls wird ermöglicht. */ @Override public void widgetSelected(SelectionEvent arg0) { bob.generateB(); enableThird(); setStep(2); } }); generateB.setEnabled(false); erklaerung02 = new Label(parent, SWT.WRAP); erklaerung02.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); new Label(parent, SWT.NONE).setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); // Button, um die Antwort von Alice oder Carol zu errechnen sendSigma = new Button(parent, SWT.PUSH); sendSigma.setText(Messages.GFlow_10); sendSigma.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); sendSigma.addSelectionListener( /** * SelectionAdapter, der darauf achtet, ob der Button "Isomorphismus berechnen" * betätigt wurde */ new SelectionAdapter() { /** * Die Person, die gerade betrachtet wird, berechnet den Isomorphismus h. Der * erläuternde Text wird fett gedruckt, der vierte Schritt des Protokolls wird * ermöglicht. */ @Override public void widgetSelected(SelectionEvent arg0) { GBeweiser p; if (secretKnown) p = alice; else p = carol; p.genH(bob.getB()); bob.setIsomorphismus(p.getH()); enableForth(); setStep(3); } }); sendSigma.setEnabled(false); erklaerung03 = new Label(parent, SWT.WRAP); erklaerung03.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); new Label(parent, SWT.NONE).setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); // Button, um die Antwort von Alice oder Carol zu verifizieren verify = new Button(parent, SWT.PUSH); verify.setText(Messages.GFlow_11); verify.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); verify.addSelectionListener( /** * SelectionAdapter, der darauf achtet, ob der Button "verifizieren" betätigt * wurde */ new SelectionAdapter() { /** * Bob erhält den Isomorphismus h und überprüft ihn. Das Ergebnis wird bekannt * gegeben, ebenso der von Bob berechnete Graph h(G<sub>b</sub>). Der * erläuternde Text wird fett gedruckt, der Durchlauf durch das Protokoll ist * beendet. */ @Override public void widgetSelected(SelectionEvent arg0) { setStep(4); graphiso.getButtons().enableOK(true); graphiso.getParamsBob().verifizieren(true); graphiso.getParamsBob().setVerifiziert(bob.verify()); if (bob.getB() == 0) { graphiso.setH_G_b(bob.getG0().change(bob.getH())); } else { graphiso.setH_G_b(bob.getG1().change(bob.getH())); } disableAll(); } }); verify.setEnabled(false); erklaerung04 = new Label(parent, SWT.WRAP); erklaerung04.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2,1)); } /** * Methode zum Erhalten des Group-Objektes, auf dem die Buttons und Labels * liegen * * @return Group-Objekt, auf dem die graphische Oberfläche des Flows liegt. */ public Composite getGroup() { return group; } /** * setzt den Text in Abhängigkeit von dem Fall, der behandelt wird. * * @param b * true, wenn der erste Fall betrachtet wird, ansonsten false */ public void setFirstCase(boolean b) { if (b) { erklaerung01.setText(Messages.GFlow_0); erklaerung02.setText(Messages.GFlow_1); erklaerung03.setText(Messages.GFlow_2); erklaerung04.setText(Messages.GFlow_3); } else { erklaerung01.setText(Messages.GFlow_4); erklaerung02.setText(Messages.GFlow_5); erklaerung03.setText(Messages.GFlow_6); erklaerung04.setText(Messages.GFlow_7); } erklaerung01.setVisible(false); erklaerung02.setVisible(false); erklaerung03.setVisible(false); erklaerung04.setVisible(false); group.layout(); group.getParent().layout(); setFont(); } /** * Methode, die den Font setzt */ private void setFont() { erklaerung01.setFont(FontService.getNormalFont()); erklaerung02.setFont(FontService.getNormalFont()); erklaerung03.setFont(FontService.getNormalFont()); erklaerung04.setFont(FontService.getNormalFont()); } /** * Highlighting der erläuternden Textteile. * * Das erklärungXX.getParent().layout() ist dafür verantwortlich, dass * die Buttons und Text beim weiter klicken ihre horizontale * Position verändern. Sorgt auf der anderen Seite aber dafür, dass * die Texte immer genug Platz haben. * * @param step * Schritt im Zero-Knowledge-Protokoll */ public void setStep(int step) { setFont(); switch (step) { case 0: erklaerung01.setVisible(false); erklaerung02.setVisible(false); erklaerung03.setVisible(false); erklaerung04.setVisible(false); case 1: erklaerung01.setFont(FontService.getNormalBoldFont()); erklaerung01.getParent().layout(); break; case 2: erklaerung02.setFont(FontService.getNormalBoldFont()); erklaerung02.getParent().layout(); break; case 3: erklaerung03.setFont(FontService.getNormalBoldFont()); erklaerung03.getParent().layout(); break; case 4: erklaerung04.setFont(FontService.getNormalBoldFont()); erklaerung04.getParent().layout(); break; } } /** * aktualisiert die Attribute des Flows */ public void update() { this.alice = graphiso.getAlice(); this.bob = graphiso.getBob(); this.carol = graphiso.getCarol(); } }
epl-1.0
arodchen/MaxSim
maxine/com.oracle.max.vm/src/com/sun/max/vm/monitor/modal/schemes/observer_thin_inflated/package-info.java
1137
/* * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * */ package com.sun.max.vm.monitor.modal.schemes.observer_thin_inflated;
gpl-2.0
ProjetoAmadeus/AmadeusLMS
src/br/ufpe/cin/amadeus/amadeus_mobile/basics/ChoiceMobile.java
1814
/** Copyright 2008, 2009 UFPE - Universidade Federal de Pernambuco Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença. Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes. Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENCA.txt", junto com este programa, se não, escreva para a Fundação do Software Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. **/ package br.ufpe.cin.amadeus.amadeus_mobile.basics; public class ChoiceMobile { private int id; private String alternative; private int votes; private double percentage; public ChoiceMobile() { super(); } public ChoiceMobile(int id, String alternative, int votes, double percentage) { this.id = id; this.alternative = alternative; this.votes = votes; this.percentage = percentage; } public String getAlternative() { return alternative; } public void setAlternative(String alternative) { this.alternative = alternative; } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getPercentage() { return percentage; } public void setPercentage(double percentage) { this.percentage = percentage; } public int getVotes() { return votes; } public void setVotes(int votes) { this.votes = votes; } }
gpl-2.0
scoophealth/oscar
src/main/java/org/oscarehr/integration/mchcv/HCMagneticStripe.java
3085
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.integration.mchcv; public class HCMagneticStripe { private String healthNumber; private String firstName; private String lastName; private String expiryDate; private String sex; private String birthDate; private String cardVersion; private String issueDate; /** * Constructor * * @param stripe */ public HCMagneticStripe(String stripe) { if ((stripe == null) || (stripe.isEmpty())) { throw new RuntimeException("Card number is null"); } String[] tmp = stripe.split(";",-1); stripe = tmp[0]; if (stripe.length() < 78 || stripe.length() > 79 ) { throw new RuntimeException("Card number must contain 78 or 79 characters"); } healthNumber = stripe.substring(8, 18); String[] names = stripe.substring(19, 45).split("/"); lastName = names[0].trim(); firstName = names[1].trim(); birthDate = stripe.substring(54, 62); expiryDate = stripe.substring(46, 50); expiryDate = "20" + expiryDate; expiryDate = expiryDate + birthDate.substring(6, 8); sex = stripe.substring(53, 54); if (sex.equalsIgnoreCase("2")) { sex = "F"; } else { sex = "M"; } cardVersion = stripe.substring(62, 64); issueDate = stripe.substring(69, 75); issueDate = "20" + issueDate; } public String getHealthNumber() { return healthNumber; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getExpiryDate() { return expiryDate; } public String getSex() { return sex; } public String getBirthDate() { return birthDate; } public String getCardVersion() { return cardVersion; } public String getIssueDate() { return issueDate; } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/langtools/test/tools/javac/protectedAccess/p/SuperClass.java
1119
/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package p; public class SuperClass { protected static int i; }
gpl-2.0
blazegraph/database
bigdata-rdf-test/src/test/java/com/bigdata/rdf/sparql/ast/eval/rto/TestRTO_FOAF.java
7529
/** Copyright (C) SYSTAP, LLC DBA Blazegraph 2006-2016. All rights reserved. Contact: SYSTAP, LLC DBA Blazegraph 2501 Calvert ST NW #106 Washington, DC 20008 licenses@blazegraph.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Created on Sep 4, 2011 */ package com.bigdata.rdf.sparql.ast.eval.rto; import java.util.Properties; import com.bigdata.rdf.axioms.NoAxioms; import com.bigdata.rdf.sail.BigdataSail; /** * Data driven test suite for the Runtime Query Optimizer (RTO) using quads-mode * FOAF data. * * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a> * @version $Id: TestBasicQuery.java 6440 2012-08-14 17:57:33Z thompsonbry $ * * @deprecated None of these test queries are complicated enough to trigger the * RTO. The class and its queries should just be dropped. */ public class TestRTO_FOAF extends AbstractRTOTestCase { // private final static Logger log = Logger.getLogger(TestRTO_LUBM.class); /** * */ public TestRTO_FOAF() { } /** * @param name */ public TestRTO_FOAF(String name) { super(name); } /** * Data files for 3-degrees of separation starting with a crawl of TBLs foaf * card. */ private static final String[] dataFiles = new String[] { // data files "src/test/resources/data/foaf/data-0.nq.gz",// "src/test/resources/data/foaf/data-1.nq.gz",// "src/test/resources/data/foaf/data-2.nq.gz",// };// @Override public Properties getProperties() { // Note: clone to avoid modifying!!! final Properties properties = (Properties) super.getProperties().clone(); properties.setProperty(BigdataSail.Options.QUADS_MODE, "true"); properties.setProperty(BigdataSail.Options.AXIOMS_CLASS, NoAxioms.class.getName()); return properties; } /** * Find all friends of a friend. * * <pre> * PREFIX foaf: <http://xmlns.com/foaf/0.1/> * SELECT ?x ?z (count(?y) as ?connectionCount) * (sample(?xname2) as ?xname) * (sample(?zname2) as ?zname) * WHERE { * ?x foaf:knows ?y . * ?y foaf:knows ?z . * FILTER NOT EXISTS { ?x foaf:knows ?z } . * FILTER ( !sameTerm(?x,?z)) . * OPTIONAL { ?x rdfs:label ?xname2 } . * OPTIONAL { ?z rdfs:label ?zname2 } . * } * GROUP BY ?x ?z * </pre> * * FIXME This example is not complex enough to run through the RTO. This may * change when we begin to handle OPTIONALs. However, the FILTER NOT EXISTS * would also need to be handled to make this work since otherwise the query * remain 2 required SPs with a simple FILTER, a sub-SELECTs (for the FILTER * NOT EXISTS) and then two simple OPTIONALs. */ public void test_FOAF_Q1() throws Exception { final TestHelper helper = new TestHelper(// "rto/FOAF-Q1", // testURI, "rto/FOAF-Q1.rq",// queryFileURL dataFiles,// "rto/FOAF-Q1.srx"// resultFileURL ); /* * Verify that the runtime optimizer produced the expected join path. */ final int[] expected = new int[] { 2, 4, 1, 3, 5 }; assertSameJoinOrder(expected, helper); } /** * Find all friends of a friend having at least N indirect connections. * * <pre> * PREFIX foaf: <http://xmlns.com/foaf/0.1/> * SELECT ?x ?z (count(?y) as ?connectionCount) * (sample(?xname2) as ?xname) * (sample(?zname2) as ?zname) * WHERE { * ?x foaf:knows ?y . * ?y foaf:knows ?z . * FILTER NOT EXISTS { ?x foaf:knows ?z } . * FILTER ( !sameTerm(?x,?z)) . * OPTIONAL { ?x rdfs:label ?xname2 } . * OPTIONAL { ?z rdfs:label ?zname2 } . * } * GROUP BY ?x ?z * HAVING (?connectionCount > 1) * </pre> * * FIXME This example is not complex enough to run through the RTO. This may * change when we begin to handle OPTIONALs. However, the FILTER NOT EXISTS * would also need to be handled to make this work since otherwise the query * remain 2 required SPs with a simple FILTER, a sub-SELECTs (for the FILTER * NOT EXISTS) and then two simple OPTIONALs. */ public void test_FOAF_Q2() throws Exception { final TestHelper helper = new TestHelper(// "rto/FOAF-Q2", // testURI, "rto/FOAF-Q2.rq",// queryFileURL dataFiles,// "rto/FOAF-Q2.srx"// resultFileURL ); /* * Verify that the runtime optimizer produced the expected join path. */ final int[] expected = new int[] { 2, 4, 1, 3, 5 }; assertSameJoinOrder(expected, helper); } /** * Find all direct friends and extract their names (when available). * * <pre> * PREFIX foaf: <http://xmlns.com/foaf/0.1/> * CONSTRUCT { * ?u a foaf:Person . * ?u foaf:knows ?v . * ?u rdfs:label ?name . * } * WHERE { * * # Control all RTO parameters for repeatable behavior. * hint:Query hint:optimizer "Runtime". * hint:Query hint:RTO-sampleType "DENSE". * hint:Query hint:RTO-limit "100". * hint:Query hint:RTO-nedges "1". * * ?u a foaf:Person . * ?u foaf:knows ?v . * OPTIONAL { ?u rdfs:label ?name } . * } * LIMIT 100 * </pre> * * FIXME This example is not complex enough to run through the RTO. This * might change when we handle the OPTIONAL join inside of the RTO, however * it would remain 2 required JOINS and an OPTIONAL join and there is no * reason to run that query through the RTO. The query plan will always be * the most selective vertex, then the other vertex, then the OPTIONAL JOIN. * This is fully deterministic based on inspection on the query and the * range counts. The RTO is not required. */ public void test_FOAF_Q10() throws Exception { final TestHelper helper = new TestHelper(// "rto/FOAF-Q10", // testURI, "rto/FOAF-Q10.rq",// queryFileURL dataFiles,// "rto/FOAF-Q10.srx"// resultFileURL ); /* * Verify that the runtime optimizer produced the expected join path. */ final int[] expected = new int[] { 2, 4, 1, 3, 5 }; assertSameJoinOrder(expected, helper); } }
gpl-2.0
andykravets/TeachingJavaMaterials
MapsAndSets/src/Person.java
897
/** * Created by akravets on 12/30/14. */ public class Person { private String name = "Sergii"; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; if (age != person.age) return false; if (name != null ? !name.equals(person.name) : person.name != null) return false; return true; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + age; return result; } }
gpl-2.0
sirolf-otrebla/passwordgen
src/passwordgen/GUILabelPanel.java
896
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package passwordgen; import javax.swing.*; import java.awt.Dimension; /** * * @author alberto */ public class GUILabelPanel extends JPanel { private JLabel label; public GUILabelPanel(){ this.label = createLabel("lunghezza Password:"); this.setMinimumSize(new Dimension(450, 50)); this.setPreferredSize(new Dimension(450, 50)); this.setMaximumSize(new Dimension(450, 15)); layoutInit(); } private JLabel createLabel(String str){ JLabel label = new JLabel(str); return label; } private void layoutInit(){ GUIUtils.buildLM(this, BoxLayout.LINE_AXIS); GUIUtils.addToLM(this, this.label); } }
gpl-2.0
shannah/cn1
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/jdktools/modules/jpda/src/test/java/org/apache/harmony/jpda/tests/jdwp/ThreadReference/OwnedMonitorsStackDepthInfoTest.java
9336
/* * 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.harmony.jpda.tests.jdwp.ThreadReference; import org.apache.harmony.jpda.tests.framework.jdwp.CommandPacket; import org.apache.harmony.jpda.tests.framework.jdwp.JDWPCommands; import org.apache.harmony.jpda.tests.framework.jdwp.JDWPConstants; import org.apache.harmony.jpda.tests.framework.jdwp.ReplyPacket; import org.apache.harmony.jpda.tests.framework.jdwp.TaggedObject; import org.apache.harmony.jpda.tests.jdwp.share.JDWPSyncTestCase; import org.apache.harmony.jpda.tests.share.JPDADebuggeeSynchronizer; /** * JDWP Unit test for ThreadReference.OwnedMonitorsStackDepthInfo command. */ public class OwnedMonitorsStackDepthInfoTest extends JDWPSyncTestCase { static final String thisCommandName = "ThreadReference.OwnedMonitorsStackDepthInfo command "; protected String getDebuggeeClassName() { return "org.apache.harmony.jpda.tests.jdwp.ThreadReference.OwnedMonitorsStackDepthInfoDebuggee"; } // OwnedMonitorsStackDepthInfo needs canGetMonitorFrameInfo VM capability support private boolean isCapability() { // check capability, relevant for this test logWriter.println("=> Check capability: canGetMonitorFrameInfo"); debuggeeWrapper.vmMirror.capabilities(); boolean isCapability = debuggeeWrapper.vmMirror.targetVMCapabilities.canGetMonitorFrameInfo; return isCapability; } /** * This testcase exercises ThreadReference.OwnedMonitorsStackDepthInfo * command. <BR> * At first the test starts OwnedMonitorsStackDepthInfoDebuggee which runs * the tested thread 'TESTED_THREAD'. <BR> * Then the test performs the ThreadReference.OwnedMonitorsStackDepthInfo * command for the tested thread and gets list of monitor objects. * The returned monitor objects are equal to expected count and their stack depth are * equal to expected depth. This test will perform MonitorInfo to guarrantee that returend * monitors do belong to the test thread. */ public void testOwnedMonitorsStackDepthInfo() { String thisTestName = "testOwnedMonitorsStackDepthInfo"; logWriter.println("==> " + thisTestName + " for " + thisCommandName + ": START..."); synchronizer.receiveMessage(JPDADebuggeeSynchronizer.SGNL_READY); if (!isCapability()) { logWriter.println("##WARNING: this VM dosn't possess capability: canGetInstanceInfo"); return; } // Getting ID of the tested thread logWriter.println("==> testedThreadName = " + OwnedMonitorsStackDepthInfoDebuggee.TESTED_THREAD); logWriter.println("==> Get testedThreadID..."); long testedThreadID = debuggeeWrapper.vmMirror .getThreadID(OwnedMonitorsStackDepthInfoDebuggee.TESTED_THREAD); // Compose the OwnedMonitorsStackDepthInfo command CommandPacket stackDepthPacket = new CommandPacket( JDWPCommands.ThreadReferenceCommandSet.CommandSetID, JDWPCommands.ThreadReferenceCommandSet.OwnedMonitorsStackDepthInfoCommand); stackDepthPacket.setNextValueAsThreadID(testedThreadID); // Suspend the VM before perform command logWriter.println("==> testedThreadID = " + testedThreadID); logWriter.println("==> suspend testedThread..."); debuggeeWrapper.vmMirror.suspendThread(testedThreadID); // Perform the command and attain the reply package ReplyPacket stackDepthReply = debuggeeWrapper.vmMirror .performCommand(stackDepthPacket); checkReplyPacket(stackDepthReply, "ThreadReference::OwnedMonitorsStackDepthInfo command"); // Expected return values, these values is attained from RI behavior int expectedMonitorCount = 3; int[] expectedStackDepth = new int[] { 6, 7, 7 }; // Analyze the reply package int owned = stackDepthReply.getNextValueAsInt(); assertEquals(thisCommandName + "returned number of owned monitors is not equal to expected number.", expectedMonitorCount, owned, null, null); logWriter .println("==> CHECK: PASSED: returned owned monitors have the same counts as expected"); logWriter.println("==> Owned monitors: " + owned); for (int i = 0; i < owned; i++) { // Attain monitor object ID TaggedObject monitorObject = stackDepthReply .getNextValueAsTaggedObject(); // Attain monitor stack depth int returnedDepthInfo = stackDepthReply.getNextValueAsInt(); assertEquals(thisCommandName + "returned monitor is not owned by test thread", expectedStackDepth[i], returnedDepthInfo, null, null); logWriter.println("==> CHECK: PASSED: returned owned monitor has the expected stack depth"); logWriter.println("==> Stack depth: " + returnedDepthInfo); /* * Test the returned monitor object does belong to the test thread by MonitorInfo Command */ // Compose the MonitorInfo Command CommandPacket monitorInfoPacket = new CommandPacket( JDWPCommands.ObjectReferenceCommandSet.CommandSetID, JDWPCommands.ObjectReferenceCommandSet.MonitorInfoCommand); monitorInfoPacket.setNextValueAsObjectID(monitorObject.objectID); // Perform the command and attain the reply package ReplyPacket monitorInfoReply = debuggeeWrapper.vmMirror .performCommand(monitorInfoPacket); checkReplyPacket(monitorInfoReply, "ObjectReference::MonitorInfo command"); // Attain thread id from monitor info long ownerThreadID = monitorInfoReply.getNextValueAsThreadID(); assertEquals(thisCommandName + "returned monitor is not owned by test thread", ownerThreadID, testedThreadID, null, null); logWriter.println("==> CHECK: PASSED: returned monitor does belong to the test thread."); logWriter.println("==> Monitor owner thread ID: " + ownerThreadID); } synchronizer.sendMessage(JPDADebuggeeSynchronizer.SGNL_CONTINUE); assertAllDataRead(stackDepthReply); } public void testOwnedMonitorsStackDepthInfo_Unsuspended() { String thisTestName = "testOwnedMonitorsStackDepthInfo"; logWriter.println("==> " + thisTestName + " for " + thisCommandName + ": START..."); synchronizer.receiveMessage(JPDADebuggeeSynchronizer.SGNL_READY); if (!isCapability()) { logWriter .println("##WARNING: this VM dosn't possess capability: OwnedMonitorsStackDepthInfo"); return; } // Getting ID of the tested thread logWriter.println("==> testedThreadName = " + OwnedMonitorsStackDepthInfoDebuggee.TESTED_THREAD); logWriter.println("==> Get testedThreadID..."); long testedThreadID = debuggeeWrapper.vmMirror .getThreadID(OwnedMonitorsStackDepthInfoDebuggee.TESTED_THREAD); // Compose the OwnedMonitorsStackDepthInfo command CommandPacket stackDepthPacket = new CommandPacket( JDWPCommands.ThreadReferenceCommandSet.CommandSetID, JDWPCommands.ThreadReferenceCommandSet.OwnedMonitorsStackDepthInfoCommand); stackDepthPacket.setNextValueAsThreadID(testedThreadID); // Perform the command and attain the reply package ReplyPacket checkedReply = debuggeeWrapper.vmMirror .performCommand(stackDepthPacket); short errorCode = checkedReply.getErrorCode(); if (errorCode != JDWPConstants.Error.NONE) { if (errorCode == JDWPConstants.Error.THREAD_NOT_SUSPENDED) { logWriter.println("=> CHECK PASSED: Expected error (THREAD_NOT_SUSPENDED) is returned"); return; } } printErrorAndFail(thisCommandName + " should throw exception when VM is not suspended."); } public static void main(String[] args) { junit.textui.TestRunner.run(OwnedMonitorsStackDepthInfoTest.class); } }
gpl-2.0
intelie/esper
examples/servershell/src/main/java/com/espertech/esper/example/servershell/jms/JMSContext.java
1686
/************************************************************************************** * 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.servershell.jms; import javax.jms.*; public class JMSContext { private ConnectionFactory factory; private Connection connection; private Session session; private Destination destination; public JMSContext(ConnectionFactory factory, Connection connection, Session session, Destination destination) { this.factory = factory; this.connection = connection; this.session = session; this.destination = destination; } public void destroy() throws JMSException { session.close(); connection.close(); } public Connection getConnection() { return connection; } public Destination getDestination() { return destination; } public ConnectionFactory getFactory() { return factory; } public Session getSession() { return session; } }
gpl-2.0
klusark/scummvm
backends/platform/android/org/scummvm/scummvm/ScummVMActivity.java
5831
package org.scummvm.scummvm; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.media.AudioManager; import android.os.Bundle; import android.os.Environment; import android.util.DisplayMetrics; import android.util.Log; import android.view.SurfaceView; import android.view.SurfaceHolder; import android.view.MotionEvent; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import java.io.File; public class ScummVMActivity extends Activity { private class MyScummVM extends ScummVM { private boolean usingSmallScreen() { // Multiple screen sizes came in with Android 1.6. Have // to use reflection in order to continue supporting 1.5 // devices :( DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); try { // This 'density' term is very confusing. int DENSITY_LOW = metrics.getClass().getField("DENSITY_LOW").getInt(null); int densityDpi = metrics.getClass().getField("densityDpi").getInt(metrics); return densityDpi <= DENSITY_LOW; } catch (Exception e) { return false; } } public MyScummVM(SurfaceHolder holder) { super(ScummVMActivity.this.getAssets(), holder); // Enable ScummVM zoning on 'small' screens. // FIXME make this optional for the user // disabled for now since it crops too much //enableZoning(usingSmallScreen()); } @Override protected void getDPI(float[] values) { DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); values[0] = metrics.xdpi; values[1] = metrics.ydpi; } @Override protected void displayMessageOnOSD(String msg) { Log.i(LOG_TAG, "OSD: " + msg); Toast.makeText(ScummVMActivity.this, msg, Toast.LENGTH_LONG).show(); } @Override protected void setWindowCaption(final String caption) { runOnUiThread(new Runnable() { public void run() { setTitle(caption); } }); } @Override protected String[] getPluginDirectories() { String[] dirs = new String[1]; dirs[0] = ScummVMApplication.getLastCacheDir().getPath(); return dirs; } @Override protected void showVirtualKeyboard(final boolean enable) { runOnUiThread(new Runnable() { public void run() { showKeyboard(enable); } }); } @Override protected String[] getSysArchives() { return new String[0]; } } private MyScummVM _scummvm; private ScummVMEvents _events; private Thread _scummvm_thread; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setVolumeControlStream(AudioManager.STREAM_MUSIC); setContentView(R.layout.main); takeKeyEvents(true); // This is a common enough error that we should warn about it // explicitly. if (!Environment.getExternalStorageDirectory().canRead()) { new AlertDialog.Builder(this) .setTitle(R.string.no_sdcard_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.no_sdcard) .setNegativeButton(R.string.quit, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .show(); return; } SurfaceView main_surface = (SurfaceView)findViewById(R.id.main_surface); main_surface.requestFocus(); getFilesDir().mkdirs(); // Store savegames on external storage if we can, which means they're // world-readable and don't get deleted on uninstall. String savePath = Environment.getExternalStorageDirectory() + "/ScummVM/Saves/"; File saveDir = new File(savePath); saveDir.mkdirs(); if (!saveDir.isDirectory()) { // If it doesn't work, resort to the internal app path. savePath = getDir("saves", MODE_WORLD_READABLE).getPath(); } // Start ScummVM _scummvm = new MyScummVM(main_surface.getHolder()); _scummvm.setArgs(new String[] { "ScummVM", "--config=" + getFileStreamPath("scummvmrc").getPath(), "--path=" + Environment.getExternalStorageDirectory().getPath(), "--gui-theme=scummmodern", "--savepath=" + savePath }); _events = new ScummVMEvents(this, _scummvm); main_surface.setOnKeyListener(_events); main_surface.setOnTouchListener(_events); _scummvm_thread = new Thread(_scummvm, "ScummVM"); _scummvm_thread.start(); } @Override public void onStart() { Log.d(ScummVM.LOG_TAG, "onStart"); super.onStart(); } @Override public void onResume() { Log.d(ScummVM.LOG_TAG, "onResume"); super.onResume(); if (_scummvm != null) _scummvm.setPause(false); } @Override public void onPause() { Log.d(ScummVM.LOG_TAG, "onPause"); super.onPause(); if (_scummvm != null) _scummvm.setPause(true); } @Override public void onStop() { Log.d(ScummVM.LOG_TAG, "onStop"); super.onStop(); } @Override public void onDestroy() { Log.d(ScummVM.LOG_TAG, "onDestroy"); super.onDestroy(); if (_events != null) { _events.sendQuitEvent(); try { // 1s timeout _scummvm_thread.join(1000); } catch (InterruptedException e) { Log.i(ScummVM.LOG_TAG, "Error while joining ScummVM thread", e); } _scummvm = null; } } @Override public boolean onTrackballEvent(MotionEvent e) { if (_events != null) return _events.onTrackballEvent(e); return false; } private void showKeyboard(boolean show) { SurfaceView main_surface = (SurfaceView)findViewById(R.id.main_surface); InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); if (show) imm.showSoftInput(main_surface, InputMethodManager.SHOW_IMPLICIT); else imm.hideSoftInputFromWindow(main_surface.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY); } }
gpl-2.0
arthurmelo88/palmetalADP
adempiere_360/base/src/org/compiere/model/X_A_Asset_Group.java
7082
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.KeyNamePair; /** Generated Model for A_Asset_Group * @author Adempiere (generated) * @version Release 3.6.0LTS - $Id$ */ public class X_A_Asset_Group extends PO implements I_A_Asset_Group, I_Persistent { /** * */ private static final long serialVersionUID = 20100614L; /** Standard Constructor */ public X_A_Asset_Group (Properties ctx, int A_Asset_Group_ID, String trxName) { super (ctx, A_Asset_Group_ID, trxName); /** if (A_Asset_Group_ID == 0) { setA_Asset_Group_ID (0); setIsCreateAsActive (true); // Y setIsDepreciated (false); setIsOneAssetPerUOM (false); setIsOwned (false); setName (null); } */ } /** Load Constructor */ public X_A_Asset_Group (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 3 - Client - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_A_Asset_Group[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Asset Group. @param A_Asset_Group_ID Group of Assets */ public void setA_Asset_Group_ID (int A_Asset_Group_ID) { if (A_Asset_Group_ID < 1) set_ValueNoCheck (COLUMNNAME_A_Asset_Group_ID, null); else set_ValueNoCheck (COLUMNNAME_A_Asset_Group_ID, Integer.valueOf(A_Asset_Group_ID)); } /** Get Asset Group. @return Group of Assets */ public int getA_Asset_Group_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Group_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Group_ID())); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Create As Active. @param IsCreateAsActive Create Asset and activate it */ public void setIsCreateAsActive (boolean IsCreateAsActive) { set_Value (COLUMNNAME_IsCreateAsActive, Boolean.valueOf(IsCreateAsActive)); } /** Get Create As Active. @return Create Asset and activate it */ public boolean isCreateAsActive () { Object oo = get_Value(COLUMNNAME_IsCreateAsActive); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Depreciate. @param IsDepreciated The asset will be depreciated */ public void setIsDepreciated (boolean IsDepreciated) { set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated)); } /** Get Depreciate. @return The asset will be depreciated */ public boolean isDepreciated () { Object oo = get_Value(COLUMNNAME_IsDepreciated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set One Asset Per UOM. @param IsOneAssetPerUOM Create one asset per UOM */ public void setIsOneAssetPerUOM (boolean IsOneAssetPerUOM) { set_Value (COLUMNNAME_IsOneAssetPerUOM, Boolean.valueOf(IsOneAssetPerUOM)); } /** Get One Asset Per UOM. @return Create one asset per UOM */ public boolean isOneAssetPerUOM () { Object oo = get_Value(COLUMNNAME_IsOneAssetPerUOM); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Owned. @param IsOwned The asset is owned by the organization */ public void setIsOwned (boolean IsOwned) { set_Value (COLUMNNAME_IsOwned, Boolean.valueOf(IsOwned)); } /** Get Owned. @return The asset is owned by the organization */ public boolean isOwned () { Object oo = get_Value(COLUMNNAME_IsOwned); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Track Issues. @param IsTrackIssues Enable tracking issues for this asset */ public void setIsTrackIssues (boolean IsTrackIssues) { set_Value (COLUMNNAME_IsTrackIssues, Boolean.valueOf(IsTrackIssues)); } /** Get Track Issues. @return Enable tracking issues for this asset */ public boolean isTrackIssues () { Object oo = get_Value(COLUMNNAME_IsTrackIssues); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } }
gpl-2.0
bramalingam/bioformats
components/forks/poi/src/loci/poi/hssf/record/BeginRecord.java
3220
/* * #%L * Fork of Apache Jakarta POI. * %% * Copyright (C) 2008 - 2016 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /* ==================================================================== 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 loci.poi.hssf.record; import loci.poi.util.LittleEndian; /** * The begin record defines the start of a block of records for a (grpahing * data object. This record is matched with a corresponding EndRecord. * * @see EndRecord * * @author Glen Stampoultzis (glens at apache.org) */ public class BeginRecord extends Record { public static final short sid = 0x1033; public BeginRecord() { } /** * Constructs a BeginRecord record and sets its fields appropriately. * @param in the RecordInputstream to read the record from */ public BeginRecord(RecordInputStream in) { super(in); } protected void validateSid(short id) { if (id != sid) { throw new RecordFormatException("NOT A BEGIN RECORD"); } } protected void fillFields(RecordInputStream in) { } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("[BEGIN]\n"); buffer.append("[/BEGIN]\n"); return buffer.toString(); } public int serialize(int offset, byte [] data) { LittleEndian.putShort(data, 0 + offset, sid); LittleEndian.putShort(data, 2 + offset, (( short ) 0)); // no record info return getRecordSize(); } public int getRecordSize() { return 4; } public short getSid() { return sid; } }
gpl-2.0
Z-Shang/onscripter-gbk
svn/onscripter-read-only/src/org/bouncycastle/asn1/ocsp/ServiceLocator.java
839
package org.bouncycastle.asn1.ocsp; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.DERObject; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.x500.X500Name; public class ServiceLocator extends ASN1Encodable { X500Name issuer; DERObject locator; /** * Produce an object suitable for an ASN1OutputStream. * <pre> * ServiceLocator ::= SEQUENCE { * issuer Name, * locator AuthorityInfoAccessSyntax OPTIONAL } * </pre> */ public DERObject toASN1Object() { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(issuer); if (locator != null) { v.add(locator); } return new DERSequence(v); } }
gpl-2.0
ymstmsys/primecloud-controller
auto-project/auto-zabbix/src/main/java/jp/primecloud/auto/zabbix/util/JsonPropertyNameProcessor.java
2529
/* * Copyright 2014 by SCSK Corporation. * * This file is part of PrimeCloud Controller(TM). * * PrimeCloud Controller(TM) 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. * * PrimeCloud Controller(TM) 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 PrimeCloud Controller(TM). If not, see <http://www.gnu.org/licenses/>. */ package jp.primecloud.auto.zabbix.util; import java.util.Locale; import jp.primecloud.auto.zabbix.model.host.HostGetParam; import jp.primecloud.auto.zabbix.model.user.UserGetParam; import net.sf.json.processors.PropertyNameProcessor; /** * <p> * Javaのプロパティ名をJSONのキーにマッピングするクラスです。 * </p> * */ public class JsonPropertyNameProcessor implements PropertyNameProcessor { /** * {@inheritDoc} */ @Override @SuppressWarnings("rawtypes") public String processPropertyName(Class beanClass, String name) { if (name == null || name.length() == 0) { return name; } if (beanClass != null) { if (HostGetParam.class.isAssignableFrom(beanClass)) { if (name.equals("selectParentTemplates")) { return name; } else if (name.equals("selectGroups")) { return name; } } if (UserGetParam.class.isAssignableFrom(beanClass)) { if (name.equals("selectUsrgrps")) { return name; } } } StringBuilder sb = new StringBuilder(); int pos = 0; for (int i = 1; i < name.length(); i++) { if (Character.isUpperCase(name.charAt(i))) { if (sb.length() != 0) { sb.append('_'); } sb.append(name.substring(pos, i)); pos = i; } } if (sb.length() != 0) { sb.append('_'); } sb.append(name.substring(pos, name.length())); return sb.toString().toLowerCase(Locale.ENGLISH); } }
gpl-2.0
arthurmelo88/palmetalADP
adempiere_360/client/src/org/compiere/apps/ALoginRes_es.java
3183
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.apps; import java.util.ListResourceBundle; /** * Base Resource Bundle * * @author Erwin Cortes * @translator Jordi Luna * @version $Id: ALoginRes_es.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ */ public final class ALoginRes_es extends ListResourceBundle { /** Translation Content */ static final Object[][] contents = new String[][] { { "Connection", "Conexi\u00f3n" }, { "Defaults", "Predeterminados" }, { "Login", "Autenticaci\u00f3n ADempiere" }, { "File", "Archivo" }, { "Exit", "Salir" }, { "Help", "Ayuda" }, { "About", "Acerca de" }, { "Host", "&Servidor" }, { "Database", "Base de datos" }, { "User", "&Usuario" }, { "EnterUser", "Introduzca Usuario Aplicaci\u00f3n" }, { "Password", "&Contrase\u00f1a" }, { "EnterPassword", "Introduzca Contrase\u00f1a Aplicaci\u00f3n" }, { "Language", "&Idioma" }, { "SelectLanguage", "Seleccione su idioma" }, { "Role", "Perfil" }, { "Client", "Entidad" }, { "Organization", "Organizaci\u00f3n" }, { "Date", "Fecha" }, { "Warehouse", "Almac\u00e9n" }, { "Printer", "Impresora" }, { "Connected", "Conectado" }, { "NotConnected", "No Conectado" }, { "DatabaseNotFound", "Base de datos no encontrada" }, { "UserPwdError", "Usuario-Contrase\u00f1a no coinciden" }, { "RoleNotFound", "Perfil no encontrado/incompleto" }, { "Authorized", "Autorizado" }, { "Ok", "Aceptar" }, { "Cancel", "Cancelar" }, { "VersionConflict", "Conflicto de versi\u00f3n:" }, { "VersionInfo", "Servidor <> Cliente" }, { "PleaseUpgrade", "Favor descargar una nueva versi\u00f3n desde el servidor" } }; /** * Get Contents * @return context */ public Object[][] getContents() { return contents; } // getContents } // ALoginRes_es
gpl-2.0
marcosdiez/aosp-morelang-ime
tests/src/com/android/inputmethod/latin/UtilsTests.java
2736
/* * Copyright (C) 2010,2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.latin; import android.test.AndroidTestCase; public class UtilsTests extends AndroidTestCase { // The following is meant to be a reasonable default for // the "word_separators" resource. private static final String sSeparators = ".,:;!?-"; @Override protected void setUp() throws Exception { super.setUp(); } /************************** Tests ************************/ /** * Test for getting previous word (for bigram suggestions) */ public void testGetPreviousWord() { // If one of the following cases breaks, the bigram suggestions won't work. assertEquals(EditingUtils.getPreviousWord("abc def", sSeparators), "abc"); assertNull(EditingUtils.getPreviousWord("abc", sSeparators)); assertNull(EditingUtils.getPreviousWord("abc. def", sSeparators)); // The following tests reflect the current behavior of the function // EditingUtils#getPreviousWord. // TODO: However at this time, the code does never go // into such a path, so it should be safe to change the behavior of // this function if needed - especially since it does not seem very // logical. These tests are just there to catch any unintentional // changes in the behavior of the EditingUtils#getPreviousWord method. assertEquals(EditingUtils.getPreviousWord("abc def ", sSeparators), "abc"); assertEquals(EditingUtils.getPreviousWord("abc def.", sSeparators), "abc"); assertEquals(EditingUtils.getPreviousWord("abc def .", sSeparators), "def"); assertNull(EditingUtils.getPreviousWord("abc ", sSeparators)); } /** * Test for getting the word before the cursor (for bigram) */ public void testGetThisWord() { assertEquals(EditingUtils.getThisWord("abc def", sSeparators), "def"); assertEquals(EditingUtils.getThisWord("abc def ", sSeparators), "def"); assertNull(EditingUtils.getThisWord("abc def.", sSeparators)); assertNull(EditingUtils.getThisWord("abc def .", sSeparators)); } }
gpl-2.0
mixaceh/openyu-cms
openyu-cms-core/src/main/java/org/openyu/cms/role/vo/impl/RoleImpl.java
1549
package org.openyu.cms.role.vo.impl; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.commons.lang.builder.ToStringBuilder; import org.openyu.cms.role.vo.Role; import org.openyu.cms.site.vo.Site; import org.openyu.cms.site.vo.adapter.SiteXmlAdapter; import org.openyu.commons.bean.supporter.SeqIdAuditNamesBeanSupporter; //-------------------------------------------------- //jaxb //-------------------------------------------------- @XmlRootElement(name = "role") @XmlAccessorType(XmlAccessType.FIELD) public class RoleImpl extends SeqIdAuditNamesBeanSupporter implements Role { /** * 網站 */ @XmlJavaTypeAdapter(SiteXmlAdapter.class) private Site site; private static final long serialVersionUID = -2104890043904825918L; public RoleImpl(String id) { setId(id); } public RoleImpl() { this(null); } public RoleImpl(long seq) { this(null); setSeq(seq); } public Site getSite() { return site; } public void setSite(Site site) { this.site = site; } public String toString() { ToStringBuilder builder = new ToStringBuilder(this); builder.appendSuper(super.toString()); builder.append("site", (site != null ? site.getSeq() + ", " + site.getId() : null)); return builder.toString(); } public Object clone() { RoleImpl copy = null; copy = (RoleImpl) super.clone(); copy.site = clone(site); return copy; } }
gpl-2.0
SkidJava/BaseClient
new_1.8.8/net/minecraft/client/gui/GuiCustomizeSkin.java
3429
package net.minecraft.client.gui; import java.io.IOException; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.EnumPlayerModelParts; public class GuiCustomizeSkin extends GuiScreen { /** The parent GUI for this GUI */ private final GuiScreen parentScreen; /** The title of the GUI. */ private String title; public GuiCustomizeSkin(GuiScreen parentScreenIn) { this.parentScreen = parentScreenIn; } /** * Adds the buttons (and other controls) to the screen in question. Called when the GUI is displayed and when the * window resizes, the buttonList is cleared beforehand. */ public void initGui() { int i = 0; this.title = I18n.format("options.skinCustomisation.title", new Object[0]); for (EnumPlayerModelParts enumplayermodelparts : EnumPlayerModelParts.values()) { this.buttonList.add(new GuiCustomizeSkin.ButtonPart(enumplayermodelparts.getPartId(), this.width / 2 - 155 + i % 2 * 160, this.height / 6 + 24 * (i >> 1), 150, 20, enumplayermodelparts)); ++i; } if (i % 2 == 1) { ++i; } this.buttonList.add(new GuiButton(200, this.width / 2 - 100, this.height / 6 + 24 * (i >> 1), I18n.format("gui.done", new Object[0]))); } /** * Called by the controls from the buttonList when activated. (Mouse pressed for buttons) */ protected void actionPerformed(GuiButton button) throws IOException { if (button.enabled) { if (button.id == 200) { this.mc.gameSettings.saveOptions(); this.mc.displayGuiScreen(this.parentScreen); } else if (button instanceof GuiCustomizeSkin.ButtonPart) { EnumPlayerModelParts enumplayermodelparts = ((GuiCustomizeSkin.ButtonPart)button).playerModelParts; this.mc.gameSettings.switchModelPartEnabled(enumplayermodelparts); button.displayString = this.func_175358_a(enumplayermodelparts); } } } /** * Draws the screen and all the components in it. Args : mouseX, mouseY, renderPartialTicks */ public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); this.drawCenteredString(this.fontRendererObj, this.title, this.width / 2, 20, 16777215); super.drawScreen(mouseX, mouseY, partialTicks); } private String func_175358_a(EnumPlayerModelParts playerModelParts) { String s; if (this.mc.gameSettings.getModelParts().contains(playerModelParts)) { s = I18n.format("options.on", new Object[0]); } else { s = I18n.format("options.off", new Object[0]); } return playerModelParts.func_179326_d().getFormattedText() + ": " + s; } class ButtonPart extends GuiButton { private final EnumPlayerModelParts playerModelParts; private ButtonPart(int p_i45514_2_, int p_i45514_3_, int p_i45514_4_, int p_i45514_5_, int p_i45514_6_, EnumPlayerModelParts playerModelParts) { super(p_i45514_2_, p_i45514_3_, p_i45514_4_, p_i45514_5_, p_i45514_6_, GuiCustomizeSkin.this.func_175358_a(playerModelParts)); this.playerModelParts = playerModelParts; } } }
gpl-2.0
SpoonLabs/astor
examples/time_11/src/main/java/org/joda/time/format/DateTimeFormatterBuilder.java
106805
/* * Copyright 2001-2011 Stephen Colebourne * * 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.joda.time.format; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeUtils; import org.joda.time.DateTimeZone; import org.joda.time.MutableDateTime; import org.joda.time.ReadablePartial; import org.joda.time.MutableDateTime.Property; import org.joda.time.field.MillisDurationField; import org.joda.time.field.PreciseDateTimeField; /** * Factory that creates complex instances of DateTimeFormatter via method calls. * <p> * Datetime formatting is performed by the {@link DateTimeFormatter} class. * Three classes provide factory methods to create formatters, and this is one. * The others are {@link DateTimeFormat} and {@link ISODateTimeFormat}. * <p> * DateTimeFormatterBuilder is used for constructing formatters which are then * used to print or parse. The formatters are built by appending specific fields * or other formatters to an instance of this builder. * <p> * For example, a formatter that prints month and year, like "January 1970", * can be constructed as follows: * <p> * <pre> * DateTimeFormatter monthAndYear = new DateTimeFormatterBuilder() * .appendMonthOfYearText() * .appendLiteral(' ') * .appendYear(4, 4) * .toFormatter(); * </pre> * <p> * DateTimeFormatterBuilder itself is mutable and not thread-safe, but the * formatters that it builds are thread-safe and immutable. * * @author Brian S O'Neill * @author Stephen Colebourne * @author Fredrik Borgh * @since 1.0 * @see DateTimeFormat * @see ISODateTimeFormat */ public class DateTimeFormatterBuilder { /** Array of printers and parsers (alternating). */ private ArrayList<Object> iElementPairs; /** Cache of the last returned formatter. */ private Object iFormatter; //----------------------------------------------------------------------- /** * Creates a DateTimeFormatterBuilder. */ public DateTimeFormatterBuilder() { super(); iElementPairs = new ArrayList<Object>(); } //----------------------------------------------------------------------- /** * Constructs a DateTimeFormatter using all the appended elements. * <p> * This is the main method used by applications at the end of the build * process to create a usable formatter. * <p> * Subsequent changes to this builder do not affect the returned formatter. * <p> * The returned formatter may not support both printing and parsing. * The methods {@link DateTimeFormatter#isPrinter()} and * {@link DateTimeFormatter#isParser()} will help you determine the state * of the formatter. * * @throws UnsupportedOperationException if neither printing nor parsing is supported */ public DateTimeFormatter toFormatter() { Object f = getFormatter(); DateTimePrinter printer = null; if (isPrinter(f)) { printer = (DateTimePrinter) f; } DateTimeParser parser = null; if (isParser(f)) { parser = (DateTimeParser) f; } if (printer != null || parser != null) { return new DateTimeFormatter(printer, parser); } throw new UnsupportedOperationException("Both printing and parsing not supported"); } /** * Internal method to create a DateTimePrinter instance using all the * appended elements. * <p> * Most applications will not use this method. * If you want a printer in an application, call {@link #toFormatter()} * and just use the printing API. * <p> * Subsequent changes to this builder do not affect the returned printer. * * @throws UnsupportedOperationException if printing is not supported */ public DateTimePrinter toPrinter() { Object f = getFormatter(); if (isPrinter(f)) { return (DateTimePrinter) f; } throw new UnsupportedOperationException("Printing is not supported"); } /** * Internal method to create a DateTimeParser instance using all the * appended elements. * <p> * Most applications will not use this method. * If you want a parser in an application, call {@link #toFormatter()} * and just use the parsing API. * <p> * Subsequent changes to this builder do not affect the returned parser. * * @throws UnsupportedOperationException if parsing is not supported */ public DateTimeParser toParser() { Object f = getFormatter(); if (isParser(f)) { return (DateTimeParser) f; } throw new UnsupportedOperationException("Parsing is not supported"); } //----------------------------------------------------------------------- /** * Returns true if toFormatter can be called without throwing an * UnsupportedOperationException. * * @return true if a formatter can be built */ public boolean canBuildFormatter() { return isFormatter(getFormatter()); } /** * Returns true if toPrinter can be called without throwing an * UnsupportedOperationException. * * @return true if a printer can be built */ public boolean canBuildPrinter() { return isPrinter(getFormatter()); } /** * Returns true if toParser can be called without throwing an * UnsupportedOperationException. * * @return true if a parser can be built */ public boolean canBuildParser() { return isParser(getFormatter()); } //----------------------------------------------------------------------- /** * Clears out all the appended elements, allowing this builder to be * reused. */ public void clear() { iFormatter = null; iElementPairs.clear(); } //----------------------------------------------------------------------- /** * Appends another formatter. * <p> * This extracts the underlying printer and parser and appends them * The printer and parser interfaces are the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @param formatter the formatter to add * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if formatter is null or of an invalid type */ public DateTimeFormatterBuilder append(DateTimeFormatter formatter) { if (formatter == null) { throw new IllegalArgumentException("No formatter supplied"); } return append0(formatter.getPrinter(), formatter.getParser()); } /** * Appends just a printer. With no matching parser, a parser cannot be * built from this DateTimeFormatterBuilder. * <p> * The printer interface is part of the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @param printer the printer to add, not null * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if printer is null or of an invalid type */ public DateTimeFormatterBuilder append(DateTimePrinter printer) { checkPrinter(printer); return append0(printer, null); } /** * Appends just a parser. With no matching printer, a printer cannot be * built from this builder. * <p> * The parser interface is part of the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @param parser the parser to add, not null * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if parser is null or of an invalid type */ public DateTimeFormatterBuilder append(DateTimeParser parser) { checkParser(parser); return append0(null, parser); } /** * Appends a printer/parser pair. * <p> * The printer and parser interfaces are the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @param printer the printer to add, not null * @param parser the parser to add, not null * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if printer or parser is null or of an invalid type */ public DateTimeFormatterBuilder append(DateTimePrinter printer, DateTimeParser parser) { checkPrinter(printer); checkParser(parser); return append0(printer, parser); } /** * Appends a printer and a set of matching parsers. When parsing, the first * parser in the list is selected for parsing. If it fails, the next is * chosen, and so on. If none of these parsers succeeds, then the failed * position of the parser that made the greatest progress is returned. * <p> * Only the printer is optional. In addition, it is illegal for any but the * last of the parser array elements to be null. If the last element is * null, this represents the empty parser. The presence of an empty parser * indicates that the entire array of parse formats is optional. * <p> * The printer and parser interfaces are the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @param printer the printer to add * @param parsers the parsers to add * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if any printer or parser is of an invalid type * @throws IllegalArgumentException if any parser element but the last is null */ public DateTimeFormatterBuilder append(DateTimePrinter printer, DateTimeParser[] parsers) { if (printer != null) { checkPrinter(printer); } if (parsers == null) { throw new IllegalArgumentException("No parsers supplied"); } int length = parsers.length; if (length == 1) { if (parsers[0] == null) { throw new IllegalArgumentException("No parser supplied"); } return append0(printer, parsers[0]); } DateTimeParser[] copyOfParsers = new DateTimeParser[length]; int i; for (i = 0; i < length - 1; i++) { if ((copyOfParsers[i] = parsers[i]) == null) { throw new IllegalArgumentException("Incomplete parser array"); } } copyOfParsers[i] = parsers[i]; return append0(printer, new MatchingParser(copyOfParsers)); } /** * Appends just a parser element which is optional. With no matching * printer, a printer cannot be built from this DateTimeFormatterBuilder. * <p> * The parser interface is part of the low-level part of the formatting API. * Normally, instances are extracted from another formatter. * Note however that any formatter specific information, such as the locale, * time-zone, chronology, offset parsing or pivot/default year, will not be * extracted by this method. * * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if parser is null or of an invalid type */ public DateTimeFormatterBuilder appendOptional(DateTimeParser parser) { checkParser(parser); DateTimeParser[] parsers = new DateTimeParser[] {parser, null}; return append0(null, new MatchingParser(parsers)); } //----------------------------------------------------------------------- /** * Checks if the parser is non null and a provider. * * @param parser the parser to check */ private void checkParser(DateTimeParser parser) { if (parser == null) { throw new IllegalArgumentException("No parser supplied"); } } /** * Checks if the printer is non null and a provider. * * @param printer the printer to check */ private void checkPrinter(DateTimePrinter printer) { if (printer == null) { throw new IllegalArgumentException("No printer supplied"); } } private DateTimeFormatterBuilder append0(Object element) { iFormatter = null; // Add the element as both a printer and parser. iElementPairs.add(element); iElementPairs.add(element); return this; } private DateTimeFormatterBuilder append0( DateTimePrinter printer, DateTimeParser parser) { iFormatter = null; iElementPairs.add(printer); iElementPairs.add(parser); return this; } //----------------------------------------------------------------------- /** * Instructs the printer to emit a specific character, and the parser to * expect it. The parser is case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendLiteral(char c) { return append0(new CharacterLiteral(c)); } /** * Instructs the printer to emit specific text, and the parser to expect * it. The parser is case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if text is null */ public DateTimeFormatterBuilder appendLiteral(String text) { if (text == null) { throw new IllegalArgumentException("Literal must not be null"); } switch (text.length()) { case 0: return this; case 1: return append0(new CharacterLiteral(text.charAt(0))); default: return append0(new StringLiteral(text)); } } /** * Instructs the printer to emit a field value as a decimal number, and the * parser to expect an unsigned decimal number. * * @param fieldType type of field to append * @param minDigits minimum number of digits to <i>print</i> * @param maxDigits maximum number of digits to <i>parse</i>, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null */ public DateTimeFormatterBuilder appendDecimal( DateTimeFieldType fieldType, int minDigits, int maxDigits) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } if (maxDigits < minDigits) { maxDigits = minDigits; } if (minDigits < 0 || maxDigits <= 0) { throw new IllegalArgumentException(); } if (minDigits <= 1) { return append0(new UnpaddedNumber(fieldType, maxDigits, false)); } else { return append0(new PaddedNumber(fieldType, maxDigits, false, minDigits)); } } /** * Instructs the printer to emit a field value as a fixed-width decimal * number (smaller numbers will be left-padded with zeros), and the parser * to expect an unsigned decimal number with the same fixed width. * * @param fieldType type of field to append * @param numDigits the exact number of digits to parse or print, except if * printed value requires more digits * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null or if <code>numDigits <= 0</code> * @since 1.5 */ public DateTimeFormatterBuilder appendFixedDecimal( DateTimeFieldType fieldType, int numDigits) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } if (numDigits <= 0) { throw new IllegalArgumentException("Illegal number of digits: " + numDigits); } return append0(new FixedNumber(fieldType, numDigits, false)); } /** * Instructs the printer to emit a field value as a decimal number, and the * parser to expect a signed decimal number. * * @param fieldType type of field to append * @param minDigits minimum number of digits to <i>print</i> * @param maxDigits maximum number of digits to <i>parse</i>, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null */ public DateTimeFormatterBuilder appendSignedDecimal( DateTimeFieldType fieldType, int minDigits, int maxDigits) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } if (maxDigits < minDigits) { maxDigits = minDigits; } if (minDigits < 0 || maxDigits <= 0) { throw new IllegalArgumentException(); } if (minDigits <= 1) { return append0(new UnpaddedNumber(fieldType, maxDigits, true)); } else { return append0(new PaddedNumber(fieldType, maxDigits, true, minDigits)); } } /** * Instructs the printer to emit a field value as a fixed-width decimal * number (smaller numbers will be left-padded with zeros), and the parser * to expect an signed decimal number with the same fixed width. * * @param fieldType type of field to append * @param numDigits the exact number of digits to parse or print, except if * printed value requires more digits * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null or if <code>numDigits <= 0</code> * @since 1.5 */ public DateTimeFormatterBuilder appendFixedSignedDecimal( DateTimeFieldType fieldType, int numDigits) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } if (numDigits <= 0) { throw new IllegalArgumentException("Illegal number of digits: " + numDigits); } return append0(new FixedNumber(fieldType, numDigits, true)); } /** * Instructs the printer to emit a field value as text, and the * parser to expect text. * * @param fieldType type of field to append * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null */ public DateTimeFormatterBuilder appendText(DateTimeFieldType fieldType) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } return append0(new TextField(fieldType, false)); } /** * Instructs the printer to emit a field value as short text, and the * parser to expect text. * * @param fieldType type of field to append * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null */ public DateTimeFormatterBuilder appendShortText(DateTimeFieldType fieldType) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } return append0(new TextField(fieldType, true)); } /** * Instructs the printer to emit a remainder of time as a decimal fraction, * without decimal point. For example, if the field is specified as * minuteOfHour and the time is 12:30:45, the value printed is 75. A * decimal point is implied, so the fraction is 0.75, or three-quarters of * a minute. * * @param fieldType type of field to append * @param minDigits minimum number of digits to print. * @param maxDigits maximum number of digits to print or parse. * @return this DateTimeFormatterBuilder, for chaining * @throws IllegalArgumentException if field type is null */ public DateTimeFormatterBuilder appendFraction( DateTimeFieldType fieldType, int minDigits, int maxDigits) { if (fieldType == null) { throw new IllegalArgumentException("Field type must not be null"); } if (maxDigits < minDigits) { maxDigits = minDigits; } if (minDigits < 0 || maxDigits <= 0) { throw new IllegalArgumentException(); } return append0(new Fraction(fieldType, minDigits, maxDigits)); } /** * Appends the print/parse of a fractional second. * <p> * This reliably handles the case where fractional digits are being handled * beyond a visible decimal point. The digits parsed will always be treated * as the most significant (numerically largest) digits. * Thus '23' will be parsed as 230 milliseconds. * Contrast this behaviour to {@link #appendMillisOfSecond}. * This method does not print or parse the decimal point itself. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to print or parse * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendFractionOfSecond(int minDigits, int maxDigits) { return appendFraction(DateTimeFieldType.secondOfDay(), minDigits, maxDigits); } /** * Appends the print/parse of a fractional minute. * <p> * This reliably handles the case where fractional digits are being handled * beyond a visible decimal point. The digits parsed will always be treated * as the most significant (numerically largest) digits. * Thus '23' will be parsed as 0.23 minutes (converted to milliseconds). * This method does not print or parse the decimal point itself. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to print or parse * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendFractionOfMinute(int minDigits, int maxDigits) { return appendFraction(DateTimeFieldType.minuteOfDay(), minDigits, maxDigits); } /** * Appends the print/parse of a fractional hour. * <p> * This reliably handles the case where fractional digits are being handled * beyond a visible decimal point. The digits parsed will always be treated * as the most significant (numerically largest) digits. * Thus '23' will be parsed as 0.23 hours (converted to milliseconds). * This method does not print or parse the decimal point itself. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to print or parse * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendFractionOfHour(int minDigits, int maxDigits) { return appendFraction(DateTimeFieldType.hourOfDay(), minDigits, maxDigits); } /** * Appends the print/parse of a fractional day. * <p> * This reliably handles the case where fractional digits are being handled * beyond a visible decimal point. The digits parsed will always be treated * as the most significant (numerically largest) digits. * Thus '23' will be parsed as 0.23 days (converted to milliseconds). * This method does not print or parse the decimal point itself. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to print or parse * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendFractionOfDay(int minDigits, int maxDigits) { return appendFraction(DateTimeFieldType.dayOfYear(), minDigits, maxDigits); } /** * Instructs the printer to emit a numeric millisOfSecond field. * <p> * This method will append a field that prints a three digit value. * During parsing the value that is parsed is assumed to be three digits. * If less than three digits are present then they will be counted as the * smallest parts of the millisecond. This is probably not what you want * if you are using the field as a fraction. Instead, a fractional * millisecond should be produced using {@link #appendFractionOfSecond}. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMillisOfSecond(int minDigits) { return appendDecimal(DateTimeFieldType.millisOfSecond(), minDigits, 3); } /** * Instructs the printer to emit a numeric millisOfDay field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMillisOfDay(int minDigits) { return appendDecimal(DateTimeFieldType.millisOfDay(), minDigits, 8); } /** * Instructs the printer to emit a numeric secondOfMinute field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendSecondOfMinute(int minDigits) { return appendDecimal(DateTimeFieldType.secondOfMinute(), minDigits, 2); } /** * Instructs the printer to emit a numeric secondOfDay field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendSecondOfDay(int minDigits) { return appendDecimal(DateTimeFieldType.secondOfDay(), minDigits, 5); } /** * Instructs the printer to emit a numeric minuteOfHour field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMinuteOfHour(int minDigits) { return appendDecimal(DateTimeFieldType.minuteOfHour(), minDigits, 2); } /** * Instructs the printer to emit a numeric minuteOfDay field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMinuteOfDay(int minDigits) { return appendDecimal(DateTimeFieldType.minuteOfDay(), minDigits, 4); } /** * Instructs the printer to emit a numeric hourOfDay field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendHourOfDay(int minDigits) { return appendDecimal(DateTimeFieldType.hourOfDay(), minDigits, 2); } /** * Instructs the printer to emit a numeric clockhourOfDay field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendClockhourOfDay(int minDigits) { return appendDecimal(DateTimeFieldType.clockhourOfDay(), minDigits, 2); } /** * Instructs the printer to emit a numeric hourOfHalfday field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendHourOfHalfday(int minDigits) { return appendDecimal(DateTimeFieldType.hourOfHalfday(), minDigits, 2); } /** * Instructs the printer to emit a numeric clockhourOfHalfday field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendClockhourOfHalfday(int minDigits) { return appendDecimal(DateTimeFieldType.clockhourOfHalfday(), minDigits, 2); } /** * Instructs the printer to emit a numeric dayOfWeek field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendDayOfWeek(int minDigits) { return appendDecimal(DateTimeFieldType.dayOfWeek(), minDigits, 1); } /** * Instructs the printer to emit a numeric dayOfMonth field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendDayOfMonth(int minDigits) { return appendDecimal(DateTimeFieldType.dayOfMonth(), minDigits, 2); } /** * Instructs the printer to emit a numeric dayOfYear field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendDayOfYear(int minDigits) { return appendDecimal(DateTimeFieldType.dayOfYear(), minDigits, 3); } /** * Instructs the printer to emit a numeric weekOfWeekyear field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendWeekOfWeekyear(int minDigits) { return appendDecimal(DateTimeFieldType.weekOfWeekyear(), minDigits, 2); } /** * Instructs the printer to emit a numeric weekyear field. * * @param minDigits minimum number of digits to <i>print</i> * @param maxDigits maximum number of digits to <i>parse</i>, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendWeekyear(int minDigits, int maxDigits) { return appendSignedDecimal(DateTimeFieldType.weekyear(), minDigits, maxDigits); } /** * Instructs the printer to emit a numeric monthOfYear field. * * @param minDigits minimum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMonthOfYear(int minDigits) { return appendDecimal(DateTimeFieldType.monthOfYear(), minDigits, 2); } /** * Instructs the printer to emit a numeric year field. * * @param minDigits minimum number of digits to <i>print</i> * @param maxDigits maximum number of digits to <i>parse</i>, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendYear(int minDigits, int maxDigits) { return appendSignedDecimal(DateTimeFieldType.year(), minDigits, maxDigits); } /** * Instructs the printer to emit a numeric year field which always prints * and parses two digits. A pivot year is used during parsing to determine * the range of supported years as <code>(pivot - 50) .. (pivot + 49)</code>. * * <pre> * pivot supported range 00 is 20 is 40 is 60 is 80 is * --------------------------------------------------------------- * 1950 1900..1999 1900 1920 1940 1960 1980 * 1975 1925..2024 2000 2020 1940 1960 1980 * 2000 1950..2049 2000 2020 2040 1960 1980 * 2025 1975..2074 2000 2020 2040 2060 1980 * 2050 2000..2099 2000 2020 2040 2060 2080 * </pre> * * @param pivot pivot year to use when parsing * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTwoDigitYear(int pivot) { return appendTwoDigitYear(pivot, false); } /** * Instructs the printer to emit a numeric year field which always prints * two digits. A pivot year is used during parsing to determine the range * of supported years as <code>(pivot - 50) .. (pivot + 49)</code>. If * parse is instructed to be lenient and the digit count is not two, it is * treated as an absolute year. With lenient parsing, specifying a positive * or negative sign before the year also makes it absolute. * * @param pivot pivot year to use when parsing * @param lenientParse when true, if digit count is not two, it is treated * as an absolute year * @return this DateTimeFormatterBuilder, for chaining * @since 1.1 */ public DateTimeFormatterBuilder appendTwoDigitYear(int pivot, boolean lenientParse) { return append0(new TwoDigitYear(DateTimeFieldType.year(), pivot, lenientParse)); } /** * Instructs the printer to emit a numeric weekyear field which always prints * and parses two digits. A pivot year is used during parsing to determine * the range of supported years as <code>(pivot - 50) .. (pivot + 49)</code>. * * <pre> * pivot supported range 00 is 20 is 40 is 60 is 80 is * --------------------------------------------------------------- * 1950 1900..1999 1900 1920 1940 1960 1980 * 1975 1925..2024 2000 2020 1940 1960 1980 * 2000 1950..2049 2000 2020 2040 1960 1980 * 2025 1975..2074 2000 2020 2040 2060 1980 * 2050 2000..2099 2000 2020 2040 2060 2080 * </pre> * * @param pivot pivot weekyear to use when parsing * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTwoDigitWeekyear(int pivot) { return appendTwoDigitWeekyear(pivot, false); } /** * Instructs the printer to emit a numeric weekyear field which always prints * two digits. A pivot year is used during parsing to determine the range * of supported years as <code>(pivot - 50) .. (pivot + 49)</code>. If * parse is instructed to be lenient and the digit count is not two, it is * treated as an absolute weekyear. With lenient parsing, specifying a positive * or negative sign before the weekyear also makes it absolute. * * @param pivot pivot weekyear to use when parsing * @param lenientParse when true, if digit count is not two, it is treated * as an absolute weekyear * @return this DateTimeFormatterBuilder, for chaining * @since 1.1 */ public DateTimeFormatterBuilder appendTwoDigitWeekyear(int pivot, boolean lenientParse) { return append0(new TwoDigitYear(DateTimeFieldType.weekyear(), pivot, lenientParse)); } /** * Instructs the printer to emit a numeric yearOfEra field. * * @param minDigits minimum number of digits to <i>print</i> * @param maxDigits maximum number of digits to <i>parse</i>, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendYearOfEra(int minDigits, int maxDigits) { return appendDecimal(DateTimeFieldType.yearOfEra(), minDigits, maxDigits); } /** * Instructs the printer to emit a numeric year of century field. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to <i>parse</i>, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendYearOfCentury(int minDigits, int maxDigits) { return appendDecimal(DateTimeFieldType.yearOfCentury(), minDigits, maxDigits); } /** * Instructs the printer to emit a numeric century of era field. * * @param minDigits minimum number of digits to print * @param maxDigits maximum number of digits to <i>parse</i>, or the estimated * maximum number of digits to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendCenturyOfEra(int minDigits, int maxDigits) { return appendSignedDecimal(DateTimeFieldType.centuryOfEra(), minDigits, maxDigits); } /** * Instructs the printer to emit a locale-specific AM/PM text, and the * parser to expect it. The parser is case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendHalfdayOfDayText() { return appendText(DateTimeFieldType.halfdayOfDay()); } /** * Instructs the printer to emit a locale-specific dayOfWeek text. The * parser will accept a long or short dayOfWeek text, case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendDayOfWeekText() { return appendText(DateTimeFieldType.dayOfWeek()); } /** * Instructs the printer to emit a short locale-specific dayOfWeek * text. The parser will accept a long or short dayOfWeek text, * case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendDayOfWeekShortText() { return appendShortText(DateTimeFieldType.dayOfWeek()); } /** * Instructs the printer to emit a short locale-specific monthOfYear * text. The parser will accept a long or short monthOfYear text, * case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMonthOfYearText() { return appendText(DateTimeFieldType.monthOfYear()); } /** * Instructs the printer to emit a locale-specific monthOfYear text. The * parser will accept a long or short monthOfYear text, case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendMonthOfYearShortText() { return appendShortText(DateTimeFieldType.monthOfYear()); } /** * Instructs the printer to emit a locale-specific era text (BC/AD), and * the parser to expect it. The parser is case-insensitive. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendEraText() { return appendText(DateTimeFieldType.era()); } /** * Instructs the printer to emit a locale-specific time zone name. * Using this method prevents parsing, because time zone names are not unique. * See {@link #appendTimeZoneName(Map)}. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneName() { return append0(new TimeZoneName(TimeZoneName.LONG_NAME, null), null); } /** * Instructs the printer to emit a locale-specific time zone name, providing a lookup for parsing. * Time zone names are not unique, thus the API forces you to supply the lookup. * The names are searched in the order of the map, thus it is strongly recommended * to use a {@code LinkedHashMap} or similar. * * @param parseLookup the table of names, not null * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneName(Map<String, DateTimeZone> parseLookup) { TimeZoneName pp = new TimeZoneName(TimeZoneName.LONG_NAME, parseLookup); return append0(pp, pp); } /** * Instructs the printer to emit a short locale-specific time zone name. * Using this method prevents parsing, because time zone names are not unique. * See {@link #appendTimeZoneShortName(Map)}. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneShortName() { return append0(new TimeZoneName(TimeZoneName.SHORT_NAME, null), null); } /** * Instructs the printer to emit a short locale-specific time zone * name, providing a lookup for parsing. * Time zone names are not unique, thus the API forces you to supply the lookup. * The names are searched in the order of the map, thus it is strongly recommended * to use a {@code LinkedHashMap} or similar. * * @param parseLookup the table of names, null to use the {@link DateTimeUtils#getDefaultTimeZoneNames() default names} * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneShortName(Map<String, DateTimeZone> parseLookup) { TimeZoneName pp = new TimeZoneName(TimeZoneName.SHORT_NAME, parseLookup); return append0(pp, pp); } /** * Instructs the printer to emit the identifier of the time zone. * From version 2.0, this field can be parsed. * * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneId() { return append0(TimeZoneId.INSTANCE, TimeZoneId.INSTANCE); } /** * Instructs the printer to emit text and numbers to display time zone * offset from UTC. A parser will use the parsed time zone offset to adjust * the datetime. * <p> * If zero offset text is supplied, then it will be printed when the zone is zero. * During parsing, either the zero offset text, or the offset will be parsed. * * @param zeroOffsetText the text to use if time zone offset is zero. If * null, offset is always shown. * @param showSeparators if true, prints ':' separator before minute and * second field and prints '.' separator before fraction field. * @param minFields minimum number of fields to print, stopping when no * more precision is required. 1=hours, 2=minutes, 3=seconds, 4=fraction * @param maxFields maximum number of fields to print * @return this DateTimeFormatterBuilder, for chaining */ public DateTimeFormatterBuilder appendTimeZoneOffset( String zeroOffsetText, boolean showSeparators, int minFields, int maxFields) { return append0(new TimeZoneOffset (zeroOffsetText, zeroOffsetText, showSeparators, minFields, maxFields)); } /** * Instructs the printer to emit text and numbers to display time zone * offset from UTC. A parser will use the parsed time zone offset to adjust * the datetime. * <p> * If zero offset print text is supplied, then it will be printed when the zone is zero. * If zero offset parse text is supplied, then either it or the offset will be parsed. * * @param zeroOffsetPrintText the text to print if time zone offset is zero. If * null, offset is always shown. * @param zeroOffsetParseText the text to optionally parse to indicate that the time * zone offset is zero. If null, then always use the offset. * @param showSeparators if true, prints ':' separator before minute and * second field and prints '.' separator before fraction field. * @param minFields minimum number of fields to print, stopping when no * more precision is required. 1=hours, 2=minutes, 3=seconds, 4=fraction * @param maxFields maximum number of fields to print * @return this DateTimeFormatterBuilder, for chaining * @since 2.0 */ public DateTimeFormatterBuilder appendTimeZoneOffset( String zeroOffsetPrintText, String zeroOffsetParseText, boolean showSeparators, int minFields, int maxFields) { return append0(new TimeZoneOffset (zeroOffsetPrintText, zeroOffsetParseText, showSeparators, minFields, maxFields)); } //----------------------------------------------------------------------- /** * Calls upon {@link DateTimeFormat} to parse the pattern and append the * results into this builder. * * @param pattern pattern specification * @throws IllegalArgumentException if the pattern is invalid * @see DateTimeFormat */ public DateTimeFormatterBuilder appendPattern(String pattern) { DateTimeFormat.appendPatternTo(this, pattern); return this; } //----------------------------------------------------------------------- private Object getFormatter() { Object f = iFormatter; if (f == null) { if (iElementPairs.size() == 2) { Object printer = iElementPairs.get(0); Object parser = iElementPairs.get(1); if (printer != null) { if (printer == parser || parser == null) { f = printer; } } else { f = parser; } } if (f == null) { f = new Composite(iElementPairs); } iFormatter = f; } return f; } private boolean isPrinter(Object f) { if (f instanceof DateTimePrinter) { if (f instanceof Composite) { return ((Composite)f).isPrinter(); } return true; } return false; } private boolean isParser(Object f) { if (f instanceof DateTimeParser) { if (f instanceof Composite) { return ((Composite)f).isParser(); } return true; } return false; } private boolean isFormatter(Object f) { return (isPrinter(f) || isParser(f)); } static void appendUnknownString(StringBuffer buf, int len) { for (int i = len; --i >= 0;) { buf.append('\ufffd'); } } static void printUnknownString(Writer out, int len) throws IOException { for (int i = len; --i >= 0;) { out.write('\ufffd'); } } //----------------------------------------------------------------------- static class CharacterLiteral implements DateTimePrinter, DateTimeParser { private final char iValue; CharacterLiteral(char value) { super(); iValue = value; } public int estimatePrintedLength() { return 1; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { buf.append(iValue); } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { out.write(iValue); } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { buf.append(iValue); } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { out.write(iValue); } public int estimateParsedLength() { return 1; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { if (position >= text.length()) { return ~position; } char a = text.charAt(position); char b = iValue; if (a != b) { a = Character.toUpperCase(a); b = Character.toUpperCase(b); if (a != b) { a = Character.toLowerCase(a); b = Character.toLowerCase(b); if (a != b) { return ~position; } } } return position + 1; } } //----------------------------------------------------------------------- static class StringLiteral implements DateTimePrinter, DateTimeParser { private final String iValue; StringLiteral(String value) { super(); iValue = value; } public int estimatePrintedLength() { return iValue.length(); } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { buf.append(iValue); } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { out.write(iValue); } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { buf.append(iValue); } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { out.write(iValue); } public int estimateParsedLength() { return iValue.length(); } public int parseInto(DateTimeParserBucket bucket, String text, int position) { if (text.regionMatches(true, position, iValue, 0, iValue.length())) { return position + iValue.length(); } return ~position; } } //----------------------------------------------------------------------- static abstract class NumberFormatter implements DateTimePrinter, DateTimeParser { protected final DateTimeFieldType iFieldType; protected final int iMaxParsedDigits; protected final boolean iSigned; NumberFormatter(DateTimeFieldType fieldType, int maxParsedDigits, boolean signed) { super(); iFieldType = fieldType; iMaxParsedDigits = maxParsedDigits; iSigned = signed; } public int estimateParsedLength() { return iMaxParsedDigits; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { int limit = Math.min(iMaxParsedDigits, text.length() - position); boolean negative = false; int length = 0; while (length < limit) { char c = text.charAt(position + length); if (length == 0 && (c == '-' || c == '+') && iSigned) { negative = c == '-'; // Next character must be a digit. if (length + 1 >= limit || (c = text.charAt(position + length + 1)) < '0' || c > '9') { break; } if (negative) { length++; } else { // Skip the '+' for parseInt to succeed. position++; } // Expand the limit to disregard the sign character. limit = Math.min(limit + 1, text.length() - position); continue; } if (c < '0' || c > '9') { break; } length++; } if (length == 0) { return ~position; } int value; if (length >= 9) { // Since value may exceed integer limits, use stock parser // which checks for this. value = Integer.parseInt(text.substring(position, position += length)); } else { int i = position; if (negative) { i++; } try { value = text.charAt(i++) - '0'; } catch (StringIndexOutOfBoundsException e) { return ~position; } position += length; while (i < position) { value = ((value << 3) + (value << 1)) + text.charAt(i++) - '0'; } if (negative) { value = -value; } } bucket.saveField(iFieldType, value); return position; } } //----------------------------------------------------------------------- static class UnpaddedNumber extends NumberFormatter { protected UnpaddedNumber(DateTimeFieldType fieldType, int maxParsedDigits, boolean signed) { super(fieldType, maxParsedDigits, signed); } public int estimatePrintedLength() { return iMaxParsedDigits; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { try { DateTimeField field = iFieldType.getField(chrono); FormatUtils.appendUnpaddedInteger(buf, field.get(instant)); } catch (RuntimeException e) { buf.append('\ufffd'); } } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { try { DateTimeField field = iFieldType.getField(chrono); FormatUtils.writeUnpaddedInteger(out, field.get(instant)); } catch (RuntimeException e) { out.write('\ufffd'); } } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { if (partial.isSupported(iFieldType)) { try { FormatUtils.appendUnpaddedInteger(buf, partial.get(iFieldType)); } catch (RuntimeException e) { buf.append('\ufffd'); } } else { buf.append('\ufffd'); } } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { if (partial.isSupported(iFieldType)) { try { FormatUtils.writeUnpaddedInteger(out, partial.get(iFieldType)); } catch (RuntimeException e) { out.write('\ufffd'); } } else { out.write('\ufffd'); } } } //----------------------------------------------------------------------- static class PaddedNumber extends NumberFormatter { protected final int iMinPrintedDigits; protected PaddedNumber(DateTimeFieldType fieldType, int maxParsedDigits, boolean signed, int minPrintedDigits) { super(fieldType, maxParsedDigits, signed); iMinPrintedDigits = minPrintedDigits; } public int estimatePrintedLength() { return iMaxParsedDigits; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { try { DateTimeField field = iFieldType.getField(chrono); FormatUtils.appendPaddedInteger(buf, field.get(instant), iMinPrintedDigits); } catch (RuntimeException e) { appendUnknownString(buf, iMinPrintedDigits); } } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { try { DateTimeField field = iFieldType.getField(chrono); FormatUtils.writePaddedInteger(out, field.get(instant), iMinPrintedDigits); } catch (RuntimeException e) { printUnknownString(out, iMinPrintedDigits); } } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { if (partial.isSupported(iFieldType)) { try { FormatUtils.appendPaddedInteger(buf, partial.get(iFieldType), iMinPrintedDigits); } catch (RuntimeException e) { appendUnknownString(buf, iMinPrintedDigits); } } else { appendUnknownString(buf, iMinPrintedDigits); } } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { if (partial.isSupported(iFieldType)) { try { FormatUtils.writePaddedInteger(out, partial.get(iFieldType), iMinPrintedDigits); } catch (RuntimeException e) { printUnknownString(out, iMinPrintedDigits); } } else { printUnknownString(out, iMinPrintedDigits); } } } //----------------------------------------------------------------------- static class FixedNumber extends PaddedNumber { protected FixedNumber(DateTimeFieldType fieldType, int numDigits, boolean signed) { super(fieldType, numDigits, signed, numDigits); } public int parseInto(DateTimeParserBucket bucket, String text, int position) { int newPos = super.parseInto(bucket, text, position); if (newPos < 0) { return newPos; } int expectedPos = position + iMaxParsedDigits; if (newPos != expectedPos) { if (iSigned) { char c = text.charAt(position); if (c == '-' || c == '+') { expectedPos++; } } if (newPos > expectedPos) { // The failure is at the position of the first extra digit. return ~(expectedPos + 1); } else if (newPos < expectedPos) { // The failure is at the position where the next digit should be. return ~newPos; } } return newPos; } } //----------------------------------------------------------------------- static class TwoDigitYear implements DateTimePrinter, DateTimeParser { /** The field to print/parse. */ private final DateTimeFieldType iType; /** The pivot year. */ private final int iPivot; private final boolean iLenientParse; TwoDigitYear(DateTimeFieldType type, int pivot, boolean lenientParse) { super(); iType = type; iPivot = pivot; iLenientParse = lenientParse; } public int estimateParsedLength() { return iLenientParse ? 4 : 2; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { int limit = text.length() - position; if (!iLenientParse) { limit = Math.min(2, limit); if (limit < 2) { return ~position; } } else { boolean hasSignChar = false; boolean negative = false; int length = 0; while (length < limit) { char c = text.charAt(position + length); if (length == 0 && (c == '-' || c == '+')) { hasSignChar = true; negative = c == '-'; if (negative) { length++; } else { // Skip the '+' for parseInt to succeed. position++; limit--; } continue; } if (c < '0' || c > '9') { break; } length++; } if (length == 0) { return ~position; } if (hasSignChar || length != 2) { int value; if (length >= 9) { // Since value may exceed integer limits, use stock // parser which checks for this. value = Integer.parseInt(text.substring(position, position += length)); } else { int i = position; if (negative) { i++; } try { value = text.charAt(i++) - '0'; } catch (StringIndexOutOfBoundsException e) { return ~position; } position += length; while (i < position) { value = ((value << 3) + (value << 1)) + text.charAt(i++) - '0'; } if (negative) { value = -value; } } bucket.saveField(iType, value); return position; } } int year; char c = text.charAt(position); if (c < '0' || c > '9') { return ~position; } year = c - '0'; c = text.charAt(position + 1); if (c < '0' || c > '9') { return ~position; } year = ((year << 3) + (year << 1)) + c - '0'; int pivot = iPivot; // If the bucket pivot year is non-null, use that when parsing if (bucket.getPivotYear() != null) { pivot = bucket.getPivotYear().intValue(); } int low = pivot - 50; int t; if (low >= 0) { t = low % 100; } else { t = 99 + ((low + 1) % 100); } year += low + ((year < t) ? 100 : 0) - t; bucket.saveField(iType, year); return position + 2; } public int estimatePrintedLength() { return 2; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { int year = getTwoDigitYear(instant, chrono); if (year < 0) { buf.append('\ufffd'); buf.append('\ufffd'); } else { FormatUtils.appendPaddedInteger(buf, year, 2); } } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { int year = getTwoDigitYear(instant, chrono); if (year < 0) { out.write('\ufffd'); out.write('\ufffd'); } else { FormatUtils.writePaddedInteger(out, year, 2); } } private int getTwoDigitYear(long instant, Chronology chrono) { try { int year = iType.getField(chrono).get(instant); if (year < 0) { year = -year; } return year % 100; } catch (RuntimeException e) { return -1; } } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { int year = getTwoDigitYear(partial); if (year < 0) { buf.append('\ufffd'); buf.append('\ufffd'); } else { FormatUtils.appendPaddedInteger(buf, year, 2); } } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { int year = getTwoDigitYear(partial); if (year < 0) { out.write('\ufffd'); out.write('\ufffd'); } else { FormatUtils.writePaddedInteger(out, year, 2); } } private int getTwoDigitYear(ReadablePartial partial) { if (partial.isSupported(iType)) { try { int year = partial.get(iType); if (year < 0) { year = -year; } return year % 100; } catch (RuntimeException e) {} } return -1; } } //----------------------------------------------------------------------- static class TextField implements DateTimePrinter, DateTimeParser { private static Map<Locale, Map<DateTimeFieldType, Object[]>> cParseCache = new HashMap<Locale, Map<DateTimeFieldType, Object[]>>(); private final DateTimeFieldType iFieldType; private final boolean iShort; TextField(DateTimeFieldType fieldType, boolean isShort) { super(); iFieldType = fieldType; iShort = isShort; } public int estimatePrintedLength() { return iShort ? 6 : 20; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { try { buf.append(print(instant, chrono, locale)); } catch (RuntimeException e) { buf.append('\ufffd'); } } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { try { out.write(print(instant, chrono, locale)); } catch (RuntimeException e) { out.write('\ufffd'); } } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { try { buf.append(print(partial, locale)); } catch (RuntimeException e) { buf.append('\ufffd'); } } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { try { out.write(print(partial, locale)); } catch (RuntimeException e) { out.write('\ufffd'); } } private String print(long instant, Chronology chrono, Locale locale) { DateTimeField field = iFieldType.getField(chrono); if (iShort) { return field.getAsShortText(instant, locale); } else { return field.getAsText(instant, locale); } } private String print(ReadablePartial partial, Locale locale) { if (partial.isSupported(iFieldType)) { DateTimeField field = iFieldType.getField(partial.getChronology()); if (iShort) { return field.getAsShortText(partial, locale); } else { return field.getAsText(partial, locale); } } else { return "\ufffd"; } } public int estimateParsedLength() { return estimatePrintedLength(); } @SuppressWarnings("unchecked") public int parseInto(DateTimeParserBucket bucket, String text, int position) { Locale locale = bucket.getLocale(); // handle languages which might have non ASCII A-Z or punctuation // bug 1788282 Set<String> validValues = null; int maxLength = 0; synchronized (cParseCache) { Map<DateTimeFieldType, Object[]> innerMap = cParseCache.get(locale); if (innerMap == null) { innerMap = new HashMap<DateTimeFieldType, Object[]>(); cParseCache.put(locale, innerMap); } Object[] array = innerMap.get(iFieldType); if (array == null) { validValues = new HashSet<String>(32); MutableDateTime dt = new MutableDateTime(0L, DateTimeZone.UTC); Property property = dt.property(iFieldType); int min = property.getMinimumValueOverall(); int max = property.getMaximumValueOverall(); if (max - min > 32) { // protect against invalid fields return ~position; } maxLength = property.getMaximumTextLength(locale); for (int i = min; i <= max; i++) { property.set(i); validValues.add(property.getAsShortText(locale)); validValues.add(property.getAsShortText(locale).toLowerCase(locale)); validValues.add(property.getAsShortText(locale).toUpperCase(locale)); validValues.add(property.getAsText(locale)); validValues.add(property.getAsText(locale).toLowerCase(locale)); validValues.add(property.getAsText(locale).toUpperCase(locale)); } if ("en".equals(locale.getLanguage()) && iFieldType == DateTimeFieldType.era()) { // hack to support for parsing "BCE" and "CE" if the language is English validValues.add("BCE"); validValues.add("bce"); validValues.add("CE"); validValues.add("ce"); maxLength = 3; } array = new Object[] {validValues, Integer.valueOf(maxLength)}; innerMap.put(iFieldType, array); } else { validValues = (Set<String>) array[0]; maxLength = ((Integer) array[1]).intValue(); } } // match the longest string first using our knowledge of the max length int limit = Math.min(text.length(), position + maxLength); for (int i = limit; i > position; i--) { String match = text.substring(position, i); if (validValues.contains(match)) { bucket.saveField(iFieldType, match, locale); return i; } } return ~position; } } //----------------------------------------------------------------------- static class Fraction implements DateTimePrinter, DateTimeParser { private final DateTimeFieldType iFieldType; protected int iMinDigits; protected int iMaxDigits; protected Fraction(DateTimeFieldType fieldType, int minDigits, int maxDigits) { super(); iFieldType = fieldType; // Limit the precision requirements. if (maxDigits > 18) { maxDigits = 18; } iMinDigits = minDigits; iMaxDigits = maxDigits; } public int estimatePrintedLength() { return iMaxDigits; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { try { printTo(buf, null, instant, chrono); } catch (IOException e) { // Not gonna happen. } } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { printTo(null, out, instant, chrono); } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { // removed check whether field is supported, as input field is typically // secondOfDay which is unsupported by TimeOfDay long millis = partial.getChronology().set(partial, 0L); try { printTo(buf, null, millis, partial.getChronology()); } catch (IOException e) { // Not gonna happen. } } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { // removed check whether field is supported, as input field is typically // secondOfDay which is unsupported by TimeOfDay long millis = partial.getChronology().set(partial, 0L); printTo(null, out, millis, partial.getChronology()); } protected void printTo(StringBuffer buf, Writer out, long instant, Chronology chrono) throws IOException { DateTimeField field = iFieldType.getField(chrono); int minDigits = iMinDigits; long fraction; try { fraction = field.remainder(instant); } catch (RuntimeException e) { if (buf != null) { appendUnknownString(buf, minDigits); } else { printUnknownString(out, minDigits); } return; } if (fraction == 0) { if (buf != null) { while (--minDigits >= 0) { buf.append('0'); } } else { while (--minDigits >= 0) { out.write('0'); } } return; } String str; long[] fractionData = getFractionData(fraction, field); long scaled = fractionData[0]; int maxDigits = (int) fractionData[1]; if ((scaled & 0x7fffffff) == scaled) { str = Integer.toString((int) scaled); } else { str = Long.toString(scaled); } int length = str.length(); int digits = maxDigits; while (length < digits) { if (buf != null) { buf.append('0'); } else { out.write('0'); } minDigits--; digits--; } if (minDigits < digits) { // Chop off as many trailing zero digits as necessary. while (minDigits < digits) { if (length <= 1 || str.charAt(length - 1) != '0') { break; } digits--; length--; } if (length < str.length()) { if (buf != null) { for (int i=0; i<length; i++) { buf.append(str.charAt(i)); } } else { for (int i=0; i<length; i++) { out.write(str.charAt(i)); } } return; } } if (buf != null) { buf.append(str); } else { out.write(str); } } private long[] getFractionData(long fraction, DateTimeField field) { long rangeMillis = field.getDurationField().getUnitMillis(); long scalar; int maxDigits = iMaxDigits; while (true) { switch (maxDigits) { default: scalar = 1L; break; case 1: scalar = 10L; break; case 2: scalar = 100L; break; case 3: scalar = 1000L; break; case 4: scalar = 10000L; break; case 5: scalar = 100000L; break; case 6: scalar = 1000000L; break; case 7: scalar = 10000000L; break; case 8: scalar = 100000000L; break; case 9: scalar = 1000000000L; break; case 10: scalar = 10000000000L; break; case 11: scalar = 100000000000L; break; case 12: scalar = 1000000000000L; break; case 13: scalar = 10000000000000L; break; case 14: scalar = 100000000000000L; break; case 15: scalar = 1000000000000000L; break; case 16: scalar = 10000000000000000L; break; case 17: scalar = 100000000000000000L; break; case 18: scalar = 1000000000000000000L; break; } if (((rangeMillis * scalar) / scalar) == rangeMillis) { break; } // Overflowed: scale down. maxDigits--; } return new long[] {fraction * scalar / rangeMillis, maxDigits}; } public int estimateParsedLength() { return iMaxDigits; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { DateTimeField field = iFieldType.getField(bucket.getChronology()); int limit = Math.min(iMaxDigits, text.length() - position); long value = 0; long n = field.getDurationField().getUnitMillis() * 10; int length = 0; while (length < limit) { char c = text.charAt(position + length); if (c < '0' || c > '9') { break; } length++; long nn = n / 10; value += (c - '0') * nn; n = nn; } value /= 10; if (length == 0) { return ~position; } if (value > Integer.MAX_VALUE) { return ~position; } DateTimeField parseField = new PreciseDateTimeField( DateTimeFieldType.millisOfSecond(), MillisDurationField.INSTANCE, field.getDurationField()); bucket.saveField(parseField, (int) value); return position + length; } } //----------------------------------------------------------------------- static class TimeZoneOffset implements DateTimePrinter, DateTimeParser { private final String iZeroOffsetPrintText; private final String iZeroOffsetParseText; private final boolean iShowSeparators; private final int iMinFields; private final int iMaxFields; TimeZoneOffset(String zeroOffsetPrintText, String zeroOffsetParseText, boolean showSeparators, int minFields, int maxFields) { super(); iZeroOffsetPrintText = zeroOffsetPrintText; iZeroOffsetParseText = zeroOffsetParseText; iShowSeparators = showSeparators; if (minFields <= 0 || maxFields < minFields) { throw new IllegalArgumentException(); } if (minFields > 4) { minFields = 4; maxFields = 4; } iMinFields = minFields; iMaxFields = maxFields; } public int estimatePrintedLength() { int est = 1 + iMinFields << 1; if (iShowSeparators) { est += iMinFields - 1; } if (iZeroOffsetPrintText != null && iZeroOffsetPrintText.length() > est) { est = iZeroOffsetPrintText.length(); } return est; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { if (displayZone == null) { return; // no zone } if (displayOffset == 0 && iZeroOffsetPrintText != null) { buf.append(iZeroOffsetPrintText); return; } if (displayOffset >= 0) { buf.append('+'); } else { buf.append('-'); displayOffset = -displayOffset; } int hours = displayOffset / DateTimeConstants.MILLIS_PER_HOUR; FormatUtils.appendPaddedInteger(buf, hours, 2); if (iMaxFields == 1) { return; } displayOffset -= hours * (int)DateTimeConstants.MILLIS_PER_HOUR; if (displayOffset == 0 && iMinFields <= 1) { return; } int minutes = displayOffset / DateTimeConstants.MILLIS_PER_MINUTE; if (iShowSeparators) { buf.append(':'); } FormatUtils.appendPaddedInteger(buf, minutes, 2); if (iMaxFields == 2) { return; } displayOffset -= minutes * DateTimeConstants.MILLIS_PER_MINUTE; if (displayOffset == 0 && iMinFields <= 2) { return; } int seconds = displayOffset / DateTimeConstants.MILLIS_PER_SECOND; if (iShowSeparators) { buf.append(':'); } FormatUtils.appendPaddedInteger(buf, seconds, 2); if (iMaxFields == 3) { return; } displayOffset -= seconds * DateTimeConstants.MILLIS_PER_SECOND; if (displayOffset == 0 && iMinFields <= 3) { return; } if (iShowSeparators) { buf.append('.'); } FormatUtils.appendPaddedInteger(buf, displayOffset, 3); } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { if (displayZone == null) { return; // no zone } if (displayOffset == 0 && iZeroOffsetPrintText != null) { out.write(iZeroOffsetPrintText); return; } if (displayOffset >= 0) { out.write('+'); } else { out.write('-'); displayOffset = -displayOffset; } int hours = displayOffset / DateTimeConstants.MILLIS_PER_HOUR; FormatUtils.writePaddedInteger(out, hours, 2); if (iMaxFields == 1) { return; } displayOffset -= hours * (int)DateTimeConstants.MILLIS_PER_HOUR; if (displayOffset == 0 && iMinFields == 1) { return; } int minutes = displayOffset / DateTimeConstants.MILLIS_PER_MINUTE; if (iShowSeparators) { out.write(':'); } FormatUtils.writePaddedInteger(out, minutes, 2); if (iMaxFields == 2) { return; } displayOffset -= minutes * DateTimeConstants.MILLIS_PER_MINUTE; if (displayOffset == 0 && iMinFields == 2) { return; } int seconds = displayOffset / DateTimeConstants.MILLIS_PER_SECOND; if (iShowSeparators) { out.write(':'); } FormatUtils.writePaddedInteger(out, seconds, 2); if (iMaxFields == 3) { return; } displayOffset -= seconds * DateTimeConstants.MILLIS_PER_SECOND; if (displayOffset == 0 && iMinFields == 3) { return; } if (iShowSeparators) { out.write('.'); } FormatUtils.writePaddedInteger(out, displayOffset, 3); } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { // no zone info } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { // no zone info } public int estimateParsedLength() { return estimatePrintedLength(); } public int parseInto(DateTimeParserBucket bucket, String text, int position) { int limit = text.length() - position; zeroOffset: if (iZeroOffsetParseText != null) { if (iZeroOffsetParseText.length() == 0) { // Peek ahead, looking for sign character. if (limit > 0) { char c = text.charAt(position); if (c == '-' || c == '+') { break zeroOffset; } } bucket.setOffset(Integer.valueOf(0)); return position; } if (text.regionMatches(true, position, iZeroOffsetParseText, 0, iZeroOffsetParseText.length())) { bucket.setOffset(Integer.valueOf(0)); return position + iZeroOffsetParseText.length(); } } // Format to expect is sign character followed by at least one digit. if (limit <= 1) { return ~position; } boolean negative; char c = text.charAt(position); if (c == '-') { negative = true; } else if (c == '+') { negative = false; } else { return ~position; } limit--; position++; // Format following sign is one of: // // hh // hhmm // hhmmss // hhmmssSSS // hh:mm // hh:mm:ss // hh:mm:ss.SSS // First parse hours. if (digitCount(text, position, 2) < 2) { // Need two digits for hour. return ~position; } int offset; int hours = FormatUtils.parseTwoDigits(text, position); if (hours > 23) { return ~position; } offset = hours * DateTimeConstants.MILLIS_PER_HOUR; limit -= 2; position += 2; parse: { // Need to decide now if separators are expected or parsing // stops at hour field. if (limit <= 0) { break parse; } boolean expectSeparators; c = text.charAt(position); if (c == ':') { expectSeparators = true; limit--; position++; } else if (c >= '0' && c <= '9') { expectSeparators = false; } else { break parse; } // Proceed to parse minutes. int count = digitCount(text, position, 2); if (count == 0 && !expectSeparators) { break parse; } else if (count < 2) { // Need two digits for minute. return ~position; } int minutes = FormatUtils.parseTwoDigits(text, position); if (minutes > 59) { return ~position; } offset += minutes * DateTimeConstants.MILLIS_PER_MINUTE; limit -= 2; position += 2; // Proceed to parse seconds. if (limit <= 0) { break parse; } if (expectSeparators) { if (text.charAt(position) != ':') { break parse; } limit--; position++; } count = digitCount(text, position, 2); if (count == 0 && !expectSeparators) { break parse; } else if (count < 2) { // Need two digits for second. return ~position; } int seconds = FormatUtils.parseTwoDigits(text, position); if (seconds > 59) { return ~position; } offset += seconds * DateTimeConstants.MILLIS_PER_SECOND; limit -= 2; position += 2; // Proceed to parse fraction of second. if (limit <= 0) { break parse; } if (expectSeparators) { if (text.charAt(position) != '.' && text.charAt(position) != ',') { break parse; } limit--; position++; } count = digitCount(text, position, 3); if (count == 0 && !expectSeparators) { break parse; } else if (count < 1) { // Need at least one digit for fraction of second. return ~position; } offset += (text.charAt(position++) - '0') * 100; if (count > 1) { offset += (text.charAt(position++) - '0') * 10; if (count > 2) { offset += text.charAt(position++) - '0'; } } } bucket.setOffset(Integer.valueOf(negative ? -offset : offset)); return position; } /** * Returns actual amount of digits to parse, but no more than original * 'amount' parameter. */ private int digitCount(String text, int position, int amount) { int limit = Math.min(text.length() - position, amount); amount = 0; for (; limit > 0; limit--) { char c = text.charAt(position + amount); if (c < '0' || c > '9') { break; } amount++; } return amount; } } //----------------------------------------------------------------------- static class TimeZoneName implements DateTimePrinter, DateTimeParser { static final int LONG_NAME = 0; static final int SHORT_NAME = 1; private final Map<String, DateTimeZone> iParseLookup; private final int iType; TimeZoneName(int type, Map<String, DateTimeZone> parseLookup) { super(); iType = type; iParseLookup = parseLookup; } public int estimatePrintedLength() { return (iType == SHORT_NAME ? 4 : 20); } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { buf.append(print(instant - displayOffset, displayZone, locale)); } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { out.write(print(instant - displayOffset, displayZone, locale)); } private String print(long instant, DateTimeZone displayZone, Locale locale) { if (displayZone == null) { return ""; // no zone } switch (iType) { case LONG_NAME: return displayZone.getName(instant, locale); case SHORT_NAME: return displayZone.getShortName(instant, locale); } return ""; } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { // no zone info } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { // no zone info } public int estimateParsedLength() { return (iType == SHORT_NAME ? 4 : 20); } public int parseInto(DateTimeParserBucket bucket, String text, int position) { Map<String, DateTimeZone> parseLookup = iParseLookup; parseLookup = (parseLookup != null ? parseLookup : DateTimeUtils.getDefaultTimeZoneNames()); String str = text.substring(position); for (String name : parseLookup.keySet()) { if (str.startsWith(name)) { bucket.setZone(parseLookup.get(name)); return position + name.length(); } } return ~position; } } //----------------------------------------------------------------------- static enum TimeZoneId implements DateTimePrinter, DateTimeParser { INSTANCE; static final Set<String> ALL_IDS = DateTimeZone.getAvailableIDs(); static final int MAX_LENGTH; static { int max = 0; for (String id : ALL_IDS) { max = Math.max(max, id.length()); } MAX_LENGTH = max; } public int estimatePrintedLength() { return MAX_LENGTH; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { buf.append(displayZone != null ? displayZone.getID() : ""); } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { out.write(displayZone != null ? displayZone.getID() : ""); } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { // no zone info } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { // no zone info } public int estimateParsedLength() { return MAX_LENGTH; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { String str = text.substring(position); String best = null; for (String id : ALL_IDS) { if (str.startsWith(id)) { if (best == null || id.length() > best.length()) { best = id; } } } if (best != null) { bucket.setZone(DateTimeZone.forID(best)); return position + best.length(); } return ~position; } } //----------------------------------------------------------------------- static class Composite implements DateTimePrinter, DateTimeParser { private final DateTimePrinter[] iPrinters; private final DateTimeParser[] iParsers; private final int iPrintedLengthEstimate; private final int iParsedLengthEstimate; Composite(List<Object> elementPairs) { super(); List<Object> printerList = new ArrayList<Object>(); List<Object> parserList = new ArrayList<Object>(); decompose(elementPairs, printerList, parserList); if (printerList.contains(null) || printerList.isEmpty()) { iPrinters = null; iPrintedLengthEstimate = 0; } else { int size = printerList.size(); iPrinters = new DateTimePrinter[size]; int printEst = 0; for (int i=0; i<size; i++) { DateTimePrinter printer = (DateTimePrinter) printerList.get(i); printEst += printer.estimatePrintedLength(); iPrinters[i] = printer; } iPrintedLengthEstimate = printEst; } if (parserList.contains(null) || parserList.isEmpty()) { iParsers = null; iParsedLengthEstimate = 0; } else { int size = parserList.size(); iParsers = new DateTimeParser[size]; int parseEst = 0; for (int i=0; i<size; i++) { DateTimeParser parser = (DateTimeParser) parserList.get(i); parseEst += parser.estimateParsedLength(); iParsers[i] = parser; } iParsedLengthEstimate = parseEst; } } public int estimatePrintedLength() { return iPrintedLengthEstimate; } public void printTo( StringBuffer buf, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) { DateTimePrinter[] elements = iPrinters; if (elements == null) { throw new UnsupportedOperationException(); } if (locale == null) { // Guard against default locale changing concurrently. locale = Locale.getDefault(); } int len = elements.length; for (int i = 0; i < len; i++) { elements[i].printTo(buf, instant, chrono, displayOffset, displayZone, locale); } } public void printTo( Writer out, long instant, Chronology chrono, int displayOffset, DateTimeZone displayZone, Locale locale) throws IOException { DateTimePrinter[] elements = iPrinters; if (elements == null) { throw new UnsupportedOperationException(); } if (locale == null) { // Guard against default locale changing concurrently. locale = Locale.getDefault(); } int len = elements.length; for (int i = 0; i < len; i++) { elements[i].printTo(out, instant, chrono, displayOffset, displayZone, locale); } } public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) { DateTimePrinter[] elements = iPrinters; if (elements == null) { throw new UnsupportedOperationException(); } if (locale == null) { // Guard against default locale changing concurrently. locale = Locale.getDefault(); } int len = elements.length; for (int i=0; i<len; i++) { elements[i].printTo(buf, partial, locale); } } public void printTo(Writer out, ReadablePartial partial, Locale locale) throws IOException { DateTimePrinter[] elements = iPrinters; if (elements == null) { throw new UnsupportedOperationException(); } if (locale == null) { // Guard against default locale changing concurrently. locale = Locale.getDefault(); } int len = elements.length; for (int i=0; i<len; i++) { elements[i].printTo(out, partial, locale); } } public int estimateParsedLength() { return iParsedLengthEstimate; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { DateTimeParser[] elements = iParsers; if (elements == null) { throw new UnsupportedOperationException(); } int len = elements.length; for (int i=0; i<len && position >= 0; i++) { position = elements[i].parseInto(bucket, text, position); } return position; } boolean isPrinter() { return iPrinters != null; } boolean isParser() { return iParsers != null; } /** * Processes the element pairs, putting results into the given printer * and parser lists. */ private void decompose(List<Object> elementPairs, List<Object> printerList, List<Object> parserList) { int size = elementPairs.size(); for (int i=0; i<size; i+=2) { Object element = elementPairs.get(i); if (element instanceof Composite) { addArrayToList(printerList, ((Composite)element).iPrinters); } else { printerList.add(element); } element = elementPairs.get(i + 1); if (element instanceof Composite) { addArrayToList(parserList, ((Composite)element).iParsers); } else { parserList.add(element); } } } private void addArrayToList(List<Object> list, Object[] array) { if (array != null) { for (int i=0; i<array.length; i++) { list.add(array[i]); } } } } //----------------------------------------------------------------------- static class MatchingParser implements DateTimeParser { private final DateTimeParser[] iParsers; private final int iParsedLengthEstimate; MatchingParser(DateTimeParser[] parsers) { super(); iParsers = parsers; int est = 0; for (int i=parsers.length; --i>=0 ;) { DateTimeParser parser = parsers[i]; if (parser != null) { int len = parser.estimateParsedLength(); if (len > est) { est = len; } } } iParsedLengthEstimate = est; } public int estimateParsedLength() { return iParsedLengthEstimate; } public int parseInto(DateTimeParserBucket bucket, String text, int position) { DateTimeParser[] parsers = iParsers; int length = parsers.length; final Object originalState = bucket.saveState(); boolean isOptional = false; int bestValidPos = position; Object bestValidState = null; int bestInvalidPos = position; for (int i=0; i<length; i++) { DateTimeParser parser = parsers[i]; if (parser == null) { // The empty parser wins only if nothing is better. if (bestValidPos <= position) { return position; } isOptional = true; break; } int parsePos = parser.parseInto(bucket, text, position); if (parsePos >= position) { if (parsePos > bestValidPos) { if (parsePos >= text.length() || (i + 1) >= length || parsers[i + 1] == null) { // Completely parsed text or no more parsers to // check. Skip the rest. return parsePos; } bestValidPos = parsePos; bestValidState = bucket.saveState(); } } else { if (parsePos < 0) { parsePos = ~parsePos; if (parsePos > bestInvalidPos) { bestInvalidPos = parsePos; } } } bucket.restoreState(originalState); } if (bestValidPos > position || (bestValidPos == position && isOptional)) { // Restore the state to the best valid parse. if (bestValidState != null) { bucket.restoreState(bestValidState); } return bestValidPos; } return ~bestInvalidPos; } } }
gpl-2.0
acsid/stendhal
tests/utilities/RPClass/ItemTestHelper.java
1746
/* $Id$ */ /*************************************************************************** * (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. * * * ***************************************************************************/ package utilities.RPClass; import marauroa.common.game.RPClass; import games.stendhal.server.entity.item.Item; import games.stendhal.server.entity.item.StackableItem; public class ItemTestHelper { public static Item createItem() { ItemTestHelper.generateRPClasses(); return new Item("item", "itemclass", "subclass", null); } public static Item createItem(final String name) { ItemTestHelper.generateRPClasses(); return new Item(name, "itemclass", "subclass", null); } public static Item createItem(final String name, final int quantity) { ItemTestHelper.generateRPClasses(); final StackableItem item = new StackableItem(name, "itemclass", "subclass", null); item.setQuantity(quantity); return item; } public static void generateRPClasses() { EntityTestHelper.generateRPClasses(); if (!RPClass.hasRPClass("item")) { Item.generateRPClass(); } } }
gpl-2.0
lightryuzaki/project1
src/scripting/AbstractScriptManager.java
2595
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package scripting; import client.MapleClient; import java.io.File; import java.io.FileReader; import java.io.IOException; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import constants.ServerConstants; import tools.FilePrinter; /** * * @author Matze */ public abstract class AbstractScriptManager { protected ScriptEngine engine; private ScriptEngineManager sem; protected AbstractScriptManager() { sem = new ScriptEngineManager(); } protected Invocable getInvocable(String path, MapleClient c) { path = "scripts/" + path; engine = null; if (c != null) { engine = c.getScriptEngine(path); } if (engine == null) { File scriptFile = new File(path); if (!scriptFile.exists()) { return null; } engine = sem.getEngineByName("javascript"); if (c != null) { c.setScriptEngine(path, engine); } try (FileReader fr = new FileReader(scriptFile)) { if (ServerConstants.JAVA_8){ engine.eval("load('nashorn:mozilla_compat.js');"); } engine.eval(fr); } catch (final ScriptException | IOException t) { FilePrinter.printError(FilePrinter.INVOCABLE + path.substring(12, path.length()), t, path); return null; } } return (Invocable) engine; } protected void resetContext(String path, MapleClient c) { c.removeScriptEngine("scripts/" + path); } }
gpl-2.0
dls-controls/pvmanager
pvmanager-file/src/main/java/org/epics/pvmanager/file/FileFormatRegistry.java
2767
/** * Copyright (C) 2010-14 pvmanager developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.epics.pvmanager.file; import java.util.Map; import java.util.ServiceLoader; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * Place to registers file formats so that the file datasource can use them. * * @author carcassi */ public class FileFormatRegistry { private final static FileFormatRegistry registry = new FileFormatRegistry(); private static final Map<String, FileFormat> fileFormatRegistry = new ConcurrentHashMap<>(); private static final Logger log = Logger.getLogger(FileFormatRegistry.class.getName()); /** * The default registry. This registry is the one used by the framework * to look for currently supported file format. * * @return the default registry; not null */ public static FileFormatRegistry getDefault() { return registry; } static { // Find file formats to register using the ServiceLoader ServiceLoader<FileFormat> sl = ServiceLoader.load(FileFormat.class); for (FileFormat fileFormat : sl) { registry.registerFileFormat(fileFormat); } } /** * Register a new FileFormat for a given file extension * * @param extension the file extension * @param format the FileFormat */ public void registerFileFormat(String extension, FileFormat format) { log.log(Level.FINE, "File datasource: registering extension {0}", extension); fileFormatRegistry.put(extension, format); } /** * Register a new FileFormat for the extensions declared by the format * itself. * * @param format the FileFormat */ public void registerFileFormat(FileFormat format) { for (String extension : format.getFileExtensions()) { registerFileFormat(extension, format); } } /** * Find the registered FileFormat for the given file extension * * @param extension the file extension to register the file format for * @return the FileFormat registered for this extension */ public FileFormat getFileFormatFor(String extension) { return fileFormatRegistry.get(extension); } /** * Returns true if there is a FileFormat registered for the given file extension * * @param extension the file extension to register the file format for * @return true if there is a FileFormat registered for this file extension */ public boolean contains(String extension) { return fileFormatRegistry.containsKey(extension); } }
gpl-2.0
unofficial-opensource-apple/gcc_40
libjava/java/util/zip/CheckedInputStream.java
3933
/* CheckedInputStream.java - Compute checksum of data being read Copyright (C) 1999, 2000, 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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. */ package java.util.zip; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /* Written using on-line Java Platform 1.2 API Specification * and JCL book. * Believed complete and correct. */ /** * InputStream that computes a checksum of the data being read using a * supplied Checksum object. * * @see Checksum * * @author Tom Tromey * @date May 17, 1999 */ public class CheckedInputStream extends FilterInputStream { /** * Creates a new CheckInputStream on top of the supplied OutputStream * using the supplied Checksum. */ public CheckedInputStream (InputStream in, Checksum sum) { super (in); this.sum = sum; } /** * Returns the Checksum object used. To get the data checksum computed so * far call <code>getChecksum.getValue()</code>. */ public Checksum getChecksum () { return sum; } /** * Reads one byte, updates the checksum and returns the read byte * (or -1 when the end of file was reached). */ public int read () throws IOException { int x = in.read(); if (x != -1) sum.update(x); return x; } /** * Reads at most len bytes in the supplied buffer and updates the checksum * with it. Returns the number of bytes actually read or -1 when the end * of file was reached. */ public int read (byte[] buf, int off, int len) throws IOException { int r = in.read(buf, off, len); if (r != -1) sum.update(buf, off, r); return r; } /** * Skips n bytes by reading them in a temporary buffer and updating the * the checksum with that buffer. Returns the actual number of bytes skiped * which can be less then requested when the end of file is reached. */ public long skip (long n) throws IOException { if (n == 0) return 0; int min = (int) Math.min(n, 1024); byte[] buf = new byte[min]; long s = 0; while (n > 0) { int r = in.read(buf, 0, min); if (r == -1) break; n -= r; s += r; min = (int) Math.min(n, 1024); sum.update(buf, 0, r); } return s; } /** The checksum object. */ private Checksum sum; }
gpl-2.0
stelfrich/bioformats
components/forks/jai/src/com/sun/media/imageioimpl/plugins/bmp/BMPMetadataFormat.java
10293
/* * #%L * Fork of JAI Image I/O Tools. * %% * Copyright (C) 2008 - 2017 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ /* * $RCSfile: BMPMetadataFormat.java,v $ * * * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for * use in the design, construction, operation or maintenance of any * nuclear facility. * * $Revision: 1.2 $ * $Date: 2006/04/14 21:29:14 $ * $State: Exp $ */ package com.sun.media.imageioimpl.plugins.bmp; import java.util.Arrays; import javax.imageio.ImageTypeSpecifier; import javax.imageio.metadata.IIOMetadataFormat; import javax.imageio.metadata.IIOMetadataFormatImpl; public class BMPMetadataFormat extends IIOMetadataFormatImpl { private static IIOMetadataFormat instance = null; private BMPMetadataFormat() { super(BMPMetadata.nativeMetadataFormatName, CHILD_POLICY_SOME); // root -> ImageDescriptor addElement("ImageDescriptor", BMPMetadata.nativeMetadataFormatName, CHILD_POLICY_EMPTY); addAttribute("ImageDescriptor", "bmpVersion", DATATYPE_STRING, true, null); addAttribute("ImageDescriptor", "width", DATATYPE_INTEGER, true, null, "0", "65535", true, true); addAttribute("ImageDescriptor", "height", DATATYPE_INTEGER, true, null, "1", "65535", true, true); addAttribute("ImageDescriptor", "bitsPerPixel", DATATYPE_INTEGER, true, null, "1", "65535", true, true); addAttribute("ImageDescriptor", "compression", DATATYPE_INTEGER, false, null); addAttribute("ImageDescriptor", "imageSize", DATATYPE_INTEGER, true, null, "1", "65535", true, true); addElement("PixelsPerMeter", BMPMetadata.nativeMetadataFormatName, CHILD_POLICY_EMPTY); addAttribute("PixelsPerMeter", "X", DATATYPE_INTEGER, false, null, "1", "65535", true, true); addAttribute("PixelsPerMeter", "Y", DATATYPE_INTEGER, false, null, "1", "65535", true, true); addElement("ColorsUsed", BMPMetadata.nativeMetadataFormatName, CHILD_POLICY_EMPTY); addAttribute("ColorsUsed", "value", DATATYPE_INTEGER, true, null, "0", "65535", true, true); addElement("ColorsImportant", BMPMetadata.nativeMetadataFormatName, CHILD_POLICY_EMPTY); addAttribute("ColorsImportant", "value", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addElement("BI_BITFIELDS_Mask", BMPMetadata.nativeMetadataFormatName, CHILD_POLICY_EMPTY); addAttribute("BI_BITFIELDS_Mask", "red", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("BI_BITFIELDS_Mask", "green", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("BI_BITFIELDS_Mask", "blue", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addElement("ColorSpace", BMPMetadata.nativeMetadataFormatName, CHILD_POLICY_EMPTY); addAttribute("ColorSpace", "value", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addElement("LCS_CALIBRATED_RGB", BMPMetadata.nativeMetadataFormatName, CHILD_POLICY_EMPTY); /// Should the max value be 1.7976931348623157e+308 ? addAttribute("LCS_CALIBRATED_RGB", "redX", DATATYPE_DOUBLE, false, null, "0", "65535", true, true); addAttribute("LCS_CALIBRATED_RGB", "redY", DATATYPE_DOUBLE, false, null, "0", "65535", true, true); addAttribute("LCS_CALIBRATED_RGB", "redZ", DATATYPE_DOUBLE, false, null, "0", "65535", true, true); addAttribute("LCS_CALIBRATED_RGB", "greenX", DATATYPE_DOUBLE, false, null, "0", "65535", true, true); addAttribute("LCS_CALIBRATED_RGB", "greenY", DATATYPE_DOUBLE, false, null, "0", "65535", true, true); addAttribute("LCS_CALIBRATED_RGB", "greenZ", DATATYPE_DOUBLE, false, null, "0", "65535", true, true); addAttribute("LCS_CALIBRATED_RGB", "blueX", DATATYPE_DOUBLE, false, null, "0", "65535", true, true); addAttribute("LCS_CALIBRATED_RGB", "blueY", DATATYPE_DOUBLE, false, null, "0", "65535", true, true); addAttribute("LCS_CALIBRATED_RGB", "blueZ", DATATYPE_DOUBLE, false, null, "0", "65535", true, true); addElement("LCS_CALIBRATED_RGB_GAMMA", BMPMetadata.nativeMetadataFormatName, CHILD_POLICY_EMPTY); addAttribute("LCS_CALIBRATED_RGB_GAMMA","red", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("LCS_CALIBRATED_RGB_GAMMA","green", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("LCS_CALIBRATED_RGB_GAMMA","blue", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addElement("Intent", BMPMetadata.nativeMetadataFormatName, CHILD_POLICY_EMPTY); addAttribute("Intent", "value", DATATYPE_INTEGER, false, null, "0", "65535", true, true); // root -> Palette addElement("Palette", BMPMetadata.nativeMetadataFormatName, 2, 256); addAttribute("Palette", "sizeOfPalette", DATATYPE_INTEGER, true, null); addBooleanAttribute("Palette", "sortFlag", false, false); // root -> Palette -> PaletteEntry addElement("PaletteEntry", "Palette", CHILD_POLICY_EMPTY); addAttribute("PaletteEntry", "index", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("PaletteEntry", "red", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("PaletteEntry", "green", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("PaletteEntry", "blue", DATATYPE_INTEGER, true, null, "0", "255", true, true); // root -> CommentExtensions addElement("CommentExtensions", BMPMetadata.nativeMetadataFormatName, 1, Integer.MAX_VALUE); // root -> CommentExtensions -> CommentExtension addElement("CommentExtension", "CommentExtensions", CHILD_POLICY_EMPTY); addAttribute("CommentExtension", "value", DATATYPE_STRING, true, null); } public boolean canNodeAppear(String elementName, ImageTypeSpecifier imageType) { return true; } public static synchronized IIOMetadataFormat getInstance() { if (instance == null) { instance = new BMPMetadataFormat(); } return instance; } }
gpl-2.0
testmycode/tmc-checkstyle-runner
src/test/java/fi/helsinki/cs/tmc/stylerunner/validation/CheckstyleResultTest.java
1872
package fi.helsinki.cs.tmc.stylerunner.validation; import fi.helsinki.cs.tmc.langs.abstraction.ValidationError; import fi.helsinki.cs.tmc.stylerunner.CheckstyleRunner; import fi.helsinki.cs.tmc.stylerunner.exception.TMCCheckstyleException; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Locale; import java.util.Scanner; import org.junit.Test; import static org.junit.Assert.*; public class CheckstyleResultTest { @Test public void shouldConvertJsonToCheckstyleResult() throws TMCCheckstyleException, IOException { final File testProject = new File("test-projects/invalid/ant/"); final CheckstyleRunner runner = new CheckstyleRunner(testProject, Locale.ROOT); final File outputFile = new File("target/output.txt"); runner.run(outputFile, false); final Scanner scanner = new Scanner(outputFile); final StringBuilder builder = new StringBuilder(); while (scanner.hasNextLine()) { builder.append(scanner.nextLine()); } scanner.close(); outputFile.delete(); final CheckstyleResult result = CheckstyleResult.build(builder.toString()); final List<ValidationError> errors = result.getValidationErrors().get(new File("Trivial.java")); assertFalse(result.getValidationErrors().isEmpty()); assertEquals(3, errors.size()); String expected = "Indentation incorrect. Expected 0, but was 1."; assertEquals(2, errors.get(0).getLine()); assertEquals(0, errors.get(0).getColumn()); assertEquals(expected, errors.get(0).getMessage()); expected = "'{' is not preceded with whitespace."; assertEquals(2, errors.get(1).getLine()); assertEquals(22, errors.get(1).getColumn()); assertEquals(expected, errors.get(1).getMessage()); } }
gpl-2.0
zkroliko/JTP-2
Tasks/zad7Server/src/pl/edu/agh/jtp/zad7/server/ServerStarter.java
209
package pl.edu.agh.jtp.zad7.server; public final class ServerStarter { /** * @param args */ public static void main(String[] args) { @SuppressWarnings("unused") Server server = new Server(); } }
gpl-2.0
tauprojects/mpp
src/main/java/org/deuce/trove/TObjectByteProcedure.java
1840
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package org.deuce.trove; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Interface for procedures that take two parameters of type Object and byte. * * Created: Mon Nov 5 22:03:30 2001 * * @author Eric D. Friedman * @version $Id: O2PProcedure.template,v 1.1 2006/11/10 23:28:00 robeden Exp $ */ public interface TObjectByteProcedure<K> { /** * Executes this procedure. A false return value indicates that * the application executing this procedure should not invoke this * procedure again. * * @param a an <code>Object</code> value * @param b a <code>byte</code> value * @return true if additional invocations of the procedure are * allowed. */ public boolean execute(K a, byte b); }// TObjectByteProcedure
gpl-2.0
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/font/fontlib/FLTextRenderer.java
1872
/* * 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.harmony.awt.gl.font.fontlib; import java.awt.Graphics2D; import java.awt.font.GlyphVector; import org.apache.harmony.awt.gl.TextRenderer; public class FLTextRenderer extends TextRenderer { private static final FLTextRenderer inst = new FLTextRenderer(); public static FLTextRenderer getInstance() { return inst; } /* (non-Javadoc) * @see org.apache.harmony.awt.gl.TextRenderer#drawString(java.awt.Graphics2D, java.lang.String, float, float) */ @Override public void drawString(Graphics2D g2d, String str, float x, float y) { g2d.fill(g2d.getFont().createGlyphVector(g2d.getFontRenderContext(), str).getOutline(x, y)); } /* (non-Javadoc) * @see org.apache.harmony.awt.gl.TextRenderer#drawGlyphVector(java.awt.Graphics2D, java.awt.font.GlyphVector, float, float) */ @Override public void drawGlyphVector(Graphics2D g2d, GlyphVector gv, float x, float y) { g2d.fill(gv.getOutline(x,y)); } }
gpl-2.0
klst-com/metasfresh
de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/X_C_Region.java
3661
/** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.sql.ResultSet; import java.util.Properties; /** Generated Model for C_Region * @author Adempiere (generated) */ @SuppressWarnings("javadoc") public class X_C_Region extends org.compiere.model.PO implements I_C_Region, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = 151146638L; /** Standard Constructor */ public X_C_Region (Properties ctx, int C_Region_ID, String trxName) { super (ctx, C_Region_ID, trxName); /** if (C_Region_ID == 0) { setC_Country_ID (0); setC_Region_ID (0); setName (null); } */ } /** Load Constructor */ public X_C_Region (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public org.compiere.model.I_C_Country getC_Country() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class); } @Override public void setC_Country(org.compiere.model.I_C_Country C_Country) { set_ValueFromPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class, C_Country); } /** Set Land. @param C_Country_ID Country */ @Override public void setC_Country_ID (int C_Country_ID) { if (C_Country_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Country_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Country_ID, Integer.valueOf(C_Country_ID)); } /** Get Land. @return Country */ @Override public int getC_Country_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Region. @param C_Region_ID Identifies a geographical Region */ @Override public void setC_Region_ID (int C_Region_ID) { if (C_Region_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Region_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Region_ID, Integer.valueOf(C_Region_ID)); } /** Get Region. @return Identifies a geographical Region */ @Override public int getC_Region_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Region_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Standard. @param IsDefault Default value */ @Override public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Standard. @return Default value */ @Override public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
gpl-2.0
Distrotech/icedtea6-1.13
generated/sun/awt/X11/XPixmapFormatValues.java
1684
// This file is an automatically generated file, please do not edit this file, modify the WrapperGenerator.java file instead ! package sun.awt.X11; import sun.misc.*; import java.util.logging.*; public class XPixmapFormatValues extends XWrapperBase { private Unsafe unsafe = XlibWrapper.unsafe; private final boolean should_free_memory; public static int getSize() { return 12; } public int getDataSize() { return getSize(); } long pData; public long getPData() { return pData; } public XPixmapFormatValues(long addr) { log.finest("Creating"); pData=addr; should_free_memory = false; } public XPixmapFormatValues() { log.finest("Creating"); pData = unsafe.allocateMemory(getSize()); should_free_memory = true; } public void dispose() { log.finest("Disposing"); if (should_free_memory) { log.finest("freeing memory"); unsafe.freeMemory(pData); } } public int get_depth() { log.finest("");return (Native.getInt(pData+0)); } public void set_depth(int v) { log.finest(""); Native.putInt(pData+0, v); } public int get_bits_per_pixel() { log.finest("");return (Native.getInt(pData+4)); } public void set_bits_per_pixel(int v) { log.finest(""); Native.putInt(pData+4, v); } public int get_scanline_pad() { log.finest("");return (Native.getInt(pData+8)); } public void set_scanline_pad(int v) { log.finest(""); Native.putInt(pData+8, v); } String getName() { return "XPixmapFormatValues"; } String getFieldsAsString() { String ret=""; ret += ""+"depth = " + get_depth() +", "; ret += ""+"bits_per_pixel = " + get_bits_per_pixel() +", "; ret += ""+"scanline_pad = " + get_scanline_pad() +", "; return ret; } }
gpl-2.0
marylinh/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00918.java
3625
/** * OWASP Benchmark Project v1.2beta * * 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 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 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("/BenchmarkTest00918") public class BenchmarkTest00918 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"); org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request ); String param = scr.getTheValue("vector"); String bar; String guess = "ABC"; char switchTarget = guess.charAt(2); // Simple case statement that assigns param to bar on conditions 'A', 'C', or 'D' switch (switchTarget) { case 'A': bar = param; break; case 'B': bar = "bobs_your_uncle"; break; case 'C': case 'D': bar = param; break; default: bar = "bobs_your_uncle"; break; } byte[] bytes = new byte[10]; new java.util.Random().nextBytes(bytes); String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(bytes, true); String user = "Byron"; String fullClassName = this.getClass().getName(); String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length()); user+= testCaseNumber; String cookieName = "rememberMe" + testCaseNumber; boolean foundUser = false; javax.servlet.http.Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) { javax.servlet.http.Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) { if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) { foundUser = true; } } } if (foundUser) { response.getWriter().println("Welcome back: " + user + "<br/>"); } else { javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey); rememberMe.setSecure(true); request.getSession().setAttribute(cookieName, rememberMeKey); response.addCookie(rememberMe); response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName() + " whose value is: " + rememberMe.getValue() + "<br/>"); } response.getWriter().println("Weak Randomness Test java.util.Random.nextBytes() executed"); } }
gpl-2.0
f4bio/drftpd3-extended
src/slave/src/org/drftpd/slave/TransferSlowException.java
1197
/* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD 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. * * DrFTPD 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 DrFTPD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.drftpd.slave; /** * * @author CyBeR * @version $Id: TransferSlowException.java 1945 2009-07-25 18:32:01Z djb61 $ */ @SuppressWarnings("serial") public class TransferSlowException extends TransferFailedException { public TransferSlowException(Exception e, TransferStatus status) { super(e.getMessage(),status); } public TransferSlowException(String message, TransferStatus status) { super(message,status); } }
gpl-2.0