repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
pomortaz/azure-sdk-for-java
azure-mgmt-appservice/src/main/java/com/microsoft/azure/management/appservice/implementation/AppServiceEnvironmentInner.java
22643
/** * 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.appservice.implementation; import com.microsoft.azure.management.appservice.ProvisioningState; import com.microsoft.azure.management.appservice.HostingEnvironmentStatus; import com.microsoft.azure.management.appservice.VirtualNetworkProfile; import com.microsoft.azure.management.appservice.InternalLoadBalancingMode; import java.util.List; import com.microsoft.azure.management.appservice.VirtualIPMapping; import com.microsoft.azure.management.appservice.NetworkAccessControlEntry; import com.microsoft.azure.management.appservice.NameValuePair; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; import com.microsoft.azure.Resource; /** * Description of an App Service Environment. */ @JsonFlatten public class AppServiceEnvironmentInner extends Resource { /** * Name of the App Service Environment. */ @JsonProperty(value = "properties.name") private String appServiceEnvironmentName; /** * Location of the App Service Environment, e.g. "West US". */ @JsonProperty(value = "properties.location") private String appServiceEnvironmentLocation; /** * Provisioning state of the App Service Environment. Possible values * include: 'Succeeded', 'Failed', 'Canceled', 'InProgress', 'Deleting'. */ @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) private ProvisioningState provisioningState; /** * Current status of the App Service Environment. Possible values include: * 'Preparing', 'Ready', 'Scaling', 'Deleting'. */ @JsonProperty(value = "properties.status", access = JsonProperty.Access.WRITE_ONLY) private HostingEnvironmentStatus status; /** * Name of the Virtual Network for the App Service Environment. */ @JsonProperty(value = "properties.vnetName") private String vnetName; /** * Resource group of the Virtual Network. */ @JsonProperty(value = "properties.vnetResourceGroupName") private String vnetResourceGroupName; /** * Subnet of the Virtual Network. */ @JsonProperty(value = "properties.vnetSubnetName") private String vnetSubnetName; /** * Description of the Virtual Network. */ @JsonProperty(value = "properties.virtualNetwork") private VirtualNetworkProfile virtualNetwork; /** * Specifies which endpoints to serve internally in the Virtual Network for * the App Service Environment. Possible values include: 'None', 'Web', * 'Publishing'. */ @JsonProperty(value = "properties.internalLoadBalancingMode") private InternalLoadBalancingMode internalLoadBalancingMode; /** * Front-end VM size, e.g. "Medium", "Large". */ @JsonProperty(value = "properties.multiSize") private String multiSize; /** * Number of front-end instances. */ @JsonProperty(value = "properties.multiRoleCount") private Integer multiRoleCount; /** * Description of worker pools with worker size IDs, VM sizes, and number * of workers in each pool. */ @JsonProperty(value = "properties.workerPools") private List<WorkerPoolInner> workerPools; /** * Number of IP SSL addresses reserved for the App Service Environment. */ @JsonProperty(value = "properties.ipsslAddressCount") private Integer ipsslAddressCount; /** * Edition of the metadata database for the App Service Environment, e.g. * "Standard". */ @JsonProperty(value = "properties.databaseEdition", access = JsonProperty.Access.WRITE_ONLY) private String databaseEdition; /** * Service objective of the metadata database for the App Service * Environment, e.g. "S0". */ @JsonProperty(value = "properties.databaseServiceObjective", access = JsonProperty.Access.WRITE_ONLY) private String databaseServiceObjective; /** * Number of upgrade domains of the App Service Environment. */ @JsonProperty(value = "properties.upgradeDomains", access = JsonProperty.Access.WRITE_ONLY) private Integer upgradeDomains; /** * Subscription of the App Service Environment. */ @JsonProperty(value = "properties.subscriptionId", access = JsonProperty.Access.WRITE_ONLY) private String subscriptionId; /** * DNS suffix of the App Service Environment. */ @JsonProperty(value = "properties.dnsSuffix") private String dnsSuffix; /** * Last deployment action on the App Service Environment. */ @JsonProperty(value = "properties.lastAction", access = JsonProperty.Access.WRITE_ONLY) private String lastAction; /** * Result of the last deployment action on the App Service Environment. */ @JsonProperty(value = "properties.lastActionResult", access = JsonProperty.Access.WRITE_ONLY) private String lastActionResult; /** * List of comma separated strings describing which VM sizes are allowed * for front-ends. */ @JsonProperty(value = "properties.allowedMultiSizes", access = JsonProperty.Access.WRITE_ONLY) private String allowedMultiSizes; /** * List of comma separated strings describing which VM sizes are allowed * for workers. */ @JsonProperty(value = "properties.allowedWorkerSizes", access = JsonProperty.Access.WRITE_ONLY) private String allowedWorkerSizes; /** * Maximum number of VMs in the App Service Environment. */ @JsonProperty(value = "properties.maximumNumberOfMachines", access = JsonProperty.Access.WRITE_ONLY) private Integer maximumNumberOfMachines; /** * Description of IP SSL mapping for the App Service Environment. */ @JsonProperty(value = "properties.vipMappings", access = JsonProperty.Access.WRITE_ONLY) private List<VirtualIPMapping> vipMappings; /** * Current total, used, and available worker capacities. */ @JsonProperty(value = "properties.environmentCapacities", access = JsonProperty.Access.WRITE_ONLY) private List<StampCapacityInner> environmentCapacities; /** * Access control list for controlling traffic to the App Service * Environment. */ @JsonProperty(value = "properties.networkAccessControlList") private List<NetworkAccessControlEntry> networkAccessControlList; /** * True/false indicating whether the App Service Environment is healthy. */ @JsonProperty(value = "properties.environmentIsHealthy", access = JsonProperty.Access.WRITE_ONLY) private Boolean environmentIsHealthy; /** * Detailed message about with results of the last check of the App Service * Environment. */ @JsonProperty(value = "properties.environmentStatus", access = JsonProperty.Access.WRITE_ONLY) private String environmentStatus; /** * Resource group of the App Service Environment. */ @JsonProperty(value = "properties.resourceGroup", access = JsonProperty.Access.WRITE_ONLY) private String resourceGroup; /** * Scale factor for front-ends. */ @JsonProperty(value = "properties.frontEndScaleFactor") private Integer frontEndScaleFactor; /** * Default Scale Factor for FrontEnds. */ @JsonProperty(value = "properties.defaultFrontEndScaleFactor") private Integer defaultFrontEndScaleFactor; /** * API Management Account associated with the App Service Environment. */ @JsonProperty(value = "properties.apiManagementAccountId") private String apiManagementAccountId; /** * &lt;code&gt;true&lt;/code&gt; if the App Service Environment is * suspended; otherwise, &lt;code&gt;false&lt;/code&gt;. The environment * can be suspended, e.g. when the management endpoint is no longer * available * (most likely because NSG blocked the incoming traffic). */ @JsonProperty(value = "properties.suspended") private Boolean suspended; /** * True/false indicating whether the App Service Environment is suspended. * The environment can be suspended e.g. when the management endpoint is no * longer available * (most likely because NSG blocked the incoming traffic). */ @JsonProperty(value = "properties.dynamicCacheEnabled") private Boolean dynamicCacheEnabled; /** * Custom settings for changing the behavior of the App Service * Environment. */ @JsonProperty(value = "properties.clusterSettings") private List<NameValuePair> clusterSettings; /** * Get the appServiceEnvironmentName value. * * @return the appServiceEnvironmentName value */ public String appServiceEnvironmentName() { return this.appServiceEnvironmentName; } /** * Set the appServiceEnvironmentName value. * * @param appServiceEnvironmentName the appServiceEnvironmentName value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withAppServiceEnvironmentName(String appServiceEnvironmentName) { this.appServiceEnvironmentName = appServiceEnvironmentName; return this; } /** * Get the appServiceEnvironmentLocation value. * * @return the appServiceEnvironmentLocation value */ public String appServiceEnvironmentLocation() { return this.appServiceEnvironmentLocation; } /** * Set the appServiceEnvironmentLocation value. * * @param appServiceEnvironmentLocation the appServiceEnvironmentLocation value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withAppServiceEnvironmentLocation(String appServiceEnvironmentLocation) { this.appServiceEnvironmentLocation = appServiceEnvironmentLocation; return this; } /** * Get the provisioningState value. * * @return the provisioningState value */ public ProvisioningState provisioningState() { return this.provisioningState; } /** * Get the status value. * * @return the status value */ public HostingEnvironmentStatus status() { return this.status; } /** * Get the vnetName value. * * @return the vnetName value */ public String vnetName() { return this.vnetName; } /** * Set the vnetName value. * * @param vnetName the vnetName value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withVnetName(String vnetName) { this.vnetName = vnetName; return this; } /** * Get the vnetResourceGroupName value. * * @return the vnetResourceGroupName value */ public String vnetResourceGroupName() { return this.vnetResourceGroupName; } /** * Set the vnetResourceGroupName value. * * @param vnetResourceGroupName the vnetResourceGroupName value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withVnetResourceGroupName(String vnetResourceGroupName) { this.vnetResourceGroupName = vnetResourceGroupName; return this; } /** * Get the vnetSubnetName value. * * @return the vnetSubnetName value */ public String vnetSubnetName() { return this.vnetSubnetName; } /** * Set the vnetSubnetName value. * * @param vnetSubnetName the vnetSubnetName value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withVnetSubnetName(String vnetSubnetName) { this.vnetSubnetName = vnetSubnetName; return this; } /** * Get the virtualNetwork value. * * @return the virtualNetwork value */ public VirtualNetworkProfile virtualNetwork() { return this.virtualNetwork; } /** * Set the virtualNetwork value. * * @param virtualNetwork the virtualNetwork value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withVirtualNetwork(VirtualNetworkProfile virtualNetwork) { this.virtualNetwork = virtualNetwork; return this; } /** * Get the internalLoadBalancingMode value. * * @return the internalLoadBalancingMode value */ public InternalLoadBalancingMode internalLoadBalancingMode() { return this.internalLoadBalancingMode; } /** * Set the internalLoadBalancingMode value. * * @param internalLoadBalancingMode the internalLoadBalancingMode value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withInternalLoadBalancingMode(InternalLoadBalancingMode internalLoadBalancingMode) { this.internalLoadBalancingMode = internalLoadBalancingMode; return this; } /** * Get the multiSize value. * * @return the multiSize value */ public String multiSize() { return this.multiSize; } /** * Set the multiSize value. * * @param multiSize the multiSize value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withMultiSize(String multiSize) { this.multiSize = multiSize; return this; } /** * Get the multiRoleCount value. * * @return the multiRoleCount value */ public Integer multiRoleCount() { return this.multiRoleCount; } /** * Set the multiRoleCount value. * * @param multiRoleCount the multiRoleCount value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withMultiRoleCount(Integer multiRoleCount) { this.multiRoleCount = multiRoleCount; return this; } /** * Get the workerPools value. * * @return the workerPools value */ public List<WorkerPoolInner> workerPools() { return this.workerPools; } /** * Set the workerPools value. * * @param workerPools the workerPools value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withWorkerPools(List<WorkerPoolInner> workerPools) { this.workerPools = workerPools; return this; } /** * Get the ipsslAddressCount value. * * @return the ipsslAddressCount value */ public Integer ipsslAddressCount() { return this.ipsslAddressCount; } /** * Set the ipsslAddressCount value. * * @param ipsslAddressCount the ipsslAddressCount value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withIpsslAddressCount(Integer ipsslAddressCount) { this.ipsslAddressCount = ipsslAddressCount; return this; } /** * Get the databaseEdition value. * * @return the databaseEdition value */ public String databaseEdition() { return this.databaseEdition; } /** * Get the databaseServiceObjective value. * * @return the databaseServiceObjective value */ public String databaseServiceObjective() { return this.databaseServiceObjective; } /** * Get the upgradeDomains value. * * @return the upgradeDomains value */ public Integer upgradeDomains() { return this.upgradeDomains; } /** * Get the subscriptionId value. * * @return the subscriptionId value */ public String subscriptionId() { return this.subscriptionId; } /** * Get the dnsSuffix value. * * @return the dnsSuffix value */ public String dnsSuffix() { return this.dnsSuffix; } /** * Set the dnsSuffix value. * * @param dnsSuffix the dnsSuffix value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withDnsSuffix(String dnsSuffix) { this.dnsSuffix = dnsSuffix; return this; } /** * Get the lastAction value. * * @return the lastAction value */ public String lastAction() { return this.lastAction; } /** * Get the lastActionResult value. * * @return the lastActionResult value */ public String lastActionResult() { return this.lastActionResult; } /** * Get the allowedMultiSizes value. * * @return the allowedMultiSizes value */ public String allowedMultiSizes() { return this.allowedMultiSizes; } /** * Get the allowedWorkerSizes value. * * @return the allowedWorkerSizes value */ public String allowedWorkerSizes() { return this.allowedWorkerSizes; } /** * Get the maximumNumberOfMachines value. * * @return the maximumNumberOfMachines value */ public Integer maximumNumberOfMachines() { return this.maximumNumberOfMachines; } /** * Get the vipMappings value. * * @return the vipMappings value */ public List<VirtualIPMapping> vipMappings() { return this.vipMappings; } /** * Get the environmentCapacities value. * * @return the environmentCapacities value */ public List<StampCapacityInner> environmentCapacities() { return this.environmentCapacities; } /** * Get the networkAccessControlList value. * * @return the networkAccessControlList value */ public List<NetworkAccessControlEntry> networkAccessControlList() { return this.networkAccessControlList; } /** * Set the networkAccessControlList value. * * @param networkAccessControlList the networkAccessControlList value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withNetworkAccessControlList(List<NetworkAccessControlEntry> networkAccessControlList) { this.networkAccessControlList = networkAccessControlList; return this; } /** * Get the environmentIsHealthy value. * * @return the environmentIsHealthy value */ public Boolean environmentIsHealthy() { return this.environmentIsHealthy; } /** * Get the environmentStatus value. * * @return the environmentStatus value */ public String environmentStatus() { return this.environmentStatus; } /** * Get the resourceGroup value. * * @return the resourceGroup value */ public String resourceGroup() { return this.resourceGroup; } /** * Get the frontEndScaleFactor value. * * @return the frontEndScaleFactor value */ public Integer frontEndScaleFactor() { return this.frontEndScaleFactor; } /** * Set the frontEndScaleFactor value. * * @param frontEndScaleFactor the frontEndScaleFactor value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withFrontEndScaleFactor(Integer frontEndScaleFactor) { this.frontEndScaleFactor = frontEndScaleFactor; return this; } /** * Get the defaultFrontEndScaleFactor value. * * @return the defaultFrontEndScaleFactor value */ public Integer defaultFrontEndScaleFactor() { return this.defaultFrontEndScaleFactor; } /** * Set the defaultFrontEndScaleFactor value. * * @param defaultFrontEndScaleFactor the defaultFrontEndScaleFactor value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withDefaultFrontEndScaleFactor(Integer defaultFrontEndScaleFactor) { this.defaultFrontEndScaleFactor = defaultFrontEndScaleFactor; return this; } /** * Get the apiManagementAccountId value. * * @return the apiManagementAccountId value */ public String apiManagementAccountId() { return this.apiManagementAccountId; } /** * Set the apiManagementAccountId value. * * @param apiManagementAccountId the apiManagementAccountId value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withApiManagementAccountId(String apiManagementAccountId) { this.apiManagementAccountId = apiManagementAccountId; return this; } /** * Get the suspended value. * * @return the suspended value */ public Boolean suspended() { return this.suspended; } /** * Set the suspended value. * * @param suspended the suspended value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withSuspended(Boolean suspended) { this.suspended = suspended; return this; } /** * Get the dynamicCacheEnabled value. * * @return the dynamicCacheEnabled value */ public Boolean dynamicCacheEnabled() { return this.dynamicCacheEnabled; } /** * Set the dynamicCacheEnabled value. * * @param dynamicCacheEnabled the dynamicCacheEnabled value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withDynamicCacheEnabled(Boolean dynamicCacheEnabled) { this.dynamicCacheEnabled = dynamicCacheEnabled; return this; } /** * Get the clusterSettings value. * * @return the clusterSettings value */ public List<NameValuePair> clusterSettings() { return this.clusterSettings; } /** * Set the clusterSettings value. * * @param clusterSettings the clusterSettings value to set * @return the AppServiceEnvironmentInner object itself. */ public AppServiceEnvironmentInner withClusterSettings(List<NameValuePair> clusterSettings) { this.clusterSettings = clusterSettings; return this; } }
mit
jsquared21/Intro-to-Java-Programming
Exercise_05/Exercise_05_12/Exercise_05_12.java
577
/* (Find the smallest n such that n^2 > 12,000) Use a while loop to find the smallest integer n such that n^2 is greater than 12,000. */ public class Exercise_05_12 { public static void main(String[] args) { int n = 0; // Start n at 0 // Find the smallest n such that n^2 > 12,000 <<<<<<< HEAD while (Math.pow(n, 2) <= 12000) { ======= while (Math.pow(n, 2) < 12000) { >>>>>>> f7c770b17f3c46acc01e28b1b7c3742d6c7130d0 n++; // Increment n } // Display result System.out.println( "The smallest integer n such that n^2 is greater than 12,000: " + n); } }
mit
zxh0/jvmgo-book
v1/code/java/jvmgo_java/ch05/src/main/java/com/github/jvmgo/instructions/loads/aload_2.java
477
package com.github.jvmgo.instructions.loads; import com.github.jvmgo.instructions.base.Index8Instruction; import com.github.jvmgo.rtda.Frame; import java.lang.ref.Reference; public class aload_2 extends Index8Instruction { @Override public int getOpCode() { return 0x2c; } @Override public void execute(Frame frame) throws Exception { Reference ref = frame.getLocalVars().getRef(2); frame.getOperandStack().pushRef(ref); } }
mit
Jovtcho/JavaFundamentals
Java Advanced/06.Functional-Programming-Lab/P02SumNumbers.java
667
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.function.Function; public class P02SumNumbers { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] strNums = bf.readLine().split(",\\s+"); Function<String, Integer> parser = strNum -> Integer.parseInt(strNum); int sum = 0; for (String strNum : strNums) { sum += parser.apply(strNum); } System.out.printf("Count = %d%n", strNums.length); System.out.printf("Sum = %d", sum); } }
mit
HPSoftware/hpaa-octane-dev
src/main/java/com/microfocus/application/automation/tools/results/projectparser/performance/WholeRunResult.java
2540
/* * Certain versions of software and/or documents ("Material") accessible here may contain branding from * Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017, * the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP * and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE * marks are the property of their respective owners. * __________________________________________________________________ * MIT License * * (c) Copyright 2012-2019 Micro Focus or one of its affiliates. * * The only warranties for products and services of Micro Focus and its affiliates * and licensors ("Micro Focus") are set forth in the express warranty statements * accompanying such products and services. Nothing herein should be construed as * constituting an additional warranty. Micro Focus shall not be liable for technical * or editorial errors or omissions contained herein. * The information contained herein is subject to change without notice. * ___________________________________________________________________ */ package com.microfocus.application.automation.tools.results.projectparser.performance; /** * Created by kazaky on 07/07/2016. */ public class WholeRunResult extends GoalResult { private double _actualValue; private double _goalValue; /** * Instantiates a new Whole run result. * * @param _actualValue the actual value * @param _goalValue the goal value */ public WholeRunResult(double _actualValue, double _goalValue) { this._actualValue = _actualValue; this._goalValue = _goalValue; } /** * Instantiates an empty new Whole run result. */ public WholeRunResult() { this(0,0); } /** * Gets actual value. * * @return the actual value */ public double getActualValue() { return _actualValue; } /** * Sets actual value. * * @param actualValue the actual value */ public void setActualValue(double actualValue) { this._actualValue = actualValue; } /** * Gets goal value. * * @return the goal value */ public double getGoalValue() { return _goalValue; } /** * Sets goal value. * * @param goalValue the goal value */ public void setGoalValue(double goalValue) { this._goalValue = goalValue; } }
mit
ankitg/impulse
src/com/ankitguglani/impulse/Authentication.java
7503
package com.ankitguglani.impulse; import java.util.ArrayList; import nclSDK.Ncl; import nclSDK.NclBool; import nclSDK.NclCallback; import nclSDK.NclEvent; import nclSDK.NclEventType; import nclSDK.NclMode; import nclSDK.NclProvision; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import com.google.android.glass.app.Card; import com.google.android.glass.timeline.LiveCard; import com.google.android.glass.widget.CardScrollAdapter; import com.google.android.glass.widget.CardScrollView; public class Authentication extends Activity { private static LiveCard liveCard; private static String ip = "192.168.1.225"; public static int nymiHandle = 0; final String path = Environment.getExternalStorageDirectory() + ""; public static ArrayList<NclProvision> provisions = new ArrayList<NclProvision>(); String PREFS_NAME = "provision"; private ArrayList<Card> mCards = new ArrayList<Card>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Ncl.InitiateLibrary(this, ip, 9089); final NclCallback cb = new NclCallback(this, "HandleCallBack", NclEventType.NCL_EVENT_ANY); new Thread(new Runnable() { @Override public void run() { Boolean b = Ncl.init(cb, null, "LOCK", NclMode.NCL_MODE_DEV, path + "/SomeOtherFile.txt"); } }).start(); showNotification(); } private void showNotification() { // RemoteViews views = new RemoteViews(getPackageName(), R.layout.activity_authentication); // if(liveCard != null){ // liveCard.unpublish(); // } // liveCard = new LiveCard(getApplication(),"beacon"); // liveCard.setViews(views); // Intent menuIntent = new Intent(this, MenuActivity.class); // menuIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // liveCard.setAction(PendingIntent.getActivity(getApplicationContext(), 0, menuIntent, 0)); // liveCard.publish(LiveCard.PublishMode.REVEAL); Card opt1 = new Card(this); opt1.setText(R.string.discover); mCards.add(opt1); Card opt2 = new Card(this); opt2.setText(R.string.agree); mCards.add(opt2); Card opt3 = new Card(this); opt3.setText(R.string.provision); mCards.add(opt3); Card opt4 = new Card(this); opt4.setText(R.string.find); mCards.add(opt4); Card opt5 = new Card(this); opt5.setText(R.string.validate); mCards.add(opt5); CardScrollView cardScrollView = new CardScrollView(this); CardScrollAdapter cardScrollAdapter = new CardScrollAdapter() { @Override public View getView(int arg0, View arg1, ViewGroup arg2) { return mCards.get(arg0).getView(); } @Override public int getPosition(Object arg0) { return mCards.indexOf(arg0); } @Override public Object getItem(int arg0) { return mCards.get(arg0); } @Override public int getCount() { return mCards.size(); } }; cardScrollView.setAdapter(cardScrollAdapter); cardScrollView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position){ case 0: Authentication.onDiscover(); break; case 1: Authentication.onAgree(); break; case 2: Authentication.onProvision(); break; case 3: Authentication.onFind(); break; case 4: Authentication.onValidate(); break; default: break; } } }); cardScrollView.activate(); setContentView(cardScrollView); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.authentication, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return super.onOptionsItemSelected(item); } public void HandleCallBack(NclEvent event, Object userData) { Log.d("HandleCallBack", "NclEvent: " + NclEventType.values()[event.type]); switch (NclEventType.values()[event.type]) { case NCL_EVENT_INIT: { writeToAppLog("NCL_EVENT_INIT Returned " + NclBool.values()[event.init.success] + "\n"); break; } case NCL_EVENT_DISCOVERY: { writeToAppLog("NCL_EVENT_DISCOVERY Rssi: " + event.discovery.rssi + " TxPowerLevel: " + event.discovery.txPowerLevel + "\n"); nymiHandle = event.discovery.nymiHandle; break; } case NCL_EVENT_FIND: { writeToAppLog("NCL_EVENT_FIND Rssi: " + event.find.rssi + " TxPowerLevel: " + event.find.txPowerLevel + "\n"); nymiHandle = event.find.nymiHandle; break; } case NCL_EVENT_DETECTION: { break; } case NCL_EVENT_AGREEMENT: { writeToAppLog("NCL_EVENT_AGREEMENT\n"); nymiHandle = event.agreement.nymiHandle; break; } case NCL_EVENT_PROVISION: { Authentication.provisions.add(event.provision.provision); SharedPreferences id = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = id.edit(); editor.putString("ID", SomeWhatReadable(event.provision.provision.id)); editor.commit(); break; } case NCL_EVENT_VALIDATION: { writeToAppLog("NCL_EVENT_VALIDATION\n"); nymiHandle = event.validation.nymiHandle; break; } case NCL_EVENT_CREATED_SK: { writeToAppLog("NCL_EVENT_CREATED_SK\n"); nymiHandle = event.createdSk.nymiHandle; writeToAppLog("SK: " + SomeWhatReadable(event.createdSk.sk) + "\n"); writeToAppLog("ID: " + SomeWhatReadable(event.createdSk.id) + "\n"); break; } case NCL_EVENT_GOT_SK: { writeToAppLog("NCL_EVENT_GOT_SK\n"); nymiHandle = event.gotSk.nymiHandle; writeToAppLog("SK: " + SomeWhatReadable(event.gotSk.sk) + "\n"); break; } case NCL_EVENT_PRG: { writeToAppLog("NCL_EVENT_PRG\n"); nymiHandle = event.prg.nymiHandle; writeToAppLog("Value: " + SomeWhatReadable(event.prg.value) + "\n"); break; } case NCL_EVENT_RSSI: { writeToAppLog("NCL_EVENT_RSSI Rssi: " + event.rssi.rssi + "\n"); nymiHandle = event.rssi.nymiHandle; break; } case NCL_EVENT_DISCONNECTION: { writeToAppLog("NCL_EVENT_DISCONNECTION\n"); break; } } } private static void writeToAppLog(String msg){ Log.d("Nymi", msg); } private static String SomeWhatReadable(char[] arr) { String str = ""; for (char c : arr) { str += ((int) c) + " "; } return str; } public static void onDiscover() { Ncl.startDiscovery(); } public static void onAgree() { if(!Ncl.agree(nymiHandle)) { writeToAppLog("Agree Failed!"); } } public static void onProvision() { Ncl.provision(nymiHandle); } public static void onFind() { Ncl.startFinding(provisions, provisions.size(), NclBool.NCL_FALSE); } public static void onValidate() { Ncl.validate(nymiHandle); } }
mit
gleb619/cross0ut-b0t
app/src/main/java/org/team619/crossout/program/consumer/FilterConsumer.java
1618
package org.team619.crossout.program.consumer; import lombok.extern.slf4j.Slf4j; import org.team619.crossout.program.data.Context; import org.team619.crossout.program.data.ImageContext; import org.team619.crossout.program.data.Param; import org.team619.crossout.program.filter.Filter; import java.awt.image.BufferedImage; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.team619.crossout.program.data.SupplierParameter.FILTER_CHAIN_ENABLED; @Slf4j public class FilterConsumer implements Consumer { private List<Filter<BufferedImage>> filters; private Boolean filtersEnabled; @Override public void config(Context context) { filters = context.getFilters().stream() .filter(filter -> BufferedImage.class.isAssignableFrom(filter.support())) .map(filter -> (Filter<BufferedImage>) filter) .collect(Collectors.toList()); Map<Param, Boolean> parameters = context.getParameters(); filtersEnabled = parameters.getOrDefault(FILTER_CHAIN_ENABLED, Boolean.FALSE); } @Override public ImageContext consume(ImageContext context) { final BufferedImage[] image = {context.getImage()}; if (filtersEnabled) { List<Filter<BufferedImage>> suitableFilters = filters.stream() .filter(filter -> filter.support(image[0])) .collect(Collectors.toList()); suitableFilters.forEach(filter -> image[0] = filter.filter(image[0])); } context.setImage(image[0]); return context; } }
mit
constantcontact/open-performance-platform
opp-service/src/test/java/com/opp/dao/LoadTestDataDaoTest.java
2577
package com.opp.dao; import com.opp.domain.ChartDetails; import com.opp.domain.LoadTest; import com.opp.domain.LoadTestTimeChartData; import com.opp.exception.BadRequestException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.CollectionUtils; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; /** * Created by jhermida on 9/8/16. */ @RunWith(MockitoJUnitRunner.class) public class LoadTestDataDaoTest { private LoadTestDataDao loadTestDataDao; @Mock private JdbcTemplate jdbcTemplate; private ChartDetails chartDetails; private LoadTest loadTest; @Before public void setup() throws NoSuchFieldException, IllegalAccessException { loadTestDataDao = new LoadTestDataDao(); Field field = loadTestDataDao.getClass().getDeclaredField("jdbcTemplate"); field.setAccessible(true); field.set(loadTestDataDao, jdbcTemplate); chartDetails = new ChartDetails(); loadTest = new LoadTest(); loadTest.setId(1); } @Test public void getLineTimeSeries_respPct() { chartDetails.setyAxis("resp_pct90"); when(jdbcTemplate.query(Mockito.anyString(), Mockito.any(BeanPropertyRowMapper.class))).thenReturn(new ArrayList<>()); List<LoadTestTimeChartData> timeChartDataList = loadTestDataDao.getLineTimeSeries(chartDetails, loadTest); assertTrue(CollectionUtils.isEmpty(timeChartDataList)); } @Test public void getLineTimeSeries_successfulSwitch() { chartDetails.setyAxis("resp_min"); when(jdbcTemplate.query(Mockito.anyString(), Mockito.any(BeanPropertyRowMapper.class))).thenReturn(new ArrayList<>()); List<LoadTestTimeChartData> timeChartDataList = loadTestDataDao.getLineTimeSeries(chartDetails, loadTest); assertTrue(CollectionUtils.isEmpty(timeChartDataList)); } @Test(expected = BadRequestException.class) public void getLineTimeSeries_invalidYAxis() { chartDetails.setyAxis("crap"); when(jdbcTemplate.query(Mockito.anyString(), Mockito.any(BeanPropertyRowMapper.class))).thenReturn(new ArrayList<>()); loadTestDataDao.getLineTimeSeries(chartDetails, loadTest); } }
mit
olillevik/my-server-seed
src/main/java/net/openright/simpleserverseed/application/SeedAppConfigFile.java
491
package net.openright.simpleserverseed.application; import javax.sql.DataSource; import net.openright.infrastructure.config.AppConfigFile; public class SeedAppConfigFile extends AppConfigFile implements SeedAppConfig { public SeedAppConfigFile(String filename) { super(filename); } @Override public DataSource createDataSource() { return createDataSource("seed"); } @Override public int getHttpPort() { return Integer.parseInt(getProperty("seed.http.port", "8000")); } }
mit
ericminio/sandbox
learning-java/src/test/java/ericminio/files/FilesTest.java
1385
package ericminio.files; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.Month; import java.time.format.DateTimeFormatter; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; public class FilesTest { @Test public void readWrite() throws IOException { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime dateTime = LocalDateTime.of(2015, Month.JANUARY, 15, 19, 15); String message = dateTime.format(formatter) + " [FLASH] Beauty"; Path path = Paths.get("./target/read-write-test.log"); Files.write(path, message.getBytes()); String line = Files.readAllLines(path).get(0); assertThat(line, equalTo("2015-01-15 19:15:00 [FLASH] Beauty")); } @Test public void readLines() throws IOException { Path path = Paths.get("./src/test/java/ericminio/katas/mastermind/mastermind.yop"); String line = Files.readAllLines(path).get(0); assertThat(line, equalTo("The mastermind...")); } @Test public void currentPackage() { assertThat(this.getClass().getPackage().getName(), equalTo("ericminio.files")); } }
mit
mrmaxent/Maxent
density/tools/FilterSamples.java
1834
/* Copyright (c) 2016 Steven Phillips, Miro Dudik and Rob Schapire 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 density.tools; import java.io.IOException; import density.*; import java.util.Random; public class FilterSamples { public static void main(String args[]) { String usage = "Usage: density.tools.FilterSamples samplesfile mindist outfile"; if (args.length<3) { System.out.println(usage); return; } String samplefile = args[0], outfile = args[2]; double mindist = Double.parseDouble(args[1]); boolean zeroseed = false; density.Utils.generator = new Random(zeroseed ? 0 : System.currentTimeMillis()); try { SampleSet ss = new SampleSet2(samplefile, null, null); SampleSet ss2 = ss.spatialFilter(mindist); ss2.write(outfile); } catch (IOException e) { System.err.println(e.toString()); } } }
mit
Mklueh/intelli-lab
src/eu/broth/intellilab/util/Params.java
671
package eu.broth.intellilab.util; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import java.util.LinkedList; import java.util.List; /** * @author Bastian Roth * @version 02.05.2014 */ public class Params { private List<BasicNameValuePair> pairs; public Params() { pairs = new LinkedList<>(); } public Params(String key, String value) { this(); add(key, value); } public Params add(String key, String value) { BasicNameValuePair pair = new BasicNameValuePair(key, value); pairs.add(pair); return this; } public String format() { return URLEncodedUtils.format(pairs, "utf-8"); } }
mit
TheCodingCultOfWow/IansRepo
Java Projects/CodeString/CodeString Java Source (Work In Progress)/src/cstring/interpreter/mathcompilerengine/test.java
166
package cstring.interpreter.mathcompilerengine; public class test { public static void main(String[] args) { // TODO Auto-generated method stub } }
mit
camsys/onebusaway-siri-api-v20
src/main/java/eu/datex2/schema/_2_0rc1/_2_0/OperatorActionStatusEnum.java
2206
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.11.22 at 01:45:09 PM EST // package eu.datex2.schema._2_0rc1._2_0; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for OperatorActionStatusEnum. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="OperatorActionStatusEnum"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="requested"/> * &lt;enumeration value="approved"/> * &lt;enumeration value="beingImplemented"/> * &lt;enumeration value="implemented"/> * &lt;enumeration value="rejected"/> * &lt;enumeration value="terminationRequested"/> * &lt;enumeration value="beingTerminated"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "OperatorActionStatusEnum") @XmlEnum public enum OperatorActionStatusEnum { @XmlEnumValue("requested") REQUESTED("requested"), @XmlEnumValue("approved") APPROVED("approved"), @XmlEnumValue("beingImplemented") BEING_IMPLEMENTED("beingImplemented"), @XmlEnumValue("implemented") IMPLEMENTED("implemented"), @XmlEnumValue("rejected") REJECTED("rejected"), @XmlEnumValue("terminationRequested") TERMINATION_REQUESTED("terminationRequested"), @XmlEnumValue("beingTerminated") BEING_TERMINATED("beingTerminated"); private final String value; OperatorActionStatusEnum(String v) { value = v; } public String value() { return value; } public static OperatorActionStatusEnum fromValue(String v) { for (OperatorActionStatusEnum c: OperatorActionStatusEnum.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
mit
rsandell/system-event-tracker
core/src/main/java/net/joinedminds/tools/evet/ViewBuilder.java
7793
/* * The MIT License * * Copyright (c) 2013, Robert Sandell - sandell.robert@gmail.com. All rights reserved. * * 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 net.joinedminds.tools.evet; import com.google.common.base.Splitter; import org.kohsuke.stapler.StaplerResponse; import org.koshuke.stapler.simile.timeline.TimelineEventList; import javax.xml.bind.DatatypeConverter; import java.io.IOException; import java.util.Calendar; import java.util.LinkedHashSet; import java.util.Set; import static net.joinedminds.tools.evet.Functions.ifNull; /** * Builder for displaying a time line view. * * @author Robert Sandell &lt;sandell.robert@gmail.com&gt; */ public class ViewBuilder { public static final int DEFAULT_START_DAYS = -2; protected final Db db; protected Calendar start; protected Calendar end; protected Set<String> systems; protected Set<String> tags; protected Set<String> nodes; protected FormData formData; public ViewBuilder(Db db) { this.db = db; formData = new FormData(); } public String startString() { if (start == null) { return DatatypeConverter.printDateTime(defaultStart()); } return DatatypeConverter.printDateTime(start); } public String endString() { if (end == null) { return DatatypeConverter.printDateTime(defaultEnd()); } return DatatypeConverter.printDateTime(end); } public ViewBuilder getStart(String timestamp) { start = DatatypeConverter.parseDateTime(timestamp); formData.start = (Calendar)start.clone(); ensureStart(); return this; } public ViewBuilder getStartHours(String number) { ensureStartNow(); int amount = Integer.parseInt(number); start.add(Calendar.HOUR_OF_DAY, amount); formData.startHours += amount; return this; } public ViewBuilder getStartDays(String number) { ensureStartNow(); int amount = Integer.parseInt(number); start.add(Calendar.DAY_OF_YEAR, amount); formData.startDays += amount; return this; } public ViewBuilder getStartWeeks(String number) { ensureStartNow(); int amount = Integer.parseInt(number); start.add(Calendar.WEEK_OF_YEAR, amount); formData.startWeeks += amount; return this; } public ViewBuilder getStartMonths(String number) { ensureStartNow(); int amount = Integer.parseInt(number); start.add(Calendar.MONTH, amount); formData.startMonths += amount; return this; } public ViewBuilder getStartYears(String number) { ensureStartNow(); int amount = Integer.parseInt(number); start.add(Calendar.YEAR, amount); formData.startYears += amount; return this; } public ViewBuilder getEnd(String timestamp) { end = DatatypeConverter.parseDateTime(timestamp); formData.end = (Calendar)end.clone(); ensureEnd(); return this; } public ViewBuilder getEndHours(String number) { ensureEnd(); int amount = Integer.parseInt(number); end.add(Calendar.HOUR_OF_DAY, amount); formData.endHours += amount; return this; } public ViewBuilder getEndDays(String number) { ensureEnd(); int amount = Integer.parseInt(number); end.add(Calendar.DAY_OF_YEAR, amount); formData.endDays += amount; return this; } public ViewBuilder getEndWeeks(String number) { ensureEnd(); int amount = Integer.parseInt(number); end.add(Calendar.WEEK_OF_YEAR, amount); formData.endWeeks += amount; return this; } public ViewBuilder getEndMonths(String number) { ensureEnd(); int amount = Integer.parseInt(number); end.add(Calendar.MONTH, amount); formData.endMonths += amount; return this; } public ViewBuilder getEndYears(String number) { ensureEnd(); int amount = Integer.parseInt(number); end.add(Calendar.YEAR, amount); formData.endYears += amount; return this; } public ViewBuilder getSystems(String names) { if (this.systems == null) { this.systems = new LinkedHashSet<>(); } for (String name : Splitter.on(',').omitEmptyStrings().trimResults().split(names)) { systems.add(name); } return this; } public ViewBuilder getTags(String names) { if (this.tags == null) { this.tags = new LinkedHashSet<>(); } for (String name : Splitter.on(',').omitEmptyStrings().trimResults().split(names)) { tags.add(name); } return this; } public ViewBuilder getNodes(String names) { if (this.nodes == null) { this.nodes = new LinkedHashSet<>(); } for (String name : Splitter.on(',').omitEmptyStrings().trimResults().split(names)) { nodes.add(name); } return this; } protected void ensureEnd() { if (end == null) { end = defaultEnd(); formData.end = (Calendar)end.clone(); } } private Calendar defaultEnd() { return Calendar.getInstance(); } protected void ensureStart() { if (start == null) { start = defaultStart(); formData.start = (Calendar)start.clone(); } } public Calendar defaultStart() { Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_MONTH, DEFAULT_START_DAYS); return c; } protected void ensureStartNow() { if (start == null) { start = Calendar.getInstance(); formData.start = (Calendar)start.clone(); } } /** * A class to keep track of the user request to show in the form. */ static class FormData { Calendar start; public int startHours = 0; public int startDays = 0; public int startWeeks = 0; public int startMonths = 0; public int startYears = 0; Calendar end; public int endHours = 0; public int endDays = 0; public int endWeeks = 0; public int endMonths = 0; public int endYears = 0; public String startString() { if (start == null) { return ""; } return DatatypeConverter.printDateTime(start); } public String endString() { if (end == null) { return ""; } return DatatypeConverter.printDateTime(end); } } }
mit
rmfisher/fx-animation-editor
src/main/java/animator/component/scene/selection/ResizeBehavior.java
7209
package animator.component.scene.selection; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.geometry.Rectangle2D; import javafx.scene.Node; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Region; import animator.component.scene.panning.PanningComponent; import animator.component.util.widget.EightBoxes; import java.util.function.Consumer; public class ResizeBehavior { private static final double GRID_SIZE = 10; private final BooleanProperty snapToGrid = new SimpleBooleanProperty(); private Runnable onResizeStarted; private Consumer<Rectangle2D> onResized; private Runnable onResizeDone; private ResizerComponent resizerComponent; private EightBoxes resizers; private PanningComponent panningComponent; private double xAtPress; private double yAtPress; private double widthAtPress; private double heightAtPress; private double screenXAtPress; private double screenYAtPress; private double lastScreenX; private double lastScreenY; private double panXAtPress; private double panYAtPress; private boolean dragActive; private double minWidth; private double minHeight; public void apply(ResizerComponent resizerComponent, PanningComponent panningComponent) { this.resizerComponent = resizerComponent; this.resizers = resizerComponent.getResizers(); this.panningComponent = panningComponent; addEventHandlers(resizers.getTopLeft()); addEventHandlers(resizers.getTop()); addEventHandlers(resizers.getTopRight()); addEventHandlers(resizers.getRight()); addEventHandlers(resizers.getBottomRight()); addEventHandlers(resizers.getBottom()); addEventHandlers(resizers.getBottomLeft()); addEventHandlers(resizers.getLeft()); } void setOnResizeStarted(Runnable onResizeStarted) { this.onResizeStarted = onResizeStarted; } void setOnResized(Consumer<Rectangle2D> onResized) { this.onResized = onResized; } void setOnResizeDone(Runnable onResizeDone) { this.onResizeDone = onResizeDone; } BooleanProperty snapToGridProperty() { return snapToGrid; } void setMinSize(double minWidth, double minHeight) { this.minWidth = minWidth; this.minHeight = minHeight; } private void addEventHandlers(Node resizer) { resizer.addEventHandler(MouseEvent.MOUSE_PRESSED, this::onPressed); resizer.addEventHandler(MouseEvent.MOUSE_DRAGGED, this::onDragged); resizer.addEventHandler(MouseEvent.MOUSE_RELEASED, this::onReleased); } private void onPressed(MouseEvent event) { if (event.getButton() == MouseButton.PRIMARY) { xAtPress = resizerComponent.xProperty().get(); yAtPress = resizerComponent.yProperty().get(); widthAtPress = resizerComponent.widthProperty().get(); heightAtPress = resizerComponent.heightProperty().get(); screenXAtPress = event.getScreenX(); screenYAtPress = event.getScreenY(); lastScreenX = screenXAtPress; lastScreenY = screenYAtPress; panXAtPress = panningComponent.panXProperty().get(); panYAtPress = panningComponent.panYProperty().get(); dragActive = true; if (onResizeStarted != null) { onResizeStarted.run(); } event.consume(); } } private void onDragged(MouseEvent event) { if (event.getButton() == MouseButton.PRIMARY) { if (dragActive) { lastScreenX = event.getScreenX(); lastScreenY = event.getScreenY(); if (onResized != null && event.getSource() instanceof Region) { Rectangle2D result = calculateNewSize((Region) event.getSource()); if (result != null) { onResized.accept(result); } } } event.consume(); } } private void onReleased(MouseEvent event) { if (event.getButton() == MouseButton.PRIMARY) { dragActive = false; if (onResizeDone != null) { onResizeDone.run(); } event.consume(); } } private Rectangle2D calculateNewSize(Region resizer) { double deltaXInScreen = lastScreenX - screenXAtPress; double deltaYInScreen = lastScreenY - screenYAtPress; double panningDeltaX = panningComponent.panXProperty().get() - panXAtPress; double panningDeltaY = panningComponent.panYProperty().get() - panYAtPress; double x = xAtPress; double y = yAtPress; double width = widthAtPress; double height = heightAtPress; if (isAnyRight(resizer)) { double proposedWidth = widthAtPress + deltaXInScreen - panningDeltaX; if (snapToGrid.get()) { double snappedRightEdge = snapToGrid(x + proposedWidth); proposedWidth = snappedRightEdge - x; } width = Math.max(proposedWidth, minWidth); } if (isAnyBottom(resizer)) { double proposedHeight = heightAtPress + deltaYInScreen - panningDeltaY; if (snapToGrid.get()) { double snappedBottomEdge = snapToGrid(y + proposedHeight); proposedHeight = snappedBottomEdge - y; } height = Math.max(proposedHeight, minHeight); } if (isAnyLeft(resizer)) { double proposedX = xAtPress + deltaXInScreen - panningDeltaX; if (snapToGrid.get()) { proposedX = snapToGrid(proposedX); } width = Math.max(xAtPress + widthAtPress - proposedX, minWidth); x = xAtPress + widthAtPress - width; } if (isAnyTop(resizer)) { double proposedY = yAtPress + deltaYInScreen - panningDeltaY; if (snapToGrid.get()) { proposedY = snapToGrid(proposedY); } height = Math.max(yAtPress + heightAtPress - proposedY, minHeight); y = yAtPress + heightAtPress - height; } return new Rectangle2D(x, y, width, height); } private boolean isAnyRight(Region r) { return r.equals(resizers.getRight()) || r.equals(resizers.getBottomRight()) || r.equals(resizers.getTopRight()); } private boolean isAnyBottom(Region r) { return r.equals(resizers.getBottom()) || r.equals(resizers.getBottomLeft()) || r.equals(resizers.getBottomRight()); } private boolean isAnyLeft(Region r) { return r.equals(resizers.getLeft()) || r.equals(resizers.getTopLeft()) || r.equals(resizers.getBottomLeft()); } private boolean isAnyTop(Region r) { return r.equals(resizers.getTop()) || r.equals(resizers.getTopLeft()) || r.equals(resizers.getTopRight()); } private static double snapToGrid(double value) { return Math.round(value / GRID_SIZE) * GRID_SIZE; } }
mit
CC3002/DesignPatternsInJava
src/test/java/com/cc3002/auxiliar/design/pattern/command/example05/test/SumTotalPriceTest.java
379
package com.cc3002.auxiliar.design.pattern.command.example05.test; import com.cc3002.auxiliar.design.pattern.command.example05.AbstractSumPrice; import com.cc3002.auxiliar.design.pattern.command.example05.SumTotalPrice; public class SumTotalPriceTest extends AbstractSumPriceTest { @Override protected AbstractSumPrice newCommand() { return new SumTotalPrice(); } }
mit
jpalves/solid
solid/src/test/java/solid/stream/ReverseTest.java
658
package solid.stream; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import static test_utils.AssertIterableEquals.assertIterableEquals; public class ReverseTest { @Test public void testIterator() throws Exception { assertIterableEquals(Arrays.asList(1, 2, 3), new Reverse<>(Arrays.asList(3, 2, 1))); assertIterableEquals(Arrays.asList(null, null), new Reverse<>(Arrays.asList(null, null))); assertIterableEquals(Collections.singletonList(1), new Reverse<>(Collections.singletonList(1))); assertIterableEquals(Collections.emptyList(), new Reverse<>(Collections.emptyList())); } }
mit
InnovateUKGitHub/innovation-funding-service
ifs-web-service/ifs-application-service/src/main/java/org/innovateuk/ifs/application/forms/questions/team/viewmodel/ApplicationTeamOrganisationViewModel.java
5076
package org.innovateuk.ifs.application.forms.questions.team.viewmodel; import org.innovateuk.ifs.address.resource.AddressResource; import org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum; import java.util.List; public class ApplicationTeamOrganisationViewModel implements Comparable<ApplicationTeamOrganisationViewModel> { private final long id; private final Long inviteId; private final String name; private final Long organisationType; private final String organisationTypeName; private final String companyRegistrationNumber; private final List<ApplicationTeamRowViewModel> rows; private final boolean editable; private final boolean userBelongsToOrganisation; private final boolean existing; private final AddressResource address; private boolean openAddTeamMemberForm; public ApplicationTeamOrganisationViewModel(long id, Long inviteId, String name, Long organisationType, String organisationTypeName, String companyRegistrationNumber, List<ApplicationTeamRowViewModel> rows, boolean editable, boolean existing) { this(id, inviteId, name, organisationType, organisationTypeName, companyRegistrationNumber, rows, editable, false, existing, null); } public ApplicationTeamOrganisationViewModel(long id, Long inviteId, String name, Long organisationType, String organisationTypeName, String companyRegistrationNumber, List<ApplicationTeamRowViewModel> rows, boolean editable, boolean existing, boolean userBelongsToOrganisation, AddressResource address) { this.id = id; this.inviteId = inviteId; this.name = name; this.organisationType = organisationType; this.organisationTypeName = organisationTypeName; this.companyRegistrationNumber = companyRegistrationNumber; this.rows = rows; this.editable = editable; this.userBelongsToOrganisation = userBelongsToOrganisation; this.existing = existing; this.address = address; this.openAddTeamMemberForm = false; } public long getId() { return id; } public Long getInviteId() { return inviteId; } public String getName() { return name; } public Long getOrganisationType() { return organisationType; } @Deprecated public String getType() { return organisationTypeName; } public String getOrganisationTypeName() { return organisationTypeName; } public String getCompanyRegistrationNumber() { return companyRegistrationNumber; } public List<ApplicationTeamRowViewModel> getRows() { return rows; } public boolean isEditable() { return editable; } public boolean isUserBelongsToOrganisation() { return userBelongsToOrganisation; } public boolean isExisting() { return existing; } public AddressResource getAddress() { return address; } public boolean isOpenAddTeamMemberForm() { return openAddTeamMemberForm; } public void setOpenAddTeamMemberForm(boolean openAddTeamMemberForm) { this.openAddTeamMemberForm = openAddTeamMemberForm; } public boolean isLead() { return rows.stream().anyMatch(ApplicationTeamRowViewModel::isLead); } public boolean isSingleUserRemaining() { return rows.size() == 1; } @Override public int compareTo(ApplicationTeamOrganisationViewModel that) { if (this.isLead()) { return -1; } else if (that.isLead()) { return 1; } return name.compareTo(that.getName()); } public boolean isBusiness() { return OrganisationTypeEnum.isBusiness(organisationType); } public boolean isResearch() { return OrganisationTypeEnum.isResearch(organisationType); } public boolean isRTO() { return OrganisationTypeEnum.isRTO(organisationType); } public boolean isPublicSectorOrCharity() { return OrganisationTypeEnum.isPublicSectorOrCharity(organisationType); } public boolean isKnowledgeBase() { return OrganisationTypeEnum.isKnowledgeBase(organisationType); } }
mit
ghajba/XMLBeam-example
src/main/java/hu/japy/dev/xmlbeam/Main.java
1213
package hu.japy.dev.xmlbeam; import java.io.IOException; import org.xmlbeam.XBProjector; /** * This is the main class, holding most of the logic. * * @author GHajba * */ public class Main { public static void main(String[] args) { try { final MixingOverridingToString mixin = new MixingOverridingToString() { private TodoProjection me; @Override public String toString() { return "I am a ToDo in with a mixin toString method: " + this.me.getBody(); }; }; final XBProjector xbProjector = new XBProjector(); TodoProjection todo = xbProjector.io().url("http://www.w3schools.com/xml/note.xml").read(TodoProjection.class); System.out.println("The body of the projection: " + todo.getBody()); System.out.println(todo); xbProjector.mixins().addProjectionMixin(TodoProjection.class, mixin); todo = xbProjector.io().url("http://www.w3schools.com/xml/note.xml").read(TodoProjection.class); System.out.println(todo); } catch (final IOException e) { e.printStackTrace(); } } }
mit
ItinoseSan/Twi-Java
src/main/java/twijava/http/core/HttpRequest.java
2051
package twijava.http.core; import twijava.APIKeyFactory; import twijava.url.TwitterApiURLs; import twijava.http.HttpResponseHandler; import twijava.oauth.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.TreeMap; public class HttpRequest { public String get(String uri,TreeMap<String,String>data){ return makeSendParam("GET",uri,data); } public String post(String uri,TreeMap<String,String>data){ return makeSendParam("POST",uri,data); } private String makeSendParam(String method, String uri, TreeMap<String,String>data) { try { TreeMap<String,String>keyMap = APIKeyFactory.apiKeyMap(); StringBuilder urlBuilder = new StringBuilder(); String url = urlBuilder .append(TwitterApiURLs.END_POINT_URL) .append(uri).toString(); System.out.println("Request Url:"+url); TreeMap<String, String> oauthMap = OAuthMapFactory.getOAuthMap(keyMap.get("ck"),keyMap.get("ac")); String signature = OAuthSignatureFactory.makeSignature(method, url, data, oauthMap); String oAuthHeader = OAuthHeaderFactory.makeOAuthHeader(signature, oauthMap,keyMap.get("cks"),keyMap.get("ats")); String urlWithParam = OAuthParamFactory.makeURLwithParam(url, data); URL sendUrl = new URL(urlWithParam); return sendRequest(sendUrl,oAuthHeader,method); } catch (Exception e) { return e.toString(); } } private String sendRequest(URL sendUrl,String oAuthHeader,String method) { try { HttpURLConnection urlConnection = (HttpURLConnection) sendUrl.openConnection(); urlConnection.setRequestProperty("Authorization", oAuthHeader); urlConnection.setRequestMethod(method); urlConnection.connect(); return HttpResponseHandler.receiveResponse(urlConnection); } catch (Exception e) { return e.toString(); } } }
mit
cloverstudio/Spika-Android
app/src/main/java/com/clover_studio/spikachatmodule/utils/Preferences.java
1776
package com.clover_studio.spikachatmodule.utils; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.clover_studio.spikachatmodule.models.Config; /** * Created by ubuntu_ivo on 22.07.15.. */ public class Preferences { private SharedPreferences sharedPreferences; public Preferences(Context context) { sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); } public void setToken(String token) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(Const.Preferences.TOKEN, token); editor.apply(); } public String getToken(){ return sharedPreferences.getString(Const.Preferences.TOKEN, ""); } public void setUserId(String userId) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(Const.Preferences.USER_ID, userId); editor.apply(); } public String getUserId(){ return sharedPreferences.getString(Const.Preferences.USER_ID, ""); } public void setConfig(Config config) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(Const.Preferences.SOCKET_URL, config.socketUrl); editor.putString(Const.Preferences.BASE_URL, config.apiBaseUrl); editor.apply(); } public Config getConfig(){ Config config = new Config(); config.apiBaseUrl = sharedPreferences.getString(Const.Preferences.BASE_URL, ""); config.socketUrl = sharedPreferences.getString(Const.Preferences.SOCKET_URL, ""); config.showSidebar = false; config.showTitlebar = false; return config; } }
mit
sideshowcecil/myx-monitor
myx-monitor/src/main/java-apigen/edu/uci/isr/xarch/XArchListener.java
1342
/* * Copyright (c) 2000-2005 Regents of the University of California. * All rights reserved. * * This software was developed at the University of California, Irvine. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Irvine. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ package edu.uci.isr.xarch; /** * Describes an object that receives and handles xArch * events. * * @author Eric M. Dashofy [edashofy@ics.uci.edu] */ public interface XArchListener{ /** * Called automatically when an xArch event * occurs, usually indicating a change in an * xArch document. * * @param evt xArch event that occurred. */ public void handleXArchEvent(XArchEvent evt); }
mit
UNITY-BARS-Develop/R2D2
backend/r2d2/src/main/java/com/unitybars/r2d2/dao/sqlite/SqliteServiceTypeParameterValueDao.java
5023
package com.unitybars.r2d2.dao.sqlite; import com.unitybars.r2d2.dao.ServiceTypeParameterValueDao; import com.unitybars.r2d2.entity.ServiceTypeParameter; import com.unitybars.r2d2.entity.ServiceTypeParameterValue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import javax.sql.DataSource; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by oleg.nestyuk * Date: 13-Dec-16. */ @Repository @Qualifier("sqliteData") public class SqliteServiceTypeParameterValueDao implements ServiceTypeParameterValueDao { private JdbcTemplate jdbcTemplate; @Autowired public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override public List<ServiceTypeParameterValue> getAllServiceTypeParameterValues() { String sql = "SELECT " + "SERVICE_TYPE_PARAMETER_VALUES.* , SERVICE_TYPE_PARAMETER.name as service_type_parameter_name " + "FROM SERVICE_TYPE_PARAMETER_VALUES " + "JOIN SERVICE_TYPE_PARAMETER ON SERVICE_TYPE_PARAMETER_VALUES.service_type_parameter_id=SERVICE_TYPE_PARAMETER.id "; return jdbcTemplate.query(sql, new ServiceTypeParameterValueRowMapper()); } @Override public List<ServiceTypeParameterValue> getServiceTypeParameterValuesForService(String serviceId) { String sql = "SELECT " + "SERVICE_TYPE_PARAMETER_VALUES.* , SERVICE_TYPE_PARAMETER.name as service_type_parameter_name " + "FROM SERVICE_TYPE_PARAMETER_VALUES " + "JOIN SERVICE_TYPE_PARAMETER ON SERVICE_TYPE_PARAMETER_VALUES.service_type_parameter_id=SERVICE_TYPE_PARAMETER.id " + "WHERE SERVICE_TYPE_PARAMETER_VALUES.service_id = ?"; return jdbcTemplate.query(sql, new ServiceTypeParameterValueRowMapper(), serviceId); } @Override public void create(Map<ServiceTypeParameter, String> parameters, String serviceId) { List<String[]> parametersList = new ArrayList<>(); for (Map.Entry<ServiceTypeParameter, String> entry : parameters.entrySet()) { parametersList.add(new String[]{entry.getKey().toString(), entry.getValue()}); } String sql = "INSERT INTO SERVICE_TYPE_PARAMETER_VALUES (service_type_parameter_id, service_id, value) " + "VALUES (?, ?, ?)"; jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement preparedStatement, int i) throws SQLException { preparedStatement.setString(1, parametersList.get(i)[0]); preparedStatement.setString(2, serviceId); preparedStatement.setString(3, parametersList.get(i)[1]); } @Override public int getBatchSize() { return parametersList.size(); } }); } @Override public void update(Map<ServiceTypeParameter, String> parameters, String serviceId) { List<String[]> parametersList = new ArrayList<>(); for (Map.Entry<ServiceTypeParameter, String> entry : parameters.entrySet()) { parametersList.add(new String[]{entry.getKey().toString(), entry.getValue()}); } String sql = "UPDATE SERVICE_TYPE_PARAMETER_VALUES " + "SET value = ?" + "WHERE service_id = ? AND service_type_parameter_id = ?"; jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement preparedStatement, int i) throws SQLException { preparedStatement.setString(1, parametersList.get(i)[1]); preparedStatement.setString(2, serviceId); preparedStatement.setString(3, parametersList.get(i)[0]); } @Override public int getBatchSize() { return parametersList.size(); } }); } public class ServiceTypeParameterValueRowMapper implements RowMapper { @Override public ServiceTypeParameterValue mapRow(ResultSet resultSet, int i) throws SQLException { return new ServiceTypeParameterValue( resultSet.getInt("id"), resultSet.getString("service_id"), ServiceTypeParameter.getServiceTypeParameter(resultSet.getString("service_type_parameter_name")), resultSet.getString("value") ); } } }
mit
reasonml-editor/reasonml-idea-plugin
src/com/reason/ide/search/ORFindUsagesProvider.java
1829
package com.reason.ide.search; import com.intellij.lang.HelpID; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNamedElement; import com.reason.lang.core.psi.PsiModule; import com.reason.lang.core.psi.PsiQualifiedElement; import com.reason.lang.core.psi.impl.PsiLowerIdentifier; import com.reason.lang.core.psi.impl.PsiUpperIdentifier; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class ORFindUsagesProvider implements com.intellij.lang.findUsages.FindUsagesProvider { @Override public boolean canFindUsagesFor(@NotNull PsiElement element) { return element instanceof PsiUpperIdentifier || element instanceof PsiLowerIdentifier; } @Nullable @Override public String getHelpId(@NotNull PsiElement psiElement) { return HelpID.FIND_OTHER_USAGES; } @NotNull @Override public String getType(@NotNull PsiElement element) { String type = PsiTypeElementProvider.getType(element); return type == null ? "unknown type" : type; } @NotNull @Override public String getDescriptiveName(@NotNull PsiElement element) { if (element instanceof PsiModule) { return "Module " + ((PsiModule) element).getName(); } else if (element instanceof PsiNamedElement) { String name = ((PsiNamedElement) element).getName(); return name == null ? "" : name; } return ""; } @NotNull @Override public String getNodeText(@NotNull PsiElement element, boolean useFullName) { if (element instanceof PsiQualifiedElement) { return ((PsiQualifiedElement) element).getQualifiedName(); } if (element instanceof PsiNamedElement) { String name = ((PsiNamedElement) element).getName(); if (name != null) { return name; } } return element.getText(); } }
mit
johnhurt/orgama
archetypes/orgama-module-archetype/src/main/resources/archetype-resources/src/main/java/client/ClientClass.java
58
package ${package}.client; public class ClientClass { }
mit
matthieu-vergne/jMetal
jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/espea/ESPEABuilder.java
5854
package org.uma.jmetal.algorithm.multiobjective.espea; import org.uma.jmetal.algorithm.AlgorithmBuilder; import org.uma.jmetal.algorithm.multiobjective.espea.util.EnergyArchive.ReplacementStrategy; import org.uma.jmetal.algorithm.multiobjective.espea.util.ScalarizationWrapper; import org.uma.jmetal.algorithm.multiobjective.espea.util.ScalarizationWrapper.ScalarizationType; import org.uma.jmetal.operator.crossover.CrossoverOperator; import org.uma.jmetal.operator.mutation.MutationOperator; import org.uma.jmetal.operator.selection.SelectionOperator; import org.uma.jmetal.operator.selection.impl.RandomSelection; import org.uma.jmetal.problem.Problem; import org.uma.jmetal.solution.Solution; import org.uma.jmetal.util.evaluator.SolutionListEvaluator; import org.uma.jmetal.util.evaluator.impl.SequentialSolutionListEvaluator; import java.util.List; public class ESPEABuilder<S extends Solution<?>> implements AlgorithmBuilder<ESPEA<S>> { private final Problem<S> problem; private int maxEvaluations; private int populationSize; private CrossoverOperator<S> crossoverOperator; private CrossoverOperator<S> fullArchiveCrossoverOperator; private MutationOperator<S> mutationOperator; private SelectionOperator<List<S>, S> selectionOperator; private SolutionListEvaluator<S> evaluator; private ScalarizationWrapper scalarization; private boolean normalizeObjectives; private ReplacementStrategy replacementStrategy; public ESPEABuilder(Problem<S> problem, CrossoverOperator<S> crossoverOperator, MutationOperator<S> mutationOperator) { this.problem = problem; this.maxEvaluations = 25000; this.populationSize = 100; this.crossoverOperator = crossoverOperator; this.fullArchiveCrossoverOperator = crossoverOperator; this.mutationOperator = mutationOperator; this.selectionOperator = new RandomSelection<>(); this.evaluator = new SequentialSolutionListEvaluator<>(); this.scalarization = new ScalarizationWrapper(ScalarizationType.UNIFORM); this.normalizeObjectives = true; this.replacementStrategy = ReplacementStrategy.LARGEST_DIFFERENCE; } @Override public ESPEA<S> build() { return new ESPEA<>(problem, maxEvaluations, populationSize, crossoverOperator, fullArchiveCrossoverOperator, mutationOperator, selectionOperator, scalarization, evaluator, normalizeObjectives, replacementStrategy); } /** * @return the maxEvaluations */ public int getMaxEvaluations() { return maxEvaluations; } /** * @return the populationSize */ public int getPopulationSize() { return populationSize; } /** * @return the crossoverOperator */ public CrossoverOperator<S> getCrossoverOperator() { return crossoverOperator; } /** * @return the fullArchiveCrossoverOperator */ public CrossoverOperator<S> getFullArchiveCrossoverOperator() { return fullArchiveCrossoverOperator; } /** * @return the mutationOperator */ public MutationOperator<S> getMutationOperator() { return mutationOperator; } /** * @return the selectionOperator */ public SelectionOperator<List<S>, S> getSelectionOperator() { return selectionOperator; } /** * @return the evaluator */ public SolutionListEvaluator<S> getEvaluator() { return evaluator; } /** * @return the scalarization */ public ScalarizationWrapper getScalarization() { return scalarization; } /** * @param maxEvaluations the maxEvaluations to set */ public void setMaxEvaluations(int maxEvaluations) { this.maxEvaluations = maxEvaluations; } /** * @param populationSize the populationSize to set */ public void setPopulationSize(int populationSize) { this.populationSize = populationSize; } /** * @param crossoverOperator the crossoverOperator to set */ public void setCrossoverOperator(CrossoverOperator<S> crossoverOperator) { this.crossoverOperator = crossoverOperator; } /** * @param fullArchiveCrossoverOperator the fullArchiveCrossoverOperator to set */ public void setFullArchiveCrossoverOperator(CrossoverOperator<S> fullArchiveCrossoverOperator) { this.fullArchiveCrossoverOperator = fullArchiveCrossoverOperator; } /** * @param mutationOperator the mutationOperator to set */ public void setMutationOperator(MutationOperator<S> mutationOperator) { this.mutationOperator = mutationOperator; } /** * @param selectionOperator the selectionOperator to set */ public void setSelectionOperator(SelectionOperator<List<S>, S> selectionOperator) { this.selectionOperator = selectionOperator; } /** * @param evaluator the evaluator to set */ public void setEvaluator(SolutionListEvaluator<S> evaluator) { this.evaluator = evaluator; } /** * @param scalarization the scalarization to set */ public void setScalarization(ScalarizationWrapper scalarization) { this.scalarization = scalarization; } /** * @return the normalizeObjectives */ public boolean isNormalizeObjectives() { return normalizeObjectives; } /** * @param normalizeObjectives the normalizeObjectives to set */ public void setNormalizeObjectives(boolean normalizeObjectives) { this.normalizeObjectives = normalizeObjectives; } /** * @return the replacement strategy */ public ReplacementStrategy getOperationType() { return replacementStrategy; } /** * @param replacementStrategy the replacement strategy to set */ public void setReplacementStrategy(ReplacementStrategy replacementStrategy) { this.replacementStrategy = replacementStrategy; } }
mit
obasola/master
src/test/java/com/kumasi/journal/test/persistence/BookCategoryPersistenceTest.java
2330
/* * Created on 24 Oct 2015 ( Time 23:20:17 ) * Generated by Telosys Tools Generator ( version 2.1.1 ) */ package com.kumasi.journal.test.persistence; import com.kumasi.journal.domain.jpa.BookCategoryEntity; import com.kumasi.journal.mock.BookCategoryEntityMock; import com.kumasi.journal.persistence.PersistenceServiceProvider; import com.kumasi.journal.persistence.services.BookCategoryPersistence; import org.junit.Assert; import org.junit.Test; /** * JUnit test case for BookCategory persistence service * * @author Telosys Tools Generator * */ public class BookCategoryPersistenceTest { @Test public void test1() { System.out.println("Test count ..." ); BookCategoryPersistence service = PersistenceServiceProvider.getService(BookCategoryPersistence.class); System.out.println("CountAll = " + service.countAll() ); } @Test public void test2() { System.out.println("Test BookCategory persistence : delete + load ..." ); BookCategoryPersistence service = PersistenceServiceProvider.getService(BookCategoryPersistence.class); BookCategoryEntityMock mock = new BookCategoryEntityMock(); // TODO : set primary key values here process( service, mock, 0 , 0 ); // process( service, mock, ... ); } private void process(BookCategoryPersistence service, BookCategoryEntityMock mock, Integer bookId, Integer categoryId ) { System.out.println("----- " ); System.out.println(" . load : " ); BookCategoryEntity entity = service.load( bookId, categoryId ); if ( entity != null ) { // Found System.out.println(" FOUND : " + entity ); // Save (update) with the same values to avoid database integrity errors System.out.println(" . save : " + entity ); service.save(entity); System.out.println(" saved : " + entity ); } else { // Not found System.out.println(" NOT FOUND" ); // Create a new instance entity = mock.createInstance( bookId, categoryId ) ; Assert.assertNotNull(entity); /* NB : this entity is a "Join Table" System.out.println(" . insert : " + entity ); service.insert(entity); System.out.println(" inserted : " + entity ); */ System.out.println(" . delete : " ); boolean deleted = service.delete( bookId, categoryId ); System.out.println(" deleted = " + deleted); } } }
mit
wolfgangimig/joa
java/joa-im/src-gen/com/wilutions/mslib/uccollaborationlib/impl/Fire__ILyncClientEvents.java
3631
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.uccollaborationlib.impl; import com.wilutions.com.*; import com.wilutions.mslib.uccollaborationlib._ILyncClientEvents; @SuppressWarnings("all") public class Fire__ILyncClientEvents { public final static void onOnStateChanged(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.IClient _eventSource, final com.wilutions.mslib.uccollaborationlib.IClientStateChangedEventData _eventData) throws ComException { assert(__joa__disp != null); assert(_eventSource != null); assert(_eventData != null); __joa__disp._fireEvent(_ILyncClientEvents.class, (l)->l.onOnStateChanged(_eventSource,_eventData)); } public final static void onOnNotificationReceived(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.ILyncClient _eventSource, final com.wilutions.mslib.uccollaborationlib.ILyncClientNotificationReceivedEventData _eventData) throws ComException { assert(__joa__disp != null); assert(_eventSource != null); assert(_eventData != null); __joa__disp._fireEvent(_ILyncClientEvents.class, (l)->l.onOnNotificationReceived(_eventSource,_eventData)); } public final static void onOnCredentialRequested(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.ILyncClient _eventSource, final com.wilutions.mslib.uccollaborationlib.ICredentialRequestedEventData _eventData) throws ComException { assert(__joa__disp != null); assert(_eventSource != null); assert(_eventData != null); __joa__disp._fireEvent(_ILyncClientEvents.class, (l)->l.onOnCredentialRequested(_eventSource,_eventData)); } public final static void onOnSignInDelayed(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.ILyncClient _eventSource, final com.wilutions.mslib.uccollaborationlib.ISignInDelayedEventData _eventData) throws ComException { assert(__joa__disp != null); assert(_eventSource != null); assert(_eventData != null); __joa__disp._fireEvent(_ILyncClientEvents.class, (l)->l.onOnSignInDelayed(_eventSource,_eventData)); } public final static void onOnCapabilitiesChanged(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.ILyncClient _eventSource, final com.wilutions.mslib.uccollaborationlib.IPreferredCapabilitiesChangedEventData _eventData) throws ComException { assert(__joa__disp != null); assert(_eventSource != null); assert(_eventData != null); __joa__disp._fireEvent(_ILyncClientEvents.class, (l)->l.onOnCapabilitiesChanged(_eventSource,_eventData)); } public final static void onOnDelegatorClientAdded(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.ILyncClient _eventSource, final com.wilutions.mslib.uccollaborationlib.IDelegatorClientCollectionEventData _eventData) throws ComException { assert(__joa__disp != null); assert(_eventSource != null); assert(_eventData != null); __joa__disp._fireEvent(_ILyncClientEvents.class, (l)->l.onOnDelegatorClientAdded(_eventSource,_eventData)); } public final static void onOnDelegatorClientRemoved(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.ILyncClient _eventSource, final com.wilutions.mslib.uccollaborationlib.IDelegatorClientCollectionEventData _eventData) throws ComException { assert(__joa__disp != null); assert(_eventSource != null); assert(_eventData != null); __joa__disp._fireEvent(_ILyncClientEvents.class, (l)->l.onOnDelegatorClientRemoved(_eventSource,_eventData)); } }
mit
CenturionFox/wolfarmor
src/main/java/dev/satyrn/wolfarmor/item/ItemWolfArmor.java
9231
package dev.satyrn.wolfarmor.item; import com.google.common.collect.Multimap; import dev.satyrn.wolfarmor.api.entity.passive.IArmoredWolf; import dev.satyrn.wolfarmor.api.item.IItemWolfArmor; import dev.satyrn.wolfarmor.api.item.IWolfArmorMaterial; import net.minecraft.block.BlockDispenser; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; import net.minecraft.dispenser.IBehaviorDispenseItem; import net.minecraft.dispenser.IBlockSource; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.passive.EntityWolf; import net.minecraft.init.Enchantments; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import javax.annotation.Nonnull; import java.util.List; import java.util.UUID; public class ItemWolfArmor extends Item implements IItemWolfArmor { private static final String NBT_TAG_DISPLAY = "Display"; private static final String NBT_TAG_COLOR = "Color"; private static final IBehaviorDispenseItem DISPENSE_ITEM = new BehaviorDefaultDispenseItem() { /** * Handles dispense of specified stack * @param source The source block * @param stack The stack * @return The stack to dispense */ @Override @Nonnull protected ItemStack dispenseStack(@Nonnull IBlockSource source, @Nonnull ItemStack stack) { ItemStack itemStack = dispenseWolfArmor(source, stack); return !itemStack.isEmpty() ? itemStack : super.dispenseStack(source, stack); } }; private final IWolfArmorMaterial material; public ItemWolfArmor(IWolfArmorMaterial material) { super(); this.material = material; this.maxStackSize = 1; this.canRepair = true; this.setMaxDamage(material.getDurability()); this.setCreativeTab(CreativeTabs.MISC); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(this, DISPENSE_ITEM); } /** * Removes color data from the given stack * * @param stack The item stack */ public void removeColor(@Nonnull ItemStack stack) { if(!stack.isEmpty() && this.getMaterial().getCanBeDyed()) { if(this.getHasColor(stack)) { NBTTagCompound stackCompound = stack.getTagCompound(); if (stackCompound != null) { stackCompound.getCompoundTag(NBT_TAG_DISPLAY).removeTag(NBT_TAG_COLOR); } } } } /** * Gets the armor material * * @return The armor material */ public IWolfArmorMaterial getMaterial() { return this.material; } /** * Gets whether or not the armor has an overlay * * @param stack The stack to check for an overlay * @return Whether or not the wolf armor has an overlay layer */ public boolean getHasOverlay(@Nonnull ItemStack stack) { return this.getMaterial().getHasOverlay() || this.getColor(stack) != -1; } /** * whether or not the stack has a color applied * * @param stack The item stack * @return A boolean representing whether or not the stack has a color applied */ public boolean getHasColor(@Nonnull ItemStack stack) { if(!stack.isEmpty() && this.getMaterial().getCanBeDyed()) { if(stack.hasTagCompound()) { NBTTagCompound tagCompound = stack.getTagCompound(); if (tagCompound != null && tagCompound.hasKey(NBT_TAG_DISPLAY)) { NBTTagCompound display = tagCompound.getCompoundTag(NBT_TAG_DISPLAY); return display.hasKey(NBT_TAG_COLOR); } } } return false; } /** * Gets the color of the item stack * * @param stack The item stack * @return The integer value of the color */ public int getColor(@Nonnull ItemStack stack) { if (!this.getMaterial().getCanBeDyed() || stack.isEmpty()) { return -1; } NBTTagCompound tagCompound = stack.getTagCompound(); if (tagCompound != null) { NBTTagCompound display = tagCompound.getCompoundTag(NBT_TAG_DISPLAY); if (display.hasKey(NBT_TAG_COLOR)) { return display.getInteger(NBT_TAG_COLOR); } } return this.getMaterial().getDefaultColor(); } /** * Sets the color of the item stack * * @param stack The item stack * @param color The integer value of the color */ public void setColor(@Nonnull ItemStack stack, int color) { if (!this.getMaterial().getCanBeDyed()) { throw new UnsupportedOperationException("Wolf armor material is not dyeable!"); } else if(!stack.isEmpty()) { NBTTagCompound tagCompound = stack.getTagCompound(); if (tagCompound == null) { tagCompound = new NBTTagCompound(); stack.setTagCompound(tagCompound); } NBTTagCompound display = tagCompound.getCompoundTag(NBT_TAG_DISPLAY); if (!tagCompound.hasKey(NBT_TAG_DISPLAY)) { tagCompound.setTag(NBT_TAG_DISPLAY, display); } display.setInteger(NBT_TAG_COLOR, color); } } /** * Gets the damage reduction amount. * * @return The damage reduction amount */ @Deprecated public double getDamageReductionAmount() { return getMaterial().getDamageReductionAmount(); } /** * Helper method for dispensing item stacks * * @param source The block source * @param stack The dispensing stack * @return An item stack to dispense, or null if default dispense should occur. */ @Nonnull private static ItemStack dispenseWolfArmor(@Nonnull IBlockSource source, @Nonnull ItemStack stack) { BlockPos blockPos = source.getBlockPos().offset(source.getBlockState().getValue(BlockDispenser.FACING)); List<EntityWolf> wolves = source.getWorld().getEntitiesWithinAABB(EntityWolf.class, new AxisAlignedBB(blockPos)); if (!wolves.isEmpty()) { EntityWolf wolf = null; for (EntityWolf entity : wolves) { if (entity.isTamed() && !entity.isChild()) { wolf = entity; break; } } if (wolf != null) { ItemStack copyStack = stack.copy(); copyStack.setCount(1); IArmoredWolf wolfArmor = (IArmoredWolf)wolf; if (!wolfArmor.canEquipItem(copyStack)) { return stack; } wolfArmor.equipArmor(copyStack); stack.shrink(1); } } return stack; } //endregion Private Methods //region Accessors / Mutators /** * Gets the item enchantability from the item's armor material * * @return The item enchantability */ @Override public int getItemEnchantability() { return this.getMaterial().getEnchantability(); } @Override public boolean canApplyAtEnchantingTable(ItemStack itemStack, Enchantment enchantment) { if(enchantment == Enchantments.SWEEPING) return false; return enchantment.type == EnumEnchantmentType.BREAKABLE || enchantment.type == EnumEnchantmentType.WEAPON || enchantment.type == EnumEnchantmentType.ARMOR || enchantment.type == EnumEnchantmentType.ARMOR_FEET; } /** * Gets whether or not the item can be repaired by the given item in an anvil * * @param originalStack The original item stack * @param repairStack The repair item stack * @return Whether or not the item can be repaired */ @Override public boolean getIsRepairable(@Nonnull ItemStack originalStack, @Nonnull ItemStack repairStack) { return this.getMaterial().getRepairItem() == repairStack.getItem() || super.getIsRepairable(originalStack, repairStack); } @Override @Nonnull public Multimap<String, AttributeModifier> getAttributeModifiers(@Nonnull EntityEquipmentSlot equipmentSlot, @Nonnull ItemStack stack) { Multimap<String, AttributeModifier> multimap = super.getAttributeModifiers(equipmentSlot, stack); if(equipmentSlot == EntityEquipmentSlot.CHEST && !stack.isEmpty() && stack.getItem() instanceof ItemWolfArmor) { multimap.put(SharedMonsterAttributes.ARMOR.getName(), new AttributeModifier(ARMOR_UUID, "Armor modifier", this.getMaterial().getDamageReductionAmount(), 0)); multimap.put(SharedMonsterAttributes.ARMOR_TOUGHNESS.getName(), new AttributeModifier(ARMOR_UUID, "Armor toughness", this.getMaterial().getToughness(), 0)); } return multimap; } }
mit
tedliang/osworkflow
src/designer/com/opensymphony/workflow/designer/editor/ResultFunctionEditor.java
1171
package com.opensymphony.workflow.designer.editor; import com.opensymphony.workflow.designer.ResourceManager; import com.opensymphony.workflow.designer.WorkflowDesigner; import com.opensymphony.workflow.designer.dialogs.DialogUtils; import com.opensymphony.workflow.loader.AbstractDescriptor; import com.opensymphony.workflow.loader.ConfigFunctionDescriptor; import com.opensymphony.workflow.loader.ResultDescriptor; /** * @author baab */ public class ResultFunctionEditor extends FunctionEditor { //protected ResultEdge edge; protected ResultDescriptor descriptor; public ResultFunctionEditor(ResultDescriptor desc) { super(null); descriptor = desc; } protected AbstractDescriptor getParent() { return descriptor; } protected ConfigFunctionDescriptor getFunction() { ConfigFunctionDescriptor template = (ConfigFunctionDescriptor)DialogUtils.getUserSelection(getModel().getPalette().getPreFunctions(), ResourceManager.getString("function.select.pre"), ResourceManager.getString("function.select"), WorkflowDesigner.INSTANCE); if(template!=null) return new ConfigFunctionDescriptor(template); return null; } }
mit
fof1092/TimeVote
src/me/F_o_F_1092/TimeVote/PluginManager/Math.java
429
package me.F_o_F_1092.TimeVote.PluginManager; public class Math { public static boolean isInt(String strg) { try { Integer.parseInt(strg); } catch(NumberFormatException e) { return false; } return true; } public static boolean isDouble(String strg) { try { Double.parseDouble(strg); } catch(NumberFormatException e) { return false; } return true; } }
mit
RikkaBot/RikkaBot-core
testing/BlackEye's DAO/accounts/galaxygates/GalaxyGate.java
2884
package com.rikkabot.rikkabotcore.dao.accounts.galaxygates; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import com.rikkabot.rikkabotcore.dao.DAO; import com.manulaiko.blackeye.launcher.GameManager; import com.rikkabot.rikkabotcore.dao.galaxygates.waves.Wave; /** * GalaxyGate DAO. * =============== * * Represents a row from the `accounts_galaxygates` table. * * @author Manulaiko <manulaiko@gmail.com> */ @Accessors @Data @EqualsAndHashCode(callSuper = true) public class GalaxyGate extends DAO { /** * Gate ID. */ private int _galaxyGatesID; /** * Gate object. */ private com.rikkabot.rikkabotcore.dao.galaxygates.GalaxyGate _galaxyGate = null; /** * Collected parts. */ private int _parts; /** * Available lifes. */ private int _lifes; /** * Current wave ID. */ private int _waveID; /** * Current wave object. */ private Wave _wave = null; /** * Times this gate was completed. */ private int _times; /** * Whether the gate is in base or not. */ private boolean _isCompleted; /** * Constructor. * * @param id GalaxyGate ID. * @param galaxyGatesID Gate ID. * @param parts Collected parts. * @param lifes Available lifes. * @param waveID Current wave ID. * @param times Times this gate was completed. * @param isCompleted Whether the gate is in base or not. */ public GalaxyGate(int id, int galaxyGatesID, int parts, int lifes, int waveID, int times, boolean isCompleted) { super(id); this._galaxyGatesID = galaxyGatesID; this._parts = parts; this._lifes = lifes; this._waveID = waveID; this._times = times; this._isCompleted = isCompleted; } /////////////////////////////// // Start getters and setters // /////////////////////////////// //<editor-fold desc="Getters and Setters" defaultstate="collapsed"> /** * Returns galaxygate galaxyGate. * * @return GalaxyGate galaxyGate. */ public com.rikkabot.rikkabotcore.dao.galaxygates.GalaxyGate galaxyGate() { if(this._galaxyGate == null) { this.galaxyGate(GameManager.galaxygates.find(this.galaxyGatesID())); } return this._galaxyGate; } /** * Returns galaxygate wave. * * @return GalaxyGate wave. */ public Wave wave() { if(this._wave == null) { this.wave(this.galaxyGate().waves().get(this.waveID())); } return this._wave; } //</editor-fold> ///////////////////////////// // End getters and setters // ///////////////////////////// }
mit
Agilefreaks/droidbugfreak
BugFreak/src/main/java/co/bugfreak/ReportingService.java
60
package co.bugfreak; public interface ReportingService { }
mit
Aarronmc/WallpaperCraft
1.10.2/src/main/java/Aarron/WallpaperCraft/blocks/carpets/CheckeredCarpetRed.java
2303
package Aarron.WallpaperCraft.blocks.carpets; import javax.annotation.Nonnull; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import Aarron.WallpaperCraft.blockStates.BlockStates; import Aarron.WallpaperCraft.blockStates.BlockTypes; import Aarron.WallpaperCraft.blocks.IMetaBlock; public class CheckeredCarpetRed extends IMetaBlock<BlockTypes> { public CheckeredCarpetRed() { super(Material.CARPET, "checkeredcarpetred"); this.setSoundType(SoundType.CLOTH); this.setHardness(0.1F); } @Override protected BlockTypes getDefaultStateVariant() { return BlockTypes.Zero; } @Override protected BlockTypes fromMeta(int meta) { return BlockTypes.fromMeta(meta); } @Override protected PropertyEnum<BlockTypes> getVariantEnum() { return BlockStates.WPblocks; } public static final AxisAlignedBB CARPET_AABB = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.0625D, 1.0D); @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return CARPET_AABB; } private boolean canBlockStay(World worldIn, BlockPos pos) { return !worldIn.isAirBlock(pos.down()); } @Override public boolean isVisuallyOpaque() { return false; } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override @Nonnull @SideOnly(Side.CLIENT) public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT_MIPPED; } @Override @SideOnly(Side.CLIENT) public boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) { return side == EnumFacing.UP ? true : (blockAccess.getBlockState(pos.offset(side)).getBlock() == this ? true : super.shouldSideBeRendered(blockState, blockAccess, pos, side)); } }
mit
sergueik/SWET
src/main/java/org/mihalis/opal/breadcrumb/BreadcrumbItem.java
28343
/******************************************************************************* * Copyright (c) 2012 Laurent CARON. 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: * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation *******************************************************************************/ package org.mihalis.opal.breadcrumb; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Widget; // import org.mihalis.opal.utils.SWTGraphicUtil; // origin: https://raw.githubusercontent.com/lcaron/opal/master/src/main/java/org/mihalis/opal/breadcrumb/BreadcrumbItem.java // store a replica locally for eclipse /** * Instances of this class represent a selectable user interface object that represents an item of a breadcrumb. * <dl> * <dt><b>Styles:</b></dt> * <dd>TOGGLE,PUSH,NONE</dd> * <dt><b>Events:</b></dt> * <dd>Selection</dd> * </dl> * */ public class BreadcrumbItem extends Item { private static final int MIN_WIDTH = 40; private static final int MARGIN = 4; private static final Display display = Display.getCurrent(); private static Color SELECTED_COLOR = new Color(display, 223, 220, 213); private final Breadcrumb parentBreadcrumb; private final List<SelectionListener> selectionListeners; private Rectangle bounds; private boolean enabled; private boolean selection; private int width; private int height; private Image disabledImage; private Image selectionImage; private int alignment; private Color textColorSelected; private Color textColor; private String tooltipText; private GC gc; private int toolbarHeight; private boolean isLastItemOfTheBreadCrumb; /** * Constructs a new instance of this class given its parent (which must be a <code>Breadcrumb</code>) * and a style value describing its behavior and appearance. The item is added to the end of the * items maintained by its parent. * <p> * The style value is either one of the style constants defined in class <code>SWT</code> which is * applicable to instances of this class, or must be built by <em>bitwise OR</em>'ing together * (that is, using the <code>int</code> "|" operator) two or more of those <code>SWT</code> style constants. * The class description lists the style constants that are applicable to the class. Style bits are * also inherited from superclasses. * </p> * * @param parent a composite control which will be the parent of the new instance (cannot be null) * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li> * </ul> * * @see Widget#getStyle */ public BreadcrumbItem(final Breadcrumb parent) { this(parent, SWT.NONE); } /** * Constructs a new instance of this class given its parent (which must be a <code>Breadcrumb</code>) * and a style value describing its behavior and appearance. The item is added to the end of the * items maintained by its parent. * <p> * The style value is either one of the style constants defined in class <code>SWT</code> which is * applicable to instances of this class, or must be built by <em>bitwise OR</em>'ing together * (that is, using the <code>int</code> "|" operator) two or more of those <code>SWT</code> * style constants. The class description lists the style constants that are applicable to the class. * Style bits are also inherited from superclasses. * </p> * * @param parent a composite control which will be the parent of the new instance (cannot be null) * @param style the style of control to construct * * @exception IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @exception SWTException * <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li> * </ul> * * @see Widget#getStyle */ public BreadcrumbItem(final Breadcrumb parent, final int style) { super(parent, checkStyle(style)); parent.addItem(this); this.parentBreadcrumb = parent; this.textColor = parent.getDisplay().getSystemColor(SWT.COLOR_BLACK); this.textColorSelected = parent.getDisplay() .getSystemColor(SWT.COLOR_BLACK); this.enabled = true; if ((style & SWT.LEFT) != 0) { this.alignment = SWT.LEFT; } if ((style & SWT.CENTER) != 0) { this.alignment = SWT.CENTER; } if ((style & SWT.RIGHT) != 0) { this.alignment = SWT.RIGHT; } this.selectionListeners = new ArrayList<SelectionListener>(); this.width = this.height = -1; } private static int checkStyle(int style) { style = checkBits(style, SWT.NONE, SWT.PUSH, SWT.TOGGLE); if ((style & (SWT.PUSH | SWT.TOGGLE)) != 0) { return checkBits(style, SWT.CENTER, SWT.LEFT, SWT.RIGHT); } return style; } private static int checkBits(int style, final int int0, final int int1, final int int2) { final int mask = int0 | int1 | int2; if ((style & mask) == 0) { style |= int0; } if ((style & int0) != 0) { style = (style & ~mask) | int0; } if ((style & int1) != 0) { style = (style & ~mask) | int1; } if ((style & int2) != 0) { style = (style & ~mask) | int2; } return style; } /** * Adds the listener to the collection of listeners who will be notified when the control * is selected by the user, by sending it one of the messages defined in the * <code>SelectionListener</code> interface. * <p> * <code>widgetDefaultSelected</code> is not called. * </p> * * @param listener the listener which should be notified when the control is selected by the user, * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SelectionListener * @see #removeSelectionListener * @see SelectionEvent */ public void addSelectionListener(final SelectionListener listener) { checkWidget(); if (listener == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } this.selectionListeners.add(listener); } /** * @see org.eclipse.swt.widgets.Widget#dispose() */ @Override public void dispose() { getParent().removeItem(this); this.bounds = null; this.disabledImage = null; this.selectionImage = null; this.textColor = null; this.textColorSelected = null; super.dispose(); } /** * Returns a value which describes the position of the text in the receiver. * The value will be one of <code>LEFT</code>, <code>RIGHT</code> or <code>CENTER</code>. * * @return the alignment * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getAlignment() { checkWidget(); return this.alignment; } /** * Returns a rectangle describing the receiver's size and location relative to its parent * (or its display if its parent is null), unless the receiver is a shell. * In this case, the location is relative to the display. * * @return the receiver's bounding rectangle * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Rectangle getBounds() { checkWidget(); return this.bounds; } /** * @return the image displayed when the button is disabled * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Image getDisabledImage() { checkWidget(); return this.disabledImage; } /** * Returns <code>true</code> if the receiver is enabled, and <code>false</code> otherwise. * A disabled control is typically not selectable from the user interface and draws with * an inactive or "grayed" look. * * @return the receiver's enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #isEnabled */ public boolean getEnabled() { checkWidget(); return this.enabled; } /** * Returns the whole height of the item. * * @return the receiver's height * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getHeight() { checkWidget(); if (this.height == -1) { return computeDefaultSize().y; } return this.height; } /** * @return the default size of the item */ private Point computeDefaultSize() { final Point sizeOfTextAndImages = computeSizeOfTextAndImages(); return new Point(2 * MARGIN + sizeOfTextAndImages.x, 2 * MARGIN + sizeOfTextAndImages.y); } /** * Returns the receiver's parent, which must be a <code>Breadcrumb</code>. * * @return the receiver's parent * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Breadcrumb getParent() { checkWidget(); return this.parentBreadcrumb; } /** * Returns <code>true</code> if the receiver is selected, and false otherwise. * * @return the selection state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public boolean getSelection() { checkWidget(); return this.selection; } /** * @return the image displayed when the button is selected * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Image getSelectionImage() { checkWidget(); return this.selectionImage; } /** * Returns the color of the text when the button is enabled and not selected. * * @return the receiver's text color * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Color getTextColor() { checkWidget(); return this.textColor; } /** * Returns the color of the text when the button is not selected. * * @return the receiver's text color * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Color getTextColorSelected() { checkWidget(); return this.textColorSelected; } /** * Returns the receiver's tool tip text, or null if it has not been set. * * @return the receiver's tool tip text * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public String getTooltipText() { checkWidget(); return this.tooltipText; } /** * Returns the whole width of the item. * * @return the receiver's height * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getWidth() { checkWidget(); if (this.width == -1) { return Math.max(computeDefaultSize().x, MIN_WIDTH); } return Math.max(this.width, MIN_WIDTH); } /** * Returns <code>true</code> if the receiver is enabled, and <code>false</code> otherwise. * A disabled control is typically not selectable from the user interface and draws * with an inactive or "grayed" look. * * @return the receiver's enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #getEnabled */ public boolean isEnabled() { checkWidget(); return this.enabled; } /** * Removes the listener from the collection of listeners who will be notified when the * control is selected by the user. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SelectionListener * @see #addSelectionListener */ public void removeSelectionListener(final SelectionListener listener) { checkWidget(); if (listener == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } this.selectionListeners.remove(listener); } /** * Controls how text will be displayed in the receiver. The argument should * be one of <code>LEFT</code>, <code>RIGHT</code> or <code>CENTER</code>. * * @param alignment the new alignment * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setAlignment(final int alignment) { checkWidget(); this.alignment = alignment; } /** * Sets the receiver's size and location to the rectangular area specified by the argument. * The <code>x</code> and <code>y</code> fields of the rectangle are relative to the receiver's * parent (or its display if its parent is null). * <p> * Note: Attempting to set the width or height of the receiver to a negative number will cause * that value to be set to zero instead. * </p> * * @param rect the new bounds for the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setBounds(final Rectangle rectangle) { checkWidget(); if (this.bounds == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } this.bounds = new Rectangle(Math.max(0, rectangle.x), // Math.max(0, rectangle.y), // Math.max(0, rectangle.width), // Math.max(0, rectangle.height)); } /** * Sets the receiver's image to the argument when this is one is disabled, which may be null indicating that no image should be displayed. * * @param image the image to display on the receiver (may be null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the image has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setDisabledImage(final Image image) { checkWidget(); this.disabledImage = image; } /** * Enables the receiver if the argument is <code>true</code>, and disables it otherwise. * <p> * A disabled control is typically not selectable from the user interface and draws with an inactive or "grayed" look. * </p> * * @param enabled the new enabled state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setEnabled(final boolean enabled) { checkWidget(); this.enabled = enabled; } /** * Sets the height of the receiver. * <p> * Note: Attempting to set the width or height of the receiver to a negative number will cause that value to be set to zero * instead. * </p> * @param height the new width * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setHeight(final int height) { checkWidget(); this.height = Math.max(height, 0); } /** * Sets the selection state of the receiver. * * @param selected the new selection state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setSelection(final boolean selected) { checkWidget(); this.selection = selected; } /** * Sets the receiver's image to the argument when this one is selected, which may be * null indicating that no image should be displayed. * * @param image the image to display on the receiver (may be null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the image has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setSelectionImage(final Image image) { checkWidget(); this.selectionImage = image; } /** * Sets the receiver's text color to the argument, which may be null indicating that no image should be displayed. * * @param textColor the text color to display on the receiver (may be null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the image has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setTextColor(final Color textColor) { checkWidget(); this.textColor = textColor; } /** * Sets the receiver's text color to the argument when this one is selected, which may be null indicating that no image should be displayed. * * @param textColor the text color to display on the receiver (may be null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the image has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setTextColorSelected(final Color textColor) { checkWidget(); this.textColorSelected = textColor; } /** * Sets the receiver's tool tip text to the argument, which may be null indicating * that the default tool tip for the control will be shown. For a control that has * a default tool tip, such as the Tree control on Windows, setting the tool tip text to an * empty string replaces the default, causing no tool tip text to be shown. * <p> * The mnemonic indicator (character '&amp;') is not displayed in a tool tip. To display * a single '&amp;' in the tool tip, the character '&amp;' can be escaped by doubling it in the string. * </p> * * @param string the new tool tip text (or null) * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setTooltipText(final String string) { checkWidget(); this.tooltipText = (string == null ? "" : string); } /** * Sets the width of the receiver. * <p> * Note: Attempting to set the width or height of the receiver to a negative number will cause that value to be set to zero * instead. * </p> * @param width the new width * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setWidth(final int width) { checkWidget(); this.width = Math.max(0, width); } // --------------------------------------------- Package visibility section void fireSelectionEvent() { final Event event = new Event(); event.widget = this.parentBreadcrumb; event.display = getDisplay(); event.item = this; event.type = SWT.Selection; for (final SelectionListener selectionListener : this.selectionListeners) { selectionListener.widgetSelected(new SelectionEvent(event)); } } void drawButtonAtPosition(final int x) { if (this.selection) { drawBackgroundAtPosition(x); } if (!this.isLastItemOfTheBreadCrumb) { drawTrianglesAtPosition(x); } int xPosition = computeGap(); final Image drawnedImage = drawImageAtPosition(x + xPosition); if (drawnedImage != null) { xPosition += drawnedImage.getBounds().width + 2 * MARGIN; } drawTextAtPosition(x + xPosition); this.bounds = new Rectangle(x, 0, getWidth(), this.toolbarHeight); } private void drawBackgroundAtPosition(final int x) { this.gc.setAdvanced(true); this.gc.setAntialias(SWT.ON); this.gc.setForeground(SELECTED_COLOR); this.gc.setBackground(SELECTED_COLOR); final boolean hasBorder = this.parentBreadcrumb.hasBorder; final boolean isFirst = this.parentBreadcrumb.indexOf(this) == 0; final int borderWidth = hasBorder ? 1 : 0; int leftSide; if (isFirst) { leftSide = 0; } else { leftSide = 5 + (hasBorder ? 0 : 1); } final int xUpperLeft = x + borderWidth + leftSide; final int yUpperLeft = borderWidth; final int rectWidth = getWidth() - borderWidth - leftSide - (this.isLastItemOfTheBreadCrumb && hasBorder ? 1 : 0); final int rectHeight = getHeight() - 2 * borderWidth; this.gc.fillRectangle(xUpperLeft, yUpperLeft, rectWidth, rectHeight); if (!isFirst) { this.gc.fillPolygon(new int[] { xUpperLeft - 5, yUpperLeft, // xUpperLeft, yUpperLeft, // xUpperLeft, yUpperLeft + this.toolbarHeight / 2 // }); this.gc.fillPolygon(new int[] { xUpperLeft - 5, yUpperLeft + rectHeight, // xUpperLeft, yUpperLeft + rectHeight, // xUpperLeft, yUpperLeft + this.toolbarHeight / 2 // }); } if (!this.isLastItemOfTheBreadCrumb) { this.gc.fillPolygon(new int[] { xUpperLeft + rectWidth, yUpperLeft + 1, // xUpperLeft + rectWidth, yUpperLeft + getHeight(), // xUpperLeft + rectWidth + 5, yUpperLeft + this.toolbarHeight / 2 // }); } this.gc.setClipping((Rectangle) null); } private void drawTrianglesAtPosition(final int x) { this.gc.setForeground(Breadcrumb.BORDER_COLOR); drawTriangleAtPosition(x + getWidth()); this.gc.setAlpha(127); this.gc.setForeground(Breadcrumb.BORDER_COLOR_1); drawTriangleAtPosition(x + getWidth() + 1); this.gc.setForeground(Breadcrumb.BORDER_COLOR_2); drawTriangleAtPosition(x + getWidth() + 2); this.gc.setForeground(Breadcrumb.BORDER_COLOR_3); drawTriangleAtPosition(x + getWidth() + 3); this.gc.setAlpha(255); if (this.parentBreadcrumb.hasBorder) { this.gc.setForeground(Breadcrumb.BORDER_COLOR); this.gc.drawLine(x + getWidth(), 0, x + getWidth() + 3, 0); this.gc.drawLine(x + getWidth(), this.toolbarHeight - 1, x + getWidth() + 3, this.toolbarHeight - 1); } } private void drawTriangleAtPosition(final int x) { this.gc.drawLine(x, 0, x + 5, this.toolbarHeight / 2); this.gc.drawLine(x + 5, this.toolbarHeight / 2, x, this.toolbarHeight); } private int computeGap() { final int widthOfTextAndImage = computeSizeOfTextAndImages().x; switch (this.alignment) { case SWT.CENTER: return (getWidth() - widthOfTextAndImage) / 2; case SWT.RIGHT: return getWidth() - widthOfTextAndImage - MARGIN; default: return MARGIN; } } private Point computeSizeOfTextAndImages() { int width = 0, height = 0; final boolean textISNotEmpty = getText() != null && !getText().equals(""); if (textISNotEmpty) { final GC gc = new GC(this.parentBreadcrumb); gc.setFont(this.parentBreadcrumb.getFont()); final Point extent = gc.stringExtent(getText()); gc.dispose(); width += extent.x; height = extent.y; } final Point imageSize = computeMaxWidthAndHeightForImages(getImage(), this.selectionImage, this.disabledImage); if (imageSize.x != -1) { width += imageSize.x; height = Math.max(imageSize.y, height); if (textISNotEmpty) { width += MARGIN * 2; } } width += MARGIN; return new Point(width, height); } private Point computeMaxWidthAndHeightForImages(final Image... images) { final Point imageSize = new Point(-1, -1); for (final Image image : images) { if (image == null) { continue; } final Rectangle imageBounds = image.getBounds(); imageSize.x = Math.max(imageBounds.width, imageSize.x); imageSize.y = Math.max(imageBounds.height, imageSize.y); } return imageSize; } private Image drawImageAtPosition(final int xPosition) { Image image; if (!isEnabled()) { image = this.disabledImage; } else if (this.selection) { image = this.selectionImage; } else { image = getImage(); } if (image == null) { return null; } final int yPosition = (this.toolbarHeight - image.getBounds().height) / 2; this.gc.drawImage(image, (int) (xPosition + MARGIN * 1.5), yPosition); return image; } private void drawTextAtPosition(final int xPosition) { this.gc.setFont(this.parentBreadcrumb.getFont()); if (this.selection) { this.gc.setForeground(this.textColorSelected); } else { this.gc.setForeground(this.textColor); } final Point textSize = this.gc.stringExtent(getText()); final int yPosition = (this.toolbarHeight - textSize.y) / 2; int padding; if (this.parentBreadcrumb.indexOf(this) == 0 || this.isLastItemOfTheBreadCrumb) { padding = 0; } else { padding = 5; } this.gc.drawText(getText(), xPosition + padding, yPosition, true); } BreadcrumbItem setGc(final GC gc) { this.gc = gc; return this; } BreadcrumbItem setToolbarHeight(final int toolbarHeight) { this.toolbarHeight = toolbarHeight; return this; } BreadcrumbItem setIsLastItemOfTheBreadCrumb( final boolean isLastItemOfTheBreadCrumb) { this.isLastItemOfTheBreadCrumb = isLastItemOfTheBreadCrumb; return this; } }
mit
joedski/Cannon-Sheep-Mod
java/com/atalhlla/mod/cannonsheep/proxy/CommonProxy.java
136
package com.atalhlla.mod.cannonsheep.proxy; public class CommonProxy { public void registerRenderers() { // no-op on server... } }
mit
Azure/azure-sdk-for-java
sdk/maintenance/azure-resourcemanager-maintenance/src/main/java/com/azure/resourcemanager/maintenance/implementation/MaintenanceConfigurationsImpl.java
8618
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.maintenance.implementation; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.maintenance.fluent.MaintenanceConfigurationsClient; import com.azure.resourcemanager.maintenance.fluent.models.MaintenanceConfigurationInner; import com.azure.resourcemanager.maintenance.models.MaintenanceConfiguration; import com.azure.resourcemanager.maintenance.models.MaintenanceConfigurations; import com.fasterxml.jackson.annotation.JsonIgnore; public final class MaintenanceConfigurationsImpl implements MaintenanceConfigurations { @JsonIgnore private final ClientLogger logger = new ClientLogger(MaintenanceConfigurationsImpl.class); private final MaintenanceConfigurationsClient innerClient; private final com.azure.resourcemanager.maintenance.MaintenanceManager serviceManager; public MaintenanceConfigurationsImpl( MaintenanceConfigurationsClient innerClient, com.azure.resourcemanager.maintenance.MaintenanceManager serviceManager) { this.innerClient = innerClient; this.serviceManager = serviceManager; } public MaintenanceConfiguration getByResourceGroup(String resourceGroupName, String resourceName) { MaintenanceConfigurationInner inner = this.serviceClient().getByResourceGroup(resourceGroupName, resourceName); if (inner != null) { return new MaintenanceConfigurationImpl(inner, this.manager()); } else { return null; } } public Response<MaintenanceConfiguration> getByResourceGroupWithResponse( String resourceGroupName, String resourceName, Context context) { Response<MaintenanceConfigurationInner> inner = this.serviceClient().getByResourceGroupWithResponse(resourceGroupName, resourceName, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new MaintenanceConfigurationImpl(inner.getValue(), this.manager())); } else { return null; } } public MaintenanceConfiguration deleteByResourceGroup(String resourceGroupName, String resourceName) { MaintenanceConfigurationInner inner = this.serviceClient().delete(resourceGroupName, resourceName); if (inner != null) { return new MaintenanceConfigurationImpl(inner, this.manager()); } else { return null; } } public Response<MaintenanceConfiguration> deleteWithResponse( String resourceGroupName, String resourceName, Context context) { Response<MaintenanceConfigurationInner> inner = this.serviceClient().deleteWithResponse(resourceGroupName, resourceName, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new MaintenanceConfigurationImpl(inner.getValue(), this.manager())); } else { return null; } } public PagedIterable<MaintenanceConfiguration> list() { PagedIterable<MaintenanceConfigurationInner> inner = this.serviceClient().list(); return Utils.mapPage(inner, inner1 -> new MaintenanceConfigurationImpl(inner1, this.manager())); } public PagedIterable<MaintenanceConfiguration> list(Context context) { PagedIterable<MaintenanceConfigurationInner> inner = this.serviceClient().list(context); return Utils.mapPage(inner, inner1 -> new MaintenanceConfigurationImpl(inner1, this.manager())); } public MaintenanceConfiguration getById(String id) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourcegroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourcegroups'.", id))); } String resourceName = Utils.getValueFromIdByName(id, "maintenanceConfigurations"); if (resourceName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format( "The resource ID '%s' is not valid. Missing path segment 'maintenanceConfigurations'.", id))); } return this.getByResourceGroupWithResponse(resourceGroupName, resourceName, Context.NONE).getValue(); } public Response<MaintenanceConfiguration> getByIdWithResponse(String id, Context context) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourcegroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourcegroups'.", id))); } String resourceName = Utils.getValueFromIdByName(id, "maintenanceConfigurations"); if (resourceName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format( "The resource ID '%s' is not valid. Missing path segment 'maintenanceConfigurations'.", id))); } return this.getByResourceGroupWithResponse(resourceGroupName, resourceName, context); } public MaintenanceConfiguration deleteById(String id) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourcegroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourcegroups'.", id))); } String resourceName = Utils.getValueFromIdByName(id, "maintenanceConfigurations"); if (resourceName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format( "The resource ID '%s' is not valid. Missing path segment 'maintenanceConfigurations'.", id))); } return this.deleteWithResponse(resourceGroupName, resourceName, Context.NONE).getValue(); } public Response<MaintenanceConfiguration> deleteByIdWithResponse(String id, Context context) { String resourceGroupName = Utils.getValueFromIdByName(id, "resourcegroups"); if (resourceGroupName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format("The resource ID '%s' is not valid. Missing path segment 'resourcegroups'.", id))); } String resourceName = Utils.getValueFromIdByName(id, "maintenanceConfigurations"); if (resourceName == null) { throw logger .logExceptionAsError( new IllegalArgumentException( String .format( "The resource ID '%s' is not valid. Missing path segment 'maintenanceConfigurations'.", id))); } return this.deleteWithResponse(resourceGroupName, resourceName, context); } private MaintenanceConfigurationsClient serviceClient() { return this.innerClient; } private com.azure.resourcemanager.maintenance.MaintenanceManager manager() { return this.serviceManager; } public MaintenanceConfigurationImpl define(String name) { return new MaintenanceConfigurationImpl(name, this.manager()); } }
mit
sitewhere/sitewhere-tools
binary-decoder-archetype/src/main/resources/archetype-resources/src/main/java/__decoderJavaClass__.java
2506
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.sitewhere.rest.model.device.event.DeviceLocation; import com.sitewhere.rest.model.device.event.request.DeviceLocationCreateRequest; import com.sitewhere.rest.model.device.provisioning.DecodedDeviceEventRequest; import com.sitewhere.spi.SiteWhereException; import com.sitewhere.spi.device.provisioning.IDecodedDeviceEventRequest; import com.sitewhere.spi.device.provisioning.IDeviceEventDecoder; /** * Custom binary decoder. */ public class ${decoderJavaClass} implements IDeviceEventDecoder<byte[]> { /* * (non-Javadoc) * * @see * com.sitewhere.spi.device.provisioning.IDeviceEventDecoder#decode(java.lang.Object) */ @Override public List<IDecodedDeviceEventRequest> decode(byte[] payload) throws SiteWhereException { List<IDecodedDeviceEventRequest> events = new ArrayList<IDecodedDeviceEventRequest>(); events.add(decodeLocation(payload)); return events; } /** * Decode a {@link DeviceLocation} from a binary payload. * * @param payload * @return * @throws SiteWhereException */ protected IDecodedDeviceEventRequest decodeLocation(byte[] payload) throws SiteWhereException { DecodedDeviceEventRequest request = new DecodedDeviceEventRequest(); request.setHardwareId(parseHardwareId(payload)); request.setOriginator(parseOriginator(payload)); // Values below would be decoded from the binary payload. DeviceLocationCreateRequest location = new DeviceLocationCreateRequest(); location.setLatitude(33.7550); location.setLongitude(-84.3900); location.setElevation(333.0); location.setEventDate(new Date()); location.addOrReplaceMetadata("method", "gps"); return request; } /** * Parse hardware id from binary payload. The hardware id is the unique identifier * that SiteWhere uses to reference a device. Hardware id is required. * * @param payload * @return */ protected String parseHardwareId(byte[] payload) { return "parsed-hardware-id"; // Insert your own parse logic here. } /** * Parse originator from the binary payload. The originator is the event id of a * SiteWhere event that caused this event to fire. It is useful for linking responses * to SiteWhere commands. Originator may be null. * * @param payload * @return */ protected String parseOriginator(byte[] payload) { return null; } }
mit
PavelKniha/UcaOrm
src/com/ucasoft/orm/OrmFieldWorker.java
9657
package com.ucasoft.orm; import com.ucasoft.orm.annotations.Column; import com.ucasoft.orm.exceptions.NotFindTableAnnotation; import com.ucasoft.orm.exceptions.WrongListReference; import com.ucasoft.orm.exceptions.WrongRightJoinReference; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by UCASoft. * User: Antonov Sergey * Date: 10.07.13 * Time: 15:37 */ class OrmFieldWorker { static class ClassFieldsInfo { OrmField primaryKey; List<OrmField> fieldsWithoutKey; List<OrmField> foreignFields; HashMap<Class<? extends OrmEntity>, OrmField> referenceFields; } private static HashMap<Class<? extends OrmEntity>, ClassFieldsInfo> hashedClassesInfo = new HashMap<Class<? extends OrmEntity>, ClassFieldsInfo>(); static OrmField getPrimaryKeyField(Class<? extends OrmEntity> entityClass, boolean setAccessible) throws WrongRightJoinReference, NotFindTableAnnotation { OrmField field = getPrimaryKeyField(entityClass); if (setAccessible) // Special check true, don't do just field.setAccessible(setAccessible); field.setAccessible(true); return field; } static OrmField getPrimaryKeyField(Class<? extends OrmEntity> entityClass) throws NotFindTableAnnotation, WrongRightJoinReference { if (!hashedClassesInfo.containsKey(entityClass)){ ClassFieldsInfo classFieldsInfo = new ClassFieldsInfo(); classFieldsInfo.primaryKey = getPrimaryKeyField(entityClass, OrmTableWorker.getTableJoinLeftClass(entityClass)); hashedClassesInfo.put(entityClass, classFieldsInfo); } else { ClassFieldsInfo classFieldsInfo = hashedClassesInfo.get(entityClass); if (classFieldsInfo.primaryKey == null) classFieldsInfo.primaryKey = getPrimaryKeyField(entityClass, OrmTableWorker.getTableJoinLeftClass(entityClass)); } return hashedClassesInfo.get(entityClass).primaryKey; } private static OrmField getPrimaryKeyField(Class entityClass, Class<? extends OrmEntity> joinTo) { if (joinTo != null){ return new OrmField(joinTo, null); } if (!entityClass.equals(joinTo)) { for (Field field : entityClass.getDeclaredFields()) { Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation != null && columnAnnotation.primaryKey()) return new OrmField(field); } } if (OrmEntity.class.isAssignableFrom(entityClass.getSuperclass())) return getPrimaryKeyField(entityClass.getSuperclass(), joinTo); return null; } static List<OrmField> getAnnotationFieldsWithOutPrimaryKey(Class<? extends OrmEntity> entityClass) throws WrongListReference, WrongRightJoinReference, NotFindTableAnnotation { if (!hashedClassesInfo.containsKey(entityClass)){ ClassFieldsInfo fieldsInfo = new ClassFieldsInfo(); fieldsInfo.fieldsWithoutKey = getClassAnnotationFieldsWithOutPrimaryKey(entityClass, OrmTableWorker.getTableJoinLeftClass(entityClass), new ArrayList<OrmField>(), 0); hashedClassesInfo.put(entityClass, fieldsInfo); } else { ClassFieldsInfo fieldsInfo = hashedClassesInfo.get(entityClass); if (fieldsInfo.fieldsWithoutKey == null) fieldsInfo.fieldsWithoutKey = getClassAnnotationFieldsWithOutPrimaryKey(entityClass, OrmTableWorker.getTableJoinLeftClass(entityClass), new ArrayList<OrmField>(), 0); } return hashedClassesInfo.get(entityClass).fieldsWithoutKey; } static OrmField findAnnotationField(Class<? extends OrmEntity> entityClass, String columnName) throws NotFindTableAnnotation, WrongListReference, WrongRightJoinReference { for (OrmField field : getAllAnnotationFields(entityClass)) { if (DbColumn.getColumnName(field).equals(columnName)) { return field; } } return null; } private static List<OrmField> getClassAnnotationFieldsWithOutPrimaryKey(Class<? extends OrmEntity> entityClass, Class<? extends OrmEntity> jointTo, List<OrmField> allFields, int level) throws WrongListReference { ArrayList<OrmField> classFields = new ArrayList<OrmField>(); if (!entityClass.equals(jointTo)){ for (Field field : entityClass.getDeclaredFields()){ Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation != null && (level == 0 || columnAnnotation.inherited()) && !columnAnnotation.primaryKey()){ if (!checkForeign(entityClass, field)) classFields.add(new OrmField(field)); } } List<OrmField> fields = concatFields(allFields, classFields); Class superClass = entityClass.getSuperclass(); if (OrmEntity.class.isAssignableFrom(superClass)) return getClassAnnotationFieldsWithOutPrimaryKey(superClass, jointTo, fields, level + 1); return fields; } return allFields; } private static List<OrmField> concatFields(List<OrmField> allFields, List<OrmField> classFields) { if (classFields.size() == 0) return allFields; else { classFields.addAll(allFields); return classFields; } } static List<OrmField> getForeignFields(Class<? extends OrmEntity> entityClass) throws WrongListReference { if (!hashedClassesInfo.containsKey(entityClass)){ ClassFieldsInfo fieldsInfo = new ClassFieldsInfo(); fieldsInfo.foreignFields = getForeign(entityClass); hashedClassesInfo.put(entityClass, fieldsInfo); } else { ClassFieldsInfo fieldsInfo = hashedClassesInfo.get(entityClass); if (fieldsInfo.foreignFields == null) fieldsInfo.foreignFields = getForeign(entityClass); } return hashedClassesInfo.get(entityClass).foreignFields; } private static List<OrmField> getForeign(Class<? extends OrmEntity> entityClass) throws WrongListReference { ArrayList<OrmField> result = new ArrayList<OrmField>(); for (Field field : entityClass.getDeclaredFields()){ Column columnAnnotation = field.getAnnotation(Column.class); if (columnAnnotation != null && checkForeign(entityClass, field)) result.add(new OrmField(field)); } return result; } private static boolean checkForeign(Class parentClass, Field field) throws WrongListReference { Class type = field.getType(); if (type.getSimpleName().equals("List")) { ParameterizedType listType = (ParameterizedType) field.getGenericType(); Class itemType = (Class) listType.getActualTypeArguments()[0]; if (OrmEntity.class.isAssignableFrom(itemType)){ boolean okReference = false; for (Field classField : itemType.getDeclaredFields()){ if (classField.getType().equals(parentClass)) { okReference = true; break; } } if (!okReference) throw new WrongListReference(itemType, parentClass); } return true; } return false; } static List<OrmField> getAllAnnotationFields(Class<? extends OrmEntity> entityClass) throws WrongRightJoinReference, NotFindTableAnnotation, WrongListReference { ArrayList<OrmField> result = new ArrayList<OrmField>(); result.add(getPrimaryKeyField(entityClass)); result.addAll(getAnnotationFieldsWithOutPrimaryKey(entityClass)); return result; } static OrmField getReferenceField(Class<? extends OrmEntity> entityClass, Class<? extends OrmEntity> referenceTo) throws NotFindTableAnnotation, WrongListReference, WrongRightJoinReference { if (!hashedClassesInfo.containsKey(entityClass)) { ClassFieldsInfo classFieldsInfo = new ClassFieldsInfo(); classFieldsInfo.referenceFields = new HashMap<Class<? extends OrmEntity>, OrmField>(); classFieldsInfo.referenceFields.put(referenceTo, getClassReferenceField(entityClass, referenceTo)); hashedClassesInfo.put(entityClass, classFieldsInfo); } else { ClassFieldsInfo classFieldsInfo = hashedClassesInfo.get(entityClass); if (classFieldsInfo.referenceFields == null) { classFieldsInfo.referenceFields = new HashMap<Class<? extends OrmEntity>, OrmField>(); classFieldsInfo.referenceFields.put(referenceTo, getClassReferenceField(entityClass, referenceTo)); } else if (!classFieldsInfo.referenceFields.containsKey(referenceTo)) classFieldsInfo.referenceFields.put(referenceTo, getClassReferenceField(entityClass, referenceTo)); } return hashedClassesInfo.get(entityClass).referenceFields.get(referenceTo); } private static OrmField getClassReferenceField(Class<? extends OrmEntity> entityClass, Class<? extends OrmEntity> referenceTo) throws NotFindTableAnnotation, WrongListReference, WrongRightJoinReference { for (OrmField field : getAnnotationFieldsWithOutPrimaryKey(entityClass)){ if (referenceTo.isAssignableFrom(field.getType())) return field; } return null; } }
mit
hujianhong/Java
design-pattern/src/main/java/me/huding/designpattern/flyweight/FlyweightFactory.java
447
package me.huding.designpattern.flyweight; import java.util.HashMap; import java.util.Map; public class FlyweightFactory { private static Map<String, Flyweight> map = new HashMap<>(); private FlyweightFactory(){} public static Flyweight getFlyweight(String istate){ Flyweight flyweight = map.get(istate); if(flyweight == null){ flyweight = new ConcreteFlyweight(istate); map.put(istate, flyweight); } return flyweight; } }
mit
rearadmiral/log-o-matic-android
src/main/java/com/dephillipsdesign/logomatic/LogLevel.java
97
package com.dephillipsdesign.logomatic; public enum LogLevel { DEBUG, INFO, ERROR }
mit
Pisi-Deff/TestTaskInvoiceSystem
src/main/java/ee/eerikmagi/testtasks/arvato/invoice_system/logic/AbstractCustomerPaymentLogic.java
4254
package ee.eerikmagi.testtasks.arvato.invoice_system.logic; import java.math.BigDecimal; import java.time.LocalDateTime; import java.time.YearMonth; import java.util.ArrayList; import java.util.List; import ee.eerikmagi.testtasks.arvato.invoice_system.model.Customer; import ee.eerikmagi.testtasks.arvato.invoice_system.model.Invoice; import ee.eerikmagi.testtasks.arvato.invoice_system.model.InvoiceEntry; import ee.eerikmagi.testtasks.arvato.invoice_system.model.InvoiceEntryType; import ee.eerikmagi.testtasks.arvato.invoice_system.model.InvoiceParking; import ee.eerikmagi.testtasks.arvato.invoice_system.model.Parking; /** * Abstract base class for customer payment logic. * * Contains logic that is shared between {@link RegularCustomerPaymentLogic} and {@link PremiumCustomerPaymentLogic} */ public abstract class AbstractCustomerPaymentLogic implements IPaymentLogic { private static final int HOUR_EXPENSIVE_TIME_END = 19; private static final int HOUR_EXPENSIVE_TIME_START = 7; private static final int TIMEUNIT_MINUTES = 30; @Override public Invoice calculateInvoice(Customer customer, List<Parking> parkings, YearMonth ym) { return calculateInvoice(customer, parkings, ym, LocalDateTime.now()); } @Override public Invoice calculateInvoice(Customer customer, List<Parking> parkings, YearMonth ym, LocalDateTime dt) { List<InvoiceEntry> entries = new ArrayList<>(); parkings.stream().forEach((p) -> entries.add(getParkingEntry(p))); BigDecimal total = entries.stream() .map((e) -> e.getCost()) .reduce(BigDecimal.ZERO, (tot, cost) -> tot.add(cost)); Invoice inv = new Invoice() .setEntries(entries) .setTotal(total) .setFinalSum(total) .setIncomplete(isCurrentMonth(dt, ym)); return inv; } /** * Creates an {@link InvoiceEntry} based on the provided {@link Parking} object. * Calculates the spans and costs of that parking. * * @param parking The parking object to handle. * @return The invoice entry for the given parking object. */ protected InvoiceEntry getParkingEntry(Parking parking) { List<InvoiceParking> parkings = new ArrayList<>(); LocalDateTime start = parking.getStartDateTime(); LocalDateTime end = parking.getEndDateTime(); LocalDateTime cursor = start; long ipTimeUnitsCount = 0; // go through the time difference in TIMEUNIT_MINUTES chunks and split it into spans if // the parking goes through a cheap-expensive time change while (cursor.isBefore(end)) { ipTimeUnitsCount++; LocalDateTime next = cursor.plusMinutes(TIMEUNIT_MINUTES); if (next.isBefore(end) && hasTimerangeChanged(cursor, next)) { parkings.add(createParkingSpan(parking, start, next, ipTimeUnitsCount)); ipTimeUnitsCount = 0; start = next; } cursor = next; } parkings.add(createParkingSpan(parking, start, end, ipTimeUnitsCount)); return new InvoiceEntry() .setParking(parking) .setParkingSpans(parkings) .setType(InvoiceEntryType.PARKING) .setCost(parkings.stream() .map((p) -> p.getCost()) .reduce(BigDecimal.ZERO, (tot, cost) -> tot.add(cost)) .setScale(2)); } protected boolean hasTimerangeChanged(LocalDateTime cursor, LocalDateTime next) { return isCheapTime(cursor) && !isCheapTime(next) || !isCheapTime(cursor) && isCheapTime(next); } protected InvoiceParking createParkingSpan(Parking p, LocalDateTime start, LocalDateTime end, long ipTimeUnitsCount) { BigDecimal timeUnitCost = getTimeUnitCost(start); return new InvoiceParking() .setParking(new Parking() .setStartDateTime(start) .setEndDateTime(end) .setParkingHouse(p.getParkingHouse()) ) .setTimeUnitMinutes(TIMEUNIT_MINUTES) .setTimeUnitsCount(ipTimeUnitsCount) .setTimeUnitCost(timeUnitCost) .setCost(timeUnitCost.multiply(BigDecimal.valueOf(ipTimeUnitsCount))); } protected boolean isCheapTime(LocalDateTime dt) { return dt.getHour() < HOUR_EXPENSIVE_TIME_START || dt.getHour() >= HOUR_EXPENSIVE_TIME_END; } protected boolean isCurrentMonth(LocalDateTime dt, YearMonth ym) { return YearMonth.from(dt).equals(ym); } /** * Returns the cost per time unit at the provided time. */ abstract protected BigDecimal getTimeUnitCost(LocalDateTime dateTime); }
mit
bing-ads-sdk/BingAds-Java-SDK
proxies/com/microsoft/bingads/v12/campaignmanagement/GetKeywordsByAdGroupIdRequest.java
2619
package com.microsoft.bingads.v12.campaignmanagement; import java.util.Collection; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="AdGroupId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="ReturnAdditionalFields" type="{https://bingads.microsoft.com/CampaignManagement/v12}KeywordAdditionalField" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "adGroupId", "returnAdditionalFields" }) @XmlRootElement(name = "GetKeywordsByAdGroupIdRequest") public class GetKeywordsByAdGroupIdRequest { @XmlElement(name = "AdGroupId") protected Long adGroupId; @XmlElement(name = "ReturnAdditionalFields", type = String.class, nillable = true) @XmlJavaTypeAdapter(Adapter13 .class) protected Collection<KeywordAdditionalField> returnAdditionalFields; /** * Gets the value of the adGroupId property. * * @return * possible object is * {@link Long } * */ public Long getAdGroupId() { return adGroupId; } /** * Sets the value of the adGroupId property. * * @param value * allowed object is * {@link Long } * */ public void setAdGroupId(Long value) { this.adGroupId = value; } /** * Gets the value of the returnAdditionalFields property. * * @return * possible object is * {@link String } * */ public Collection<KeywordAdditionalField> getReturnAdditionalFields() { return returnAdditionalFields; } /** * Sets the value of the returnAdditionalFields property. * * @param value * allowed object is * {@link String } * */ public void setReturnAdditionalFields(Collection<KeywordAdditionalField> value) { this.returnAdditionalFields = value; } }
mit
AllTheMods/CraftTweaker
ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeIntRange.java
6723
package stanhebben.zenscript.type; import org.objectweb.asm.*; import stanhebben.zenscript.annotations.*; import stanhebben.zenscript.compiler.*; import stanhebben.zenscript.expression.*; import stanhebben.zenscript.expression.partial.IPartialExpression; import stanhebben.zenscript.type.casting.ICastingRuleDelegate; import stanhebben.zenscript.type.natives.*; import stanhebben.zenscript.util.*; import stanhebben.zenscript.value.IntRange; import static stanhebben.zenscript.util.ZenTypeUtil.signature; /** * @author Stan */ public class ZenTypeIntRange extends ZenType { public static final ZenTypeIntRange INSTANCE = new ZenTypeIntRange(); private final IJavaMethod methodFrom; private final IJavaMethod methodTo; private ZenTypeIntRange() { ITypeRegistry dummy = new TypeRegistry(); methodFrom = JavaMethod.get(dummy, IntRange.class, "getFrom"); methodTo = JavaMethod.get(dummy, IntRange.class, "getTo"); } @Override public String getAnyClassName(IEnvironmentGlobal global) { throw new UnsupportedOperationException("range values cannot yet be used as any value"); } @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { environment.error(position, "cannot apply unary operators on int ranges"); return new ExpressionInvalid(position); } @Override public Expression binary(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, OperatorType operator) { environment.error(position, "cannot apply binary operators on int ranges"); return new ExpressionInvalid(position); } @Override public Expression trinary(ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { environment.error(position, "cannot apply ternary operators on int ranges"); return new ExpressionInvalid(position); } @Override public Expression compare(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { environment.error(position, "cannot compare int ranges"); return new ExpressionInvalid(position, BOOL); } @Override public IPartialExpression getMember(ZenPosition position, IEnvironmentGlobal environment, IPartialExpression value, String name) { switch(name) { case "from": return new ExpressionCallVirtual(position, environment, methodFrom, value.eval(environment)); case "to": return new ExpressionCallVirtual(position, environment, methodTo, value.eval(environment)); default: environment.error(position, "no such member " + name + " in int range"); return new ExpressionInvalid(position); } } @Override public IPartialExpression getStaticMember(ZenPosition position, IEnvironmentGlobal environment, String name) { environment.error(position, "int ranges don't have static members"); return new ExpressionInvalid(position); } @Override public Expression call(ZenPosition position, IEnvironmentGlobal environment, Expression receiver, Expression... arguments) { environment.error(position, "int ranges cannot be called"); return new ExpressionInvalid(position); } @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { } /* * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal * environment, Expression value, ZenType type) { if (type == this) { return * value; } * * environment.error(position, "cannot cast int ranges to any other type"); * return new ExpressionInvalid(position); } */ @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { if(numValues == 1) { return new IntRangeIterator(methodOutput); } else { return null; } } /* * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal * environment) { return type == this; } * * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal * environment) { return type == this; } */ @Override public Class toJavaClass() { return IntRange.class; } @Override public Type toASMType() { return Type.getType(IntRange.class); } @Override public int getNumberType() { return 0; } @Override public String getSignature() { return signature(IntRange.class); } @Override public boolean isPointer() { return true; } /* * @Override public void compileCast(ZenPosition position, * IEnvironmentMethod environment, ZenType type) { throw new * UnsupportedOperationException("Not supported yet."); //To change body of * generated methods, choose Tools | Templates. } */ @Override public String getName() { return "int.."; } @Override public Expression defaultValue(ZenPosition position) { return new ExpressionNull(position); } private class IntRangeIterator implements IZenIterator { private final IEnvironmentMethod method; public IntRangeIterator(IEnvironmentMethod methodOutput) { this.method = methodOutput; } @Override public void compileStart(int[] locals) { MethodOutput output = method.getOutput(); output.dup(); // copy IntRange reference methodFrom.invokeVirtual(output); output.storeInt(locals[0]); methodTo.invokeVirtual(output); } @Override public void compilePreIterate(int[] locals, Label exit) { } @Override public void compilePostIterate(int[] locals, Label exit, Label repeat) { MethodOutput output = method.getOutput(); output.dup(); // copy limit output.iinc(locals[0]); output.loadInt(locals[0]); output.ifICmpGT(repeat); output.goTo(exit); } @Override public void compileEnd() { method.getOutput().pop(); // remove limit } @Override public ZenType getType(int i) { return INT; } } }
mit
pknj/kobietydokodu.pl
koty-application/src/main/java/pl/kobietydokodu/koty/ExampleController.java
604
package pl.kobietydokodu.koty; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ExampleController { @RequestMapping("/przyklad/model") public String przykladModelu(Model model) { model.addAttribute("message", "To jest jakaœ super informacja"); return "glowny"; } @RequestMapping("/kot/{imie}") public String szczegolyKota(@PathVariable("imie") String imieKota) { return "glowny"; } }
mit
PanagiotisDrakatos/Universal-Encryption-Channel
SecureJavaChannel/src/main/java/IOSocket/SocketIOException.java
386
package IOSocket; public class SocketIOException extends Exception { public SocketIOException() { super(); } public SocketIOException(String message) { super(message); } public SocketIOException(String message, Throwable cause) { super(message, cause); } public SocketIOException(Throwable cause) { super(cause); } }
mit
exohuman/example-gradle-layout
java-project/src/main/java/com/jeromestepp/example/main.java
166
package com.jeromestepp.example; public class main { public static void main(String[] args) { Adder adder = new Adder(); int result = adder.add(2, 4); } }
mit
Gnail-nehc/testclient
src/com/testclient/service/BatchTestService.java
21744
package com.alipics.testassets.testclient.service; import java.io.File; import java.io.IOException; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.log4j.Priority; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.alipics.testassets.testclient.enums.BatchTestingFolderName; import com.alipics.testassets.testclient.enums.HistoryFolderName; import com.alipics.testassets.testclient.enums.LabFolderName; import com.alipics.testassets.testclient.enums.LoopParameterNameInForm; import com.alipics.testassets.testclient.enums.RunningStatus; import com.alipics.testassets.testclient.enums.SeperatorDefinition; import com.alipics.testassets.testclient.enums.TestSetFileName; import com.alipics.testassets.testclient.enums.TestStatus; import com.alipics.testassets.testclient.enums.TimeFormatDefiniation; import com.alipics.testassets.testclient.factory.JsonObjectMapperFactory; import com.alipics.testassets.testclient.httpmodel.BatchTestItem; import com.alipics.testassets.testclient.httpmodel.DataGridJson; import com.alipics.testassets.testclient.httpmodel.Json; import com.alipics.testassets.testclient.httpmodel.TestExecutionJson; import com.alipics.testassets.testclient.httpmodel.TestExecutionStore; import com.alipics.testassets.testclient.httpmodel.TestHistoryItem; import com.alipics.testassets.testclient.httpmodel.TestResultItem; import com.alipics.testassets.testclient.model.HttpTarget; import com.alipics.testassets.testclient.model.KeyValue; import com.alipics.testassets.testclient.model.Parameter; import com.alipics.testassets.testclient.utils.Auto; import com.alipics.testassets.testclient.utils.FileNameUtils; import com.alipics.testassets.testclient.utils.MyFileUtils; import com.alipics.testassets.testclient.utils.TemplateUtils; @Service("batchTestService") public class BatchTestService { private static final Logger logger = Logger.getLogger(TestHistoryService.class); @Autowired TestExecuteService testExecuteService; @Autowired LabEnvironmentService labEnvironmentService; public synchronized String executeBatchTest(String dirPath,Date date){ SimpleDateFormat format = new SimpleDateFormat(TimeFormatDefiniation.timeFolderFormat); String runid=format.format(null==date?new Date():date); String batchtestingfolderpath=dirPath+"/"+BatchTestingFolderName.folderName+"/"+runid; try{ List<String> list=new ArrayList<String>(); if(dirPath.endsWith("-d")) getTestsInfoUnderSpecificDir(dirPath,list); else getTestsInfoUnderSpecificRunningSet(dirPath,list); for(String defaultTest : list){ try{ String[] info = defaultTest.split(SeperatorDefinition.seperator); String testpath=info[0]; String testfilename=info[1]; Map<String,Map<String,String>> global_reference_in=new HashMap<String,Map<String,String>>(),global_reference_out=new HashMap<String,Map<String,String>>(); //一条case可能循环跑了多次 List<TestResultItem> tris = executeTestByPath(testpath,global_reference_in,global_reference_out); for(TestResultItem testresult : tris){ generateBatchExecutionResultFile(batchtestingfolderpath,testpath,testresult,testfilename); } }catch(Exception ex){ logger.error(ex.getMessage()); } } }catch(Exception ex){ logger.error(ex.getMessage()); } return batchtestingfolderpath; } public List<TestResultItem> executeTestByPath(String testpath,Map<String,Map<String,String>> global_reference_in,Map<String,Map<String,String>> global_reference_out){ List<TestResultItem> list = new ArrayList<TestResultItem>(); try{ Map parameters=new HashMap(); TestResultItem testresult = new TestResultItem(); String teststarttime=testresult.getTime(); try{ testExecuteService.setupAction(testpath,parameters,global_reference_in,global_reference_out); parameters = testExecuteService.getRequestParameterMap(testpath,global_reference_in,global_reference_out); testresult = testExecuteService.getTestResultItem(testpath,parameters); if(!testresult.getResult().equals(TestStatus.exception)){ testExecuteService.getCheckpointsAndResultFromFile(testpath,parameters,testresult.getResponseInfo(),testresult); } }catch(Exception e){ testresult.setResult(TestStatus.exception); testresult.setComment("批量执行失败.\n"+e.getClass().toString()+e.getMessage()); } finally{ testExecuteService.teardownAction(testpath,parameters,testresult.getResponseInfo(),global_reference_in,global_reference_out); generateHistoryFileByTestPath(testpath,testresult); list.add(testresult); } }catch(Exception e){ TestResultItem testresult = new TestResultItem(); testresult.setDuration(""); testresult.setResult(TestStatus.exception); testresult.setComment("getRequestParameterMap失败.\n"+e.getClass().toString()+e.getMessage()); generateHistoryFileByTestPath(testpath,testresult); list.add(testresult); } return list; } public void executeTestByPathWithoutCheckpoint(String testpath,Map<String,Map<String,String>> global_reference_in,Map<String,Map<String,String>> global_reference_out){ try{ Map<String,Object> parameters=new HashMap<String,Object>(); parameters = testExecuteService.getRequestParameterMap(testpath,global_reference_in,global_reference_out); Map<String,String> reqparas=global_reference_in.containsKey(testpath) ? global_reference_in.get(testpath) : new HashMap<String,String>(); for(Entry<String,Object> en : parameters.entrySet()){ String val=en.getValue().toString(); String name=en.getKey().toString(); reqparas.put(name, val); } global_reference_in.put(testpath, reqparas); String looptimes=(String)parameters.get(LoopParameterNameInForm.name); looptimes=looptimes!=null ?looptimes:"1"; String[] loopparas=looptimes.split(SeperatorDefinition.seperator); looptimes=loopparas[0]; if(!looptimes.isEmpty() && StringUtils.isNumeric(looptimes)){ for(int i=0;i<Integer.parseInt(looptimes);i++){ if(loopparas.length>1) Thread.sleep(Integer.parseInt(StringUtils.isNumeric(loopparas[1])?loopparas[1]:"1")); TestResultItem testresult = new TestResultItem(); String teststarttime=testresult.getTime(); try{ testExecuteService.setupAction(testpath,parameters,global_reference_in,global_reference_out); testExecuteService.getTestResultItem(testpath,parameters); }catch(Exception e){ } finally{ testExecuteService.teardownAction(testpath,parameters,testresult.getResponseInfo(),global_reference_in,global_reference_out); } } } }catch(Exception e){ } } public TestExecutionJson runTest(String source,int loop,Date date){ TestExecutionStore store = TestExecutionStore.getInstance(); Map<String,TestExecutionJson> result=store.getResultStore(); TestExecutionJson json = new TestExecutionJson(); if(result.containsKey(source)){ json=result.get(source); } int total=json.getTotal(),pass=0,fail=0,invalid=0,error=0,norun=json.getNorun(); while(loop-->0){ if(null!=source && !source.isEmpty()){ SimpleDateFormat format = new SimpleDateFormat(TimeFormatDefiniation.standard); if(null==date){ date=new Date(); } String time=format.format(date); if(source.endsWith("-c")){ Map<String,Map<String,String>> global_reference_in=new HashMap<String,Map<String,String>>(),global_reference_out=new HashMap<String,Map<String,String>>(); List<TestResultItem> tris = executeTestByPath(source,global_reference_in,global_reference_out); total=tris.size(); for(TestResultItem tri : tris){ String res=tri.getResult(); if(res.endsWith(TestStatus.pass) || res.equalsIgnoreCase("p")){ pass++; }else if(res.endsWith(TestStatus.fail) || res.equalsIgnoreCase("f")){ fail++; }else if(res.endsWith(TestStatus.invalid) || res.equalsIgnoreCase("i")){ invalid++; }else if(res.endsWith(TestStatus.exception) || res.equalsIgnoreCase("e")){ error++; }else{ norun++; } } String status=norun==0 ? RunningStatus.completed : RunningStatus.suspend+","+(pass+fail+invalid+error)+"/"+total+" be executed"; json.setLasttime(json.getTime()); json.setTime(time); json.setLaststatus(json.getStatus()); json.setStatus(status); json.setRunningtimes(json.getRunningtimes()+"+1"); //json.setReportview("http://test:!qazxsw2@192.168.81.33/testclient#report="+source); json.setTotal(total); json.setPass(pass); json.setFail(fail); json.setInvalid(invalid); json.setError(error); json.setNorun(total-pass-fail-invalid-error); }else{ String filename=source.contains("/")?source:getRunningSetFoldername(source); String batchTestingFolderPath=executeBatchTest(filename,date); json=retrieveBatchTestExecutionJson(source,date,batchTestingFolderPath,null); } }else{ json.setStatus("parameter 'source' configuration error."); } } //update resultstore for source result.put(source, json); store.setResultStore(result); return json; } public TestExecutionJson retrieveBatchTestExecutionJson(String source,Date date,String batchTestingFolderPath, String runningstatus){ TestExecutionStore store = TestExecutionStore.getInstance(); Map<String,TestExecutionJson> result=store.getResultStore(); TestExecutionJson json = new TestExecutionJson(); if(result.containsKey(source)){ json=result.get(source); } int total=json.getTotal(),pass=0,fail=0,invalid=0,error=0,norun=json.getNorun(); date=null!=date?date:new Date(); String time=new SimpleDateFormat(TimeFormatDefiniation.timeFolderFormat).format(date); if(null==batchTestingFolderPath || batchTestingFolderPath.isEmpty()){ batchTestingFolderPath="/"+BatchTestingFolderName.folderName+"/"+time; if(!source.contains("/")){ String fullname=getRunningSetFoldername(source); batchTestingFolderPath="root/"+LabFolderName.folder+"/"+fullname+batchTestingFolderPath; }else{ batchTestingFolderPath=source+batchTestingFolderPath; } } File folder=new File(batchTestingFolderPath); if(!folder.exists()){ batchTestingFolderPath=StringUtils.substringBeforeLast(batchTestingFolderPath, "/"); File f=new File(batchTestingFolderPath); batchTestingFolderPath=getRecentTest(f); folder=new File(f,batchTestingFolderPath); } for(String filename : folder.list()){ String res=StringUtils.substringAfterLast(filename, SeperatorDefinition.seperator); if(res.endsWith(TestStatus.pass) || res.equalsIgnoreCase("p")){ pass++; }else if(res.endsWith(TestStatus.fail) || res.equalsIgnoreCase("f")){ fail++; }else if(res.endsWith(TestStatus.invalid) || res.equalsIgnoreCase("i")){ invalid++; }else if(res.endsWith(TestStatus.exception) || res.equalsIgnoreCase("e")){ error++; } } norun=total-folder.list().length; if(null==runningstatus || runningstatus.isEmpty()){ runningstatus=norun==0 ? RunningStatus.completed : RunningStatus.suspend+","+folder.list().length+"/"+total+" be executed"; } //json.setTime(new SimpleDateFormat(TimeFormatDefiniation.standard).format(date)); json.setStatus(runningstatus); //json.setTotal(total); json.setPass(pass); json.setFail(fail); json.setInvalid(invalid); json.setError(error); json.setNorun(norun); result.put(source, json); store.setResultStore(result); return json; } //return .json history filename private void generateHistoryFileByTestPath(String testpath,TestResultItem testresult){ //generate history file String filename=FileNameUtils.getResultFile(testresult.getTime(),testresult.getDuration(),testresult.getResult()); try { File history=new File(testpath+"/"+HistoryFolderName.folderName); if(!history.exists()){ history.mkdirs(); } File file=new File(history,filename); file.createNewFile(); ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper(); mapper.writeValue(file, testresult); } catch (IOException e) { // TODO Auto-generated catch block logger.error("写历史记录文件失败:\n" + e.getClass().toString() + e.getMessage()); } } private void generateBatchExecutionResultFile(String batchtestingfolderpath,String testpath,TestResultItem testresult,String testfilename){ try { //create folder under BatchTesting MyFileUtils.makeDir(batchtestingfolderpath); //generate test item file under BatchTesting String teststarttime = testresult.getTime(); String duration = testresult.getDuration(); String result = testresult.getResult(); testfilename=FileNameUtils.getTestRunFile(testfilename, teststarttime, duration, result); File file=new File(batchtestingfolderpath,testfilename); file.createNewFile(); String history=FileNameUtils.getResultFile(testresult.getTime(),testresult.getDuration(),testresult.getResult()); String content=testpath+"/"+HistoryFolderName.folderName+SeperatorDefinition.testInfoSeperator+history; FileUtils.writeStringToFile(file, content); }catch (IOException e) { logger.error("写批量执行结果文件失败:\n" + e.getClass().toString() + e.getMessage()); } } public DataGridJson getRecentTestItems(String dirPath){ DataGridJson j = new DataGridJson(); if(dirPath.isEmpty()) return j; List<BatchTestItem> row=new ArrayList<BatchTestItem>(); if(!dirPath.endsWith("-c")){ row=getDefaultTestItems(dirPath); File dir=new File(dirPath+"/"+BatchTestingFolderName.folderName); String recentRunid=getRecentTest(dir); dir=new File(dirPath+"/BatchTesting/"+recentRunid); String[] files = dir.list(); for(String filename : files){ String seperator=SeperatorDefinition.seperator; String tname=filename.split(seperator)[0]; for(BatchTestItem bti : row){ if(bti.getName().equals(tname) && !bti.isDoesrun()){ BatchTestItem item= new BatchTestItem(); item.setName(tname); item.setTestpath(bti.getTestpath()); item.setPath(dirPath+"/"+BatchTestingFolderName.folderName+"/"+recentRunid+"/"+filename); item.setTime(filename.split(seperator)[1]); item.setDuration(filename.split(seperator)[2]); item.setStatus(StringUtils.substringBefore(filename.split(seperator)[3], ".")); item.setDoesrun(true); row.remove(bti); row.add(item); break; } } } }else{ File f=new File(dirPath+"/"+HistoryFolderName.folderName); if(f.exists() && f.isDirectory()){ String filename=getRecentTest(f); if(!filename.isEmpty()){ String name=StringUtils.substringAfterLast(filename, "/"); if(name.endsWith("-c")){ name=StringUtils.substringBeforeLast(name, "-c"); } String time=filename.split(SeperatorDefinition.seperator)[0]; String duration=filename.split(SeperatorDefinition.seperator)[1]; String status=filename.split(SeperatorDefinition.seperator)[2]; status=status.isEmpty()?"r":status; BatchTestItem item= new BatchTestItem(); item.setName(name); item.setTime(time); item.setDuration(duration); item.setStatus(status); item.setTestpath(dirPath); item.setPath(dirPath+"/"+HistoryFolderName.folderName+"/"+filename); row.add(item); } } } j.setRows(row); j.setTotal(row.size()); return j; } public Json getDetailTestResultByTestPath(String path){ Json j =new Json(); try{ TestResultItem tri=new TestResultItem(); File file = new File(path); if(file.exists() && file.isFile()){ if(!path.contains(HistoryFolderName.folderName)){ String content = FileUtils.readFileToString(file); String historypath=content.split(SeperatorDefinition.testInfoSeperator)[0]; String historyfile=content.split(SeperatorDefinition.testInfoSeperator)[1]; file=new File(historypath); file=new File(file,historyfile); } if(file.exists()){ ObjectMapper mapper = JsonObjectMapperFactory.getObjectMapper(); tri = mapper.readValue(file, TestResultItem.class); } else{ tri.setComment("历史记录已删除,是否删除该条目"); } } else tri.setResult(TestStatus.ready); j.setObj(tri); j.setSuccess(true); }catch (IOException e) { j.setSuccess(false); j.setMsg("获取历史记录失败,"+e.getClass().toString()+": "+e.getMessage()); logger.error("获取历史记录失败", e); } return j; } public Json deleteTestInfo(String folder, String time){ Json j =new Json(); try{ File dir = new File(folder+"/"+BatchTestingFolderName.folderName); String[] files = dir.list(); for(int i=0;i<files.length;i++){ String recentTimeFolder = getRecentTest(files); if(recentTimeFolder!=""){ File timeFolder=new File(folder+"/BatchTesting/"+recentTimeFolder); for(String testInfo : timeFolder.list()){ if(testInfo.startsWith(time)){ File f=new File(timeFolder,testInfo); if(f.isFile() && f.exists()){ f.delete(); j.setSuccess(true); break; } } } files=files.toString().replace(recentTimeFolder, "").replace("[", "").replace("]", "").replace(" ", "").split(","); } } } catch (Exception e) { j.setSuccess(false); logger.error("删除TestInfo失败", e); } return j; } private String getRecentTest(File dir){ String[] list = dir.list(); if(list.length>0) return Collections.max(Arrays.asList(list)); else return ""; } private String getRecentTest(String[] list){ if(list.length>0) return Collections.max(Arrays.asList(list)); else return ""; } private List<BatchTestItem> getDefaultTestItems(String dirPath){ List<BatchTestItem> row=new ArrayList<BatchTestItem>(); List<String> testsinfo=new ArrayList<String>(); returnTestsInfoUnderSpecificDir(dirPath,testsinfo); for(String info : testsinfo){ String[] arr=info.split(SeperatorDefinition.seperator); if(arr.length==2){ BatchTestItem bti = new BatchTestItem(); bti.setTestpath(arr[0]); bti.setName(arr[1]); bti.setStatus(TestStatus.ready); row.add(bti); } } return row; } public void returnTestsInfoUnderSpecificDir(String dirPath,List<String> testPaths){ MyFileUtils.makeDir(dirPath+"/"+BatchTestingFolderName.folderName); if(dirPath.endsWith("-d")) getTestsInfoUnderSpecificDir(dirPath,testPaths); else getTestsInfoUnderSpecificRunningSet(dirPath,testPaths); } private void getTestsInfoUnderSpecificDir(String dirPath,List<String> list){ File dir=new File(dirPath); String folder[] = dir.list(); for (String f : folder) { String childpath=dirPath.replace("\\", "/")+"/"+f; if(f.endsWith("-d")){ getTestsInfoUnderSpecificDir(childpath, list); } else if(f.endsWith("-c")){ String filename=f.substring(0, f.length()-2); list.add(childpath+SeperatorDefinition.seperator+filename); } } } private void getTestsInfoUnderSpecificRunningSet(String dirPath,List<String> list){ String runningSetFullName=dirPath; if(!dirPath.contains("@")){ for(String fn : new File("root/"+LabFolderName.folder).list()){ if(fn.startsWith(dirPath)){ runningSetFullName="root/"+LabFolderName.folder+"/"+fn; break; } } } String[] tests=labEnvironmentService.getAllTestPathInRunningSet(runningSetFullName); for(String testpath : tests){ String[] arr=testpath.split("/"); String filename=arr[arr.length-1]; if(filename.endsWith("-c")){ String testname=filename.substring(0, filename.length()-2); list.add(testpath+SeperatorDefinition.seperator+testname); } } } //folder: path or runningset name public int getNumberOfCaseFromFolder(String folder){ //dir int total=0; File f=new File(folder); if(folder.contains("/")){ total=getNumberOfCaseUnderDir(f); }else{//runningset if(!folder.isEmpty()){ f=new File("root/"+LabFolderName.folder+"/"+folder+"/"+TestSetFileName.TestSet); if(f.exists() && f.isFile()){ try { String content=FileUtils.readFileToString(f); total=content.split(SeperatorDefinition.seperator).length; } catch (IOException e) { // TODO Auto-generated catch block total=0; logger.error("读文件异常,"+e.getClass()+e.getMessage()); } } } } return total; } private int getNumberOfCaseUnderDir(File f){ int total = 0; if(f.exists() && f.isDirectory()){ if(f.getName().endsWith("-d")){ for(File child : f.listFiles()){ total += getNumberOfCaseUnderDir(child); } }else if(f.getName().endsWith("-c")){ total = 1; } } return total; } public String getRunningSetFoldername(String name){ File f=new File("root/"+LabFolderName.folder); if(f.exists() && f.isDirectory()){ for(String filename : f.list()){ if(filename.startsWith(name+SeperatorDefinition.seperator)) return filename; } } return ""; } }
mit
johan-gorter/Instantlogic
instantlogic-interaction/src/main/java/org/instantlogic/interaction/ApplicationEnvironment.java
394
package org.instantlogic.interaction; /** * The environment is injected into the application. * * Here are methods that are available to the application. */ public interface ApplicationEnvironment { // TODO: Consider usefullness // public void addTransactionListener(TransactionListener listener); public void setPersistenceStrategy(PersistenceStrategy newPersistenceStrategy); }
mit
danask/Java_Algorithms
src/ask/ctci/hard/LongestWord.java
1203
package ask.ctci.hard; import java.util.Arrays; import java.util.HashMap; public class LongestWord { public static String printLongestWord(String arr[]) { HashMap<String, Boolean> map = new HashMap<String, Boolean>(); for (String str : arr) { map.put(str, true); } Arrays.sort(arr, new LengthComparator()); // Sort by length for (String s : arr) { if (canBuildWord(s, true, map)) { System.out.println(s); return s; } } return ""; } public static boolean canBuildWord(String str, boolean isOriginalWord, HashMap<String, Boolean> map) { if (map.containsKey(str) && !isOriginalWord) { return map.get(str); } for (int i = 1; i < str.length(); i++) { String left = str.substring(0, i); String right = str.substring(i); if (map.containsKey(left) && map.get(left) == true && canBuildWord(right, false, map)) { return true; } } map.put(str, false); return false; } public static void main(String[] args) { String[] arr = createGiantArray(); printLongestWord(arr); } public static String[] createGiantArray() { String arr[] = {"dog", "d", "boy", "walk", "walker", "dogwalk", "dogwalker"}; return arr; } }
mit
kentchiu/tree
src/test/java/com/kentchiu/tree/visitor/TreePrintVisitorTest.java
3672
package com.kentchiu.tree.visitor; import com.kentchiu.tree.domain.Composite; import com.kentchiu.tree.domain.Composites; import org.junit.Test; import java.util.List; import java.util.function.Function; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class TreePrintVisitorTest { @Test public void testDumpTree() throws Exception { Function<Composite, String> function = composite -> composite.getId(); TreePrintVisitor<Composite> visitor = new TreePrintVisitor<>(function); Composites.root().accept(visitor); List<String> lines = visitor.getLines(); int i = 0; assertThat(lines.get(i++), is(" ├─ root")); assertThat(lines.get(i++), is(" │ ├─ 0")); assertThat(lines.get(i++), is(" │ │ ├─ 0_0")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_0_0")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_0_0")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_0_1")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_0_2")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_0_3")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_0_1")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_1_0")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_1_1")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_1_2")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_1_3")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_0_2")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_2_0")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_2_1")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_2_2")); assertThat(lines.get(i++), is(" │ │ │ │ ├─ 0_0_2_3")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_0_3")); assertThat(lines.get(i++), is(" │ │ ├─ 0_1")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_1_0")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_1_1")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_1_2")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_1_3")); assertThat(lines.get(i++), is(" │ │ ├─ 0_2")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_2_0")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_2_1")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_2_2")); assertThat(lines.get(i++), is(" │ │ │ ├─ 0_2_3")); assertThat(lines.get(i++), is(" │ │ ├─ 0_3")); assertThat(lines.get(i++), is(" │ ├─ 1")); assertThat(lines.get(i++), is(" │ │ ├─ 1_0")); assertThat(lines.get(i++), is(" │ │ ├─ 1_1")); assertThat(lines.get(i++), is(" │ │ ├─ 1_2")); assertThat(lines.get(i++), is(" │ │ ├─ 1_3")); assertThat(lines.get(i++), is(" │ ├─ 2")); assertThat(lines.get(i++), is(" │ │ ├─ 2_0")); assertThat(lines.get(i++), is(" │ │ ├─ 2_1")); assertThat(lines.get(i++), is(" │ │ ├─ 2_2")); assertThat(lines.get(i++), is(" │ │ ├─ 2_3")); assertThat(lines.get(i++), is(" │ ├─ 3")); assertThat(lines.get(i++), is(" │ ├─ 4")); assertThat(lines.get(i++), is(" │ ├─ 5")); } }
mit
timeu/dygraphs-gwt
dygraphs-gwt-sample/src/main/java/sample/client/examples/AnnotationExample.java
6716
package sample.client.examples; import com.github.timeu.dygraphsgwt.client.Dygraphs; import com.github.timeu.dygraphsgwt.client.DygraphsOptions; import com.github.timeu.dygraphsgwt.client.callbacks.Annotation; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.VerticalPanel; import java.util.ArrayList; import java.util.List; /** * Created by uemit.seren on 7/29/15. */ public class AnnotationExample extends Composite { private VerticalPanel panel = new VerticalPanel(); private FlowPanel list = new FlowPanel(); private FlowPanel events = new FlowPanel(); private int lastAnnotationX = 0; private List<Annotation> annotations = new ArrayList<>(); private Dygraphs dygraphs; private String saveBg; private int num = 0; public AnnotationExample() { initWidget(panel); panel.add(new HTML("<p>Click any point to add an annotation to it or click 'Add Annotation'.")); HorizontalPanel buttonPanel = new HorizontalPanel(); Button addBtn = new Button("Add Annotation"); addBtn.addClickHandler(event -> { int x = lastAnnotationX + 2; Annotation annotation = new Annotation(); annotation.series = "line"; annotation.x = "200610"+x; annotation.shortText = String.valueOf(x); annotation.text="Line "+x; annotation.tickHeight=10; annotations.add(annotation); lastAnnotationX = x; dygraphs.getJSO().setAnnotations(annotations.toArray(new Annotation[]{})); }); Button shoveBottomBtn = new Button("Shove to bottom"); shoveBottomBtn.addClickHandler(event ->{ boolean toBottom = shoveBottomBtn.getText().equals("Shove to bottom"); Annotation[] annotations = dygraphs.getJSO().annotations(); for (Annotation annotation: annotations) { annotation.attachAtBottom = toBottom; } dygraphs.getJSO().setAnnotations(annotations); if (toBottom) { shoveBottomBtn.setText("Lift back up"); } else { shoveBottomBtn.setText("Shove to bottom"); } }); buttonPanel.add(addBtn); buttonPanel.add(shoveBottomBtn); panel.add(buttonPanel); panel.add(list); initDygraphs(); panel.add(events); } private static Annotation createAnnotation(int x) { Annotation annotation = new Annotation(); annotation.series = "sine wave"; annotation.x = "200610" +x; annotation.shortText=String.valueOf(x); annotation.text="Stock Market Crash "+ x; return annotation; } private static String getNameFromAnnotation(Annotation annotation) { return "(" + annotation.series + ", " + annotation.x + ")"; } public void initDygraphs() { for (int x=10;x< 15;x+=2) { annotations.add(createAnnotation(x)); lastAnnotationX = x; } Annotation specialAnnot = new Annotation(); specialAnnot.series = "another line"; specialAnnot.x = "20061013"; specialAnnot.icon ="http://dygraphs.com/gallery/images/dollar.png"; specialAnnot.width=18D; specialAnnot.height=23D; specialAnnot.tickHeight=4; specialAnnot.text="Another one"; specialAnnot.cssClass = "annotation"; specialAnnot.clickHandler =(annot, point, dygraph, event) -> events.add(new HTML("Special Handler")); annotations.add(specialAnnot); DygraphsOptions options = new DygraphsOptions(); options.rollPeriod = 1; options.showRoller = true; options.width = 480; options.height = 320; options.drawCallback = (g, initialDraw) -> { Annotation[] anns = g.annotations(); list.clear(); for (Annotation annotation : anns) { String name = getNameFromAnnotation(annotation); String shortText = (annotation.shortText != null ? annotation.shortText : "(icon)"); HTML listItem = new HTML("<div id='" + name + "'>" + name + ": " + shortText + " -> " + annotation.text + " </div>"); list.add(listItem); } }; options.annotationClickHandler = (ann, point, dygraphjs, event) -> { events.add(new HTML("<div>click: " + getNameFromAnnotation(ann) + "</div>")); }; options.annotationDblClickHandler = (ann, point, dygraphjs, event) -> { events.add(new HTML("<div>dblclick: " + getNameFromAnnotation(ann) + "</div>")); }; options.annotationMouseOverHandler = (ann, point, dygraphjs, event) -> { DOM.getElementById(getNameFromAnnotation(ann)).getStyle().setFontWeight(Style.FontWeight.BOLD); saveBg = ann.div.getStyle().getBackgroundColor(); ann.div.getStyle().setBackgroundColor("#ddd"); }; options.annotationMouseOutHandler = (ann, point, dygraphjs, event) -> { DOM.getElementById(getNameFromAnnotation(ann)).getStyle().setFontWeight(Style.FontWeight.NORMAL); ann.div.getStyle().setBackgroundColor(saveBg); }; options.pointClickCallback = (event, point) -> { if (point.getAnnotation()!=null) return; // If not, add one. Annotation annotation = new Annotation(); annotation.series = point.getName(); annotation.xval = point.getXval(); annotation.shortText = String.valueOf(num); annotation.text = "Annotation #"+num; annotations.add(annotation); dygraphs.getJSO().setAnnotations(annotations.toArray(new Annotation[]{})); num++; }; dygraphs = new Dygraphs(()-> { String r = "date,parabola,line,another line,sine wave\n"; for (int i = 1; i <= 31; i++) { r += "200610" + (i < 10 ? "0"+i : String.valueOf(i)); r += "," + 10*(i*(31-i)); r += "," + 10*(8*i); r += "," + 10*(250 - 8*i); r += "," + 10*(125 + 125 * Math.sin(0.3*i)); r += "\n"; } return r; },options); panel.add(dygraphs); dygraphs.getJSO().setAnnotations(annotations.toArray(new Annotation[]{})); } }
mit
attemoi/SongbookAPI
src/main/java/fi/attemoisio/songbookapi/model/error/ErrorResponse.java
2102
/* * The MIT License * * Copyright 2015 Atte Moisio. * * 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 fi.attemoisio.songbookapi.model.error; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "Error") public class ErrorResponse { private int code; private String message; private String description; private int httpStatus; @XmlElement(name = "code") public int getCode() { return code; } public void setCode(int code) { this.code = code; } @XmlElement(name = "message") public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @XmlElement(name = "description") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @XmlElement(name = "http_status") public int getHttpStatus() { return httpStatus; } public void setHttpStatus(int httpStatus) { this.httpStatus = httpStatus; } }
mit
Azure/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/cosmos/generated/CassandraClustersGetByResourceGroupSamples.java
1057
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.cosmos.generated; import com.azure.core.util.Context; /** Samples for CassandraClusters GetByResourceGroup. */ public final class CassandraClustersGetByResourceGroupSamples { /* * x-ms-original-file: specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-10-15/examples/CosmosDBManagedCassandraClusterGet.json */ /** * Sample code: CosmosDBManagedCassandraClusterGet. * * @param azure The entry point for accessing resource management APIs in Azure. */ public static void cosmosDBManagedCassandraClusterGet(com.azure.resourcemanager.AzureResourceManager azure) { azure .cosmosDBAccounts() .manager() .serviceClient() .getCassandraClusters() .getByResourceGroupWithResponse("cassandra-prod-rg", "cassandra-prod", Context.NONE); } }
mit
trentech/SimpleTags
src/main/java/com/gmail/trentech/simpletags/EventListener.java
6267
package com.gmail.trentech.simpletags; import java.util.List; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.command.SendCommandEvent; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.event.message.MessageChannelEvent; import org.spongepowered.api.event.message.MessageEvent.MessageFormatter; import org.spongepowered.api.service.context.Context; import org.spongepowered.api.service.permission.SubjectReference; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.Text.Builder; import org.spongepowered.api.text.TextTemplate; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.channel.MessageChannel; import org.spongepowered.api.text.channel.MessageReceiver; import org.spongepowered.api.text.channel.MutableMessageChannel; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.text.selector.Selector; import org.spongepowered.api.text.serializer.TextSerializers; import com.gmail.trentech.simpletags.events.ChangeTagEvent; import com.gmail.trentech.simpletags.tags.GroupTag; import com.gmail.trentech.simpletags.tags.PlayerTag; import com.gmail.trentech.simpletags.tags.SingleTag; import com.gmail.trentech.simpletags.tags.Tag; import com.gmail.trentech.simpletags.tags.WorldTag; public class EventListener { @Listener(order = Order.LATE) public void onMessageChannelEventChat(MessageChannelEvent.Chat event, @First Player player) { Builder playerTag = Text.builder().onHover(TextActions.showText(Text.of(player.getName()))); Optional<PlayerTag> optionalPlayerTag = PlayerTag.get(player); if (!optionalPlayerTag.isPresent()) { playerTag.append(PlayerTag.getDefault(player)); } else { playerTag.append(optionalPlayerTag.get().getTag()); } Text worldTag = Text.EMPTY; Optional<WorldTag> optionalWorldTag = WorldTag.get(player.getWorld().getProperties()); if (optionalWorldTag.isPresent()) { worldTag = optionalWorldTag.get().getTag(); } Builder groupTagBuilder = Text.builder(); for (Entry<Set<Context>, List<SubjectReference>> parent : player.getSubjectData().getAllParents().entrySet()) { for (SubjectReference subject : parent.getValue()) { String group = subject.getSubjectIdentifier(); if (group.equalsIgnoreCase("op_0") || group.equalsIgnoreCase("op_1") || group.equalsIgnoreCase("op_2") || group.equalsIgnoreCase("op_3") || group.equalsIgnoreCase("op_4")) { group = "op"; } Optional<GroupTag> optionalGroupTag = GroupTag.get(group); if (optionalGroupTag.isPresent()) { groupTagBuilder.append(optionalGroupTag.get().getTag()); } } } MessageFormatter formatter = event.getFormatter(); String oldStr = TextSerializers.FORMATTING_CODE.serialize(formatter.getHeader().toText()); String name = oldStr.substring(oldStr.indexOf("<"), oldStr.lastIndexOf(">") + 1); Text old = TextSerializers.FORMATTING_CODE.deserialize(oldStr.replace(name, "").replaceFirst(player.getName(), "")); formatter.setHeader(TextTemplate.of(worldTag, groupTagBuilder.build(), playerTag.build(), old, TextColors.RESET)); } @Listener public void onSendCommandEvent(SendCommandEvent event, @First CommandSource src) { String command = event.getCommand(); if (!command.equalsIgnoreCase("say")) { return; } if(Sponge.getPluginManager().isLoaded("simplechat")) { return; } String message = event.getArguments(); if(message == null || message.equals("")) { return; } MutableMessageChannel channel = MessageChannel.TO_ALL.asMutable(); if(message.startsWith("@")) { channel = MessageChannel.TO_NONE.asMutable(); String selector = message.substring(0, message.indexOf(" ")); for(Entity entity : Selector.parse(selector).resolve(src)) { if(entity instanceof Player) { channel.addMember((MessageReceiver) entity); } } if(channel.getMembers().size() == 0) { src.sendMessage(Text.of(TextColors.RED, "Selector returned no players")); return; } channel.addMember(Sponge.getServer().getConsole()); message = message.replace(selector, ""); } Text text = TextSerializers.FORMATTING_CODE.deserialize(message); if(src instanceof Player) { Player player = (Player) src; Optional<PlayerTag> optionalPlayerTag = PlayerTag.get(player); if (optionalPlayerTag.isPresent()) { text = Text.join(optionalPlayerTag.get().getTag(), Text.of(" "), text); } else { text = Text.join(PlayerTag.getDefault(player), Text.of(" "), text); } } else { Optional<SingleTag> optionalTag = SingleTag.get("simpletags", "console"); if(optionalTag.isPresent()) { text = Text.join(optionalTag.get().getTag(), Text.of(" "), text); } } channel.send(text); event.setCancelled(true); } @Listener public void onChangeTagEventUpdate(ChangeTagEvent.Update event) { Tag tag = event.getTag(); if (tag instanceof GroupTag) { GroupTag.cache.put(tag.getName(), (GroupTag) tag); } else if (tag instanceof WorldTag) { WorldTag.cache.put(tag.getName(), (WorldTag) tag); } else if (tag instanceof PlayerTag) { PlayerTag.cache.put(tag.getName(), (PlayerTag) tag); } else if (tag instanceof SingleTag) { SingleTag.cache.put(tag.getName(), (SingleTag) tag); } } @Listener public void onChangeTagEventDelete(ChangeTagEvent.Delete event) { Tag tag = event.getTag(); if (tag instanceof GroupTag) { GroupTag.cache.remove(tag.getName()); } else if (tag instanceof WorldTag) { WorldTag.cache.remove(tag.getName()); } else if (tag instanceof PlayerTag) { PlayerTag.cache.remove(tag.getName()); } else if (tag instanceof SingleTag) { SingleTag.cache.remove(tag.getName()); } } }
mit
bvoid/engine
engine-core/src/main/java/com/gritzer/mvc/view/lwjgl/MouseWheelHandler.java
442
package com.gritzer.mvc.view.lwjgl; import javax.inject.Inject; import javax.inject.Named; import org.lwjgl.glfw.GLFWScrollCallback; import com.gritzer.mvc.view.event.EventController; @Named public class MouseWheelHandler extends GLFWScrollCallback { @Inject private EventController eventController; @Override public void invoke(long window, double xoffset, double yoffset) { eventController.mouseWheelMoved(yoffset); } }
mit
Slikey/EffectLib
src/main/java/de/slikey/effectlib/EffectManager.java
23860
package de.slikey.effectlib; import de.slikey.effectlib.math.Transforms; import de.slikey.effectlib.util.ConfigUtils; import de.slikey.effectlib.util.CustomSound; import de.slikey.effectlib.util.Disposable; import de.slikey.effectlib.util.DynamicLocation; import de.slikey.effectlib.util.ImageLoadCallback; import de.slikey.effectlib.util.ImageLoadTask; import de.slikey.effectlib.util.ParticleDisplay; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; import org.bukkit.util.Vector; import java.awt.Font; import java.awt.image.BufferedImage; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.google.common.base.CaseFormat; /** * Dispose the EffectManager if you don't need him anymore. * * @author Kevin * */ public class EffectManager implements Disposable { private static List<EffectManager> effectManagers; private static Map<String, Class<? extends Effect>> effectClasses = new HashMap<String, Class<? extends Effect>>(); private final Plugin owningPlugin; private final Logger logger; private final Map<Effect, BukkitTask> effects; private ParticleDisplay display; private boolean disposed; private boolean disposeOnTermination; private boolean debug = false; private boolean stackTraces = true; private int visibleRange = 32; private File imageCacheFolder; private Map<String, BufferedImage[]> imageCache = new HashMap<String, BufferedImage[]>(); public EffectManager(Plugin owningPlugin) { this(owningPlugin, owningPlugin.getLogger()); } public EffectManager(Plugin owningPlugin, Logger logger) { if (owningPlugin == null) { throw new IllegalArgumentException("EffectManager must be given a valid owning plugin"); } imageCacheFolder = new File(owningPlugin.getDataFolder(), "imagecache"); this.owningPlugin = owningPlugin; this.logger = logger; Transforms.setEffectManager(this); effects = new HashMap<Effect, BukkitTask>(); disposed = false; disposeOnTermination = false; } private ParticleDisplay getDisplay() { if (display == null) { display = ParticleDisplay.newInstance(); } display.setManager(this); return display; } public void display(Particle particle, Location center, float offsetX, float offsetY, float offsetZ, float speed, int amount, float size, Color color, Material material, byte materialData, double range, List<Player> targetPlayers) { getDisplay().display(particle, center, offsetX, offsetY, offsetZ, speed, amount, size, color, material, materialData, range, targetPlayers); } public void start(Effect effect) { if (disposed) { throw new IllegalStateException("EffectManager is disposed and not able to accept any effects."); } if (disposeOnTermination) { throw new IllegalStateException("EffectManager is awaiting termination to dispose and not able to accept any effects."); } if (effects.containsKey(effect)) { effect.cancel(false); } if (!owningPlugin.isEnabled()) return; BukkitScheduler s = Bukkit.getScheduler(); BukkitTask task = null; switch (effect.getType()) { case INSTANT: if(effect.isAsynchronous()) { task = s.runTaskAsynchronously(owningPlugin, effect); } else { task = s.runTask(owningPlugin, effect); } break; case DELAYED: if (effect.isAsynchronous()) { task = s.runTaskLaterAsynchronously(owningPlugin, effect, effect.getDelay()); } else { task = s.runTaskLater(owningPlugin, effect, effect.getDelay()); } break; case REPEATING: if (effect.isAsynchronous()) { task = s.runTaskTimerAsynchronously(owningPlugin, effect, effect.getDelay(), effect.getPeriod()); } else { task = s.runTaskTimer(owningPlugin, effect, effect.getDelay(), effect.getPeriod()); } break; } synchronized (this) { effects.put(effect, task); } } public Effect start(String effectClass, ConfigurationSection parameters, Location origin, Entity originEntity) { return start(effectClass, parameters, origin, null, originEntity, null, null); } public Effect start(String effectClass, ConfigurationSection parameters, Entity originEntity) { return start(effectClass, parameters, originEntity == null ? null : originEntity.getLocation(), null, originEntity, null, null); } public Effect start(String effectClass, ConfigurationSection parameters, Location origin) { return start(effectClass, parameters, origin, null, null, null, null); } public Effect start(String effectClass, ConfigurationSection parameters, Location origin, Player targetPlayer){ return start(effectClass, parameters, new DynamicLocation(origin, null), new DynamicLocation(null, null), (ConfigurationSection)null, targetPlayer); } /** * Start an Effect from a Configuration map of parameters. * * @param effectClass The name of the Effect class to instantiate. If unqualified, defaults to the de.slikey.effectlib.effect namespace. * @param parameters A Configuration-driven map of key/value parameters. Each of these will be applied directly to the corresponding field in the Effect instance. * @param origin The origin Location * @param target The target Location, only used in some Effects (like LineEffect) * @param originEntity The origin Entity, the effect will attach to the Entity's Location * @param targetEntity The target Entity, only used in some Effects * @param parameterMap A map of parameter values to replace. These must start with the "$" character, values in the parameters map that contain a $key will be replaced with the value in this parameterMap. * @return */ @Deprecated public Effect start(String effectClass, ConfigurationSection parameters, Location origin, Location target, Entity originEntity, Entity targetEntity, Map<String, String> parameterMap) { return start(effectClass, parameters, new DynamicLocation(origin, originEntity), new DynamicLocation(target, targetEntity), parameterMap); } /** * Start an Effect from a Configuration map of parameters. * * @param effectClass The name of the Effect class to instantiate. If unqualified, defaults to the de.slikey.effectlib.effect namespace. * @param parameters A Configuration-driven map of key/value parameters. Each of these will be applied directly to the corresponding field in the Effect instance. * @param origin The origin Location * @param target The target Location, only used in some Effects (like LineEffect) * @param parameterMap A map of parameter values to replace. These must start with the "$" character, values in the parameters map that contain a $key will be replaced with the value in this parameterMap. * @return */ @Deprecated public Effect start(String effectClass, ConfigurationSection parameters, DynamicLocation origin, DynamicLocation target, Map<String, String> parameterMap) { return start(effectClass, parameters, origin, target, parameterMap, null); } public Effect getEffectByClassName(String effectClass) { Class<? extends Effect> effectLibClass; try { // First check the name as given effectLibClass = effectClasses.get(effectClass); // A shaded manager may provide a fully-qualified path. if (effectLibClass == null && !effectClass.contains(".")) { effectClass = "de.slikey.effectlib.effect." + effectClass; if (!effectClass.endsWith("Effect")) { effectClass = effectClass + "Effect"; } effectLibClass = effectClasses.get(effectClass); } if (effectLibClass == null) { effectLibClass = (Class<? extends Effect>) Class.forName(effectClass); effectClasses.put(effectClass, effectLibClass); } } catch (Throwable ex) { onError("Error loading EffectLib class: " + effectClass, ex); return null; } Effect effect = null; try { Constructor constructor = effectLibClass.getConstructor(EffectManager.class); effect = (Effect) constructor.newInstance(this); } catch (Exception ex) { onError("Error loading EffectLib class: " + effectClass, ex); } return effect; } public Effect getEffect(String effectClass, ConfigurationSection parameters, DynamicLocation origin, DynamicLocation target, ConfigurationSection parameterMap, Player targetPlayer) { Effect effect = getEffectByClassName(effectClass); if (effect == null) { return null; } // Some specific shortcuts if (parameters.contains("particle_offset")) { parameters.set("particle_offset_x", parameters.get("particle_offset")); parameters.set("particle_offset_y", parameters.get("particle_offset")); parameters.set("particle_offset_z", parameters.get("particle_offset")); parameters.set("particle_offset", null); } if (parameters.contains("particleOffset")) { parameters.set("particleOffsetX", parameters.get("particleOffset")); parameters.set("particleOffsetY", parameters.get("particleOffset")); parameters.set("particleOffsetZ", parameters.get("particleOffset")); parameters.set("particleOffset", null); } Collection<String> keys = parameters.getKeys(false); for (String key : keys) { if (key.equals("class")) { continue; } setField(effect, key, parameters, parameterMap); } if (origin != null) { effect.setDynamicOrigin(origin); } effect.setDynamicTarget(target); if (targetPlayer != null) effect.setTargetPlayer(targetPlayer); return effect; } @Deprecated public Effect start(String effectClass, ConfigurationSection parameters, DynamicLocation origin, DynamicLocation target, Map<String, String> parameterMap, Player targetPlayer) { ConfigurationSection configMap = null; if (parameterMap != null) { configMap = ConfigUtils.toStringConfiguration(parameterMap); } return start(effectClass, parameters, origin, target, configMap, targetPlayer); } /** * Start an effect, possibly using parameter replacement. * * @param effectClass the effect class to start * @param parameters any parameters to pass to the effect * @param origin the origin location * @param target the target location * @param parameterMap a configuration of variables from the parameter config to replace * @param targetPlayer The player who should see this effect. * @return */ public Effect start(String effectClass, ConfigurationSection parameters, DynamicLocation origin, DynamicLocation target, ConfigurationSection parameterMap, Player targetPlayer) { Effect effect = getEffect(effectClass, parameters, origin, target, parameterMap, targetPlayer); if (effect == null) { return null; } effect.start(); return effect; } public void cancel(boolean callback) { List<Effect> allEffects = new ArrayList<Effect>(effects.keySet()); for (Effect effect : allEffects) { effect.cancel(callback); } } public void done(Effect effect) { synchronized (this) { BukkitTask existingTask = effects.get(effect); if (existingTask != null) { existingTask.cancel(); } effects.remove(effect); } if (effect.callback != null && owningPlugin.isEnabled()) { Bukkit.getScheduler().runTask(owningPlugin, effect.callback); } if (disposeOnTermination && effects.isEmpty()) { dispose(); } } @Override public void dispose() { if (disposed) { return; } disposed = true; cancel(false); if (effectManagers != null) { effectManagers.remove(this); } } public void disposeOnTermination() { disposeOnTermination = true; if (effects.isEmpty()) { dispose(); } } public void enableDebug(boolean enable) { debug = enable; } public void enableStackTraces(boolean enable) { stackTraces = enable; } public boolean isDebugEnabled() { return debug; } public void onError(Throwable ex) { getLogger().log(Level.SEVERE, "Unexpected EffectLib Error: " + ex.getMessage(), ex); } public void onError(String message) { if (debug) { getLogger().log(Level.WARNING, message); } } public void onError(String message, Throwable ex) { if (debug) { if (stackTraces) { getLogger().log(Level.WARNING, message, ex); } else { getLogger().log(Level.WARNING, message); } } } public Logger getLogger() { return logger; } public int getParticleRange() { return visibleRange; } public void setParticleRange(int range) { visibleRange = range; } public Plugin getOwningPlugin() { return owningPlugin; } protected boolean setField(Object effect, String key, ConfigurationSection section, ConfigurationSection parameterMap) { try { String stringValue = section.getString(key); String fieldKey = key; // Allow underscore_style and dash_style parameters if (key.contains("-")) { key = key.replace("-", "_"); } if (key.contains("_")) { key = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, key); } ConfigurationSection fieldSection = section; if (parameterMap != null && stringValue.startsWith("$") && parameterMap.contains(stringValue)) { fieldKey = stringValue; fieldSection = parameterMap; } Field field = effect.getClass().getField(key); if (field.getType().equals(Integer.TYPE) || field.getType().equals(Integer.class)) { int intValue = Integer.MAX_VALUE; if (!ConfigUtils.isMaxValue(stringValue)) { intValue = fieldSection.getInt(fieldKey); } field.set(effect, intValue); } else if (field.getType().equals(Float.TYPE) || field.getType().equals(Float.class)) { float floatValue = Float.MAX_VALUE; if (!ConfigUtils.isMaxValue(stringValue)) { floatValue = (float)fieldSection.getDouble(fieldKey); } field.set(effect,floatValue); } else if (field.getType().equals(Double.TYPE) || field.getType().equals(Double.class)) { double doubleValue = Double.MAX_VALUE; if (!ConfigUtils.isMaxValue(stringValue)) { doubleValue = fieldSection.getDouble(fieldKey); } field.set(effect, doubleValue); } else if (field.getType().equals(Boolean.TYPE) || field.getType().equals(Boolean.class)) { field.set(effect, fieldSection.getBoolean(fieldKey)); } else if (field.getType().equals(Long.TYPE) || field.getType().equals(Long.class)) { long longValue = Long.MAX_VALUE; if (!ConfigUtils.isMaxValue(stringValue)) { longValue = fieldSection.getLong(fieldKey); } field.set(effect, longValue); } else if (field.getType().equals(Short.TYPE) || field.getType().equals(Short.class)) { short shortValue = Short.MAX_VALUE; if (!ConfigUtils.isMaxValue(stringValue)) { shortValue = (short)fieldSection.getInt(fieldKey); } field.set(effect, shortValue); } else if (field.getType().equals(Byte.TYPE) || field.getType().equals(Byte.class)) { byte byteValue = Byte.MAX_VALUE; if (!ConfigUtils.isMaxValue(stringValue)) { byteValue = (byte)fieldSection.getInt(fieldKey); } field.set(effect, byteValue); } else if (field.getType().equals(String.class)) { String value = fieldSection.getString(fieldKey); field.set(effect, value); } else if (field.getType().equals(Color.class)) { String value = fieldSection.getString(fieldKey); Integer rgb = null; if (value.equalsIgnoreCase("random")) { byte red = (byte)(Math.random() * 255); byte green = (byte)(Math.random() * 255); byte blue = (byte)(Math.random() * 255); rgb = (red << 16) | (green << 8) | blue; } else { rgb = Integer.parseInt(value, 16); } Color color = Color.fromRGB(rgb); field.set(effect, color); } else if (Map.class.isAssignableFrom(field.getType()) && section.isConfigurationSection(key)) { Map<String, Object> map = (Map<String, Object>)field.get(effect); ConfigurationSection subSection = section.getConfigurationSection(key); Set<String> keys = subSection.getKeys(false); for (String mapKey : keys) { map.put(mapKey, subSection.get(mapKey)); } } else if (Map.class.isAssignableFrom(field.getType()) && Map.class.isAssignableFrom(section.get(key).getClass())) { field.set(effect, section.get(key)); } else if (ConfigurationSection.class.isAssignableFrom(field.getType())) { ConfigurationSection configSection = ConfigUtils.getConfigurationSection(section, key); if (parameterMap != null) { ConfigurationSection baseConfiguration = configSection; configSection = new MemoryConfiguration(); Set<String> keys = baseConfiguration.getKeys(false); // Note this doesn't handle sections within sections. for (String baseKey : keys) { Object baseValue = baseConfiguration.get(baseKey); if (baseValue instanceof String && ((String)baseValue).startsWith("$")) { // If this is an equation it will get parsed when needed String parameterValue = parameterMap.getString((String)baseValue); baseValue = parameterValue == null ? baseValue : parameterValue; } configSection.set(baseKey, baseValue); } } field.set(effect, configSection); } else if (field.getType().equals(Vector.class)) { String value = fieldSection.getString(fieldKey); String[] pieces = value.split(","); double x = pieces.length > 0 ? Double.parseDouble(pieces[0]) : 0; double y = pieces.length > 1 ? Double.parseDouble(pieces[1]) : 0; double z = pieces.length > 2 ? Double.parseDouble(pieces[2]) : 0; field.set(effect, new Vector(x, y, z)); } else if (field.getType().isEnum()) { Class<Enum> enumType = (Class<Enum>)field.getType(); String value = fieldSection.getString(fieldKey); Enum enumValue = Enum.valueOf(enumType, value.toUpperCase()); field.set(effect, enumValue); } else if (field.getType().equals(Font.class)) { // Should caching the fonts be considered? // Or is the performance gain negligible? String value = fieldSection.getString(fieldKey); Font font = Font.decode(value); field.set(effect, font); } else if (field.getType().equals(CustomSound.class)) { String value = fieldSection.getString(fieldKey); field.set(effect, new CustomSound(value)); } else { onError("Unable to assign EffectLib property " + key + " of class " + effect.getClass().getSimpleName()); return false; } return true; } catch (Exception ex) { onError("Error assigning EffectLib property " + key + " of class " + effect.getClass().getSimpleName() + ": " + ex.getMessage(), ex); } return false; } public static void initialize() { effectManagers = new ArrayList<EffectManager>(); } public static List<EffectManager> getManagers() { if (effectManagers == null) { initialize(); } return effectManagers; } public static void disposeAll() { if (effectManagers != null) { for (Iterator<EffectManager> i = effectManagers.iterator(); i.hasNext();) { EffectManager em = i.next(); i.remove(); em.dispose(); } } } public void setImageCacheFolder(File folder) { imageCacheFolder = folder; } public File getImageCacheFolder() { return imageCacheFolder; } public void loadImage(final String fileName, final ImageLoadCallback callback) { BufferedImage[] images = imageCache.get(fileName); if (images != null) { callback.loaded(images); return; } owningPlugin.getServer().getScheduler().runTaskAsynchronously(owningPlugin, new ImageLoadTask(this, fileName, new ImageLoadCallback() { @Override public void loaded(final BufferedImage[] images) { owningPlugin.getServer().getScheduler().runTask(owningPlugin, new Runnable() { @Override public void run() { imageCache.put(fileName, images); callback.loaded(images); } }); } })); } public void registerEffectClass(String key, Class<? extends Effect> effectClass) { effectClasses.put(key, effectClass); } }
mit
jurgendl/jhaws
jhaws/wicket/src/main/java/org/jhaws/common/web/wicket/qtip/QTip.java
619
package org.jhaws.common.web.wicket.qtip; import org.jhaws.common.web.wicket.CssResourceReference; import org.jhaws.common.web.wicket.JavaScriptResourceReference; import org.jhaws.common.web.wicket.WicketApplication; // v3.0.3 /** * @see http://qtip2.com */ public class QTip { public static JavaScriptResourceReference JS = new JavaScriptResourceReference(QTip.class, "jquery.qtip.js").addJavaScriptResourceReferenceDependency(WicketApplication.get().getJavaScriptLibrarySettings().getJQueryReference()); public static CssResourceReference CSS = new CssResourceReference(QTip.class, "jquery.qtip.css"); }
mit
3203317/yb
abc-app-xxx/src/main/java/net/abc/xxx/shiro/UserRealm.java
1381
package net.abc.xxx.shiro; import javax.annotation.Resource; import net.abc.xxx.model.User; import net.abc.xxx.service.UserService; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.DisabledAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; /** * * @author huangxin <3203317@qq.com> * */ public class UserRealm extends AuthorizingRealm { @Resource private UserService userService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // TODO Auto-generated method stub return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String acc = (String) token.getPrincipal(); User user = userService.getByName(acc); if (null == user) throw new UnknownAccountException(); if (1 != user.getStatus()) throw new DisabledAccountException(); SimpleAuthenticationInfo auth = new SimpleAuthenticationInfo(user, user.getUser_pass(), getName()); return auth; } }
mit
inFullMobile/restricted-register-plugin
src/main/java/com/infullmobile/jenkins/plugin/restrictedregister/settings/RegistrationRulesSet.java
3943
package com.infullmobile.jenkins.plugin.restrictedregister.settings; import com.infullmobile.jenkins.plugin.restrictedregister.ConfigurableDataVerifier; import com.infullmobile.jenkins.plugin.restrictedregister.PluginModule; import com.infullmobile.jenkins.plugin.restrictedregister.module.impl.JenkinsDescriptorImpl; import com.infullmobile.jenkins.plugin.restrictedregister.util.Utils; import hudson.DescriptorExtensionList; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.util.FormValidation; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.LinkedList; import java.util.List; /** * Created by Adam Kobus on 25.05.2016. * Copyright (c) 2016 inFullMobile * License: MIT, file: /LICENSE */ public class RegistrationRulesSet extends AbstractDescribableImpl<RegistrationRulesSet> { private String ruleName; private List<RegistrationRuleConfig> configs; @DataBoundConstructor public RegistrationRulesSet() { } public boolean isUserDataValid(JSONObject payload) { final List<ConfigurableDataVerifier> verifiers = PluginModule.getDefault() .getExtensionsProvider().getConfigurableDataVerifiers(); for (ConfigurableDataVerifier verifier : verifiers) { if (!validateDataWithVerifier(payload, verifier)) { return false; } } return true; } public boolean validateDataWithVerifier(JSONObject payload, ConfigurableDataVerifier verifier) { final RegistrationRuleConfig config = getConfigForVerifier(verifier); return config == null || verifier.isFormDataValid(payload, config); } // Access and render @DataBoundSetter public void setRuleName(String ruleName) { this.ruleName = ruleName; } @SuppressWarnings("unused") public String getRuleName() { return this.ruleName; } @DataBoundSetter public void setConfigs(List<RegistrationRuleConfig> configs) { if (this.configs == null) { this.configs = new LinkedList<>(); } this.configs.clear(); if (configs != null) { this.configs.addAll(configs); } } @SuppressWarnings("WeakerAccess") public List<RegistrationRuleConfig> getConfigs() { if (this.configs == null) { configs = new LinkedList<>(); } return this.configs; } @Nullable private RegistrationRuleConfig getConfigForVerifier(ConfigurableDataVerifier verifier) { for (RegistrationRuleConfig config : getConfigs()) { if (verifier.isConfigTypeValid(config)) { return config; } } return null; } @Extension public static class RegistrationRulesSetDescriptor extends Descriptor<RegistrationRulesSet> { @Nonnull @Override public String getDisplayName() { return Utils.getDescriptorDisplayName(this); } // Access and render @SuppressWarnings("unused") public DescriptorExtensionList<RegistrationRuleConfig, Descriptor<RegistrationRuleConfig>> getConfigDescriptors() { return JenkinsDescriptorImpl.getJenkinsInstanceOrDie().getDescriptorList(RegistrationRuleConfig.class); } // Validation @SuppressWarnings("unused") public FormValidation doCheckRuleName(@QueryParameter String value) { if (StringUtils.isEmpty(value)) { return FormValidation.error("Rule name cannot be empty."); } else { return FormValidation.ok(); } } } }
mit
ferzerkerx/album-finder
src/main/java/module-info.java
780
open module ferzerkerx.albumfinder { requires spring.context; requires spring.core; requires spring.beans; requires spring.jdbc; requires spring.orm; requires java.sql; requires spring.boot.autoconfigure; requires spring.tx; requires spring.boot; requires spring.security.web; requires spring.security.core; requires spring.security.config; requires spring.web; requires java.naming; requires java.persistence; requires org.hibernate.orm.core; requires org.apache.commons.lang3; requires com.fasterxml.jackson.annotation; requires javax.servlet.api; requires java.validation; requires org.slf4j; requires spring.security.crypto; requires lombok; exports com.ferzerkerx.albumfinder; }
mit
colanconnon/CryptoMessage
CryptoMessageAndroid/MyApplication/app/src/main/java/com/colanconnon/cryptomessage/encryption/RSAKeyManager.java
3523
package com.colanconnon.cryptomessage.encryption; import android.content.Context; import android.content.SharedPreferences; import android.util.Base64; import android.util.Log; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; /** * Created by colanconnon on 3/18/15. */ public class RSAKeyManager { private PublicKey publicKey; private PrivateKey privateKey; private Context context; public RSAKeyManager(Context context){ this.context = context; } public void generateKeyPair(){ SharedPreferences prefs = context.getSharedPreferences("com.colanconnon.cryptomessage", Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); RSAEncrypt rsaEncrypt = new RSAEncrypt(); rsaEncrypt.generateKeyPair(); PublicKey publicKey = rsaEncrypt.getPublicKey(); PrivateKey privateKey = rsaEncrypt.getPrivateKey(); byte[] bytesPublicKey = publicKey.getEncoded(); String publicKeyString = Base64.encodeToString(bytesPublicKey, Base64.DEFAULT); byte[] bytesPrivateKey = privateKey.getEncoded(); String privateKeyString = Base64.encodeToString(bytesPrivateKey, Base64.DEFAULT); editor.putString("privateKey", privateKeyString); editor.putString("publicKey", publicKeyString); editor.commit(); } public boolean isKeysInEditor(){ SharedPreferences prefs = context.getSharedPreferences("com.colanconnon.cryptomessage", Context.MODE_PRIVATE); String privateKey = prefs.getString("privateKey", null); String publicKey = prefs.getString("publicKey", null); if(privateKey == null){ return false; } if(publicKey == null){ return false; } return true; } public void getKeysFromEditor(){ SharedPreferences prefs = context.getSharedPreferences("com.colanconnon.cryptomessage", Context.MODE_PRIVATE); String privateKey = prefs.getString("privateKey", null); String publicKey = prefs.getString("publicKey", null); if(privateKey == null){ return; } if(publicKey == null){ return; } byte[] privateKeyBytes = Base64.decode(privateKey,Base64.DEFAULT); PKCS8EncodedKeySpec x509KeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); byte[] publicKeyBytes = Base64.decode(publicKey, Base64.DEFAULT); X509EncodedKeySpec x509KeySpec2 = new X509EncodedKeySpec(publicKeyBytes); try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); this.privateKey = keyFactory.generatePrivate(x509KeySpec); this.publicKey = keyFactory.generatePublic(x509KeySpec2); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } } public PublicKey getPublicKey() { return publicKey; } public String getPublicKeyString(){ byte[] bytesPublicKey = this.publicKey.getEncoded(); String publicKeyString = Base64.encodeToString(bytesPublicKey, Base64.DEFAULT); return publicKeyString; } public PrivateKey getPrivateKey() { return privateKey; } }
mit
Muxi-Studio/AndroidHomework
jinyixin/NO10/app/src/main/java/com/muxistudio/jinyixin/no10/MainActivity.java
3336
package com.muxistudio.jinyixin.no10; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class MainActivity extends ActionBarActivity { private HttpClient httpClient; private HttpGet httpGet; private String temp; private TextView content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); content = (TextView) findViewById(R.id.content); //网络连接的部分不允许写在主线程里面,一定要注意 new Thread(new Runnable() { @Override public void run() { httpClient = new DefaultHttpClient();// httpGet = new HttpGet("https://api.douban.com/v2/book/search?q=哈利波特&count=1");// //try一下,以防网络不稳定而挂掉 //buffer的内容如果不清楚书上有,我也有在tower上整理:关于输入输出的一个分享 try { HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); String line = null; StringBuilder builder = new StringBuilder(); while ((line = br.readLine()) != null) { builder.append(line); } temp = builder.toString(); Log.i("result", temp); //runOnUiThread是填写UI的方法,因为在非主线程不允许填写UI runOnUiThread(new Runnable() { @Override public void run() { content.setText(temp); } }); } } catch (IOException e) { //可以输出一个什么网络错误的提示 } } }).start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
mit
pomortaz/azure-sdk-for-java
azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/NetworkInterfaceBase.java
2337
package com.microsoft.azure.management.network; import com.microsoft.azure.management.apigeneration.Fluent; import java.util.List; /** * The base network interface shared across regular and virtual machine scale set network interface. */ @Fluent public interface NetworkInterfaceBase { /** * @return <tt>true</tt> if IP forwarding is enabled in this network interface */ boolean isIpForwardingEnabled(); /** * @return the MAC Address of the network interface */ String macAddress(); /** * * @return the Internal DNS name assigned to this network interface */ String internalDnsNameLabel(); /** * Gets the fully qualified domain name of this network interface. * <p> * A network interface receives FQDN as a part of assigning it to a virtual machine. * * @return the qualified domain name */ String internalFqdn(); /** * @return the internal domain name suffix */ String internalDomainNameSuffix(); /** * @return IP addresses of this network interface's DNS servers */ List<String> dnsServers(); /** * @return applied DNS servers */ List<String> appliedDnsServers(); /** * @return the network security group resource id associated with this network interface */ String networkSecurityGroupId(); /** * Gets the network security group associated this network interface. * <p> * This method makes a rest API call to fetch the Network Security Group resource. * * @return the network security group associated with this network interface. */ NetworkSecurityGroup getNetworkSecurityGroup(); /** * @return the resource ID of the associated virtual machine, or null if none. */ String virtualMachineId(); /** * Gets the private IP address allocated to this network interface's primary IP configuration. * <p> * The private IP will be within the virtual network subnet of this network interface. * * @return the private IP addresses */ String primaryPrivateIp(); /** * @return the private IP allocation method (Dynamic, Static) of this network interface's * primary IP configuration. */ IPAllocationMethod primaryPrivateIpAllocationMethod(); }
mit
pavelkuchin/checkers
src/main/java/com/checkers/server/services/StepService.java
670
package com.checkers.server.services; import com.checkers.server.beans.Step; import com.checkers.server.exceptions.ApplicationException; import com.checkers.server.exceptions.CheckersException; import java.util.List; /** * * * @author Pavel_Kuchin */ public interface StepService { Step getStep(Long suid) throws ApplicationException; Step newStep(Step step) throws ApplicationException, CheckersException; List<Step> getGameSteps(Long gauid) throws ApplicationException; Step getGameLastStep(Long gauid) throws ApplicationException; Step getAsyncGameLastStep(Long gauid, String username) throws InterruptedException, ApplicationException; }
mit
streamreasoning/HeavenTeststand
src/test/it/polimi/export/processing/inference/CompletenessSoundnessTest.java
5399
package it.polimi.export.processing.inference; import it.polimi.export.processing.validation.DatasetAnalyser; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import lombok.extern.log4j.Log4j; import org.apache.jena.riot.RDFDataMgr; import org.hamcrest.CoreMatchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.rdf.model.Model; @Log4j public class CompletenessSoundnessTest { @Rule public ErrorCollector jenasmplCompletenessCollector = new ErrorCollector(); @Rule public ErrorCollector jenarhodfCompletenessCollector = new ErrorCollector(); @Rule public ErrorCollector jenafullCompletenessCollector = new ErrorCollector(); @Rule public ErrorCollector jenarhodfSoundnessCollector = new ErrorCollector(); @Rule public ErrorCollector jenasmplSoundnessCollector = new ErrorCollector(); @Rule public ErrorCollector jenafullSoundnessCollector = new ErrorCollector(); String expPath = "src/main/resources/data/output/2014-11-30/"; @Test public void jenarhodfTest() throws IOException { Dataset plain = RDFDataMgr.loadDataset(expPath + "plain2369/" + "Result_EN0__2014_11_30__CLND_UNIV10INDEX0SEED01000Lines.trig"); Dataset rhodf = RDFDataMgr.loadDataset(expPath + "jenarhodf/" + "Result_EN0__2014_11_30__CLND_UNIV10INDEX0SEED01000Lines.trig"); DatasetAnalyser analyser = new DatasetAnalyser(rhodf); Iterator<String> listNames = plain.listNames(); while (listNames.hasNext()) { String modelName = listNames.next(); Boolean complete = analyser.isComplete(modelName, plain.getNamedModel(modelName)); Boolean sound = analyser.isSound(modelName, plain.getNamedModel(modelName)); if (!complete) { log.info("RHODF Not Complete " + modelName); Model completeDiff = analyser.getCompleteDiff(modelName, plain.getNamedModel(modelName)); write(modelName, completeDiff, "/jenarhodf/COMPLETEDIFF"); } if (!sound) { log.info("RHODF Not Sound " + modelName); write(modelName, analyser.getSoundDiff(modelName, plain.getNamedModel(modelName)), "/jenarhodf/SOUNDIFF"); } jenarhodfCompletenessCollector.checkThat(complete, CoreMatchers.equalTo(true)); jenarhodfSoundnessCollector.checkThat(sound, CoreMatchers.equalTo(true)); } } @Test public void smplTest() throws IOException { Dataset plain = RDFDataMgr.loadDataset(expPath + "plain2369/" + "Result_EN0__2014_11_30__CLND_UNIV10INDEX0SEED01000Lines.trig"); Dataset smpl = RDFDataMgr.loadDataset(expPath + "jenasmpl/" + "Result_EN0__2014_11_30__CLND_UNIV10INDEX0SEED01000Lines.trig"); DatasetAnalyser analyser = new DatasetAnalyser(smpl); Iterator<String> listNames = plain.listNames(); while (listNames.hasNext()) { String modelName = listNames.next(); Boolean complete = analyser.isComplete(modelName, plain.getNamedModel(modelName)); Boolean sound = analyser.isSound(modelName, plain.getNamedModel(modelName)); if (!complete) { log.info("JenaSMPL Not Complete " + modelName); Model completeDiff = analyser.getCompleteDiff(modelName, plain.getNamedModel(modelName)); write(modelName, completeDiff, "/jenasmpl/COMPLETEDIFF"); } if (!sound) { log.info("JenaSMPL Not Sound " + modelName); write(modelName, analyser.getSoundDiff(modelName, plain.getNamedModel(modelName)), "/jenasmpl/SOUNDDIFF"); } jenasmplCompletenessCollector.checkThat(complete, CoreMatchers.equalTo(true)); jenasmplSoundnessCollector.checkThat(sound, CoreMatchers.equalTo(true)); } } @Test public void fullTest() throws IOException { Dataset plain = RDFDataMgr.loadDataset(expPath + "plain2369/" + "Result_EN0__2014_11_30__CLND_UNIV10INDEX0SEED01000Lines.trig"); Dataset full = RDFDataMgr.loadDataset(expPath + "jenafull/" + "Result_EN0__2014_11_30__CLND_UNIV10INDEX0SEED01000Lines.trig"); DatasetAnalyser analyser = new DatasetAnalyser(full); Iterator<String> listNames = plain.listNames(); while (listNames.hasNext()) { String modelName = listNames.next(); Boolean complete = analyser.isComplete(modelName, plain.getNamedModel(modelName)); Boolean sound = analyser.isSound(modelName, plain.getNamedModel(modelName)); if (!complete) { log.info("JenaFULL Not Complete " + modelName); Model completeDiff = analyser.getCompleteDiff(modelName, plain.getNamedModel(modelName)); write(modelName, completeDiff, "/jenafull/COMPLETEDIFF"); } if (!sound) { log.info("JenaFULL Not Sound " + modelName); write(modelName, analyser.getSoundDiff(modelName, plain.getNamedModel(modelName)), "/jenafull/SOUNDDIFF"); } jenafullCompletenessCollector.checkThat(complete, CoreMatchers.equalTo(true)); jenafullSoundnessCollector.checkThat(sound, CoreMatchers.equalTo(true)); } } protected void write(String name, Model m, String w) { File file = new File(expPath + w + "_EN0__2014_11_30__CLND_UNIV10INDEX0SEED01000Lines.nt"); try (FileOutputStream fop = new FileOutputStream(file, true)) { if (!file.exists()) { file.createNewFile(); } fop.write(name.getBytes()); fop.write(System.getProperty("line.separator").getBytes()); m.write(fop, "N-TRIPLE"); fop.write(System.getProperty("line.separator").getBytes()); fop.flush(); fop.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
mit
limpoxe/Android-Plugin-Framework
Samples/PluginTest/src/main/java/com/example/plugintest/manymethods/k/c/A5.java
8249
package com.example.plugintest.manymethods.k.c; public class A5 { public static void a0(String msg) { System.out.println("msg=" + msg + 0); } public static void a1(String msg) { System.out.println("msg=" + msg + 1); } public static void a2(String msg) { System.out.println("msg=" + msg + 2); } public static void a3(String msg) { System.out.println("msg=" + msg + 3); } public static void a4(String msg) { System.out.println("msg=" + msg + 4); } public static void a5(String msg) { System.out.println("msg=" + msg + 5); } public static void a6(String msg) { System.out.println("msg=" + msg + 6); } public static void a7(String msg) { System.out.println("msg=" + msg + 7); } public static void a8(String msg) { System.out.println("msg=" + msg + 8); } public static void a9(String msg) { System.out.println("msg=" + msg + 9); } public static void a10(String msg) { System.out.println("msg=" + msg + 10); } public static void a11(String msg) { System.out.println("msg=" + msg + 11); } public static void a12(String msg) { System.out.println("msg=" + msg + 12); } public static void a13(String msg) { System.out.println("msg=" + msg + 13); } public static void a14(String msg) { System.out.println("msg=" + msg + 14); } public static void a15(String msg) { System.out.println("msg=" + msg + 15); } public static void a16(String msg) { System.out.println("msg=" + msg + 16); } public static void a17(String msg) { System.out.println("msg=" + msg + 17); } public static void a18(String msg) { System.out.println("msg=" + msg + 18); } public static void a19(String msg) { System.out.println("msg=" + msg + 19); } public static void a20(String msg) { System.out.println("msg=" + msg + 20); } public static void a21(String msg) { System.out.println("msg=" + msg + 21); } public static void a22(String msg) { System.out.println("msg=" + msg + 22); } public static void a23(String msg) { System.out.println("msg=" + msg + 23); } public static void a24(String msg) { System.out.println("msg=" + msg + 24); } public static void a25(String msg) { System.out.println("msg=" + msg + 25); } public static void a26(String msg) { System.out.println("msg=" + msg + 26); } public static void a27(String msg) { System.out.println("msg=" + msg + 27); } public static void a28(String msg) { System.out.println("msg=" + msg + 28); } public static void a29(String msg) { System.out.println("msg=" + msg + 29); } public static void a30(String msg) { System.out.println("msg=" + msg + 30); } public static void a31(String msg) { System.out.println("msg=" + msg + 31); } public static void a32(String msg) { System.out.println("msg=" + msg + 32); } public static void a33(String msg) { System.out.println("msg=" + msg + 33); } public static void a34(String msg) { System.out.println("msg=" + msg + 34); } public static void a35(String msg) { System.out.println("msg=" + msg + 35); } public static void a36(String msg) { System.out.println("msg=" + msg + 36); } public static void a37(String msg) { System.out.println("msg=" + msg + 37); } public static void a38(String msg) { System.out.println("msg=" + msg + 38); } public static void a39(String msg) { System.out.println("msg=" + msg + 39); } public static void a40(String msg) { System.out.println("msg=" + msg + 40); } public static void a41(String msg) { System.out.println("msg=" + msg + 41); } public static void a42(String msg) { System.out.println("msg=" + msg + 42); } public static void a43(String msg) { System.out.println("msg=" + msg + 43); } public static void a44(String msg) { System.out.println("msg=" + msg + 44); } public static void a45(String msg) { System.out.println("msg=" + msg + 45); } public static void a46(String msg) { System.out.println("msg=" + msg + 46); } public static void a47(String msg) { System.out.println("msg=" + msg + 47); } public static void a48(String msg) { System.out.println("msg=" + msg + 48); } public static void a49(String msg) { System.out.println("msg=" + msg + 49); } public static void a50(String msg) { System.out.println("msg=" + msg + 50); } public static void a51(String msg) { System.out.println("msg=" + msg + 51); } public static void a52(String msg) { System.out.println("msg=" + msg + 52); } public static void a53(String msg) { System.out.println("msg=" + msg + 53); } public static void a54(String msg) { System.out.println("msg=" + msg + 54); } public static void a55(String msg) { System.out.println("msg=" + msg + 55); } public static void a56(String msg) { System.out.println("msg=" + msg + 56); } public static void a57(String msg) { System.out.println("msg=" + msg + 57); } public static void a58(String msg) { System.out.println("msg=" + msg + 58); } public static void a59(String msg) { System.out.println("msg=" + msg + 59); } public static void a60(String msg) { System.out.println("msg=" + msg + 60); } public static void a61(String msg) { System.out.println("msg=" + msg + 61); } public static void a62(String msg) { System.out.println("msg=" + msg + 62); } public static void a63(String msg) { System.out.println("msg=" + msg + 63); } public static void a64(String msg) { System.out.println("msg=" + msg + 64); } public static void a65(String msg) { System.out.println("msg=" + msg + 65); } public static void a66(String msg) { System.out.println("msg=" + msg + 66); } public static void a67(String msg) { System.out.println("msg=" + msg + 67); } public static void a68(String msg) { System.out.println("msg=" + msg + 68); } public static void a69(String msg) { System.out.println("msg=" + msg + 69); } public static void a70(String msg) { System.out.println("msg=" + msg + 70); } public static void a71(String msg) { System.out.println("msg=" + msg + 71); } public static void a72(String msg) { System.out.println("msg=" + msg + 72); } public static void a73(String msg) { System.out.println("msg=" + msg + 73); } public static void a74(String msg) { System.out.println("msg=" + msg + 74); } public static void a75(String msg) { System.out.println("msg=" + msg + 75); } public static void a76(String msg) { System.out.println("msg=" + msg + 76); } public static void a77(String msg) { System.out.println("msg=" + msg + 77); } public static void a78(String msg) { System.out.println("msg=" + msg + 78); } public static void a79(String msg) { System.out.println("msg=" + msg + 79); } public static void a80(String msg) { System.out.println("msg=" + msg + 80); } public static void a81(String msg) { System.out.println("msg=" + msg + 81); } public static void a82(String msg) { System.out.println("msg=" + msg + 82); } public static void a83(String msg) { System.out.println("msg=" + msg + 83); } public static void a84(String msg) { System.out.println("msg=" + msg + 84); } public static void a85(String msg) { System.out.println("msg=" + msg + 85); } public static void a86(String msg) { System.out.println("msg=" + msg + 86); } public static void a87(String msg) { System.out.println("msg=" + msg + 87); } public static void a88(String msg) { System.out.println("msg=" + msg + 88); } public static void a89(String msg) { System.out.println("msg=" + msg + 89); } public static void a90(String msg) { System.out.println("msg=" + msg + 90); } public static void a91(String msg) { System.out.println("msg=" + msg + 91); } public static void a92(String msg) { System.out.println("msg=" + msg + 92); } public static void a93(String msg) { System.out.println("msg=" + msg + 93); } public static void a94(String msg) { System.out.println("msg=" + msg + 94); } public static void a95(String msg) { System.out.println("msg=" + msg + 95); } public static void a96(String msg) { System.out.println("msg=" + msg + 96); } public static void a97(String msg) { System.out.println("msg=" + msg + 97); } public static void a98(String msg) { System.out.println("msg=" + msg + 98); } public static void a99(String msg) { System.out.println("msg=" + msg + 99); } }
mit
christianbellinaef/vertx-jersey
vertx-jersey/src/main/java/com/englishtown/vertx/guice/GuiceJerseyBinder.java
3290
package com.englishtown.vertx.guice; import com.englishtown.vertx.jersey.JerseyHandler; import com.englishtown.vertx.jersey.JerseyOptions; import com.englishtown.vertx.jersey.JerseyServer; import com.englishtown.vertx.jersey.impl.DefaultJerseyHandler; import com.englishtown.vertx.jersey.impl.DefaultJerseyOptions; import com.englishtown.vertx.jersey.impl.WriteStreamBodyWriter; import com.englishtown.vertx.jersey.inject.ContainerResponseWriterProvider; import com.englishtown.vertx.jersey.inject.VertxPostResponseProcessor; import com.englishtown.vertx.jersey.inject.VertxRequestProcessor; import com.englishtown.vertx.jersey.inject.VertxResponseProcessor; import com.englishtown.vertx.jersey.inject.impl.VertxResponseWriterProvider; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.multibindings.Multibinder; import org.glassfish.hk2.api.ServiceLocator; import org.glassfish.hk2.api.ServiceLocatorFactory; import org.glassfish.jersey.server.model.ModelProcessor; import javax.inject.Singleton; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.ReaderInterceptor; import javax.ws.rs.ext.WriterInterceptor; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Guice Jersey binder */ public class GuiceJerseyBinder extends AbstractModule { /** * Configures a {@link com.google.inject.Binder} via the exposed methods. */ @Override protected void configure() { // Create HK2 service locator and bind jersey injections ServiceLocator locator = ServiceLocatorFactory.getInstance().create(null); bind(ServiceLocator.class).toInstance(locator); bind(JerseyServer.class).to(GuiceJerseyServer.class); bind(JerseyHandler.class).to(DefaultJerseyHandler.class); bind(JerseyOptions.class).to(DefaultJerseyOptions.class); bind(ContainerResponseWriterProvider.class).to(VertxResponseWriterProvider.class); bind(MessageBodyWriter.class).to(WriteStreamBodyWriter.class).in(Singleton.class); Multibinder.newSetBinder(binder(), VertxRequestProcessor.class); Multibinder.newSetBinder(binder(), VertxResponseProcessor.class); Multibinder.newSetBinder(binder(), VertxPostResponseProcessor.class); Multibinder.newSetBinder(binder(), ContainerRequestFilter.class); Multibinder.newSetBinder(binder(), ContainerResponseFilter.class); Multibinder.newSetBinder(binder(), ReaderInterceptor.class); Multibinder.newSetBinder(binder(), WriterInterceptor.class); Multibinder.newSetBinder(binder(), ModelProcessor.class); } @Provides List<VertxRequestProcessor> provideVertxRequestProcessorList(Set<VertxRequestProcessor> processors) { return new ArrayList<>(processors); } @Provides List<VertxResponseProcessor> provideVertxResponseProcessorList(Set<VertxResponseProcessor> processors) { return new ArrayList<>(processors); } @Provides List<VertxPostResponseProcessor> provideVertxPostResponseProcessorList(Set<VertxPostResponseProcessor> processors) { return new ArrayList<>(processors); } }
mit
jmreyes/tutela-client-android
tutela/src/main/java/net/jmreyes/tutela/ui/doctor/main/mypatients/MyPatientsInteractor.java
326
package net.jmreyes.tutela.ui.doctor.main.mypatients; /** * Created by juanma on 8/11/14. */ public interface MyPatientsInteractor { public void makeRequest(final MyPatientsPresenter.OnFinishedListener listener); public void makeSearchRequest(String query, final MyPatientsPresenter.OnFinishedListener listener); }
mit
fmarchioni/mastertheboss
jax-rs/crud/src/main/java/com/mastertheboss/jaxrs/CustomerRepository.java
1406
package com.mastertheboss.jaxrs; import javax.enterprise.context.ApplicationScoped; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import javax.ws.rs.WebApplicationException; @ApplicationScoped public class CustomerRepository { @PersistenceContext private EntityManager entityManager; public List<Customer> findAll() { return entityManager.createNamedQuery("Customers.findAll", Customer.class) .getResultList(); } public Customer findCustomerById(Long id) { Customer customer = entityManager.find(Customer.class, id); if (customer == null) { throw new WebApplicationException("Customer with id of " + id + " does not exist.", 404); } return customer; } @Transactional public void updateCustomer(Customer customer) { Customer customerToUpdate = findCustomerById(customer.getId()); customerToUpdate.setName(customer.getName()); customerToUpdate.setSurname(customer.getSurname()); } @Transactional public void createCustomer(Customer customer) { entityManager.persist(customer); } @Transactional public void deleteCustomer(Long customerId) { Customer c = findCustomerById(customerId); entityManager.remove(c); } }
mit
ikbenpinda/slackernews
src/main/java/nl/achan/subscribers/UserApplicationGateway.java
1569
package nl.achan.subscribers; import com.google.gson.Gson; import nl.achan.util.ArticleSerializer; import nl.achan.util.domain.ArticleView; import nl.achan.util.jms.MessageReceiverTopicGateway; import javax.jms.JMSException; import javax.jms.TextMessage; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Etienne on 10-6-2017. */ public class UserApplicationGateway { private String topic; private MessageReceiverTopicGateway receiver; private ArticleSerializer serializer; private Logger logger; private OnMessageReceived callback; public UserApplicationGateway() { serializer = new ArticleSerializer(); logger = Logger.getLogger(UserApplicationGateway.class.getName()); } public void subscribe(String topic, OnMessageReceived callback){ this.topic = topic; this.callback = callback; receiver = new MessageReceiverTopicGateway(topic); receiver.setListener(message -> { ArticleView article = null;//serializer.fromMessage(message); try { article = new Gson().fromJson( ((TextMessage) message).getText(), ArticleView.class); } catch (JMSException e) { e.printStackTrace(); } logger.log(Level.INFO, "Received new article in topic: " + topic + ": " + article.toString()); if (callback != null) callback.execute(article); }); } public interface OnMessageReceived { void execute(ArticleView article); } }
mit
i-den/SoftwareUniversity
Software University/10) Java OOP - February2019/05. Abstractions - Exercises/06. Greedy Times/greed/currency/Gem.java
225
package greed.currency; public class Gem extends Currency { public static final String REGEX_PATTERN = "(?i)\\b[\\w]+gem\\b"; public Gem(String name, long amount) { super(name, amount); } }
mit
zgqq/mah
mah-core/src/main/java/mah/plugin/config/XmlPluginMetainfoParser.java
6971
/** * MIT License * * Copyright (c) 2017 zgqq * * 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 mah.plugin.config; import mah.app.config.ParserConfigException; import mah.common.util.XmlUtils; import mah.plugin.PluginMetainfo; import mah.plugin.loader.PluginClassLoader; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Collectors; /** * Created by zgq on 2017-01-08 20:02 */ public class XmlPluginMetainfoParser { private final File pluginDir; private final List<? extends InputStream> metainfoFiles; private static final PluginClassLoader PLUGIN_CLASSLOADER = new PluginClassLoader(); public XmlPluginMetainfoParser(File pluginDir, List<? extends InputStream> metainfoFiles) { this.pluginDir = pluginDir; this.metainfoFiles = metainfoFiles; } @NotNull protected final List<PluginMetainfo> parsePluginMetainfosFromJars(File pluginDir, List<String> pluginNames) throws Exception { List<PluginMetainfo> pluginMetainfos = null; if (pluginDir != null && pluginDir.isDirectory()) { List<String> pluginFiles = Arrays.stream(pluginDir.list((dir, name) -> { if (name.endsWith(".jar")) { return true; } else { return false; } })).collect(Collectors.toList()); for (String pluginFile : pluginFiles) { File file = new File(pluginDir.getAbsolutePath() + File.separator + pluginFile); JarFile jarFile = new JarFile(file); JarEntry jarEntry = jarFile.getJarEntry("META-INF/plugin.xml"); InputStream inputStream = jarFile.getInputStream(jarEntry); pluginMetainfos = parsePluginMetainfos(inputStream, pluginNames); for (PluginMetainfo pluginMetainfo : pluginMetainfos) { //Load plugin PLUGIN_CLASSLOADER.loadClass(pluginMetainfo.getPluginClass(), jarFile); pluginMetainfo.setPluginLoader(PLUGIN_CLASSLOADER); } } } if (pluginMetainfos == null) { return new ArrayList<>(); } return pluginMetainfos; } @NotNull public List<PluginMetainfo> parsePluginMetainfos(List<String> pluginNames) { try { List<PluginMetainfo> pluginMetainfos = parseBuiltinPluginMetainfos(pluginNames); List<PluginMetainfo> jarPluginMetainfos = parsePluginMetainfosFromJars(pluginDir, pluginNames); pluginMetainfos.addAll(jarPluginMetainfos); return pluginMetainfos; } catch (Exception e) { throw new ParserConfigException(e); } } protected List<PluginMetainfo> parsePluginMetainfos(InputStream inputStream, List<String> pluginNames) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(inputStream); return parseMetainfos(doc, pluginNames); } catch (Exception e) { throw new ParserConfigException(e); } } @NotNull private List<PluginMetainfo> parseBuiltinPluginMetainfos(List<String> pluginNames) throws Exception { ArrayList<PluginMetainfo> allPluginMeteInfos = new ArrayList<>(); for (InputStream metainfoFile : metainfoFiles) { List<PluginMetainfo> pluginMetainfos = parseBuiltinPluginMetainfo(metainfoFile, pluginNames); allPluginMeteInfos.addAll(pluginMetainfos); } return allPluginMeteInfos; } private List<PluginMetainfo> parseBuiltinPluginMetainfo(InputStream metainfoFile, List<String> pluginNames) throws Exception { Document doc = XmlUtils.getDocument(metainfoFile); List<PluginMetainfo> pluginMetainfos = parseMetainfos(doc, pluginNames); for (PluginMetainfo pluginMetainfo : pluginMetainfos) { pluginMetainfo.setPluginLoader(getClass().getClassLoader()); } return pluginMetainfos; } private List<PluginMetainfo> parseMetainfos(Document doc, List<String> pluginNames) { List<PluginMetainfo> metainfos = new ArrayList<>(); NodeList pluginNodes = doc.getElementsByTagName("plugin"); int length = pluginNodes.getLength(); for (int j = 0; j < length; j++) { Node item = pluginNodes.item(j); PluginMetainfo metainfo = parseMetaInfo(item); if (pluginNames == null || pluginNames.contains(metainfo.getName())) { metainfos.add(metainfo); } } return metainfos; } private PluginMetainfo parseMetaInfo(Node item) { PluginMetainfo metainfo = new PluginMetainfo(); NodeList pluginInfoNode = item.getChildNodes(); for (int k = 0; k < pluginInfoNode.getLength(); k++) { Node info = pluginInfoNode.item(k); String nodeName = info.getNodeName(); if (nodeName.equals("class")) { metainfo.setPluginClass(info.getTextContent()); } else if (nodeName.equals("author")) { metainfo.setAuthor(info.getTextContent()); } else if (nodeName.equals("name")) { metainfo.setName(info.getTextContent()); } else if (nodeName.equals("description")) { metainfo.setDescription(info.getTextContent()); } } return metainfo; } }
mit
kwong/UpdatingViewsOnSQLite
src/datastructs/NotEqualsNode.java
1648
package datastructs; import parser.SQLParser; public class NotEqualsNode extends Node { Node lnode; Node rnode; public NotEqualsNode(Node lnode, Node rnode) { super(lnode, rnode); this.lnode = lnode; this.rnode = rnode; } public BoolNode eval() { String left, right; Node lnew, rnew; /* if (rnode.eval() == null) return null; try { right = Integer.parseInt(rnode.eval().toString().trim()); } catch (NumberFormatException nfe) { return null; } */ if (lnode instanceof StrNode || lnode instanceof IntNode || lnode instanceof BoolNode) { left = lnode.eval().toString(); } else if (lnode instanceof AttributeNode) { if (lnode.eval() == null) return new BoolNode((evalType == SQLParser.INSERT) ? false : true, null, null); try { left = lnode.eval().toString().trim(); } catch (NumberFormatException nfe) { return new BoolNode((evalType == SQLParser.INSERT) ? false : true, null, null); } } else { lnew = (Node) lnode.eval(); left = ((StrNode) lnew).eval(); } if (rnode instanceof StrNode || rnode instanceof IntNode || rnode instanceof BoolNode) { right = rnode.eval().toString(); } else if (rnode instanceof AttributeNode) { if (rnode.eval() == null) return new BoolNode((evalType == SQLParser.INSERT) ? false : true, null, null); try { right = rnode.eval().toString().trim(); } catch (NumberFormatException nfe) { return new BoolNode((evalType == SQLParser.INSERT) ? false : true, null, null); } } else { rnew = (Node) (rnode.eval()); right = ((StrNode) rnew).eval(); } return new BoolNode(!left.equalsIgnoreCase(right), null, null); } }
mit
diosmosis/junit-bdd-lite
src/main/java/flarestar/bdd/model/BddSuite.java
2341
package flarestar.bdd.model; import flarestar.bdd.annotations.Describe; import flarestar.bdd.annotations.It; import java.lang.reflect.Method; import java.util.*; /** * TODO */ public class BddSuite { private Class<?> testKlass; private Class<?>[] testTargets; private String customDescription; public BddSuite(Class<?> testKlass) { this.testKlass = testKlass; Describe annotation = testKlass.getAnnotation(Describe.class); if (annotation == null) { throw new IllegalArgumentException("Test class " + testKlass + " must be annotated w/ @Describe."); } testTargets = annotation.value(); customDescription = annotation.desc(); } public Iterable<Class<?>> getInnerSuites() { List<Class<?>> result = new ArrayList<Class<?>>(); for (Class<?> innerClass : testKlass.getClasses()) { if (innerClass.getAnnotation(Describe.class) == null) { continue; } result.add(innerClass); } return result; } public Iterable<Method> getTestMethods() { List<Method> methods = new ArrayList<Method>(); for (Method method : testKlass.getMethods()) { if (method.getAnnotation(It.class) == null) { continue; } methods.add(method); } Collections.sort(methods, new Comparator<Method>() { public int compare(Method method1, Method method2) { return method1.getName().compareTo(method2.getName()); } }); return methods; } public String getDescriptionText() { StringBuilder result = new StringBuilder(); result.append(testKlass.getName()); if (customDescription != null && !customDescription.isEmpty()) { result.append(" [tests "); result.append(customDescription); result.append("]"); } else if (testTargets.length > 0) { result.append(" [tests "); for (int i = 0; i != testTargets.length; ++i) { if (i != 0) { result.append(", "); } result.append(testTargets[i].getName()); } result.append("]"); } return result.toString(); } }
mit
myid999/javademo
core/src/main/java/demo/java/v1c12genericprogramming/PairTest1/Pair.java
517
package demo.java.v1c12genericprogramming.PairTest1; /** * @version 1.00 2004-05-10 * @author Cay Horstmann */ public class Pair<T> { public Pair() { first = null; second = null; } public Pair(T first, T second) { this.first = first; this.second = second; } public T getFirst() { return first; } public T getSecond() { return second; } public void setFirst(T newValue) { first = newValue; } public void setSecond(T newValue) { second = newValue; } private T first; private T second; }
mit
vdurmont/apipixie
apipixie/src/main/java/com/ligati/apipixie/tools/Preconditionner.java
486
package com.ligati.apipixie.tools; import com.ligati.apipixie.APIPixieFeature; import com.ligati.apipixie.exception.APIConfigurationException; import com.ligati.apipixie.exception.APIUsageException; public class Preconditionner { public static void checkNotNull(Object obj, String msg) { if (obj == null) throw new APIUsageException(msg); } public static void checkNotNullConfig(Object obj, String msg) { if (obj == null) throw new APIConfigurationException(msg); } }
mit
vonwenm/JANEL
Test/TestLaunch/src/testpackage/TestLaunch046.java
1122
package testpackage; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class TestLaunch046 { public static void main(String[] args) { BufferedWriter bufferedLogFileWriter = null; try { bufferedLogFileWriter = new BufferedWriter(new FileWriter("C:\\Test\\JanelTestLog046.txt")); bufferedLogFileWriter.write("Testing Janel's service by installing the service, starting it, then uninstalling it.\r\n"); bufferedLogFileWriter.write("TestLaunch046 SUCCESSFUL"); bufferedLogFileWriter.flush(); // sleep for 15 seconds just in case tester wants to see the service. long startTime = System.currentTimeMillis(); long currentTime; do { Thread.sleep(5000); currentTime = System.currentTimeMillis(); } while (currentTime - startTime < 15000); } catch(Exception ex) { ex.printStackTrace(); System.out.println("TestLaunch046 FAILURE"); System.exit(1); } finally { if(bufferedLogFileWriter != null) { try { bufferedLogFileWriter.close(); } catch(IOException ioe) { } } } System.exit(0); } }
mit
JBYoshi/SpongeAPI
src/main/java/org/spongepowered/api/entity/ai/task/builtin/creature/RangeAgentAITask.java
3661
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.api.entity.ai.task.builtin.creature; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.ai.task.AITask; import org.spongepowered.api.entity.ai.task.AITaskBuilder; import org.spongepowered.api.entity.living.Ranger; /** * An {@link AITask} which uses the ranging aspect of the Ranger to attack * the target. */ public interface RangeAgentAITask extends AITask<Ranger> { /** * Creates a new {@link Builder} to build a new {@link RangeAgentAITask}. * * @return A new builder */ static Builder builder() { return Sponge.getRegistry().createBuilder(Builder.class); } /** * Gets the movement speed modifier for moving towards a targeted * {@link Entity}. * * @return The movement speed modifier */ double getMoveSpeed(); /** * Sets the movement speed modifier for moving towards a targeted * {@link Entity}. * * @param speed The movement speed modifier * @return This task, for chaining */ RangeAgentAITask setMoveSpeed(double speed); /** * Gets the delay in ticks between attempts to attack the targeted * {@link Entity}. * * @return The delay in ticks between attempts to attack */ int getDelayBetweenAttacks(); /** * The time, in ticks, this {@link Ranger} will wait before attacking * again. * * @param delay The delay, in ticks * @return This task, for chaining */ RangeAgentAITask setDelayBetweenAttacks(int delay); /** * Gets the radius of which the owning {@link Ranger} will attempt to * attack a targeted {@link Entity}. * * @return The radius of which the owning entity will attempt to attack */ float getAttackRadius(); /** * Sets the radius of which the owning {@link Ranger} will attempt to * attack a targeted {@link Entity}. * * @param radius The radius of which the owning entity will attempt to * attack * @return This task, for chaining */ RangeAgentAITask setAttackRadius(float radius); interface Builder extends AITaskBuilder<Ranger, RangeAgentAITask, RangeAgentAITask.Builder> { Builder moveSpeed(double speed); Builder delayBetweenAttacks(int delay); Builder attackRadius(float radius); } }
mit
smtchahal/RegexTester
app/src/main/java/smtchahal/regextester/JSONAdapter.java
3099
package smtchahal.regextester; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Iterator; public class JSONAdapter extends BaseAdapter { private static final String LOG_TAG = "JSONAdapter"; private JSONArray mJsonArray; private final Context mContext; private final LayoutInflater mInflater; public JSONAdapter(Context context, LayoutInflater inflater, JSONArray jsonArray) { mContext = context; mInflater = inflater; mJsonArray = jsonArray; } @Override public int getCount() { return mJsonArray.length(); } @Override public JSONObject getItem(int position) { return mJsonArray.optJSONObject(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; // check if the view already exists // if so, no need to inflate and findViewById again! if (convertView == null) { // Inflate the custom row layout from XML convertView = mInflater.inflate(R.layout.row_regex, null); // create a new "Holder" with subviews holder = new ViewHolder(); holder.regexKeyTextView = (TextView) convertView.findViewById(R.id.regex_key_textview); holder.regexValueTextView = (TextView) convertView.findViewById(R.id.regex_value_textview); // hang onto the holder for future recyclage convertView.setTag(holder); } else { // skip all the expensive inflation/findViewById // and just get the holder you already made holder = (ViewHolder) convertView.getTag(); } JSONObject jsonObject = getItem(position); Iterator<String>keys = jsonObject.keys(); String key = ""; String value = ""; try { while (keys.hasNext()) { key = keys.next(); value = jsonObject.getString(key); } holder.regexKeyTextView.setText(key); holder.regexValueTextView.setText(value); } catch (JSONException e) { Toast.makeText(mContext, R.string.json_exception_toast_message, Toast.LENGTH_LONG).show(); Log.d(LOG_TAG, "JSONException, this shouldn't have happened..."); Log.d(LOG_TAG, "e.getMessage() = " + e.getMessage()); } return convertView; } public void updateData(JSONArray jsonArray) { // update the adapter's dataset mJsonArray = jsonArray; notifyDataSetChanged(); } private static class ViewHolder { public TextView regexKeyTextView; public TextView regexValueTextView; } }
mit
drilic/TicketTracker
app/src/main/java/rs/tickettracker/helpers/ContentProviderTestHelper.java
2385
package rs.tickettracker.helpers; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.util.Log; import com.activeandroid.Configuration; import com.activeandroid.DatabaseHelper; import com.activeandroid.query.Select; import java.util.List; import model.Status; import model.Ticket; import rs.tickettracker.providers.TicketTrackerCP; /** * This helper class is used for Content Provider test data. */ public class ContentProviderTestHelper { /** * Get all tickets from database. * @param activity - current activity */ public static void getAllTickets(Activity activity) { String[] allColumns = {TicketTrackerCP.COLUMN_ID, "ticketName"}; Uri contentUri = Uri.parse(TicketTrackerCP.CONTENT_URI + TicketTrackerCP.AUTHORITIES + "/" + TicketTrackerCP.TABLE_TICKET); Cursor c = activity.getContentResolver().query( contentUri, new String[]{"ticketName"}, null, null, "ticketName"); if (c != null) if (c.moveToFirst()) { do { Log.i("***", c.getString(c.getColumnIndex("ticketName"))); } while (c.moveToNext()); } } /** * Insert new ticket in database. * @param activity - current activity. */ public static void insertNewTicket(Activity activity) { Configuration dbConfiguration = new Configuration.Builder(activity).create(); DatabaseHelper database = new DatabaseHelper(dbConfiguration); Status s = new Select().from(Status.class).where("status = ?", "Active").executeSingle(); SQLiteDatabase db = database.getWritableDatabase(); { ContentValues entry = new ContentValues(); entry.put("ticketName", "Finale"); entry.put("possibleGain", 1000d); entry.put("status", s.getId()); List<Ticket> tickets = Ticket.getAll(); entry.put("_id", tickets.size() + 1); Uri contentUri = Uri.parse("content://" + TicketTrackerCP.AUTHORITIES + "/" + TicketTrackerCP.TABLE_TICKET); activity.getContentResolver().insert(contentUri, entry); } db.close(); } }
mit
all-trees/tree-svg
src/test/java/nl/dvberkel/box/BoundingBoxMergeTest.java
1193
package nl.dvberkel.box; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class BoundingBoxMergeTest { @Test public void shouldBeAbleToMergeWithNoOtherBoxes() { BoundingBox a = new BoundingBox(0, 0, 1, 1); BoundingBox merged = a.merge(); assertThat(merged, is(a)); } @Test public void shouldBeAbleToMergeWithSameBox() { BoundingBox a = new BoundingBox(0, 0, 1, 1); BoundingBox merged = a.merge(a); assertThat(merged, is(a)); } @Test public void shouldBeAbleToMergeWithOtherBox() { BoundingBox a = new BoundingBox(0, 0, 1, 1); BoundingBox b = new BoundingBox(1, 1, 1, 1); BoundingBox merged = a.merge(b); assertThat(merged, is(new BoundingBox(0, 0, 2, 2))); } @Test public void shouldBeAbleToMergeWithOtherBoxes() { BoundingBox a = new BoundingBox(0, 0, 1, 1); BoundingBox b = new BoundingBox(1, 1, 1, 1); BoundingBox c = new BoundingBox(2, 0, 1, 1); BoundingBox merged = a.merge(b, c); assertThat(merged, is(new BoundingBox(0, 0, 3, 2))); } }
mit
JohnDeere/MyJohnDeereAPI-OAuth-Java-Client
src/main/java/com/deere/democlient/apis/AbstractApiBaseWrapper.java
308
package com.deere.democlient.apis; import com.deere.rest.RestRequestBuilder; import static com.deere.democlient.apis.AbstractApiBase.oauthRequestTo; public class AbstractApiBaseWrapper { public RestRequestBuilder oauthRequestToWrapper(String baseUri) { return oauthRequestTo(baseUri); } }
mit
davidsan/racing-line
src/li260/algo/RadarDijkstra.java
1324
package li260.algo; import li260.circuit.Circuit; import li260.circuit.Terrain; import li260.circuit.ToolsTerrain; import li260.geometry.VTools; import li260.geometry.Vecteur; import li260.voiture.Voiture; public class RadarDijkstra extends RadarClassique { private static final long serialVersionUID = 1L; public RadarDijkstra(double[] thetas, Voiture v, Circuit c) { super(thetas, v, c); } public double calcScore(double d) { Vecteur p = new Vecteur(v.getPosition()); Vecteur dir = new Vecteur(v.getDirection()); VTools.rotation(dir, d); int score = (int) Double.POSITIVE_INFINITY; int coup = 0; /* optimisation */ while (ToolsTerrain.isRunnable(c.getTerrain(p))) { if (c.getTerrain(p) == Terrain.EndLine && VTools.prodScal(dir, c.getDirectionArrivee()) <= 0) { return -Double.POSITIVE_INFINITY; } int tmp = (int) c.getDist((int) p.getX(), (int) p.getY()); if (tmp == 0) { tmp = Integer.MAX_VALUE + coup; } if (tmp < score) { score = tmp; } p.autoAdd(VTools.prodDouble(dir, EPS)); coup++; } return -1 * score; } public double[] distancesInPixels() { double[] pixel = new double[scores.length]; for (int i = 0; i < pixel.length; i++) { pixel[i] = 0.1 * (scores[i]) * -1; if (pixel[i] < 0) { pixel[i] = 0; } } return pixel; } }
mit
xChasingWaves/clase
Programacion/Unidad03/C1/Ejercicio02.java
458
package C1; public class Ejercicio02 { public static void main(String[] args) { int nota = LibLeer.entero("Introduce la nota: "); int edad = LibLeer.entero("Introduce la edad: "); char sexo = LibLeer.caracter("Introduce el sexo (V/M): "); if (nota >= 5 && edad >= 18 && sexo == 'M') { System.out.println("ACEPTADA"); } else if (nota >= 5 && edad >= 18 && sexo == 'V') { System.out.println("POSIBLE"); } } }
mit
tbepler/JProbe
src/util/genome/probe/ProbeUtils.java
12942
package util.genome.probe; import util.DNAUtils; import util.genome.GenomicCoordinate; import util.genome.GenomicRegion; import util.genome.GenomicSequence; import util.genome.NoSuchBaseException; import util.genome.Strand; import util.genome.kmer.Kmer; import util.genome.kmer.NoSuchWordException; import util.genome.pwm.PWM; import util.progress.ProgressEvent; import util.progress.ProgressListener; import util.progress.ProgressEvent.Type; import java.util.*; public class ProbeUtils { public static final Collection<Character> DNA_BASES = getDNABases(); private static Collection<Character> getDNABases(){ Collection<Character> bases = new HashSet<Character>(); bases.add('A'); bases.add('C'); bases.add('G'); bases.add('T'); return bases; } public static interface Filter{ public boolean keep(Probe p); } public static ProbeGroup filter(ProbeGroup probes, Filter f){ List<Probe> filtered = new ArrayList<Probe>(); for(Probe p : probes){ if(f.keep(p)){ filtered.add(p); } } return new ProbeGroup(filtered); } public static ProbeGroup joinProbes(ProgressListener l, Iterable<Probe> givenProbes, int bindingSites, int minDist, int maxDist){ List<Probe> probes = new ArrayList<Probe>(); for(Probe p : givenProbes){ probes.add(p); } Collections.sort(probes); Queue<Probe> joinedProbes = new PriorityQueue<Probe>(); int percentComplete = fireJoinProbesProgress(l, 0, probes.size(), -1); //for sub list of size=bindingSites in the list of probes for(int i=0; i<probes.size(); i++){ Probe combined = join(probes, i, bindingSites, minDist, maxDist); if(combined != null){ joinedProbes.add(combined); } percentComplete = fireJoinProbesProgress(l, i+1, probes.size(), percentComplete); } if(l != null){ l.update(new ProgressEvent(null, Type.COMPLETED, "Done joining probes.")); } return new ProbeGroup(joinedProbes); } protected static int fireJoinProbesProgress(ProgressListener l, int progress, int maxProgress, int prevPercent){ if(l == null) return 0; int percent = progress*100/maxProgress; if(percent != prevPercent){ l.update(new ProgressEvent(null, Type.UPDATE, progress, maxProgress, "Joining probes...")); } return percent; } public static ProbeGroup joinProbes(ProgressListener l, Iterable<Probe> givenProbes, int bindingSites, int minDist, int maxDist, int probeLen){ List<Probe> probes = new ArrayList<Probe>(); for(Probe p : givenProbes){ probes.add(p); } Collections.sort(probes); Queue<Probe> joinedProbes = new PriorityQueue<Probe>(); int percentComplete = fireJoinProbesProgress(l, 0, probes.size(), -1); //for sub list of size=bindingSites in the list of probes for(int i=0; i<probes.size(); i++){ Probe combined = join(probes, i, bindingSites, minDist, maxDist, probeLen); if(combined != null){ joinedProbes.add(combined); } percentComplete = fireJoinProbesProgress(l, i+1, probes.size(), percentComplete); } if(l != null){ l.update(new ProgressEvent(null, Type.COMPLETED, "Done joining probes.")); } return new ProbeGroup(joinedProbes); } public static Probe join(List<Probe> probes, int start, int bindingSites, int minDist, int maxDist, int probeLen){ Probe combined = join(probes, start, bindingSites, minDist, maxDist); if(combined != null){ GenomicRegion bindingRegion = GenomicRegion.union(combined.getBindingSites()); if(bindingRegion.getSize() > probeLen){ //do not create probe if the binding region will not fit return null; } int flank = probeLen - (int) bindingRegion.getSize(); GenomicCoordinate regStart; GenomicCoordinate regEnd; //since decrement and increment work with negative numbers, this will correctly expand or reduce the //region to the desired probe size if(flank%2==0){ regStart = bindingRegion.getStart().decrement(flank/2); regEnd = bindingRegion.getEnd().increment(flank/2); }else{ //if flank odd, add +1 to left regStart = bindingRegion.getStart().decrement(flank/2 + 1); regEnd = bindingRegion.getEnd().increment(flank/2); } assert(new GenomicRegion(regStart, regEnd).getSize() == probeLen); Probe subprobe = combined.subprobe(new GenomicRegion(regStart, regEnd), combined.getName()); if(subprobe.numBindingSites() == bindingSites){ return subprobe; } } return null; } public static Probe join(List<Probe> probes, int start, int bindingSites, int minDist, int maxDist){ Probe combined = join(probes, start, probes.size(), bindingSites); if(combined != null && meetsBindingCriteria(combined, minDist, maxDist)){ return combined; } return null; } private static boolean meetsBindingCriteria(Probe probe, int minDist, int maxDist){ GenomicRegion[] bindingSites = probe.getBindingSites(); for(int i=0; i<bindingSites.length-1; i++){ if(!meetsBindingCriteria(bindingSites[i], bindingSites[i+1], minDist, maxDist)){ return false; } } return true; } private static boolean meetsBindingCriteria(GenomicRegion siteA, GenomicRegion siteB, int minDist, int maxDist){ long dist = siteA.distance(siteB); return dist >= minDist && dist <= maxDist; } private static Probe join(List<Probe> probes, int start, int end, int bindingSites){ Probe combined = probes.get(start); for(int i=start+1; i<end; i++){ if(combined.numBindingSites() > bindingSites) return null; if(combined.numBindingSites() == bindingSites) return combined; Probe nextProbe = probes.get(i); if(combined.adjacentTo(nextProbe) || combined.overlaps(nextProbe)){ combined = combined.combine(nextProbe, combineNames(combined, nextProbe)); }else{ return null; } } if(combined.numBindingSites() != bindingSites){ return null; } return combined; } private static String combineNames(Probe a, Probe b){ String x = a.getName(); String y = b.getName(); if(x.equals(y)){ return x; } return x+"/"+y; } //private static long scorePWM; //private static long scoreKmer; public static List<Probe> extractFrom( GenomicSequence seq, Strand strand, String name, Kmer kmer, PWM pwm, int probeLength, int bindingSiteLength, int windowSize, double escoreThreshhold ){ Collection<Probe> probes = new LinkedHashSet<Probe>(); //scorePWM = 0; //scoreKmer = 0; //iterate over each subsequence of size bindingSiteLength within seq GenomicCoordinate stop = seq.getEnd().decrement(bindingSiteLength - 2); GenomicCoordinate start = seq.getStart(); while(start.compareTo(stop) < 0){ GenomicSequence bindingSite = seq.subsequence(start, start.increment(bindingSiteLength - 1)); //check if the binding site meets the threshhold criteria if(meetsThreshhold(score(bindingSite, kmer), escoreThreshhold)){ //scan window around binding site with the PWM for best scoring region GenomicRegion center = scanWindow(seq, bindingSite.getRegion(), pwm, windowSize); if(center != null){ //check which orientation the probe should be boolean reverse = reverseOrientation(seq.subsequence(center), pwm); //create a probe centered on the center region Probe p = createProbe(seq, center, strand, name + "_probe" + (probes.size() + 1), probeLength, reverse); //pwm.canScore() ensures that the probe only contains bases recognized //by the pwm if(p != null && !probes.contains(p) && pwm.canScore(p.getSequence())){ probes.add(p); } } } start = start.increment(1); } List<Probe> probeList = new ArrayList<Probe>(probes); //System.err.println("PWM Score time = "+scorePWM+", Kmer Score time = "+scoreKmer); //System.err.println(kmer.getClass()); return probeList; } private static boolean reverseOrientation(GenomicSequence seq, PWM pwm){ return pwm.score(seq.getSequence().toUpperCase()) < pwm.score(DNAUtils.reverseCompliment(seq.getSequence().toUpperCase())); } private static Probe createProbe(GenomicSequence seq, GenomicRegion center, Strand strand, String name, int probeLength, boolean reverse){ int flankLength = probeLength - (int) center.getSize(); GenomicCoordinate start; GenomicCoordinate end; //if flanklength is odd, then take 1 base less from the right if(flankLength % 2 == 1){ start = center.getStart().decrement(flankLength/2 + 1); end = center.getEnd().increment(flankLength/2); }else{ start = center.getStart().decrement(flankLength/2); end = center.getEnd().increment(flankLength/2); } //make sure start and end are in bounds if(start.compareTo(seq.getStart()) < 0 || end.compareTo(seq.getEnd()) > 0){ return null; } GenomicSequence probeSeq = seq.subsequence(start, end); if(reverse){ probeSeq = probeSeq.reverseCompliment(); strand = Strand.reverse(strand); } return new Probe(probeSeq, new GenomicRegion[]{center}, name, strand); } private static GenomicRegion scanWindow(GenomicSequence seq, GenomicRegion bindingSite, PWM pwm, int windowSize){ GenomicCoordinate windowStart = bindingSite.getStart().decrement(windowSize); if(windowStart.compareTo(seq.getStart()) < 0) windowStart = seq.getStart(); GenomicCoordinate windowEnd = bindingSite.getEnd().increment(windowSize); if(windowEnd.compareTo(seq.getEnd()) > 0) windowEnd = seq.getEnd(); GenomicRegion window = new GenomicRegion(windowStart, windowEnd); if(window.getSize() < pwm.length()) return null; //score each region of size pwm.length() within the window region and keep the highest scoring region GenomicRegion best = null; double bestScore = Double.NEGATIVE_INFINITY; //System.err.println("PWM length: "+pwm.length()); GenomicRegion cur = new GenomicRegion(window.getStart(), window.getStart().increment(pwm.length() - 1)); while(cur.getEnd().compareTo(window.getEnd()) <= 0){ GenomicSequence curSeq = seq.subsequence(cur); try{ double score = score(curSeq, pwm); //System.err.println("Score = "+score); if(score > bestScore){ bestScore = score; best = cur; } } catch (NoSuchBaseException e){ //catch the NoSuchBaseException in case the sequence contains characters not recognized by //the pwm } cur = cur.increment(1); } return best; } private static double score(GenomicSequence seq, PWM pwm){ //long start = System.currentTimeMillis(); double s = Math.max(pwm.score(seq.getSequence().toUpperCase()), pwm.score(DNAUtils.reverseCompliment(seq.getSequence().toUpperCase()))); //scorePWM += System.currentTimeMillis() - start; return s; } private static boolean meetsThreshhold(double[] scores, double threshhold){ if(scores.length < 1){ return false; } for(double d : scores){ if(d < threshhold) return false; } return true; } private static double[] score(GenomicSequence seq, Kmer kmer){ //long start = System.currentTimeMillis(); try{ double[] s = kmer.escoreSequence(seq.getSequence().toUpperCase()); //scoreKmer += System.currentTimeMillis() - start; return s; } catch (NoSuchWordException e){ return new double[]{}; } } public static Probe mutate(ProgressListener l, Probe p, Kmer kmer, Set<Character> alphabet, int bindingSiteBarrier, double escoreCutoff, double maxOverlap){ return Mutate.mutate(l, p, kmer, escoreCutoff, bindingSiteBarrier, maxOverlap, alphabet); } public static Probe mutate(ProgressListener l, Probe p, Kmer kmer, Set<Character> alphabet, int bindingSiteBarrier, double escoreCutoff, double maxOverlap, String primer){ return Mutate.mutate(l, p, kmer, escoreCutoff, bindingSiteBarrier, maxOverlap, alphabet, primer); } public static List<Probe> generateBindingSitePermuations(Probe p){ List<Probe> permutedProbes = new ArrayList<Probe>(); GenomicRegion[] bindingSites = p.getBindingSites(); List<List<GenomicRegion>> permutations = permutations(bindingSites); for(int i=0; i<permutations.size(); i++){ permutedProbes.add(new Probe(p, permutations.get(i), p.getName() + "_t"+i)); } return permutedProbes; } private static List<List<GenomicRegion>> permutations(GenomicRegion[] bindingSites){ return permutations(new ArrayList<GenomicRegion>(), 0, bindingSites); } private static List<List<GenomicRegion>> permutations(List<GenomicRegion> prefix, int index, GenomicRegion[] bindingSites){ List<List<GenomicRegion>> permutes = new ArrayList<List<GenomicRegion>>(); if(index == bindingSites.length){ //there are no binding sites left, so return a list containing the prefix permutation permutes.add(prefix); return permutes; } //first get all permutations with the index binding site added List<GenomicRegion> newPrefix = new ArrayList<GenomicRegion>(prefix); newPrefix.add(bindingSites[index]); permutes.addAll(permutations(newPrefix, index+1, bindingSites)); //now all permutations without the index binding site permutes.addAll(permutations(prefix, index+1, bindingSites)); return permutes; } }
mit
kwonhong/PublicMessenger
MessengerProject/src/com/example/messenger/chatroom/ChatRoomSlidingFragment.java
3743
package com.example.messenger.chatroom; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.messengerproject.R; public class ChatRoomSlidingFragment extends Fragment { DemoCollectionPagerAdapter mDemoCollectionPagerAdapter; ViewPager mViewPager; public ChatRoomSlidingFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_friend, container, false); mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter( getActivity().getSupportFragmentManager()); mViewPager = (ViewPager) rootView.findViewById(R.id.pager); mViewPager.setAdapter(mDemoCollectionPagerAdapter); final ActionBar actionBar = getActivity().getActionBar(); // Specify that tabs should be displayed in the action bar. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create a tab listener that is called when the user changes tabs. ActionBar.TabListener tabListener = new ActionBar.TabListener() { @Override public void onTabReselected(Tab arg0, android.app.FragmentTransaction arg1) { // TODO Auto-generated method stub } @Override public void onTabSelected(ActionBar.Tab tab, android.app.FragmentTransaction arg1) { // TODO Auto-generated method stub mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab arg0, android.app.FragmentTransaction arg1) { // TODO Auto-generated method stub } }; actionBar.addTab(actionBar.newTab().setText("Single").setTabListener(tabListener)); actionBar.addTab(actionBar.newTab().setText("Group").setTabListener(tabListener)); actionBar.addTab(actionBar.newTab().setText("Public").setTabListener(tabListener)); mViewPager = (ViewPager) rootView.findViewById(R.id.pager); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { // When swiping between pages, select the // corresponding tab. getActivity().getActionBar().setSelectedNavigationItem(position); } }); return rootView; } public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter { public DemoCollectionPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { Fragment fragment = null; if ( i == 0 ) { fragment = new SingleChatFragment(); } else if (i == 1) { fragment = new GroupChatFragment(); } else if (i == 2) { fragment = new PublicChatFragment(); } return fragment; } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { return "OBJECT " + (position + 1); } } public static class DemoObjectFragment extends Fragment { public static final String ARG_OBJECT = "object"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // The last two arguments ensure LayoutParams are inflated // properly. View rootView = inflater.inflate(R.layout.fragment_community, container, false); return rootView; } } }
mit
facebook/fresco
samples/animation2/src/main/java/com/facebook/samples/animation2/MediaControlFragment.java
2367
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.samples.animation2; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.ToggleButton; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.facebook.fresco.animation.backend.AnimationBackend; import com.facebook.fresco.animation.drawable.AnimatedDrawable2; import com.facebook.samples.animation2.utils.AnimationControlsManager; import com.facebook.samples.animation2.utils.SampleAnimationBackendConfigurator; /** Sample that displays an animated image and media controls to start / stop / seek. */ public class MediaControlFragment extends Fragment implements SampleAnimationBackendConfigurator.BackendChangedListener { private AnimationControlsManager mAnimationControlsManager; private AnimatedDrawable2 mAnimatedDrawable; @Nullable @Override public View onCreateView( LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_media_controls, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { ImageView imageView = (ImageView) view.findViewById(R.id.animation_container); // Create a new animated drawable. The backend will be set by the backend configurator. mAnimatedDrawable = new AnimatedDrawable2(); imageView.setImageDrawable(mAnimatedDrawable); mAnimationControlsManager = new AnimationControlsManager( mAnimatedDrawable, (SeekBar) view.findViewById(R.id.seekbar), (ToggleButton) view.findViewById(R.id.playpause), view.findViewById(R.id.reset)); new SampleAnimationBackendConfigurator((Spinner) view.findViewById(R.id.spinner), this); } @Override public void onBackendChanged(final AnimationBackend backend) { mAnimatedDrawable.setAnimationBackend(backend); mAnimationControlsManager.updateBackendData(backend); mAnimatedDrawable.invalidateSelf(); } }
mit
tblsoft/solr-cmd-utils
src/main/java/de/tblsoft/solr/pipeline/filter/AbstractStatusFilter.java
4275
package de.tblsoft.solr.pipeline.filter; import de.tblsoft.solr.http.HTTPHelper; import de.tblsoft.solr.pipeline.AbstractFilter; import de.tblsoft.solr.pipeline.bean.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * Created by tblsoft on 26.11.16. * * abstract class to implement multiple status filter. */ public abstract class AbstractStatusFilter extends AbstractFilter { private static Logger LOG = LoggerFactory.getLogger(AbstractStatusFilter.class); protected int documentCounter = 0; protected long lapStart = 0; protected int lapCount = 0; protected long start = 0; protected String webHook; protected List<String> fieldsToPrint; @Override public void init() { LOG.info("start processing"); lapStart = System.currentTimeMillis(); start = System.currentTimeMillis(); webHook = getProperty("webHook", null); fieldsToPrint = getPropertyAsList("fieldsToPrint", null); if(webHook != null) { HTTPHelper.webHook(webHook, "status", "progress.start", "documentCounter", String.valueOf(documentCounter), "expectedDocumentCount", String.valueOf(pipelineExecuter.getExpectedDocumentCount()), "processId", getPipelineExecuter().getProcessId()); } super.init(); } @Override public void document(Document document) { documentCounter++; lapCount++; if(printCurrentStatus()) { long now = System.currentTimeMillis(); long duration = now - start; long lapDuration = now - lapStart; printStatus(duration, lapDuration, document); lapStart = now; lapCount = 0; } super.document(document); } abstract boolean printCurrentStatus(); @Override public void end() { printEnd(); super.end(); }; protected String getFormattedDuration(long duration) { if(duration < 300000 ) { long durationInSeconds = duration / 1000; return durationInSeconds + " seconds"; } else if (duration < 180*60*1000) { long durationInMinute = duration / 1000 / 60; return durationInMinute + " minutes"; } else { long durationInMinute = duration / 1000 / 60; long durationInHours = durationInMinute / 60; return durationInHours + " hours " + durationInMinute + " minutes"; } } void printStatus(long duration, long lapDuration, Document document) { StringBuilder printFields = new StringBuilder(); if(fieldsToPrint != null) { for(String fieldToPrint : fieldsToPrint) { String fieldValue = document.getFieldValue(fieldToPrint); if(fieldValue != null) { printFields.append(" "); printFields.append(fieldToPrint); printFields.append(":"); printFields.append(fieldValue); } } } LOG.info("processed all " + documentCounter + " in " + getFormattedDuration(duration) + ". - processed the last " + lapCount + " documents in " + getFormattedDuration(lapDuration) + "." + printFields); if(webHook != null) { HTTPHelper.webHook(webHook, "status", "progress", "documentCounter", String.valueOf(documentCounter), "expectedDocumentCount", String.valueOf(pipelineExecuter.getExpectedDocumentCount()), "processId", getPipelineExecuter().getProcessId()); } } void printEnd() { long duration = System.currentTimeMillis() - start; LOG.info("End. processed all " + documentCounter + " in " + getFormattedDuration(duration) + "."); if(webHook != null) { HTTPHelper.webHook(webHook, "status", "progress.end", "documentCounter", String.valueOf(documentCounter), "expectedDocumentCount", String.valueOf(pipelineExecuter.getExpectedDocumentCount()), "processId", getPipelineExecuter().getProcessId()); } } }
mit
V-Lam/School-Assignments-and-Labs-2014-2017
CS 1026 - Java -- (Computer Science Fundamentals 1)/MyLabs/lab 10/SimpleReader.java
1291
import java.io.*; public class SimpleReader { /** * Method to read a file and print out the contents * @param fileName the name of the file to read from */ private int size = 0; private String fileName; private String lines []; public SimpleReader(String name) { fileName = name; File file = new File(fileName); String line = null; lines = new String[100]; // try to do the following try { // create the buffered reader BufferedReader reader = new BufferedReader(new FileReader(fileName)); // Loop while there is more data int i = 0; while((line = reader.readLine()) != null) { // store the current line lines[i] = line; i++; } // close the reader reader.close(); size = i; } catch(FileNotFoundException ex) { SimpleOutput.showError("Couldn't find " + fileName + " please pick it."); fileName = FileChooser.pickAFile(); } catch(Exception ex) { SimpleOutput.showError("Error reading file " + fileName); ex.printStackTrace(); } } public int getFileLength() { return size; } public String[] readFile() { return lines; } }
mit
gfneto/Hive2Hive
org.hive2hive.core/src/test/java/org/hive2hive/core/processes/notify/NotificationTest.java
13632
package org.hive2hive.core.processes.notify; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.hive2hive.core.H2HJUnitTest; import org.hive2hive.core.exceptions.GetFailedException; import org.hive2hive.core.exceptions.NoPeerConnectionException; import org.hive2hive.core.exceptions.NoSessionException; import org.hive2hive.core.model.versioned.Locations; import org.hive2hive.core.network.NetworkManager; import org.hive2hive.core.network.messages.MessageReplyHandler; import org.hive2hive.core.processes.ProcessFactory; import org.hive2hive.core.security.UserCredentials; import org.hive2hive.core.utils.FileTestUtil; import org.hive2hive.core.utils.H2HWaiter; import org.hive2hive.core.utils.NetworkTestUtil; import org.hive2hive.core.utils.TestExecutionUtil; import org.hive2hive.core.utils.TestProcessComponentListener; import org.hive2hive.core.utils.UseCaseTestUtil; import org.hive2hive.core.utils.helper.DenyingMessageReplyHandler; import org.hive2hive.processframework.ProcessState; import org.hive2hive.processframework.exceptions.InvalidProcessStateException; import org.hive2hive.processframework.exceptions.ProcessExecutionException; import org.hive2hive.processframework.interfaces.IProcessComponent; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * Tests the notification procedure * * @author Nico */ public class NotificationTest extends H2HJUnitTest { private static final int NETWORK_SIZE = 6; private static List<NetworkManager> network; private static List<MessageReplyHandler> messageHandlers; private static UserCredentials userACredentials; private static UserCredentials userBCredentials; private static UserCredentials userCCredentials; @BeforeClass public static void initTest() throws Exception { testClass = NotificationTest.class; beforeClass(); userACredentials = new UserCredentials("User A", randomString(), randomString()); userBCredentials = new UserCredentials("User B", randomString(), randomString()); userCCredentials = new UserCredentials("User C", randomString(), randomString()); network = NetworkTestUtil.createNetwork(NETWORK_SIZE); // create 10 nodes and login 5 of them: // node 0-2: user A // node 3-4: user B // node 5: user C UseCaseTestUtil.register(userACredentials, network.get(0)); UseCaseTestUtil.register(userBCredentials, network.get(3)); UseCaseTestUtil.register(userCCredentials, network.get(5)); // login all nodes UseCaseTestUtil.login(userACredentials, network.get(0), FileTestUtil.getTempDirectory()); UseCaseTestUtil.login(userACredentials, network.get(1), FileTestUtil.getTempDirectory()); UseCaseTestUtil.login(userACredentials, network.get(2), FileTestUtil.getTempDirectory()); UseCaseTestUtil.login(userBCredentials, network.get(3), FileTestUtil.getTempDirectory()); UseCaseTestUtil.login(userBCredentials, network.get(4), FileTestUtil.getTempDirectory()); UseCaseTestUtil.login(userCCredentials, network.get(5), FileTestUtil.getTempDirectory()); // store the message reply handler as backup messageHandlers = new ArrayList<MessageReplyHandler>(NETWORK_SIZE); for (NetworkManager client : network) { messageHandlers.add(client.getConnection().getMessageReplyHandler()); } } /** * Blocks the message reception of the peers * * @throws IOException */ private void blockMessageRecption(int... peerIndices) throws IOException { DenyingMessageReplyHandler denyingMessageReplyHandler = new DenyingMessageReplyHandler(); for (int index : peerIndices) { assert index < NETWORK_SIZE; network.get(index).getConnection().getPeer().peer().rawDataReply(denyingMessageReplyHandler); } } /** * Scenario: Call the notification process with an empty list * * @throws InvalidProcessStateException * @throws NoPeerConnectionException * @throws IllegalArgumentException * @throws NoSessionException * @throws ProcessExecutionException */ @Test public void testNotifyNobody() throws ClassNotFoundException, IOException, InvalidProcessStateException, IllegalArgumentException, NoPeerConnectionException, NoSessionException, ProcessExecutionException { NetworkManager notifier = network.get(0); CountingNotificationMessageFactory msgFactory = new CountingNotificationMessageFactory(notifier); IProcessComponent<Void> process = ProcessFactory.instance().createNotificationProcess(msgFactory, new HashSet<String>(0), notifier); TestProcessComponentListener listener = new TestProcessComponentListener(); process.attachListener(listener); process.execute(); // wait until all messages are sent TestExecutionUtil.waitTillSucceded(listener, 10); Assert.assertEquals(0, msgFactory.getArrivedMessageCount()); Assert.assertEquals(0, msgFactory.getSentMessageCount()); } /** * Scenario: User A (peer 0) contacts his own clients (peer 1 and 2) * * @throws InvalidProcessStateException * @throws NoPeerConnectionException * @throws IllegalArgumentException * @throws NoSessionException * @throws ProcessExecutionException */ @Test public void testNotifyOwnUser() throws ClassNotFoundException, IOException, InvalidProcessStateException, IllegalArgumentException, NoPeerConnectionException, NoSessionException, ProcessExecutionException { NetworkManager notifier = network.get(0); // send notification to own peers Set<String> users = new HashSet<String>(1); users.add(userACredentials.getUserId()); CountingNotificationMessageFactory msgFactory = new CountingNotificationMessageFactory(notifier); IProcessComponent<Void> process = ProcessFactory.instance().createNotificationProcess(msgFactory, new HashSet<String>(0), notifier); process.execute(); H2HWaiter waiter = new H2HWaiter(20); do { waiter.tickASecond(); } while (!msgFactory.allMsgsArrived()); Assert.assertEquals(ProcessState.EXECUTION_SUCCEEDED, process.getState()); } /** * Scenario: User A (peer 0) contacts his own clients (peer 1 and 2). * * @throws InvalidProcessStateException * @throws NoPeerConnectionException * @throws IllegalArgumentException * @throws ProcessExecutionException */ @Test public void testNotifyOwnUserSession() throws ClassNotFoundException, IOException, NoSessionException, InvalidProcessStateException, IllegalArgumentException, NoPeerConnectionException, ProcessExecutionException { NetworkManager notifier = network.get(0); // send notification to own peers Set<String> users = new HashSet<String>(1); users.add(userACredentials.getUserId()); CountingNotificationMessageFactory msgFactory = new CountingNotificationMessageFactory(notifier); IProcessComponent<Void> process = ProcessFactory.instance().createNotificationProcess(msgFactory, users, notifier); process.execute(); H2HWaiter waiter = new H2HWaiter(20); do { waiter.tickASecond(); } while (!msgFactory.allMsgsArrived()); Assert.assertEquals(ProcessState.EXECUTION_SUCCEEDED, process.getState()); } /** * Scenario: User A (peer 0) contacts his own clients (peer 1 and 2) and also the initial client of user B * (peer 3 or 4) and user C (peer 5) * * @throws InvalidProcessStateException * @throws NoPeerConnectionException * @throws IllegalArgumentException * @throws NoSessionException * @throws ProcessExecutionException */ @Test public void testNotifyOtherUsers() throws ClassNotFoundException, IOException, InvalidProcessStateException, IllegalArgumentException, NoPeerConnectionException, NoSessionException, ProcessExecutionException { NetworkManager notifier = network.get(0); // send notification to own peers Set<String> users = new HashSet<String>(3); users.add(userACredentials.getUserId()); users.add(userBCredentials.getUserId()); users.add(userCCredentials.getUserId()); CountingNotificationMessageFactory msgFactory = new CountingNotificationMessageFactory(notifier); IProcessComponent<Void> process = ProcessFactory.instance().createNotificationProcess(msgFactory, users, notifier); process.execute(); H2HWaiter waiter = new H2HWaiter(20); do { waiter.tickASecond(); } while (!msgFactory.allMsgsArrived()); Assert.assertEquals(4, msgFactory.getSentMessageCount()); Assert.assertEquals(ProcessState.EXECUTION_SUCCEEDED, process.getState()); } /** * Scenario: User A (peer 0) contacts his own clients (peer 1 and 2) and also user B * (peer 3 or 4). Peer 3 (initial) has occurred an unfriendly logout, thus, the message must be sent to * Peer 4. * * @throws InvalidProcessStateException * @throws NoPeerConnectionException * @throws IllegalArgumentException * @throws NoSessionException * @throws ProcessExecutionException */ @Test public void testNotifyUnfriendlyLogoutInitial() throws ClassNotFoundException, IOException, InterruptedException, InvalidProcessStateException, IllegalArgumentException, NoPeerConnectionException, NoSessionException, ProcessExecutionException { // kick out peer 3 (B) blockMessageRecption(3); NetworkManager notifier = network.get(0); // send notification to user A and B Set<String> users = new HashSet<String>(2); users.add(userACredentials.getUserId()); users.add(userBCredentials.getUserId()); CountingNotificationMessageFactory msgFactory = new CountingNotificationMessageFactory(notifier); IProcessComponent<Void> process = ProcessFactory.instance().createNotificationProcess(msgFactory, users, notifier); TestProcessComponentListener listener = new TestProcessComponentListener(); process.attachListener(listener); process.execute(); // wait until all messages are sent TestExecutionUtil.waitTillSucceded(listener, 20); H2HWaiter waiter = new H2HWaiter(10); do { waiter.tickASecond(); // wait until all messages are here except 1 } while (msgFactory.getArrivedMessageCount() != 3); } /** * Scenario: User A (peer 0) contacts his own clients (peer 1 and 2) and also user B * (peer 3 or 4). All peers of user B have done an unfriendly logout. * * @throws InvalidProcessStateException * @throws NoPeerConnectionException * @throws IllegalArgumentException * @throws NoSessionException * @throws ProcessExecutionException */ @Test public void testNotifyUnfriendlyLogoutAllPeers() throws ClassNotFoundException, IOException, InterruptedException, InvalidProcessStateException, IllegalArgumentException, NoPeerConnectionException, NoSessionException, ProcessExecutionException { // kick out peer 3 and 4 (B) blockMessageRecption(3, 4); NetworkManager notifier = network.get(0); // send notification to own peers Set<String> users = new HashSet<String>(2); users.add(userACredentials.getUserId()); users.add(userBCredentials.getUserId()); CountingNotificationMessageFactory msgFactory = new CountingNotificationMessageFactory(notifier); IProcessComponent<Void> process = ProcessFactory.instance().createNotificationProcess(msgFactory, users, notifier); TestProcessComponentListener listener = new TestProcessComponentListener(); process.attachListener(listener); process.execute(); // wait until all messages are sent TestExecutionUtil.waitTillSucceded(listener, 20); H2HWaiter waiter = new H2HWaiter(10); do { waiter.tickASecond(); // wait until all messages are here except 1 } while (msgFactory.getArrivedMessageCount() != 2); } /** * Scenario: User A (peer 0) contacts his own clients (peer 1 and 2), but peer 1 has done an unfriendly * leave. The locations map should be cleaned up * * @throws InvalidProcessStateException * @throws NoPeerConnectionException * @throws IllegalArgumentException * @throws NoSessionException * @throws GetFailedException * @throws ProcessExecutionException */ @Test public void testNotifyUnfriendlyLogoutOwnPeer() throws ClassNotFoundException, IOException, InterruptedException, InvalidProcessStateException, IllegalArgumentException, NoPeerConnectionException, NoSessionException, GetFailedException, ProcessExecutionException { // kick out Peer 1 blockMessageRecption(1); NetworkManager notifier = network.get(0); // send notification to own peers Set<String> users = new HashSet<String>(1); users.add(userACredentials.getUserId()); CountingNotificationMessageFactory msgFactory = new CountingNotificationMessageFactory(notifier); IProcessComponent<Void> process = ProcessFactory.instance().createNotificationProcess(msgFactory, users, notifier); TestProcessComponentListener listener = new TestProcessComponentListener(); process.attachListener(listener); process.execute(); // wait until all messages are sent TestExecutionUtil.waitTillSucceded(listener, 20); // check the locations map; should have 2 entries only Locations locations = notifier.getSession().getLocationsManager().get(); Assert.assertEquals(2, locations.getPeerAddresses().size()); } @After public void restoreMessageHandlers() throws NoPeerConnectionException { super.afterMethod(); // restore message handler from backup for a clean start for (int i = 0; i < network.size(); i++) { network.get(i).getConnection().getPeer().peer().rawDataReply(messageHandlers.get(i)); } } @AfterClass public static void endTest() { for (NetworkManager manager : network) { try { UseCaseTestUtil.logout(manager); } catch (NoPeerConnectionException | NoSessionException e) { // ignore } } NetworkTestUtil.shutdownNetwork(network); afterClass(); } }
mit
Sicmatr1x/SimpleEmployeeSystem
src/demo/beans/Job.java
1075
package demo.beans; import java.io.Serializable; /** * id, empid, jobType, jobLevel, baseSalary, department * * @author sicmatr1x * */ @SuppressWarnings("serial") public class Job implements Serializable { private int id; private int empid; private String jobType; private int jobLevel; private int baseSalary; private String department; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getEmpid() { return empid; } public void setEmpid(int empid) { this.empid = empid; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } public int getJobLevel() { return jobLevel; } public void setJobLevel(int jobLevel) { this.jobLevel = jobLevel; } public int getBaseSalary() { return baseSalary; } public void setBaseSalary(int baseSalary) { this.baseSalary = baseSalary; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } }
mit
sajithpnair/Spring
P04JMS02/src/main/java/com.spike.java.jms/App.java
401
package com.spike.java.jms; import javax.jms.JMSException; /** * Created by Sajith on 3/19/2015. */ public class App { public static void main(String[] args) { SimpleMessageProducer simpleMessageProducer = new SimpleMessageProducer(); try { simpleMessageProducer.sendMessages(); } catch (JMSException e) { e.printStackTrace(); } } }
mit
evature/android
EvaSDK/evasdk/src/main/java/com/evature/evasdk/evaapis/crossplatform/flow/ReplyElement.java
1575
package com.evature.evasdk.evaapis.crossplatform.flow; import com.evature.evasdk.evaapis.crossplatform.EvaLocation; import com.evature.evasdk.util.DLog; import java.io.Serializable; import java.util.List; import org.json.JSONException; import org.json.JSONObject; public class ReplyElement extends FlowElement implements Serializable { private static final String TAG = "ReplyElement"; public String attributeType; public Object attributeValue; public enum ReplyAttribute { Unknown, CallSupport, ReservationID, Cancellation, Baggage, MultiSegment }; public ReplyAttribute attributeKey; public ReplyElement(JSONObject jFlowElement, List<String> parseErrors, EvaLocation[] locations, JSONObject jApiReply) { super(jFlowElement, parseErrors, locations); try { String jAttributeKey = jFlowElement.getString("AttributeKey"); attributeType = jFlowElement.getString("AttributeType"); if (jApiReply.has(attributeType)) { attributeValue = jApiReply.getJSONObject(attributeType).opt(jAttributeKey); } try { attributeKey = ReplyAttribute.valueOf(jAttributeKey.replace(" ","").replace("-","")); } catch(IllegalArgumentException e) { DLog.w(TAG, "Unexpected ReplyAttribute in Flow element", e); attributeKey = ReplyAttribute.Unknown; } } catch(JSONException e) { parseErrors.add("Exception during parsing Reply element: "+e.getMessage()); } } }
mit
WaiPhyoMg/Android
mywork1/ListView/gen/com/example/listview/R.java
1341
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.example.listview; public final class R { public static final class attr { } public static final class drawable { public static final int ic_action_search=0x7f020000; public static final int ic_launcher=0x7f020001; } public static final class id { public static final int RelativeLayout1=0x7f050001; public static final int hello=0x7f050000; public static final int listView1=0x7f050002; public static final int menu_settings=0x7f050003; } public static final class layout { public static final int activity_main=0x7f030000; public static final int contextmenu=0x7f030001; } public static final class menu { public static final int activity_main=0x7f070000; } public static final class string { public static final int app_name=0x7f040000; public static final int hello_world=0x7f040001; public static final int menu_settings=0x7f040002; public static final int title_activity_main=0x7f040003; } public static final class style { public static final int AppTheme=0x7f060000; } }
mit
pink-lucifer/preresearch
core-java/src/main/java/com/lufs/java/json/JodatimeCodec.java
17547
package com.lufs.java.json; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONLexer; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.deserializer.ContextObjectDeserializer; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.alibaba.fastjson.serializer.*; import org.joda.time.*; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import java.io.IOException; import java.lang.reflect.Type; import java.util.Locale; import static com.alibaba.fastjson.parser.JSONToken.LITERAL_ISO8601_DATE; public class JodatimeCodec {//extends ContextObjectDeserializer implements ObjectSerializer, ContextObjectSerializer, ObjectDeserializer { public static final JodatimeCodec instance = new JodatimeCodec(); private final static String defaultPatttern = "yyyy-MM-dd HH:mm:ss"; private final static DateTimeFormatter defaultFormatter = DateTimeFormat.forPattern(defaultPatttern); private final static DateTimeFormatter formatter_dt19_tw = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_cn = DateTimeFormat.forPattern("yyyy年M月d日 HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_cn_1 = DateTimeFormat.forPattern("yyyy年M月d日 H时m分s秒"); private final static DateTimeFormatter formatter_dt19_kr = DateTimeFormat.forPattern("yyyy년M월d일 HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_us = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_eur = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_de = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss"); private final static DateTimeFormatter formatter_dt19_in = DateTimeFormat.forPattern("dd-MM-yyyy HH:mm:ss"); private final static DateTimeFormatter formatter_d8 = DateTimeFormat.forPattern("yyyyMMdd"); private final static DateTimeFormatter formatter_d10_tw = DateTimeFormat.forPattern("yyyy/MM/dd"); private final static DateTimeFormatter formatter_d10_cn = DateTimeFormat.forPattern("yyyy年M月d日"); private final static DateTimeFormatter formatter_d10_kr = DateTimeFormat.forPattern("yyyy년M월d일"); private final static DateTimeFormatter formatter_d10_us = DateTimeFormat.forPattern("MM/dd/yyyy"); private final static DateTimeFormatter formatter_d10_eur = DateTimeFormat.forPattern("dd/MM/yyyy"); private final static DateTimeFormatter formatter_d10_de = DateTimeFormat.forPattern("dd.MM.yyyy"); private final static DateTimeFormatter formatter_d10_in = DateTimeFormat.forPattern("dd-MM-yyyy"); private final static DateTimeFormatter ISO_FIXED_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.getDefault()); private final static String formatter_iso8601_pattern = "yyyy-MM-dd'T'HH:mm:ss"; private final static DateTimeFormatter formatter_iso8601 = DateTimeFormat.forPattern(formatter_iso8601_pattern); /* @SuppressWarnings("unchecked") public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName, String format, int feature) { JSONLexer lexer = parser.lexer; if (lexer.token() == JSONToken.NULL) { lexer.nextToken(); return null; } if (lexer.token() == JSONToken.LITERAL_STRING) { String text = lexer.stringVal(); lexer.nextToken(); DateTimeFormatter formatter = null; if (format != null) { if (defaultPatttern.equals(format)) { formatter = defaultFormatter; } else { formatter = DateTimeFormat.forPattern(format); } } if ("".equals(text)) { return null; } if (type == LocalDateTime.class) { LocalDateTime localDateTime; if (text.length() == 10 || text.length() == 8) { LocalDate localDate = parseLocalDate(text, format, formatter); localDateTime = new LocalDateTime(localDate, LocalTime.MIDNIGHT); } else { localDateTime = parseDateTime(text, formatter); } return (T) localDateTime; } else if (type == LocalDate.class) { LocalDate localDate; if (text.length() == 23) { LocalDateTime localDateTime = LocalDateTime.parse(text); localDate = new LocalDate(localDateTime.getYear(), localDateTime.getMonthOfYear(), localDateTime.getDayOfMonth()); } else { localDate = parseLocalDate(text, format, formatter); } return (T) localDate; } else if (type == LocalTime.class) { LocalTime localDate; if (text.length() == 23) { LocalDateTime localDateTime = LocalDateTime.parse(text); localDate = new LocalTime(localDateTime.getHourOfDay(), localDateTime.getMinuteOfHour(), localDateTime.getSecondOfMinute(), localDateTime.getMillisOfSecond()); } else { localDate = LocalTime.parse(text); } return (T) localDate; } else if (type == Zoned.class) { if (formatter == defaultFormatter) { formatter = ISO_FIXED_FORMAT; } ZonedDateTime zonedDateTime = parseZonedDateTime(text, formatter); return (T) zonedDateTime; } else if (type == OffsetDateTime.class) { OffsetDateTime offsetDateTime = OffsetDateTime.parse(text); return (T) offsetDateTime; } else if (type == OffsetTime.class) { OffsetTime offsetTime = OffsetTime.parse(text); return (T) offsetTime; } else if (type == DateTimeZone.class) { DateTimeZone offsetTime = DateTimeZone.forID(text); return (T) offsetTime; } else if (type == Period.class) { Period period = Period.parse(text); return (T) period; } else if (type == Duration.class) { Duration duration = Duration.parse(text); return (T) duration; } else if (type == Instant.class) { Instant instant = Instant.parse(text); return (T) instant; } } else { throw new UnsupportedOperationException(); } return null; } protected LocalDateTime parseDateTime(String text, DateTimeFormatter formatter) { if (formatter == null) { if (text.length() == 19) { char c4 = text.charAt(4); char c7 = text.charAt(7); char c10 = text.charAt(10); char c13 = text.charAt(13); char c16 = text.charAt(16); if (c13 == ':' && c16 == ':') { if (c4 == '-' && c7 == '-') { if (c10 == 'T') { formatter = ISODateTimeFormat.basicDateTime(); } else if (c10 == ' ') { formatter = defaultFormatter; } } else if (c4 == '-' && c7 == '-') { formatter = defaultFormatter; } else if (c4 == '/' && c7 == '/') { // tw yyyy/mm/dd formatter = formatter_dt19_tw; } else { char c0 = text.charAt(0); char c1 = text.charAt(1); char c2 = text.charAt(2); char c3 = text.charAt(3); char c5 = text.charAt(5); if (c2 == '/' && c5 == '/') { // mm/dd/yyyy or mm/dd/yyyy int v0 = (c0 - '0') * 10 + (c1 - '0'); int v1 = (c3 - '0') * 10 + (c4 - '0'); if (v0 > 12) { formatter = formatter_dt19_eur; } else if (v1 > 12) { formatter = formatter_dt19_us; } else { String country = Locale.getDefault().getCountry(); if (country.equals("US")) { formatter = formatter_dt19_us; } else if (country.equals("BR") // || country.equals("AU")) { formatter = formatter_dt19_eur; } } } else if (c2 == '.' && c5 == '.') { // dd.mm.yyyy formatter = formatter_dt19_de; } else if (c2 == '-' && c5 == '-') { // dd-mm-yyyy formatter = formatter_dt19_in; } } } } if (text.length() >= 17) { char c4 = text.charAt(4); if (c4 == '年') { if (text.charAt(text.length() - 1) == '秒') { formatter = formatter_dt19_cn_1; } else { formatter = formatter_dt19_cn; } } else if (c4 == '년') { formatter = formatter_dt19_kr; } } } return formatter == null ? // LocalDateTime.parse(text) // : LocalDateTime.parse(text, formatter); } protected LocalDate parseLocalDate(String text, String format, DateTimeFormatter formatter) { if (formatter == null) { if (text.length() == 8) { formatter = formatter_d8; } if (text.length() == 10) { char c4 = text.charAt(4); char c7 = text.charAt(7); if (c4 == '/' && c7 == '/') { // tw yyyy/mm/dd formatter = formatter_d10_tw; } char c0 = text.charAt(0); char c1 = text.charAt(1); char c2 = text.charAt(2); char c3 = text.charAt(3); char c5 = text.charAt(5); if (c2 == '/' && c5 == '/') { // mm/dd/yyyy or mm/dd/yyyy int v0 = (c0 - '0') * 10 + (c1 - '0'); int v1 = (c3 - '0') * 10 + (c4 - '0'); if (v0 > 12) { formatter = formatter_d10_eur; } else if (v1 > 12) { formatter = formatter_d10_us; } else { String country = Locale.getDefault().getCountry(); if (country.equals("US")) { formatter = formatter_d10_us; } else if (country.equals("BR") // || country.equals("AU")) { formatter = formatter_d10_eur; } } } else if (c2 == '.' && c5 == '.') { // dd.mm.yyyy formatter = formatter_d10_de; } else if (c2 == '-' && c5 == '-') { // dd-mm-yyyy formatter = formatter_d10_in; } } if (text.length() >= 9) { char c4 = text.charAt(4); if (c4 == '年') { formatter = formatter_d10_cn; } else if (c4 == '년') { formatter = formatter_d10_kr; } } } return formatter == null ? // LocalDate.parse(text) // : LocalDate.parse(text, formatter); } protected ZonedDateTime parseZonedDateTime(String text, DateTimeFormatter formatter) { if (formatter == null) { if (text.length() == 19) { char c4 = text.charAt(4); char c7 = text.charAt(7); char c10 = text.charAt(10); char c13 = text.charAt(13); char c16 = text.charAt(16); if (c13 == ':' && c16 == ':') { if (c4 == '-' && c7 == '-') { if (c10 == 'T') { formatter = ISODateTimeFormat.basicDateTime(); } else if (c10 == ' ') { formatter = defaultFormatter; } } else if (c4 == '-' && c7 == '-') { formatter = defaultFormatter; } else if (c4 == '/' && c7 == '/') { // tw yyyy/mm/dd formatter = formatter_dt19_tw; } else { char c0 = text.charAt(0); char c1 = text.charAt(1); char c2 = text.charAt(2); char c3 = text.charAt(3); char c5 = text.charAt(5); if (c2 == '/' && c5 == '/') { // mm/dd/yyyy or mm/dd/yyyy int v0 = (c0 - '0') * 10 + (c1 - '0'); int v1 = (c3 - '0') * 10 + (c4 - '0'); if (v0 > 12) { formatter = formatter_dt19_eur; } else if (v1 > 12) { formatter = formatter_dt19_us; } else { String country = Locale.getDefault().getCountry(); if (country.equals("US")) { formatter = formatter_dt19_us; } else if (country.equals("BR") // || country.equals("AU")) { formatter = formatter_dt19_eur; } } } else if (c2 == '.' && c5 == '.') { // dd.mm.yyyy formatter = formatter_dt19_de; } else if (c2 == '-' && c5 == '-') { // dd-mm-yyyy formatter = formatter_dt19_in; } } } } if (text.length() >= 17) { char c4 = text.charAt(4); if (c4 == '年') { if (text.charAt(text.length() - 1) == '秒') { formatter = formatter_dt19_cn_1; } else { formatter = formatter_dt19_cn; } } else if (c4 == '년') { formatter = formatter_dt19_kr; } } } return formatter == null ? // ZonedDateTime.parse(text) // : ZonedDateTime.parse(text, formatter); } public int getFastMatchToken() { return JSONToken.LITERAL_STRING; } public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { SerializeWriter out = serializer.out; if (object == null) { out.writeNull(); } else { if (fieldType == null) { fieldType = object.getClass(); } if (fieldType == LocalDateTime.class) { final int mask = SerializerFeature.UseISO8601DateFormat.getMask(); LocalDateTime dateTime = (LocalDateTime) object; String format = serializer.getDateFormatPattern(); if (format == null && (features & mask) != 0 || serializer.isEnabled(SerializerFeature.UseISO8601DateFormat)) { format = formatter_iso8601_pattern; } if (dateTime.getMillisOfSecond() == 0 || format != null) { if (format == null) { format = JSON.DEFFAULT_DATE_FORMAT; } write(out, dateTime, format); } else { out.writeString(object.toString()); } } else { out.writeString(object.toString()); } } } public void write(JSONSerializer serializer, Object object, BeanContext context) throws IOException { SerializeWriter out = serializer.out; String format = context.getFormat(); write(out, (ReadablePartial) object, format); } private void write(SerializeWriter out, ReadablePartial object, String format) { DateTimeFormatter formatter; if (format == formatter_iso8601_pattern) { formatter = formatter_iso8601; } else { formatter = DateTimeFormat.forPattern(format); } String text = formatter.print((ReadableInstant) object); out.writeString(text); }*/ }
mit
walokra/fotorest
fotorest-wicket/src/main/java/com/ruleoftech/lab/components/LinkPropertyColumn.java
2762
package com.ruleoftech.lab.components; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.FilterForm; import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.FilteredPropertyColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.TextFilter; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; import org.apache.wicket.model.PropertyModel; @SuppressWarnings("serial") public abstract class LinkPropertyColumn<T> extends FilteredPropertyColumn<T, String> { public LinkPropertyColumn(IModel<String> displayModel, IModel<T> labelModel) { super(displayModel, null); } public LinkPropertyColumn(final IModel<String> displayModel, final String sortProperty, final String propertyExpression) { super(displayModel, propertyExpression, sortProperty); } public LinkPropertyColumn(IModel<String> displayModel, String propertyExpressions) { super(displayModel, propertyExpressions); } @Override public void populateItem(Item<ICellPopulator<T>> cellItem, String componentId, IModel<T> rowModel) { cellItem.add(new LinkPanel(cellItem, componentId, rowModel)); } /** * Override this method to react to link clicks. Your own/internal row id * will most likely be inside the model. */ public abstract void onClick(Item<ICellPopulator<T>> cellItem, String componentId, IModel<T> model, AjaxRequestTarget target); public class LinkPanel extends Panel { public LinkPanel(final Item<ICellPopulator<T>> cellItem, final String componentId, final IModel<T> model) { super(componentId); AjaxLink<T> link = new AjaxLink<T>("link") { @Override public void onClick(AjaxRequestTarget target) { LinkPropertyColumn.this.onClick(cellItem, componentId, model, target); } }; link.add(new Label("label", getDataModel(model))); add(link); } } /* * (non-Javadoc) * * @see org.apache.wicket.extensions.markup.html.repeater.data.table.filter. * IFilteredColumn#getFilter(java.lang.String, * org.apache.wicket.extensions.markup * .html.repeater.data.table.filter.FilterForm) */ @Override public Component getFilter(String componentId, FilterForm<?> form) { return new TextFilter<T>(componentId, getFilterModel(form), form); } protected IModel<T> getFilterModel(final FilterForm<?> form) { return new PropertyModel<T>(form.getDefaultModel(), getPropertyExpression()); } }
mit
zoho/projects-java-wrappers
source/com/zoho/projects/api/BugsAPI.java
4262
/* $Id$ */ package com.zoho.projects.api; import java.util.HashMap; import java.util.List; import com.zoho.projects.model.Bug; import com.zoho.projects.model.Customfield; import com.zoho.projects.model.Defaultfield; import com.zoho.projects.parser.BugParser; import com.zoho.projects.util.ZohoHTTPClient; /** * BugsAPI is used to: * * Get list of bugs. * * Get the details of a bug. * * Creates a bug. * * Update the details of a bug. * * Delete an existing bug. * * @author ramesh-2099 * */ public class BugsAPI extends API { /** * Construct a BugsAPI using user's authToken and portalId. * * @param authToken user's authToken. * * @param portalId user's portalId. */ public BugsAPI(String authToken, String portalId) { super(authToken, portalId); } //BugsParser is used to parse the JSON response into respective objects. BugParser bugParser = new BugParser(); /** * Get list of bugs for the project. * * @param projectId ID of the project. * * @param queryMap This queryMap contains the filters in the form of key-value pair. * * @return Returns list of Bug object. * * @throws Exception */ public List<Bug> getBugs(String projectId, HashMap<String, Object> queryMap)throws Exception { String url = getBaseURL()+"/projects/"+projectId+"/bugs/"; //No I18N String response = ZohoHTTPClient.get(url, getQueryMap(queryMap)); return bugParser.getBugs(response); } /** * Get the details of a bug. * * @param projectId ID of the project. * * @param bugId ID of the bug. * * @return Returns the Bug object. * * @throws Exception */ public Bug get(String projectId, String bugId)throws Exception { String url = getBaseURL()+"/projects/"+projectId+"/bugs/"+bugId+"/"; //No I18N String response = ZohoHTTPClient.get(url, getQueryMap()); return bugParser.getBug(response); } /** * Create a Bug for the project. * * @param projectId ID of the project. * * @param bug Bug object. * * @return Returns the Bug object. * * @throws Exception */ public Bug create(String projectId, Bug bug)throws Exception { String url = getBaseURL()+"/projects/"+projectId+"/bugs/"; //No I18N String response = ZohoHTTPClient.post(url, getQueryMap(bug.toParamMAP())); return bugParser.getBug(response); } /** * Update the details of a bug. * * @param projectId ID of the project. * * @param bug Bug object. * * @return Returns the Bug object. * * @throws Exception */ public Bug update(String projectId, Bug bug)throws Exception { String url = getBaseURL()+"/projects/"+projectId+"/bugs/"+bug.getId()+"/"; //No I18N String response = ZohoHTTPClient.post(url, getQueryMap(bug.toParamMAP())); return bugParser.getBug(response); } /** * Delete an existing bug for the project. * * @param projectId ID of the project. * * @param bugId ID of the bug. * * @return Returns the String object. * * @throws Exception */ public String delete(String projectId, String bugId)throws Exception { String url = getBaseURL()+"/projects/"+projectId+"/bugs/"+bugId+"/"; //No I18N String response = ZohoHTTPClient.delete(url, getQueryMap()); return bugParser.getResult(response); } /** * Get all the default fields in the given project. * * @param projectId ID of the project. * * @return Returns the Defaultfield Object. * * @throws Exception */ public Defaultfield getDefaultFields(String projectId)throws Exception { String url = getBaseURL()+"/projects/"+projectId+"/bugs/defaultfields/"; //No I18N String response = ZohoHTTPClient.get(url, getQueryMap()); return bugParser.getDefaultfields(response); } /** * Get all the custom fields in the given project. * * @param projectId ID of the project. * * @return Returns List of CustomField Object. * * @throws Exception */ public List<Customfield> getCustomFields(String projectId)throws Exception { String url = getBaseURL()+"/projects/"+projectId+"/bugs/customfields/"; //No I18N String response = ZohoHTTPClient.get(url, getQueryMap()); return bugParser.getCustomfields(response); } }
mit
JoshuaKissoon/SuperDosna
src/dosna/simulations/performance/Simulation.java
6945
package dosna.simulations.performance; import dosna.core.DOSNAStatistician; import java.text.DecimalFormat; import java.util.concurrent.CountDownLatch; import socialkademlia.SocialKadStatistician; /** * The class that launches the simulation and aggregates the statistics after the completion of the simulation. * * @author Joshua Kissoon * @since 20140505 */ public class Simulation { private final SimConfig config; private final SimulatedUser[] users; /* A count down latch to wait for all threads to execute */ private CountDownLatch threadsWaiter; public Simulation() { this.config = new SimConfig(); this.users = new SimulatedUser[config.numUsers()]; } /** * Start the simulation */ public void start() { /* INITIALIZE SIMULATED USERS & CONNECT THEM TO THE NETWORK */ this.initializeUsers(); System.out.println("Nodes & User Initialization Finished."); /* INITIALIZE THE USER'S CONTENT */ this.createInitialUserContent(); System.out.println("Initial content creation finished."); /* INITIALIZE THE USER'S CONNECTIONS */ this.createInitialUsersConnections(); System.out.println("Initial connections creation finished."); /* Pause a little before real time operations */ try { Thread.sleep(30000); } catch (InterruptedException ex) { } System.out.println("Starting the real time operations now. \n"); /* NOW LETS RUN THE PROCESSES */ this.startSimulation(); /* USER'S DATA USAGE */ this.computeAggregatedStatistics(); } /** * Initialize simulation users and connect them to the network */ private void initializeUsers() { threadsWaiter = new CountDownLatch(this.config.numUsers()); for (int i = 0; i < config.numUsers(); i++) { String actorId = config.randomStringShort() + i; this.users[i] = new SimulatedUser(actorId, actorId + "pass", "Actor " + i + " Name", i, this.users); new Thread(new SimulatedUserInitialization(this.users[i], config, threadsWaiter)).start(); try { Thread.sleep(config.userCreationDelay()); } catch (InterruptedException ex) { } } /* Wait for all threads to finish */ try { threadsWaiter.await(); } catch (InterruptedException ex) { } } /** * Create initial content for users */ private void createInitialUserContent() { threadsWaiter = new CountDownLatch(this.config.numUsers()); for (int i = 0; i < config.numUsers(); i++) { /* Start a new thread for this user */ new Thread(new SimulatedUserCreateInitialContent(this.users[i], config, threadsWaiter)).start(); } /* Wait for threads to finish */ try { threadsWaiter.await(); } catch (InterruptedException ex) { } } /** * Create the initial connections for the users. */ private void createInitialUsersConnections() { threadsWaiter = new CountDownLatch(this.config.numUsers()); for (int i = 0; i < config.numUsers(); i++) { new Thread(new SimulatedUserCreateInitialConnections(this.users[i], config, threadsWaiter)).start(); } /* Wait for threads to finish */ try { threadsWaiter.await(); } catch (InterruptedException ex) { } } /** * Do the real time simulation operations. */ private void startSimulation() { threadsWaiter = new CountDownLatch(this.config.numUsers()); for (int i = 0; i < config.numUsers(); i++) { new Thread(new SimulatedUserActions(this.users[i], config, threadsWaiter)).start(); } /* Wait for threads to finish */ try { threadsWaiter.await(); } catch (InterruptedException ex) { } } /** * Computed the aggregate statistics for user's data usage. * * @todo Get a class to manage this aggregation */ private void computeAggregatedStatistics() { double dataSent = 0, dataReceived = 0, bootstrapTime = 0, avgContentLookupTime = 0; double avgContentLookupRouteLth = 0, avgActivityStreamLoadTime = 0; int numContentLookups = 0; int numContentLookpusFUC = 0; int numFUCUpdatesFound = 0; /* Aggregate the total user's data */ for (int i = 0; i < config.numUsers(); i++) { SimulatedUser simUser = this.users[i]; SocialKadStatistician statsMan = simUser.getKademliaNode().getStatistician(); DOSNAStatistician dosnaStatsMan = simUser.getStatistician(); dataSent += statsMan.getTotalDataSent(); dataReceived += statsMan.getTotalDataReceived(); bootstrapTime += statsMan.getBootstrapTime(); numContentLookups += statsMan.numContentLookups(); numContentLookpusFUC += statsMan.numContentLookupsFUC(); numFUCUpdatesFound += statsMan.numFUCUpdatesFound(); avgContentLookupTime += statsMan.averageContentLookupTime(); avgContentLookupRouteLth += statsMan.averageContentLookupRouteLength(); avgActivityStreamLoadTime += dosnaStatsMan.avgActivityStreamLoadTime(); } /* Print the Statistics */ DecimalFormat df = new DecimalFormat("#.00"); int numUsers = this.config.numUsers(); String stats = "\nAverage Statistics for " + numUsers + " users; \n"; stats += "Avg Data Sent: " + df.format(dataSent / numUsers) + " KBs; \n"; stats += "Avg Data Received: " + df.format(dataReceived / numUsers) + " KBs; \n"; stats += "Avg Bootstrap Time: " + df.format(bootstrapTime / numUsers) + " ms; \n"; stats += "Avg # Content Lookups: " + (numContentLookups / (double) numUsers) + "; \n"; stats += "Avg # Content Lookups FUC: " + (numContentLookpusFUC / (double) numUsers) + "; \n"; stats += "Avg # FUC Updates Found: " + (numFUCUpdatesFound / (double) numUsers) + "; \n"; stats += "Avg Content Lookup Time: " + df.format(avgContentLookupTime / numUsers) + " ms; \n"; stats += "Avg Content Lookup Route Length: " + df.format(avgContentLookupRouteLth / numUsers) + "; \n"; stats += "Avg Activity Stream load time: " + df.format(avgActivityStreamLoadTime / numUsers) + " ms; \n"; stats += "\n"; System.out.println(stats); } public static void main(String[] args) { Simulation sim = new Simulation(); sim.start(); } }
mit