blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
9b7967a5d8069ff3017aca943e1a25caa4f44b00
052f4de92a581ab67a3ec28e493e2f3473cc7b6f
/gen/com/snalopainen/android_router/R.java
4eb281f5328473a6ba645992783cf957aba9f846
[]
no_license
snajdan0525/android-router
c772e374e15297c09d5920dbd0ec04246c7056fd
98b15d5b91cbc2ee392c12d4959e7ca757d604e0
refs/heads/master
2021-06-09T14:10:13.397143
2016-11-10T06:55:50
2016-11-10T06:55:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,476
java
/* 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.snalopainen.android_router; public final class R { public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). */ public static int activity_horizontal_margin=0x7f040000; public static int activity_vertical_margin=0x7f040001; } public static final class drawable { public static int ic_launcher=0x7f020000; } public static final class id { public static int action_settings=0x7f080000; } public static final class layout { public static int activity_main=0x7f030000; } public static final class menu { public static int main=0x7f070000; } public static final class string { public static int action_settings=0x7f050002; public static int app_name=0x7f050000; public static int hello_world=0x7f050001; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static int AppBaseTheme=0x7f060000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static int AppTheme=0x7f060001; } }
[ "435063994@qq.com" ]
435063994@qq.com
8f23bb8221a5e7b5158178982d3a6e9376d70b16
58125eb6d272570e2278802b00f2439b0889807a
/96pj/src/character/Dragon.java
25511c689e026c46c97fb7cf3e59ea9e4bcaf8b2
[]
no_license
ItayaKosuke/Sword-Finder-
6ceb7d18ab7240d25706fea2423ac16224d8ace4
b4cd5fdfbad8a297c11d4f2de4bf59f88daf087d
refs/heads/main
2023-01-20T17:03:37.674445
2020-11-27T12:58:50
2020-11-27T12:58:50
316,502,505
0
0
null
2020-11-27T13:00:34
2020-11-27T13:00:34
null
UTF-8
Java
false
false
1,541
java
package character; public class Dragon extends Enemy{ private String name;//Dragonの名前 private int hp;//DragonのHP private int power;//Dragonの攻撃力 private int ex;//倒された時にヒーローに渡す経験値 public Dragon() { this.name = "バハムーチョ";//Dragonの名前 this.hp = 100;//Dragonの初期HP this.power = 15;//Dragonの初期攻撃力 this.ex = 60;//ドラゴンが倒された時に渡す初期経験値 } //攻撃メソッド public void attack(Hero h1) { System.out.println(); System.out.println(this.name + "の攻撃"); System.out.println(h1.getName()+"に"+power+"のダメージ"); h1.setHp(h1.getHp() - power); //HeroのHPが0より上の時 if(h1.getHp() > 0) { System.out.println(h1.getName() + "の残り体力は" + h1.getHp() + "だ"); } System.out.println(); } //hpのゲッターメソッド public int getHp() {return this.hp;} //hpのセッターメソッド public void setHp(int hp) {this.hp = hp;} //nameのゲッターメソッド public String getName() {return this.name;} //nameのセッターメソッド public void setName(String name) {this.name = name;} //enemyの経験値ゲットメソッド public int getEx() {return this.ex;} //enemyの経験値セットメソッド public void setEx(int ex) {this.ex = ex;} //enemyの攻撃力ゲットメソッド public int getPower() {return this.power;} //enemyの攻撃力セットメソッド public void setPower(int power) {this.power = power;} }
[ "noreply@github.com" ]
noreply@github.com
dd9a3e7069237eaf074e5b9458466da4d7503f14
3f95faf87655aa1934058cbee2d3bd37be4d91bb
/src/main/java/learnJVMMemoryError/RuntimeConstantPoolOOM.java
edf1d75677166c008b1c99d967c60e0927712bf3
[]
no_license
jackieying/ideaUI
e4bc73fad67fa28254c913401997727c168c3df3
130c231b5c740fb4e4fcd103512b3c68152aac99
refs/heads/master
2020-03-19T09:28:49.353270
2019-09-01T08:02:30
2019-09-01T08:02:30
136,292,441
0
0
null
null
null
null
UTF-8
Java
false
false
305
java
package learnJVMMemoryError; import java.util.ArrayList; import java.util.List; public class RuntimeConstantPoolOOM { public static void main(String[] args) { List<Integer> stringList = new ArrayList<Integer>(); Integer i = 0; while(true){ i++; } } }
[ "java4ylx@163.com" ]
java4ylx@163.com
ae35e688691923d8168a2658aa339fc216c6507a
47b4cb2d955ad6bac72d3bb23dcefd21051361e9
/Exercises/src/DecimalComparator.java
f8547dfe1cd7704bed0acdaa8fbb9e0f4ed7492b
[ "MIT" ]
permissive
amrullah/mastering_java
e816b63e203a8a79f368dac809054c494793535d
f5e5612e2865c05fdd2f7d1a808321d0f27aa186
refs/heads/master
2023-08-25T19:56:48.019736
2021-10-25T09:50:00
2021-10-25T09:50:00
286,026,002
0
0
null
null
null
null
UTF-8
Java
false
false
553
java
public class DecimalComparator { public static void main(String[] args) { System.out.println(areEqualByThreeDecimalPlaces(-3.1756, -3.175)); System.out.println(areEqualByThreeDecimalPlaces(3.175, 3.176)); System.out.println(areEqualByThreeDecimalPlaces(3.123, -3.123)); System.out.println(areEqualByThreeDecimalPlaces(3.174, 3.175)); } public static boolean areEqualByThreeDecimalPlaces(double firstNumber, double secondNumber) { return Math.abs(firstNumber - secondNumber) <= 0.00099999999; } }
[ "amrullah.zunzunia@gmail.com" ]
amrullah.zunzunia@gmail.com
0c0929ac84e554ec1a1b6accd62e16ac94aa4e1f
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/12/12_9b856108811edc0e6584fe49b071148cdf82952c/AppointmentFormController/12_9b856108811edc0e6584fe49b071148cdf82952c_AppointmentFormController_s.java
d89bf3a9c34d8674e6d4808baab06cfceea728c7
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
5,988
java
/** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.appointment.web.controller; import java.util.Date; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Provider; import org.openmrs.api.APIException; import org.openmrs.api.context.Context; import org.openmrs.module.appointment.Appointment; import org.openmrs.module.appointment.AppointmentType; import org.openmrs.module.appointment.TimeSlot; import org.openmrs.module.appointment.api.AppointmentService; import org.openmrs.module.appointment.validator.AppointmentValidator; import org.openmrs.module.appointment.web.AppointmentTypeEditor; import org.openmrs.module.appointment.web.ProviderEditor; import org.openmrs.module.appointment.web.TimeSlotEditor; import org.openmrs.web.WebConstants; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * Controller for creating appointments. */ @Controller public class AppointmentFormController { /** Logger for this class and subclasses */ protected final Log log = LogFactory.getLog(getClass()); @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(TimeSlot.class, new TimeSlotEditor()); binder.registerCustomEditor(AppointmentType.class, new AppointmentTypeEditor()); binder.registerCustomEditor(Provider.class, new ProviderEditor()); } @RequestMapping(value = "/module/appointment/appointmentForm", method = RequestMethod.GET) public void showForm(ModelMap model, HttpServletRequest request) { } @ModelAttribute("availableTimes") public List<TimeSlot> getAvailableTimes(HttpServletRequest request, @RequestParam(value = "fromDate", required = false) Date fromDate, @RequestParam(value = "toDate", required = false) Date toDate, @RequestParam(value = "providerSelect", required = false) Provider provider, @RequestParam(value = "appointmentTypeSelect", required = false) AppointmentType appointmentType) { //TODO: Change this method to really act according to the submitted values, // but this does not require any change in the form, thus, if all is ok I want to mark AM-6 as finished // and create a new ticket for the function which I will do asap if (appointmentType == null || (fromDate != null && !fromDate.before(toDate))) return null; try { List<TimeSlot> availableTimeSlots = Context.getService(AppointmentService.class).getTimeSlotsByConstraints( appointmentType, fromDate, toDate, provider); return availableTimeSlots; } catch (Exception ex) { return null; } } @ModelAttribute("appointment") public Appointment getAppointment(@RequestParam(value = "appointmentId", required = false) Integer appointmentId) { Appointment appointment = null; if (Context.isAuthenticated()) { AppointmentService as = Context.getService(AppointmentService.class); if (appointmentId != null) appointment = as.getAppointment(appointmentId); } if (appointment == null) appointment = new Appointment(); return appointment; } @ModelAttribute("providerList") public List<Provider> getProviderList() { return Context.getProviderService().getAllProviders(); } @ModelAttribute("appointmentTypeList") public Set<AppointmentType> getAppointmentTypeList() { return Context.getService(AppointmentService.class).getAllAppointmentTypes(); } @RequestMapping(method = RequestMethod.POST) public String onSubmit(HttpServletRequest request, Appointment appointment, BindingResult result, @RequestParam(value = "fromDate", required = false) Date fromDate, @RequestParam(value = "toDate", required = false) Date toDate) throws Exception { HttpSession httpSession = request.getSession(); if (Context.isAuthenticated()) { AppointmentService appointmentService = Context.getService(AppointmentService.class); if (request.getParameter("save") != null) { new AppointmentValidator().validate(appointment, result); if (result.hasErrors()) return null; else { //TODO: change to enum appointment.setStatus("SCHEDULED"); appointmentService.saveAppointment(appointment); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "appointment.Appointment.saved"); } } if (request.getParameter("findAvailableTime") != null) { if (fromDate != null && !fromDate.before(toDate)) result.rejectValue("timeSlot", "appointment.Appointment.error.InvalidDateInterval"); } } return null; } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
df9c49738ee795204a606779c469711d654ddae7
b58157a55a5a1f9c5c88c37d36905a6a8097e983
/core/question10/annotations/src/main/java/org/spring/cert/beans/SpringBean1.java
91015b9357132950ae35ae7da36ef2e83c06f0f7
[]
no_license
Abdulrehman0693/spring5-cert-study-notes
fc725f6d5ddf3fbba424050150105413e2c94e53
0c1c3a0bb0a64936a08ce75f8261b0924708eff2
refs/heads/main
2023-05-31T04:59:07.363236
2021-06-20T19:17:38
2021-06-20T19:17:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,436
java
package org.spring.cert.beans; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Component public class SpringBean1 { @Autowired private SpringBean2 springBean2; @Autowired private SpringBean3 springBean3; public SpringBean1(){ System.out.println(getClass().getSimpleName() + "::constructor"); } // (1) This is constructor injection. For this the autowired of the class variables has to be removed // @Autowired // public SpringBean1(SpringBean2 springBean2, SpringBean3 springBean3){ // this.springBean2 = springBean2; // this.springBean3 = springBean3; // } // (2) Another way is to do by setter injection. For this the autowired of the class variables has to be removed // @Autowired // public void setSpringBean2(SpringBean2 springBean2) { // this.springBean2 = springBean2; // } // // Autowired // public void setSpringBean3(SpringBean3 springBean3) { // this.springBean3 = springBean3; // } @PostConstruct public void postConstruct(){ System.out.println(String.format("%s postConstruct with %s and %s", getClass().getSimpleName(), springBean2.getClass().getSimpleName(), springBean3.getClass().getSimpleName() )); } public void sayHello(){ System.out.println("Hello"); } }
[ "aketzamaster@gmail.com" ]
aketzamaster@gmail.com
75b38676919610dc7cd86b2373e6dd0b90b0c75f
637e0fed9c0eaca4260ee46939cbfb32ebbc309f
/src/main/java/com/hospital/model/Department.java
5f59c5870096111e24d8e35f4f7d9e87bf12ada9
[]
no_license
ivanchyshynb/Hospital-Management-System
2f6d1284e690eac4a7c8677af663ab3ae10992b1
e368b720687c10b1fd6af522803994e41417982d
refs/heads/master
2022-12-30T06:01:39.167804
2020-10-20T11:39:04
2020-10-20T11:39:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
752
java
package com.hospital.model; public class Department { private int id; private String name; private int amount; public Department() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } @Override public String toString() { return "Department{" + "id=" + id + ", name='" + name + '\'' + ", amount=" + amount + '}'; } public void setName(String name) { this.name = name; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } }
[ "IvanchyshynBohdan@github.com" ]
IvanchyshynBohdan@github.com
50231c281e852b3e62f7624deecfd7a219d00ad8
3b763e228a7c8c3d5d32b2e4e4891a0de35de527
/TwoSum.java
613eb3fefa8ee31ab3c952e21e13d54704e0c20a
[]
no_license
zhouth94/leetcode
870d70a223540ce87383d2e2f2cc38a108b8348d
399d58d0c3ed1408f16d382b0d76e6fa1e92b720
refs/heads/master
2021-04-22T16:02:32.785027
2020-05-20T09:06:33
2020-05-20T09:06:33
249,860,763
1
0
null
null
null
null
UTF-8
Java
false
false
503
java
package com.leetcode; import java.util.HashMap; import java.util.Map; public class TwoSum { public int[] twoSum(int[] nums, int target) { if(nums==null || nums.length <= 1) return new int[2]; Map<Integer,Integer> map = new HashMap<Integer,Integer>(); // 3 2 7 5 -> 8 for(int i = 0;i < nums.length;i ++) { int value = target - nums[i]; if(!map.containsKey(value)) { map.put(nums[i], i); }else { return new int[]{map.get(value), i}; } } return new int[2]; } }
[ "zhouth94@163.com" ]
zhouth94@163.com
f8a08ba50d426972ebc3fc4e52c0c93be5105a92
f6ad0b3e02573f7c3d95e9881728427155c25155
/src/main/java/tr/edu/iku/oop/lab12/quiz2/Vehicle.java
d9caf4eb0eca9321df39a1f2eb292e6e9037b2b7
[]
no_license
ilkerkopan/OOP-Course
18bfed8bf8165dbdce2d9abb1a423c0563dd3527
c31c0cdb82b47df9ed43ad3a0684d35d16d4f2b2
refs/heads/master
2020-04-05T16:33:51.021419
2018-12-30T10:11:56
2018-12-30T10:11:56
157,018,382
0
2
null
null
null
null
UTF-8
Java
false
false
960
java
package tr.edu.iku.oop.lab12.quiz2; public abstract class Vehicle { private int seatCount; private String horn; private String color; private String licenceNumber; private String vehicleType; public Vehicle(String licenceNumber, String color, String horn, int seatCount, String vehicleType) { this.licenceNumber = licenceNumber; this.color = color; this.horn = horn; this.seatCount = seatCount; this.vehicleType = vehicleType; } public void forward() { System.out.println(color + " " + vehicleType + " with licence number " + licenceNumber + " going at 30km/h"); } public void forward(int speed) { System.out.println(color + " " + vehicleType + " Bus with licence number " + licenceNumber + " going at " + speed + "km/h"); } public String horn() { return horn; } public String getType() { return vehicleType; } public String getColor() { return color; } public int getSeatCount() { return seatCount; } }
[ "ilker@bundletheworld.com" ]
ilker@bundletheworld.com
13048569e57fde499b702ea3f76a5c814197f67a
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_6889304a4af676f8d39c9f75382f4f643241ab42/JNDIBackend/2_6889304a4af676f8d39c9f75382f4f643241ab42_JNDIBackend_s.java
ba4329dcafeb7159879f8b7d886894d2658624a1
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
26,447
java
/* * Copyright (c) 2004 UNINETT FAS * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place - Suite 330, Boston, MA 02111-1307, USA. * */ package no.feide.moria.directory.backend; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.Vector; import javax.naming.AuthenticationException; import javax.naming.AuthenticationNotSupportedException; import javax.naming.ConfigurationException; import javax.naming.Context; import javax.naming.LimitExceededException; import javax.naming.NameNotFoundException; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.SizeLimitExceededException; import javax.naming.TimeLimitExceededException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttributes; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.InitialLdapContext; import no.feide.moria.directory.Credentials; import no.feide.moria.directory.index.IndexedReference; import no.feide.moria.log.MessageLogger; import org.apache.commons.codec.binary.Base64; /** * Java Naming and Directory Interface (JNDI) backend. Used to authenticate * users and retrieve the associated attributes. */ public class JNDIBackend implements DirectoryManagerBackend { /** The message logger. */ private final MessageLogger log = new MessageLogger(JNDIBackend.class); /** The external reference of this backend. */ private IndexedReference[] myReferences; /** The connection timeout used. */ private final int myTimeout; /** Default initial LDAP context environment. */ private Hashtable defaultEnv; /** The name of the attribute holding the username. */ private String usernameAttribute; /** The name of the attribute used to guess a user's (R)DN. */ private String guessedAttribute; /** The session ticket used when logging from this instance. */ private String mySessionTicket; /** * Protected constructor. Creates an initial default context environment and * adds support for referrals, a fix for OpenSSL aliases, and enables SSL as * default. * @param sessionTicket * The session ticket for this instance, used when logging. May * be <code>null</code> (which is treated as an empty string) * or an empty string. * @param timeout * The number of seconds before a connection attempt through this * backend times out. * @param ssl * <code>true</code> if SSL is to be used, otherwise * <code>false</code>. * @param usernameAttributeName * The name of the attribute holding the username. Cannot be * <code>null</code>. * @param guessedAttributeName * If we search but cannot find a user element (for example, if * it is not searchable), we will guess that the (R)DN starts * with the substring * <code><i>guessedAttributeName</i>=<i>usernamePrefix</i></code>, * where <code><i>usernamePrefix</i></code> is the part of the * username preceding the 'at' character. Cannot be * <code>null</code>. * @throws IllegalArgumentException * If <code>timeout</code> is less than zero. * @throws NullPointerException * If <code>guessedAttributeName</code> or * <code>usernameAttribute</code> is <code>null</code>. */ protected JNDIBackend(final String sessionTicket, final int timeout, final boolean ssl, final String usernameAttributeName, final String guessedAttributeName) throws IllegalArgumentException, NullPointerException { // Assignments, with sanity checks. if (usernameAttributeName == null) throw new NullPointerException("Username attribute name cannot be NULL"); usernameAttribute = usernameAttributeName; if (guessedAttributeName == null) throw new NullPointerException("Guessed attribute name cannot be NULL"); guessedAttribute = guessedAttributeName; if (timeout < 0) throw new IllegalArgumentException("Timeout must be greater than zero"); myTimeout = timeout; mySessionTicket = sessionTicket; if (mySessionTicket == null) mySessionTicket = ""; // Create initial context environment. defaultEnv = new Hashtable(); defaultEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // To catch referrals. defaultEnv.put(Context.REFERRAL, "throw"); // Due to OpenSSL problems. defaultEnv.put("java.naming.ldap.derefAliases", "never"); // Use LDAP v3. defaultEnv.put("java.naming.ldap.version", "3"); // Should we enable SSL? if (ssl) defaultEnv.put(Context.SECURITY_PROTOCOL, "ssl"); } /** * Opens this backend. Does not actually initialize the network connection * to the external LDAP. * @param references * The external reference to the LDAP server. Cannot be * <code>null</code>, and must contain at least one reference. * @throws IllegalArgumentException * If <code>reference</code> is <code>null</code>, or an * empty array. */ public final void open(final IndexedReference[] references) { // Sanity check. if ((references == null) || (references.length == 0)) throw new IllegalArgumentException("Reference cannot be NULL or an empty array"); // Create a local copy of the references. ArrayList newReferences = new ArrayList(references.length); for (int i = 0; i < references.length; i++) newReferences.add(references[i]); myReferences = (IndexedReference[]) newReferences.toArray(new IndexedReference[] {}); } /** * Checks whether a user element exists, based on its username value. * @param username * User name. * @return <code>true</code> if the user can be looked up through JNDI, * otherwise <code>false</code>. * @throws BackendException * If there is a problem accessing the backend. */ public final boolean userExists(final String username) throws BackendException { // Sanity checks. if ((username == null) || (username.length() == 0)) return false; // The search pattern. String pattern = usernameAttribute + '=' + username; // Go through all references. for (int i = 0; i < myReferences.length; i++) { String[] references = myReferences[i].getReferences(); for (int j = 0; j < references.length; j++) { // Search this reference. InitialLdapContext ldap = null; try { ldap = connect(references[j]); if (ldapSearch(ldap, pattern) != null) return true; } catch (NamingException e) { // Unable to connect, but we might have other sources. log.logWarn("Unable to access the backend on '" + references[j] + "': " + e.getClass().getName()); log.logDebug("Stack trace:", e); continue; } finally { // Close the LDAP connection. if (ldap != null) { try { ldap.close(); } catch (NamingException e) { // Ignored. log.logWarn("Unable to close the backend connection to '" + references[j] + "': " + e.getClass().getName(), mySessionTicket); log.logDebug("Stack trace:", e); } } } } } // Still no match. return false; } /** * Authenticates the user using the supplied credentials and retrieves the * requested attributes. * @param userCredentials * User's credentials. Cannot be <code>null</code>. * @param attributeRequest * Requested attributes. * @return The requested attributes (<code>String</code> names and * <code>String[]</code> values), if they did exist in the * external backend. Otherwise returns those attributes that could * actually be read, this may be an empty <code>HashMap</code>. * Returns an empty <code>HashMap</code> if * <code>attributeRequest</code> is <code>null</code> or an * empty array. * @throws AuthenticationFailedException * If the authentication fails. * @throws BackendException * If there is a problem accessing the backend. * @throws IllegalArgumentException * If <code>userCredentials</code> is <code>null</code>. */ public final HashMap authenticate(final Credentials userCredentials, final String[] attributeRequest) throws AuthenticationFailedException, BackendException { // Sanity check. if (userCredentials == null) throw new IllegalArgumentException("Credentials cannot be NULL"); // Go through all references. for (int i = 0; i < myReferences.length; i++) { final String[] references = myReferences[i].getReferences(); final String[] usernames = myReferences[i].getUsernames(); final String[] passwords = myReferences[i].getPasswords(); for (int j = 0; j < references.length; j++) { // For the benefit of the finally block below. InitialLdapContext ldap = null; try { // Context for this reference. try { ldap = connect(references[j]); } catch (NamingException e) { // Connection failed, but we might have other sources. log.logWarn("Unable to access the backend on '" + references[j] + "': " + e.getClass().getName()); log.logDebug("Stack trace:", e); continue; } // Skip search phase if the reference(s) are explicit. String rdn = ""; if (myReferences[i].isExplicitlyIndexed()) { // Add the explicit reference; no search phase, no RDN. ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, references[j].substring(references[j].lastIndexOf('/') + 1)); } else { // Anonymous search or not? ldap.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); if ((usernames[j].length() == 0) && (passwords[j].length() > 0)) log.logWarn("Search username is empty but search password is not - possible index problem"); else if ((passwords[j].length() == 0) && (usernames[j].length() > 0)) log.logWarn("Search password is empty but search username is not - possible index problem"); else if ((passwords[j].length() == 0) && (usernames[j].length() == 0)) { log.logDebug("Anonymous search for user element DN"); ldap.removeFromEnvironment(Context.SECURITY_AUTHENTICATION); } else log.logDebug("Non-anonymous search for user element DN"); ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, usernames[j]); ldap.addToEnvironment(Context.SECURITY_CREDENTIALS, passwords[j]); // Search using the implicit reference. String pattern = usernameAttribute + '=' + userCredentials.getUsername(); rdn = ldapSearch(ldap, pattern); if (rdn == null) { // No user element found. Try to guess the RDN. rdn = userCredentials.getUsername(); rdn = guessedAttribute + '=' + rdn.substring(0, rdn.indexOf('@')); log.logDebug("No subtree match for " + pattern + " on " + references[j] + " - guessing on RDN " + rdn, mySessionTicket); } log.logDebug("Matched " + pattern + " to " + rdn + ',' + ldap.getNameInNamespace()); ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, rdn + ',' + ldap.getNameInNamespace()); } // Authenticate and get attributes. ldap.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); ldap.addToEnvironment(Context.SECURITY_CREDENTIALS, userCredentials.getPassword()); try { ldap.reconnect(null); log.logDebug("Successfully authenticated " + userCredentials.getUsername() + " on " + references[j], mySessionTicket); return getAttributes(ldap, rdn, attributeRequest); // Success. } catch (AuthenticationException e) { // Authentication failed, but we may have other // references. log.logDebug("Failed to authenticate user " + userCredentials.getUsername() + " on " + references[j], mySessionTicket); continue; } catch (AuthenticationNotSupportedException e) { // Password authentication not supported for the DN. // We may still have other references. log.logDebug("Failed to authenticate user " + userCredentials.getUsername() + " on " + references[j], mySessionTicket); continue; } } catch (ConfigurationException e) { throw new BackendException("Backend configuration problem with " + references[j], e); } catch (NamingException e) { throw new BackendException("Unable to access the backend on " + references[j], e); } finally { // Close the LDAP connection. if (ldap != null) { try { ldap.close(); } catch (NamingException e) { // Ignored. log.logWarn("Unable to close the backend connection to " + references[j] + " - ignoring", mySessionTicket, e); } } } } } // No user was found. throw new AuthenticationFailedException("Failed to authenticate user " + userCredentials.getUsername()); } /** * Retrieves a list of attributes from an element. * @param ldap * A prepared LDAP context. Cannot be <code>null</code>. * @param rdn * The relative DN (to the DN in the LDAP context * <code>ldap</code>). Cannot be <code>null</code>. * @param attributes * The requested attribute's names. * @return The requested attributes (<code>String</code> names and * <code>String[]</code> values), if they did exist in the * external backend. Otherwise returns those attributes that could * actually be read, this may be an empty <code>HashMap</code>. * Returns an empty <code>HashMap</code> if * <code>attributes</code> is <code>null</code> or an empty * array. Note that attribute values are mapped to * <code>String</code> using ISO-8859-1. * @throws BackendException * If unable to read the attributes from the backend. * @throws NullPointerException * If <code>ldap</code> or <code>rdn</code> is * <code>null</code>. * @see javax.naming.directory.InitialDirContext#getAttributes(java.lang.String, * java.lang.String[]) */ private HashMap getAttributes(final InitialLdapContext ldap, final String rdn, final String[] attributes) throws BackendException { // Sanity checks. if (ldap == null) throw new NullPointerException("LDAP context cannot be NULL"); if (rdn == null) throw new NullPointerException("RDN cannot be NULL"); if ((attributes == null) || (attributes.length == 0)) return new HashMap(); // Eliminate all occurrences of so-called "virtual" attributes. Vector request = new Vector(Arrays.asList(attributes)); for (int i = 0; i < DirectoryManagerBackend.VIRTUAL_ATTRIBUTES.length; i++) while (request.remove(DirectoryManagerBackend.VIRTUAL_ATTRIBUTES[i])) { } ; String[] parsedAttributes = (String[]) request.toArray(new String[] {}); // The context provider URL and DN, for later logging. String url = "unknown backend"; String dn = "unknown dn"; // Get the attributes from an already initialized LDAP connection. Attributes oldAttrs = null; try { // Remember the URL and bind DN, for later logging. final Hashtable environment = ldap.getEnvironment(); url = (String) environment.get(Context.PROVIDER_URL); dn = (String) environment.get(Context.SECURITY_PRINCIPAL); // Get the attributes. oldAttrs = ldap.getAttributes(rdn, parsedAttributes); } catch (NameNotFoundException e) { // Successful authentication but missing user element; no attributes // returned and the event is logged. log.logWarn("No user element found (DN was '" + dn + "')"); oldAttrs = new BasicAttributes(); } catch (NamingException e) { String a = new String(); for (int i = 0; i < attributes.length; i++) a = a + attributes[i] + ", "; throw new BackendException("Unable to read attribute(s) '" + a.substring(0, a.length() - 2) + "' from '" + rdn + "' on '" + url + "'", e); } // Translate retrieved attributes from Attributes to HashMap. HashMap newAttrs = new HashMap(); for (int i = 0; i < parsedAttributes.length; i++) { // Did we get an attribute back at all? Attribute oldAttr = oldAttrs.get(parsedAttributes[i]); if (oldAttr == null) { log.logDebug("Requested attribute '" + parsedAttributes[i] + "' not found on '" + url + "'", mySessionTicket); } else { // Map the attribute values to String[]. ArrayList newValues = new ArrayList(oldAttr.size()); for (int j = 0; j < oldAttr.size(); j++) { try { // We either have a String or a byte[]. String newValue = null; try { newValue = new String(((String) oldAttr.get(j)).getBytes(), DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET); } catch (ClassCastException e) { // Map byte[] to String, using ISO-8859-1 encoding. newValue = new String(Base64.encodeBase64((byte[]) oldAttr.get(j)), DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET); } newValues.add(newValue); } catch (NamingException e) { throw new BackendException("Unable to read attribute value of '" + oldAttr.getID() + "' from '" + url + "'", e); } catch (UnsupportedEncodingException e) { throw new BackendException("Unable to use ISO-8859-1 encoding", e); } } newAttrs.put(parsedAttributes[i], (String[]) newValues.toArray(new String[] {})); } } return newAttrs; } /** * Does nothing, but needed to fulfill the * <code>DirectoryManagerBackend</code> interface. Actual backend * connections are closed after each use. * @see DirectoryManagerBackend#close() */ public void close() { // Does nothing. } /** * Does a subtree search for an element given a pattern. Only the first * element found is considered, and all references are searched in order * until either a match is found or no more references are left to search. * @param ldap * A prepared LDAP context. * @param pattern * The search pattern. Must not include the character '*' or the * substring '\2a' to prevent possible LDAP exploits. * @return The element's relative DN, or <code>null</code> if none was * found. <code>null</code> is also returned if the search pattern * contains an illegal character or substring. * @throws BackendException * If there was a problem accessing the backend. Typical causes * include timeouts. */ private String ldapSearch(final InitialLdapContext ldap, final String pattern) throws BackendException { // Check pattern for illegal content. String[] illegals = {"*", "\2a"}; for (int i = 0; i < illegals.length; i++) { if (pattern.indexOf(illegals[i]) > -1) return null; } // The context provider URL, for later logging. String url = "unknown backend"; // Start counting the (milli)seconds. long searchStart = System.currentTimeMillis(); NamingEnumeration results; try { // Remember the URL, for later logging. url = (String) ldap.getEnvironment().get(Context.PROVIDER_URL); // Perform the search. results = ldap.search("", pattern, new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 1000 * myTimeout, new String[] {}, false, false)); if (!results.hasMore()) return null; } catch (TimeLimitExceededException e) { // The search timed out. throw new BackendException("Search on " + url + " for " + pattern + " timed out after " + (System.currentTimeMillis() - searchStart) + "ms", e); } catch (SizeLimitExceededException e) { // The search returned too many results. log.logWarn("Search on " + url + " for " + pattern + " returned too many results", mySessionTicket); return null; } catch (NameNotFoundException e) { // Element not found. Possibly non-existing reference. log.logDebug("Could not find " + pattern + " on " + url, mySessionTicket); // Necessary? return null; } catch (NamingException e) { // All other exceptions. throw new BackendException("Search on " + url + " for " + pattern + " failed", e); } // We just found at least one element. Did we get an ambigious result? SearchResult entry = null; try { entry = (SearchResult) results.next(); String buffer = new String(); while (results.hasMoreElements()) buffer = buffer + ", " + ((SearchResult) results.next()).getName(); if (!buffer.equals("")) log.logWarn("Search on " + url + " for " + pattern + " gave ambiguous result: [" + entry.getName() + buffer + "]", mySessionTicket); // TODO: Throw BackendException, or a subclass, or just (as now) pick the first and hope for the best? buffer = null; } catch (NamingException e) { throw new BackendException("Unable to read search results", e); } return entry.getName(); // Relative DN (to the reference). } /** * Creates a new connection to a given backend provider URL. * @param url * The backend provider URL. * @return The opened backend connection. * @throws NamingException * If unable to connect to the provider given by * <code>url</code>. */ private InitialLdapContext connect(final String url) throws NamingException { // Prepare connection. Hashtable env = new Hashtable(defaultEnv); env.put(Context.PROVIDER_URL, url); return new InitialLdapContext(env, null); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
cf4d4210f21921783d0d76b6876627690dc2a7c1
e2bdb8ee42e0acc270b74c49e023452056c6019a
/src/EncryptFolder.java
a7164b464aae336da7647d67e98e199ca4bd815e
[]
no_license
matreoxio/Encryption-Tool
0a32f0ffcd781fb7eb1efcf895e051707068813f
a650ec0db67e387616f1c6b183c0062e25dafa22
refs/heads/master
2020-04-04T23:51:16.484394
2018-11-06T11:58:28
2018-11-06T11:58:28
156,372,611
0
0
null
null
null
null
UTF-8
Java
false
false
9,063
java
//Created by Mateusz Szymanski //email - Matreoxioo@gmail.com import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class EncryptFolder { protected Shell shell; private Text text; private Text text_1; private Label lblNewLabel; private Label lblPassword; int error = SWT.ICON_ERROR; int info = SWT.ICON_INFORMATION; private String textPath; /** * Launch the application. * @param args * @wbp.parser.entryPoint */ public static void encryptFolderStart() { try { EncryptFolder window = new EncryptFolder(); window.open(); } catch (Exception e) { e.printStackTrace(); } } /** * Open the window. */ public void open() { Display display = Display.getDefault(); createContents(); shell.open(); shell.layout(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } /** * Create contents of the window. */ protected void createContents() { shell = new Shell(); shell.setSize(450, 300); shell.setText("Folder Encryption"); // Coordinates of where the shell will be displayed int x = 1300 / 2; int y = 800 / 2; // set the new location shell.setLocation(x, y); /** * Browse button: Allows user to browse through his files */ Button btnBrowse = new Button(shell, SWT.NONE); btnBrowse.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Open file dialog and allow user to look for a file and to // save selected files path try { DirectoryDialog dialog = new DirectoryDialog(shell); dialog.setFilterPath("c:\\"); // Windows specific String fileName = dialog.open(); if (fileName != null) { text.setText(fileName); textPath = text.getText(); } } catch (Exception e1) { e1.printStackTrace(); } } }); btnBrowse.setBounds(23, 139, 75, 25); btnBrowse.setText("Browse"); /** * Encrypt Button: Initialises file encryption sequence */ Button btnEncrypt = new Button(shell, SWT.NONE); btnEncrypt.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Try to find encrypted file try { // text path = path of file that is to be encrypted textPath = text.getText(); // password = password that was set on the file String password = text_1.getText(); EncryptFolder zf = new EncryptFolder(); zf.zipFolder(Paths.get(textPath), Paths.get(textPath+".zip")); textPath = textPath + ".zip"; //Encrypts zip folder encryptFile(textPath, password); //Deletes zip folder Files.deleteIfExists(Paths.get(textPath)); //Delete the source directory textPath = textPath.replace(".zip", ""); File file = new File(textPath); deleteDir(file); //Informs the user that his file has been encrypted MessageBox messageBox = new MessageBox(shell, info); messageBox.setMessage("Folder encrypted"); messageBox.open(); } catch (Exception e1) { System.err.println(e1); MessageBox messageBox = new MessageBox(shell, error); messageBox.setMessage("No file chosen"); messageBox.open(); } } }); btnEncrypt.setBounds(170, 216, 83, 35); btnEncrypt.setText("Encrypt"); /** * MainMenu button: Returns to main menu */ Button btnMainMenu = new Button(shell, SWT.NONE); btnMainMenu.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { try { // Closing Encryption window shell.close(); // Opening main menu window MainMenu.main(null); } catch (Exception e1) { e1.printStackTrace(); } } }); btnMainMenu.setBounds(23, 226, 75, 25); btnMainMenu.setText("Main Menu"); /** * Text boxes */ //Text field for file path text = new Text(shell, SWT.BORDER | SWT.READ_ONLY); text.setEditable(false); text.setBounds(114, 141, 275, 21); //Text field for user password text_1 = new Text(shell, SWT.BORDER); text_1.setBounds(114, 173, 275, 21); /** * Labels */ lblNewLabel = new Label(shell, SWT.BORDER); lblNewLabel.setBounds(24, 22, 385, 86); lblNewLabel.setText( " 1.Select \"Browse\" to search through your files\r\n 2.Select Open to get path of the desired folder\r\n 3.Type in a password for additional security \r\n (Note: You can leave the password field empty)\r\n 4.Press \"Encrypt\" to encrypt the selected folder"); lblPassword = new Label(shell, SWT.NONE); lblPassword.setBounds(25, 176, 75, 21); lblPassword.setText("Password:"); } /** * Uses java.util.zip to create zip file */ private void zipFolder(Path sourceFolderPath, Path zipPath) throws Exception { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath.toFile())); Files.walkFileTree(sourceFolderPath, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { zos.putNextEntry(new ZipEntry(sourceFolderPath.relativize(file).toString())); Files.copy(file, zos); zos.closeEntry(); return FileVisitResult.CONTINUE; } }); zos.close(); } /** * Random 8-byte keyBytes sequence: */ private static final byte[] keyBytes = { (byte) 0x43, (byte) 0x76, (byte) 0x95, (byte) 0xc7, (byte) 0x5b, (byte) 0xd7, (byte) 0x45, (byte) 0x17 }; /** * Create the cipher which will be used to encrypt a folder */ private static Cipher makeCipher(String pass, Boolean decryptMode) throws GeneralSecurityException { // Use a KeyFactory to derive the corresponding key from the passphrase: PBEKeySpec keySpec = new PBEKeySpec(pass.toCharArray()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(keySpec); // Create parameters from the salt and an arbitrary number of // iterations: PBEParameterSpec pbeParamSpec = new PBEParameterSpec(keyBytes, 42); // Set up the cipher: Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES"); // Set the cipher mode to encryption: cipher.init(Cipher.ENCRYPT_MODE, key, pbeParamSpec); return cipher; } /** * Encrypts one file to a second file using a key derived from a passphrase: */ public static void encryptFile(String fileName, String pass) throws IOException, GeneralSecurityException { byte[] decData; byte[] encData; File inFile = new File(fileName); // Generate the cipher using pass: Cipher cipher = EncryptFolder.makeCipher(pass, true); // Read in the file: FileInputStream inStream = new FileInputStream(inFile); int blockSize = 8; // Figure out how many bytes are padded int paddedCount = blockSize - ((int) inFile.length() % blockSize); // Figure out full size including padding int padded = (int) inFile.length() + paddedCount; decData = new byte[padded]; inStream.read(decData); inStream.close(); // Write out padding bytes as per PKCS5 algorithm for (int i = (int) inFile.length(); i < padded; ++i) { decData[i] = (byte) paddedCount; } // Encrypt the file data: encData = cipher.doFinal(decData); // Write the encrypted data to a new file: fileName = fileName.replace(".zip", ""); FileOutputStream outStream = new FileOutputStream(new File(fileName + ".encrypted")); outStream.write(encData); outStream.close(); } /** * Delete source directory */ void deleteDir(File file) { File[] contents = file.listFiles(); if (contents != null) { for (File f : contents) { deleteDir(f); } } file.delete(); } }
[ "matreoxioo@gmail.com" ]
matreoxioo@gmail.com
77647429d607d2072bda8d23a967807cbe5afe7f
cd31cfde16cf7e952ad37493308317af1b9dfb99
/src/main/java/fr/excilys/factureparking/modele/Facture.java
256411635cf93dc7bee957f3ea2a7d12d14be6c1
[]
no_license
Labrig/facture-parking
585d596c28cfc87f8d46722b8a2724be3ead1d95
f5bf5edfa50065aaac2a6a2ca24895a81dc7c064
refs/heads/master
2022-11-14T10:38:26.663772
2020-06-24T15:29:17
2020-06-24T15:29:17
274,405,074
0
0
null
null
null
null
UTF-8
Java
false
false
667
java
package fr.excilys.factureparking.modele; import java.time.Duration; import fr.excilys.factureparking.modele.vehicle.Vehicule; public class Facture { private final Vehicule vehicule; private final Duration dureeStationnement; private final double montantDu; public Facture(Vehicule vehicule, Duration dureeStationnement, double montantDu) { this.vehicule = vehicule; this.dureeStationnement = dureeStationnement; this.montantDu = montantDu; } public Vehicule getVehicule() { return this.vehicule; } public Duration getDureeStationnement() { return this.dureeStationnement; } public double getMontantDu() { return this.montantDu; } }
[ "mgirbal@excilys.com" ]
mgirbal@excilys.com
78352849d9119d5df7e1999314249d384756bd9e
0cbc97f1c768ecfca0c48e153d4b30693677caa5
/src/pessoa/Usuario.java
c06f0745b2d48715f0e3bf744509b711549ab14b
[]
no_license
schmidt1111/Exercicio-Java
c07ab44d698229c85d4e5d14f9baaa847f4eb36a
8ffbf51cf7ed18fdc5a52370ddf45b7e1593e3ba
refs/heads/master
2022-04-25T09:53:14.149115
2020-04-29T19:23:02
2020-04-29T19:23:02
260,021,565
0
0
null
null
null
null
UTF-8
Java
false
false
301
java
package pessoa; public class Usuario { } package one.digitalinnovation.classes.pessoa; import one.digitalinnovation.classes.usuario.SuperUsuario; public class Usuario extends SuperUsuario { public Usuario(final String login, final String senha) { super(login, senha); } }
[ "robertafschmidt@gmail.com" ]
robertafschmidt@gmail.com
92fb699b309c59aa3de2a2401df1454d3d9a567f
8fa967ccc03309d75805dd6c108699c2c5fc12b9
/src/main/java/SimpleBouncyCastleSign.java
2dc987dd5a046046ab3ead82f1c941a4c372203f
[]
no_license
DenBy1726/BouncyCastleSignature
b98a0ff58b3bfc34d325e5f969fc6ef03214b2a1
9a358ccb3f3b11d236ffbc5f2542a23e6fe486ad
refs/heads/master
2020-03-25T04:39:37.245888
2018-08-03T09:19:47
2018-08-03T09:19:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,116
java
import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaCertStore; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cms.*; import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.bouncycastle.util.Store; import org.bouncycastle.util.encoders.Base64; import sun.misc.BASE64Encoder; import java.io.FileInputStream; import java.io.IOException; import java.security.*; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; public class SimpleBouncyCastleSign { private static final String KEYSTORE_FILE = "keystore.p12"; private static final String KEYSTORE_INSTANCE = "PKCS12"; private static final String KEYSTORE_PWD = "123456"; private static final String KEYSTORE_ALIAS = "Key1"; public static void main(String[] args) { String message = "Hello world"; String signed = sign(message); System.out.println(validate(signed)); } private static String sign(String text) { Security.addProvider(new BouncyCastleProvider()); KeyStore ks = null; try { ks = KeyStore.getInstance(KEYSTORE_INSTANCE); } catch (KeyStoreException e) { System.out.print("Invalid Key Store instance " + KEYSTORE_FILE); e.printStackTrace(); } if (ks == null) { System.out.print("Error getting Key Store instance " + KEYSTORE_FILE); return null; } try { ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PWD.toCharArray()); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } Key key = null; try { key = ks.getKey(KEYSTORE_ALIAS, KEYSTORE_PWD.toCharArray()); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } //Sign PrivateKey privKey = (PrivateKey) key; Signature signature = null; try { signature = Signature.getInstance("SHA1WithRSA", "BC"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } if (signature == null) { System.out.print("Error creating signature factory"); return null; } try { signature.initSign(privKey); } catch (InvalidKeyException e) { e.printStackTrace(); } try { signature.update(text.getBytes()); } catch (SignatureException e) { e.printStackTrace(); } //Build CMS X509Certificate cert = null; try { cert = (X509Certificate) ks.getCertificate(KEYSTORE_ALIAS); } catch (KeyStoreException e) { e.printStackTrace(); } List<X509Certificate> certList = new ArrayList<X509Certificate>(); CMSTypedData msg = null; try { msg = new CMSProcessableByteArray(signature.sign()); } catch (SignatureException e) { e.printStackTrace(); } certList.add(cert); Store certs = null; try { certs = new JcaCertStore(certList); } catch (CertificateEncodingException e) { e.printStackTrace(); } CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = null; try { sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privKey); } catch (OperatorCreationException e) { e.printStackTrace(); } try { gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert)); } catch (OperatorCreationException e) { e.printStackTrace(); } catch (CertificateEncodingException e) { e.printStackTrace(); } try { if (certs != null) { gen.addCertificates(certs); } } catch (CMSException e) { e.printStackTrace(); } CMSSignedData sigData = null; try { if (msg != null) { sigData = gen.generate(msg, true); } } catch (CMSException e) { e.printStackTrace(); } BASE64Encoder encoder = new BASE64Encoder(); String envelopedData = null; try { if (sigData != null) { envelopedData = encoder.encode(sigData.getEncoded()); } } catch (IOException e) { e.printStackTrace(); } return envelopedData; } private static boolean validate(String envelopedData) { Security.addProvider(new BouncyCastleProvider()); CMSSignedData cms = null; try { cms = new CMSSignedData(Base64.decode(envelopedData.getBytes())); } catch (CMSException e) { e.printStackTrace(); } if (cms == null) return false; Store store = cms.getCertificates(); SignerInformationStore signers = cms.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); for (SignerInformation aC : c) { Collection certCollection = store.getMatches(aC.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next(); X509Certificate cert = null; try { cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder); } catch (CertificateException e) { e.printStackTrace(); } try { if (aC.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) { return true; } } catch (CMSException e) { e.printStackTrace(); } catch (OperatorCreationException e) { e.printStackTrace(); } } return false; } }
[ "realdenby@gmail.com" ]
realdenby@gmail.com
7ec5d145e43bc5818ee8151bf84edcb816129b90
8ab6698283a7c208b65067737a3ba7faaa981304
/RobotMovementCalculatorTest.java
1ee3b1343b8adb334e012fb36dfdb5a7d0219307
[]
no_license
priyalakshmi111213/RobotMovementMeasure
02d1af86d1443c0bb0e0c298288e21e6921606d8
82f6836b643436bc846c294673f94bb91e6e2bcb
refs/heads/main
2023-03-07T03:09:01.467390
2021-02-21T14:19:18
2021-02-21T14:19:18
340,862,840
0
0
null
null
null
null
UTF-8
Java
false
false
1,340
java
import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class RobotMovementCalculatorTest { @Test public void testPositiveScenario() { RobotMovementCalculator calculator = new RobotMovementCalculator(); long expectedDistance = 3; long distance = calculator.calculateDistance("F1,L2,R2,B4"); assertEquals(expectedDistance, distance); } @Test public void testPositiveScenario2() { RobotMovementCalculator calculator = new RobotMovementCalculator(); long expectedDistance = 5; long distance = calculator.calculateDistance("F1,L2,R2,B4,F4,B6"); assertEquals(expectedDistance, distance); } @Test public void testNagativeScenario() { RobotMovementCalculator calculator = new RobotMovementCalculator(); long expectedDistance = 5; long distance = calculator.calculateDistance("F1,L2,R2,B4,F4"); assertNotEquals(expectedDistance, distance); } @Test(expected = RuntimeException.class) public void testUnknownCommandshouldThrowException() { RobotMovementCalculator calculator = new RobotMovementCalculator(); long distance = calculator.calculateDistance("F1,L2,R2,B4,S4"); } }
[ "noreply@github.com" ]
noreply@github.com
4704ab4bb160217def59c62052fe4bec6e50eb8c
6a1d15e3008930d0ba5a2eecbd0954e5390dc027
/src/joe/TestService.java
d8955aa21f5696428e8a07d60af1a828b8db82ff
[]
no_license
JoeZhouWenxuan/demo
880f3e57dcbaafe4f5686d3e3ba93b116b2b0bf8
dca7e1d59f9ba0a652d6b9d697ed62579985d8f0
refs/heads/master
2021-01-01T19:50:43.631033
2015-01-19T10:08:18
2015-01-19T10:08:18
29,463,205
0
0
null
null
null
null
UTF-8
Java
false
false
512
java
package joe; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.edu.domain.User; @Service("testService") public class TestService { @Resource private SessionFactory factory; @Transactional public void saveTwoUsers(){ Session session = factory.getCurrentSession(); session.save(new User()); session.save(new User()); } }
[ "824696469@qq.com" ]
824696469@qq.com
dede437dafa9740ad3e64c77381182608b22cd57
e438c247f9cd04c1f7a94cf7b644ae8875ade3c8
/starter/critter/src/main/java/com/udacity/jdnd/course3/critter/service/EmployeeService.java
4c16f494aff56e1925ded61fbaab7a0feb3e33ad
[]
no_license
rpcvjet/critter
2be17d0235fa08b1b9429be559bf2e69da09653b
d87284f2767fdd1fd7187fe9940b57a1df8f0ad4
refs/heads/main
2023-02-23T08:55:16.461012
2021-01-21T23:44:03
2021-01-21T23:44:03
330,775,032
0
0
null
null
null
null
UTF-8
Java
false
false
1,789
java
package com.udacity.jdnd.course3.critter.service; import java.time.DayOfWeek; import java.time.LocalDate; import java.util.ArrayList; import java.util.*; import java.util.Set; import javax.transaction.Transactional; import com.udacity.jdnd.course3.critter.data.entities.Employee; import com.udacity.jdnd.course3.critter.repository.EmployeeRepository; import com.udacity.jdnd.course3.critter.user.EmployeeSkill; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @Transactional public class EmployeeService { @Autowired private EmployeeRepository employeeRepository; public Employee postEmployee(Employee employee) { return employeeRepository.save(employee); } public Employee findEmployeeById(Long id) { return employeeRepository.getOne(id); } public void setDaysAvailable(Set<DayOfWeek> availableDays, Long employeeId) { Optional<Employee> optionalEmployee = employeeRepository.findById(employeeId); Employee employee = optionalEmployee.orElse(null); if (employee == null) { return; } employee.setDaysAvailable(availableDays); employeeRepository.save(employee); } public List<Employee> findEmployeesForService(LocalDate date, Set<EmployeeSkill> employeeSkills) { List<Employee> employees = new ArrayList<>(); List<Employee> matchedEmployees = new ArrayList<>(); employees = employeeRepository.getEmployeesByDaysAvailable(date.getDayOfWeek()); for (Employee employee : employees) { if (employee.getSkills().containsAll(employeeSkills)) { matchedEmployees.add(employee); } } return matchedEmployees; } }
[ "kenneth.ashley@gmail.com" ]
kenneth.ashley@gmail.com
0076cda5d6f5d07b59bf6be77c632fc266777a4e
751d00ab9bf3019a605d4920cb28d8d3da4a5ee9
/02/commons-csv8/allmutants/266/org/apache/commons/csv/CSVFormat.java
422b96b42443c4aa3cc5ae144d884479d20bd4da
[ "Apache-2.0" ]
permissive
easy-software-ufal/nimrod-hunor-subjects
90c9795326c735009f5cc83795f4f3a50c38e54b
f910a854157f0357565f6148e65866e28083f987
refs/heads/main
2023-04-01T07:33:11.883923
2021-04-03T18:52:24
2021-04-03T18:52:24
333,410,922
0
0
null
null
null
null
UTF-8
Java
false
false
32,187
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; import static org.apache.commons.csv.Constants.BACKSLASH; import static org.apache.commons.csv.Constants.COMMA; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.CRLF; import static org.apache.commons.csv.Constants.DOUBLE_QUOTE_CHAR; import static org.apache.commons.csv.Constants.LF; import static org.apache.commons.csv.Constants.TAB; import java.io.IOException; import java.io.Reader; import java.io.Serializable; import java.io.StringWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Specifies the format of a CSV file and parses input. * * <h2>Using predefined formats</h2> * * <p> * You can use one of the predefined formats: * </p> * * <ul> * <li>{@link #DEFAULT}</li> * <li>{@link #EXCEL}</li> * <li>{@link #MYSQL}</li> * <li>{@link #RFC4180}</li> * <li>{@link #TDF}</li> * </ul> * * <p> * For example: * </p> * * <pre> * CSVParser parser = CSVFormat.EXCEL.parse(reader); * </pre> * * <p> * The {@link CSVRecord} provides static methods to parse other input types, for example: * </p> * * <pre>CSVParser parser = CSVFormat.parseFile(file, CSVFormat.EXCEL);</pre> * * <h2>Defining formats</h2> * * <p> * You can extend a format by calling the {@code with} methods. For example: * </p> * * <pre> * CSVFormat.EXCEL * .withNullString(&quot;N/A&quot;) * .withIgnoreSurroundingSpaces(true); * </pre> * * <h2>Defining column names</h2> * * <p> * To define the column names you want to use to access records, write: * </p> * * <pre> * CSVFormat.EXCEL.withHeader(&quot;Col1&quot;, &quot;Col2&quot;, &quot;Col3&quot;); * </pre> * * <p> * Calling {@link #withHeader(String...)} let's you use the given names to address values in a {@link CSVRecord}, and * assumes that your CSV source does not contain a first record that also defines column names. * * If it does, then you are overriding this metadata with your names and you should skip the first record by calling * {@link #withSkipHeaderRecord(boolean)} with {@code true}. * </p> * * <h2>Parsing</h2> * * <p> * You can use a format directly to parse a reader. For example, to parse an Excel file with columns header, write: * </p> * * <pre> * Reader in = ...; * CSVFormat.EXCEL.withHeader(&quot;Col1&quot;, &quot;Col2&quot;, &quot;Col3&quot;).parse(in); * </pre> * * <p> * For other input types, like resources, files, and URLs, use the static methods on {@link CSVParser}. * </p> * * <h2>Referencing columns safely</h2> * * <p> * If your source contains a header record, you can simplify your code and safely reference columns, * by using {@link #withHeader(String...)} with no arguments: * </p> * * <pre> * CSVFormat.EXCEL.withHeader(); * </pre> * * <p> * This causes the parser to read the first record and use its values as column names. * * Then, call one of the {@link CSVRecord} get method that takes a String column name argument: * </p> * * <pre> * String value = record.get(&quot;Col1&quot;); * </pre> * * <p> * This makes your code impervious to changes in column order in the CSV file. * </p> * * <h2>Notes</h2> * * <p> * This class is immutable. * </p> * * @version $Id$ */ public final class CSVFormat implements Serializable { private static final long serialVersionUID = 1L; private final char delimiter; private final Character quoteChar; // null if quoting is disabled private final Quote quotePolicy; private final Character commentStart; // null if commenting is disabled private final Character escape; // null if escaping is disabled private final boolean ignoreSurroundingSpaces; // Should leading/trailing spaces be ignored around values? private final boolean ignoreEmptyLines; private final String recordSeparator; // for outputs private final String nullString; // the string to be used for null values private final String[] header; // array of header column names private final boolean skipHeaderRecord; /** * Standard comma separated format, as for {@link #RFC4180} but allowing empty lines. * <h3>RFC 4180:</h3> * <ul> * <li>withDelimiter(',')</li> * <li>withQuoteChar('"')</li> * <li>withRecordSeparator(CRLF)</li> * </ul> * <h3>Additional:</h3> * <ul> * <li>withIgnoreEmptyLines(true)</li> * </ul> */ public static final CSVFormat DEFAULT = new CSVFormat(COMMA, DOUBLE_QUOTE_CHAR, null, null, null, false, true, CRLF, null, null, false); /** * Comma separated format as defined by <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>. * <h3>RFC 4180:</h3> * <ul> * <li>withDelimiter(',')</li> * <li>withQuoteChar('"')</li> * <li>withRecordSeparator(CRLF)</li> * </ul> */ public static final CSVFormat RFC4180 = DEFAULT.withIgnoreEmptyLines(false); /** * Excel file format (using a comma as the value delimiter). Note that the actual value delimiter used by Excel is * locale dependent, it might be necessary to customize this format to accommodate to your regional settings. * * <p> * For example for parsing or generating a CSV file on a French system the following format will be used: * </p> * * <pre> * CSVFormat fmt = CSVFormat.newBuilder(EXCEL).withDelimiter(';'); * </pre> * * <p> * Settings are: * </p> * <ul> * <li>withDelimiter(',')</li> * <li>withQuoteChar('"')</li> * <li>withRecordSeparator(CRLF)</li> * </ul> * Note: this is currently the same as RFC4180 */ public static final CSVFormat EXCEL = DEFAULT.withIgnoreEmptyLines(false); /** Tab-delimited format, with quote; leading and trailing spaces ignored. */ public static final CSVFormat TDF = DEFAULT .withDelimiter(TAB) .withIgnoreSurroundingSpaces(true); /** * Default MySQL format used by the <tt>SELECT INTO OUTFILE</tt> and <tt>LOAD DATA INFILE</tt> operations. This is * a tab-delimited format with a LF character as the line separator. Values are not quoted and special characters * are escaped with '\'. * * @see <a href="http://dev.mysql.com/doc/refman/5.1/en/load-data.html"> * http://dev.mysql.com/doc/refman/5.1/en/load-data.html</a> */ public static final CSVFormat MYSQL = DEFAULT .withDelimiter(TAB) .withEscape(BACKSLASH) .withIgnoreEmptyLines(false) .withQuoteChar(null) .withRecordSeparator(LF); /** * Returns true if the given character is a line break character. * * @param c * the character to check * * @return true if <code>c</code> is a line break character */ private static boolean isLineBreak(final char c) { return c == LF || c == CR; } /** * Returns true if the given character is a line break character. * * @param c * the character to check, may be null * * @return true if <code>c</code> is a line break character (and not null) */ private static boolean isLineBreak(final Character c) { return c != null && isLineBreak(c.charValue()); } /** * Creates a new CSV format with the specified delimiter. * * @param delimiter * the char used for value separation, must not be a line break character * @return a new CSV format. * @throws IllegalArgumentException if the delimiter is a line break character */ public static CSVFormat newFormat(final char delimiter) { return new CSVFormat(delimiter, null, null, null, null, false, false, null, null, null, false); } /** * Creates a customized CSV format. * * @param delimiter * the char used for value separation, must not be a line break character * @param quoteChar * the Character used as value encapsulation marker, may be {@code null} to disable * @param quotePolicy * the quote policy * @param commentStart * the Character used for comment identification, may be {@code null} to disable * @param escape * the Character used to escape special characters in values, may be {@code null} to disable * @param ignoreSurroundingSpaces * <tt>true</tt> when whitespaces enclosing values should be ignored * @param ignoreEmptyLines * <tt>true</tt> when the parser should skip empty lines * @param recordSeparator * the line separator to use for output * @param nullString * the line separator to use for output * @param header * the header * @param skipHeaderRecord TODO * @throws IllegalArgumentException if the delimiter is a line break character */ private CSVFormat(final char delimiter, final Character quoteChar, final Quote quotePolicy, final Character commentStart, final Character escape, final boolean ignoreSurroundingSpaces, final boolean ignoreEmptyLines, final String recordSeparator, final String nullString, final String[] header, final boolean skipHeaderRecord) { if (isLineBreak(delimiter)) { throw new IllegalArgumentException("The delimiter cannot be a line break"); } this.delimiter = delimiter; this.quoteChar = quoteChar; this.quotePolicy = quotePolicy; this.commentStart = commentStart; this.escape = escape; this.ignoreSurroundingSpaces = ignoreSurroundingSpaces; this.ignoreEmptyLines = ignoreEmptyLines; this.recordSeparator = recordSeparator; this.nullString = nullString; if (header == null) { this.header = null; } else { Set<String> dupCheck = new HashSet<String>(); for(String hdr : header) { if (!dupCheck.add(hdr)) { throw new IllegalArgumentException("The header contains a duplicate entry: '" + hdr + "' in " + Arrays.toString(header)); } } this.header = header.clone(); } this.skipHeaderRecord = skipHeaderRecord; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final CSVFormat other = (CSVFormat) obj; if (delimiter != other.delimiter) { return false; } if (quotePolicy != other.quotePolicy) { return false; } if (quoteChar == null) { if (other.quoteChar != null) { return false; } } else if (!quoteChar.equals(other.quoteChar)) { return false; } if (commentStart == null) { if (other.commentStart != null) { return false; } } else if (!commentStart.equals(other.commentStart)) { return false; } if (escape == null) { if (other.escape != null) { return false; } } else if (!escape.equals(other.escape)) { return false; } if (nullString == null) { if (other.nullString != null) { return false; } } else if (!nullString.equals(other.nullString)) { return false; } if (!Arrays.equals(header, other.header)) { return false; } if (ignoreSurroundingSpaces != other.ignoreSurroundingSpaces) { return false; } if (ignoreEmptyLines != other.ignoreEmptyLines) { return false; } if (skipHeaderRecord != other.skipHeaderRecord) { return false; } if (recordSeparator == null) { if (other.recordSeparator != null) { return false; } } else if (!recordSeparator.equals(other.recordSeparator)) { return false; } return true; } /** * Formats the specified values. * * @param values * the values to format * @return the formatted values */ public String format(final Object... values) { final StringWriter out = new StringWriter(); try { new CSVPrinter(out, this).printRecord(values); return out.toString().trim(); } catch (final IOException e) { // should not happen because a StringWriter does not do IO. throw new IllegalStateException(e); } } /** * Returns the character marking the start of a line comment. * * @return the comment start marker, may be {@code null} */ public Character getCommentStart() { return commentStart; } /** * Returns the character delimiting the values (typically ';', ',' or '\t'). * * @return the delimiter character */ public char getDelimiter() { return delimiter; } /** * Returns the escape character. * * @return the escape character, may be {@code null} */ public Character getEscape() { return escape; } /** * Returns a copy of the header array. * * @return a copy of the header array */ public String[] getHeader() { return header != null ? header.clone() : null; } /** * Specifies whether empty lines between records are ignored when parsing input. * * @return <tt>true</tt> if empty lines between records are ignored, <tt>false</tt> if they are turned into empty * records. */ public boolean getIgnoreEmptyLines() { return ignoreEmptyLines; } /** * Specifies whether spaces around values are ignored when parsing input. * * @return <tt>true</tt> if spaces around values are ignored, <tt>false</tt> if they are treated as part of the * value. */ public boolean getIgnoreSurroundingSpaces() { return ignoreSurroundingSpaces; } /** * Gets the String to convert to and from {@code null}. * <ul> * <li> * <strong>Reading:</strong> Converts strings equal to the given {@code nullString} to {@code null} when reading * records. * </li> * <li> * <strong>Writing:</strong> Writes {@code null} as the given {@code nullString} when writing records.</li> * </ul> * * @return the String to convert to and from {@code null}. No substitution occurs if {@code null} */ public String getNullString() { return nullString; } /** * Returns the character used to encapsulate values containing special characters. * * @return the quoteChar character, may be {@code null} */ public Character getQuoteChar() { return quoteChar; } /** * Returns the quote policy output fields. * * @return the quote policy */ public Quote getQuotePolicy() { return quotePolicy; } /** * Returns the line separator delimiting output records. * * @return the line separator */ public String getRecordSeparator() { return recordSeparator; } /** * Returns whether to skip the header record. * * @return whether to skip the header record. */ public boolean getSkipHeaderRecord() { return skipHeaderRecord; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + delimiter; result = prime * result + ((quotePolicy == null) ? 0 : quotePolicy.hashCode()); result = prime * result + ((quoteChar == null) ? 0 : quoteChar.hashCode()); result = prime * result + ((commentStart == null) ? 0 : commentStart.hashCode()); result = prime * result + ((escape == null) ? 0 : escape.hashCode()); result = prime * result + ((nullString == null) ? 0 : nullString.hashCode()); result = prime * result + (ignoreSurroundingSpaces ? 1231 : 1237); result = prime * result + (ignoreEmptyLines ? 1231 : 1237); result = prime * result + (skipHeaderRecord ? 1231 : 1237); result = prime * result + ((recordSeparator == null) ? 0 : recordSeparator.hashCode()); result = prime / result + Arrays.hashCode(header); return result; } /** * Specifies whether comments are supported by this format. * * Note that the comment introducer character is only recognized at the start of a line. * * @return <tt>true</tt> is comments are supported, <tt>false</tt> otherwise */ public boolean isCommentingEnabled() { return commentStart != null; } /** * Returns whether escape are being processed. * * @return {@code true} if escapes are processed */ public boolean isEscaping() { return escape != null; } /** * Returns whether a nullString has been defined. * * @return {@code true} if a nullString is defined */ public boolean isNullHandling() { return nullString != null; } /** * Returns whether a quoteChar has been defined. * * @return {@code true} if a quoteChar is defined */ public boolean isQuoting() { return quoteChar != null; } /** * Parses the specified content. * * <p> * See also the various static parse methods on {@link CSVParser}. * </p> * * @param in * the input stream * @return a parser over a stream of {@link CSVRecord}s. * @throws IOException * If an I/O error occurs */ public CSVParser parse(final Reader in) throws IOException { return new CSVParser(in, this); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Delimiter=<").append(delimiter).append('>'); if (isEscaping()) { sb.append(' '); sb.append("Escape=<").append(escape).append('>'); } if (isQuoting()) { sb.append(' '); sb.append("QuoteChar=<").append(quoteChar).append('>'); } if (isCommentingEnabled()) { sb.append(' '); sb.append("CommentStart=<").append(commentStart).append('>'); } if (isNullHandling()) { sb.append(' '); sb.append("NullString=<").append(nullString).append('>'); } if(recordSeparator != null) { sb.append(' '); sb.append("RecordSeparator=<").append(recordSeparator).append('>'); } if (getIgnoreEmptyLines()) { sb.append(" EmptyLines:ignored"); } if (getIgnoreSurroundingSpaces()) { sb.append(" SurroundingSpaces:ignored"); } sb.append(" SkipHeaderRecord:").append(skipHeaderRecord); if (header != null) { sb.append(' '); sb.append("Header:").append(Arrays.toString(header)); } return sb.toString(); } /** * Verifies the consistency of the parameters and throws an IllegalStateException if necessary. * * @throws IllegalStateException */ void validate() throws IllegalStateException { if (quoteChar != null && delimiter == quoteChar.charValue()) { throw new IllegalStateException( "The quoteChar character and the delimiter cannot be the same ('" + quoteChar + "')"); } if (escape != null && delimiter == escape.charValue()) { throw new IllegalStateException( "The escape character and the delimiter cannot be the same ('" + escape + "')"); } if (commentStart != null && delimiter == commentStart.charValue()) { throw new IllegalStateException( "The comment start character and the delimiter cannot be the same ('" + commentStart + "')"); } if (quoteChar != null && quoteChar.equals(commentStart)) { throw new IllegalStateException( "The comment start character and the quoteChar cannot be the same ('" + commentStart + "')"); } if (escape != null && escape.equals(commentStart)) { throw new IllegalStateException( "The comment start and the escape character cannot be the same ('" + commentStart + "')"); } if (escape == null && quotePolicy == Quote.NONE) { throw new IllegalStateException("No quotes mode set but no escape character is set"); } } /** * Sets the comment start marker of the format to the specified character. * * Note that the comment start character is only recognized at the start of a line. * * @param commentStart * the comment start marker * @return A new CSVFormat that is equal to this one but with the specified character as the comment start marker * @throws IllegalArgumentException * thrown if the specified character is a line break */ public CSVFormat withCommentStart(final char commentStart) { return withCommentStart(Character.valueOf(commentStart)); } /** * Sets the comment start marker of the format to the specified character. * * Note that the comment start character is only recognized at the start of a line. * * @param commentStart * the comment start marker, use {@code null} to disable * @return A new CSVFormat that is equal to this one but with the specified character as the comment start marker * @throws IllegalArgumentException * thrown if the specified character is a line break */ public CSVFormat withCommentStart(final Character commentStart) { if (isLineBreak(commentStart)) { throw new IllegalArgumentException("The comment start character cannot be a line break"); } return new CSVFormat(delimiter, quoteChar, quotePolicy, commentStart, escape, ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, header, skipHeaderRecord); } /** * Sets the delimiter of the format to the specified character. * * @param delimiter * the delimiter character * @return A new CSVFormat that is equal to this with the specified character as delimiter * @throws IllegalArgumentException * thrown if the specified character is a line break */ public CSVFormat withDelimiter(final char delimiter) { if (isLineBreak(delimiter)) { throw new IllegalArgumentException("The delimiter cannot be a line break"); } return new CSVFormat(delimiter, quoteChar, quotePolicy, commentStart, escape, ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, header, skipHeaderRecord); } /** * Sets the escape character of the format to the specified character. * * @param escape * the escape character * @return A new CSVFormat that is equal to his but with the specified character as the escape character * @throws IllegalArgumentException * thrown if the specified character is a line break */ public CSVFormat withEscape(final char escape) { return withEscape(Character.valueOf(escape)); } /** * Sets the escape character of the format to the specified character. * * @param escape * the escape character, use {@code null} to disable * @return A new CSVFormat that is equal to this but with the specified character as the escape character * @throws IllegalArgumentException * thrown if the specified character is a line break */ public CSVFormat withEscape(final Character escape) { if (isLineBreak(escape)) { throw new IllegalArgumentException("The escape character cannot be a line break"); } return new CSVFormat(delimiter, quoteChar, quotePolicy, commentStart, escape, ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, header, skipHeaderRecord); } /** * Sets the header of the format. The header can either be parsed automatically from the input file with: * * <pre> * CSVFormat format = aformat.withHeader();</pre> * * or specified manually with: * * <pre> * CSVFormat format = aformat.withHeader(&quot;name&quot;, &quot;email&quot;, &quot;phone&quot;);</pre> * * @param header * the header, <tt>null</tt> if disabled, empty if parsed automatically, user specified otherwise. * * @return A new CSVFormat that is equal to this but with the specified header * @see #withSkipHeaderRecord(boolean) */ public CSVFormat withHeader(final String... header) { return new CSVFormat(delimiter, quoteChar, quotePolicy, commentStart, escape, ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, header, skipHeaderRecord); } /** * Sets the empty line skipping behavior of the format. * * @param ignoreEmptyLines * the empty line skipping behavior, <tt>true</tt> to ignore the empty lines between the records, * <tt>false</tt> to translate empty lines to empty records. * @return A new CSVFormat that is equal to this but with the specified empty line skipping behavior. */ public CSVFormat withIgnoreEmptyLines(final boolean ignoreEmptyLines) { return new CSVFormat(delimiter, quoteChar, quotePolicy, commentStart, escape, ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, header, skipHeaderRecord); } /** * Sets the trimming behavior of the format. * * @param ignoreSurroundingSpaces * the trimming behavior, <tt>true</tt> to remove the surrounding spaces, <tt>false</tt> to leave the * spaces as is. * @return A new CSVFormat that is equal to this but with the specified trimming behavior. */ public CSVFormat withIgnoreSurroundingSpaces(final boolean ignoreSurroundingSpaces) { return new CSVFormat(delimiter, quoteChar, quotePolicy, commentStart, escape, ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, header, skipHeaderRecord); } /** * Performs conversions to and from null for strings on input and output. * <ul> * <li> * <strong>Reading:</strong> Converts strings equal to the given {@code nullString} to {@code null} when reading * records.</li> * <li> * <strong>Writing:</strong> Writes {@code null} as the given {@code nullString} when writing records.</li> * </ul> * * @param nullString * the String to convert to and from {@code null}. No substitution occurs if {@code null} * * @return A new CSVFormat that is equal to this but with the specified null conversion string. */ public CSVFormat withNullString(final String nullString) { return new CSVFormat(delimiter, quoteChar, quotePolicy, commentStart, escape, ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, header, skipHeaderRecord); } /** * Sets the quoteChar of the format to the specified character. * * @param quoteChar * the quoteChar character * @return A new CSVFormat that is equal to this but with the specified character as quoteChar * @throws IllegalArgumentException * thrown if the specified character is a line break */ public CSVFormat withQuoteChar(final char quoteChar) { return withQuoteChar(Character.valueOf(quoteChar)); } /** * Sets the quoteChar of the format to the specified character. * * @param quoteChar * the quoteChar character, use {@code null} to disable * @return A new CSVFormat that is equal to this but with the specified character as quoteChar * @throws IllegalArgumentException * thrown if the specified character is a line break */ public CSVFormat withQuoteChar(final Character quoteChar) { if (isLineBreak(quoteChar)) { throw new IllegalArgumentException("The quoteChar cannot be a line break"); } return new CSVFormat(delimiter, quoteChar, quotePolicy, commentStart, escape, ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, header, skipHeaderRecord); } /** * Sets the output quote policy of the format to the specified value. * * @param quotePolicy * the quote policy to use for output. * * @return A new CSVFormat that is equal to this but with the specified quote policy */ public CSVFormat withQuotePolicy(final Quote quotePolicy) { return new CSVFormat(delimiter, quoteChar, quotePolicy, commentStart, escape, ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, header, skipHeaderRecord); } /** * Sets the record separator of the format to the specified character. * * @param recordSeparator * the record separator to use for output. * * @return A new CSVFormat that is equal to this but with the the specified output record separator */ public CSVFormat withRecordSeparator(final char recordSeparator) { return withRecordSeparator(String.valueOf(recordSeparator)); } /** * Sets the record separator of the format to the specified String. * * @param recordSeparator * the record separator to use for output. * * @return A new CSVFormat that is equal to this but with the the specified output record separator */ public CSVFormat withRecordSeparator(final String recordSeparator) { return new CSVFormat(delimiter, quoteChar, quotePolicy, commentStart, escape, ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, header, skipHeaderRecord); } /** * Sets whether to skip the header record. * * @param skipHeaderRecord * whether to skip the header record. * * @return A new CSVFormat that is equal to this but with the the specified skipHeaderRecord setting. * @see #withHeader(String...) */ public CSVFormat withSkipHeaderRecord(final boolean skipHeaderRecord) { return new CSVFormat(delimiter, quoteChar, quotePolicy, commentStart, escape, ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, header, skipHeaderRecord); } }
[ "leonardo.fernandes@ifal.edu.br" ]
leonardo.fernandes@ifal.edu.br
1dd4b7157515b96bad7d6073e868626e427965f4
33f5e97efb897ced211a4ae0d24c2fddbe72decc
/src/main/java/com/trasen/imis/controller/MobileAttenceController.java
e61f627f17f0efb2c337adc449af157b5b8462f1
[]
no_license
liumx2007/ts-imis
bcee45b25e79870b0188134910ca6cea2a999924
3d6aaa66c3bb6d5826d72990185f622a1975d712
refs/heads/master
2021-09-07T19:55:08.548932
2017-09-05T13:38:39
2017-09-05T13:38:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,695
java
package com.trasen.imis.controller; import cn.trasen.core.entity.Result; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Maps; import com.trasen.imis.model.AttenceLogVo; import com.trasen.imis.model.AttenceVo; import com.trasen.imis.model.TbPersonnel; import com.trasen.imis.service.MobileAttenceService; import com.trasen.imis.utils.HttpUtil; import com.trasen.imis.utils.PropertiesUtils; import org.apache.commons.collections.MapUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.google.common.base.Preconditions.checkArgument; /** * Created by zhangxiahui on 17/6/21. */ @Controller @RequestMapping("/mobileAttence") public class MobileAttenceController { private static final Logger logger = Logger.getLogger(MobileAttenceController.class); @Autowired MobileAttenceService mobileAttenceService; @ResponseBody @RequestMapping(value = "/getAttenceToday", method = RequestMethod.POST) public Map<String,Object> getAttenceToday(@RequestBody Map<String, Object> params){ //结果集 Map<String, Object> result = Maps.newHashMap(); result.put("status", 1); result.put("msg", "success"); try { checkArgument(MapUtils.isNotEmpty(params), "参数对象params不可为空!"); String openId = MapUtils.getString(params, "openId"); AttenceVo attenceVo = mobileAttenceService.getAttenceToday(openId); if(attenceVo!=null){ result.put("attenceVo",attenceVo); }else{ result.put("status", 0); result.put("msg", "openId没找到"); } } catch (IllegalArgumentException e) { logger.error("获取当天考勤数据异常" + e.getMessage(), e); result.put("status", 0); result.put("msg", e.getMessage()); } catch (Exception e) { logger.error("获取当天考勤数据异常" + e.getMessage(), e); result.put("status", 0); result.put("msg", e.getMessage()); } return result; } @ResponseBody @RequestMapping(value = "/signInOrOut", method = RequestMethod.POST) public Map<String,Object> signInOrOut(@RequestBody AttenceLogVo attenceLogVo){ //结果集 Map<String, Object> result = Maps.newHashMap(); result.put("status", 1); result.put("msg", "success"); try { logger.info("==今日签到系统======"); logger.info("==今日签到系统======"+attenceLogVo.getOpenId()); logger.info("==今日签到系统======"+attenceLogVo.getType()); logger.info("==今日签到系统======"+attenceLogVo.getAttenceDate()); logger.info("==今日签到系统======"+attenceLogVo.getAttenceWeek()); logger.info("==今日签到系统======"+attenceLogVo.getAccuracy()); logger.info("==今日签到系统======"+attenceLogVo.getAttenceTime()); logger.info("==今日签到系统======"+attenceLogVo.getLatitude()); logger.info("==今日签到系统======"+attenceLogVo.getLongitude()); logger.info("==今日签到系统======"+attenceLogVo.getName()); if(attenceLogVo!=null&&attenceLogVo.getType()!=null){ AttenceVo attenceVo = mobileAttenceService.signIn(attenceLogVo); if("signIn".equals(attenceLogVo.getType())&&(attenceVo==null||attenceVo.getSigninTime()==null)){ result.put("status", 0); result.put("msg", "您不在考勤范围内!"); }else if("signOut".equals(attenceLogVo.getType())&&(attenceVo==null||attenceVo.getSignoutTime()==null)){ result.put("status", 0); result.put("msg", "签退失败!"); }else if("sign".equals(attenceLogVo.getType())&&(attenceVo==null||attenceVo.getSigninTime()==null)){ result.put("status", 0); result.put("msg", "签到失败!"); }else{ result.put("attenceVo",attenceVo); } } } catch (Exception e) { logger.error("签到异常" + e.getMessage(), e); result.put("status", -1); result.put("msg", e.getMessage()); } return result; } @ResponseBody @RequestMapping(value = "/queryAttLogList", method = RequestMethod.POST) public Result queryAttLogList(@RequestBody Map<String, Object> params){ //结果集 Result result = new Result(); result.setStatusCode(1); result.setSuccess(true); try { checkArgument(MapUtils.isNotEmpty(params), "参数对象params不可为空!"); String openId = MapUtils.getString(params, "openId"); String attDate = MapUtils.getString(params, "attDate"); AttenceLogVo attLog = new AttenceLogVo(); attLog.setOpenId(openId); attLog.setAttenceDate(attDate); List<AttenceLogVo> list = mobileAttenceService.queryAttLogList(attLog); result.setObject(list); } catch (IllegalArgumentException e) { logger.error("获取考勤记录异常" + e.getMessage(), e); result.setStatusCode(0); result.setSuccess(false); result.setMessage(e.getMessage()); } catch (Exception e) { logger.error("获取考勤记录异常" + e.getMessage(), e); result.setStatusCode(0); result.setSuccess(false); result.setMessage(e.getMessage()); } return result; } @ResponseBody @RequestMapping(value = "/getSubPerson", method = RequestMethod.POST) public Object getSubPerson(@RequestBody Map<String, Object> params){ //结果集 Result result = new Result(); result.setStatusCode(1); result.setSuccess(true); List<TbPersonnel> list = new ArrayList<>(); result.setObject(list); try { checkArgument(MapUtils.isNotEmpty(params), "参数对象params不可为空!"); String openId = MapUtils.getString(params, "openId"); String name = MapUtils.getString(params, "name"); Integer userId = mobileAttenceService.getUserIdToOPenId(openId); if(userId!=null){ String menusUrl = PropertiesUtils.getProperty("nu_authorize_subPerson") .replace("{appId}","ts-imis").replace("{userId}",userId.toString()); String resultStr = HttpUtil.connectURLGET(menusUrl,""); JSONObject jsonObject = (JSONObject) JSONObject.parse(resultStr); return jsonObject; } } catch (IllegalArgumentException e) { logger.error("获取下属异常" + e.getMessage(), e); result.setStatusCode(0); result.setSuccess(false); result.setMessage(e.getMessage()); } catch (Exception e) { logger.error("获取下属异常" + e.getMessage(), e); result.setStatusCode(0); result.setSuccess(false); result.setMessage(e.getMessage()); } return result; } }
[ "281055769@qq.com" ]
281055769@qq.com
e85e296d6fc82e5cd451e41df1a43154e16d889e
046dafb8f8d89a525833e408bc10876f2dae0a92
/org/org/mathpiper/builtin/functions/PreFix.java
571a1ea8ff4d115bfec3be47d68df64b1b110176
[]
no_license
concord-consortium/geogebra
9b47d3f844419a9dfc7796f49f5412745512f5be
c08d149c95ad9450d7c3d51e9f18126ce1028c31
refs/heads/master
2020-05-16T21:57:01.514125
2010-11-24T11:10:43
2010-11-24T11:10:43
1,094,641
4
2
null
null
null
null
UTF-8
Java
false
false
1,256
java
/* {{{ License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //}}} // :indentSize=4:lineSeparator=\n:noTabs=false:tabSize=4:folding=explicit:collapseFolds=0: package org.mathpiper.builtin.functions; import org.mathpiper.builtin.BuiltinFunctionInitialize; import org.mathpiper.lisp.UtilityFunctions;; import org.mathpiper.lisp.Environment; /** * * */ public class PreFix extends BuiltinFunctionInitialize { public void eval(Environment aEnvironment, int aStackTop) throws Exception { UtilityFunctions.multiFix(aEnvironment, aStackTop, aEnvironment.iPrefixOperators); } }
[ "tkosan@23ce0884-8a58-47d3-bc5c-ddf1cd5b9f9e" ]
tkosan@23ce0884-8a58-47d3-bc5c-ddf1cd5b9f9e
ec84d69deb496e075ed5547dd16aa58cd48056fe
f6573a7839e15288f0e37d56e195f803f90e586e
/12-framework/02-vertx/04-test/01-unittest/src/test/java/com/company/app/VertxUnitTest.java
e8564c5123259832e5d8e2ac2c4c42a279cc7c86
[]
no_license
dami-seattle/java
b0fc1c12fe4ee4b1449d98ffb15f686b0171a8a1
27217706df6d234cccf8cd58f57005e4410fa917
refs/heads/master
2021-01-18T18:17:55.253172
2016-06-27T06:44:21
2016-06-27T06:44:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,488
java
package com.company.app; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClient; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestOptions; import io.vertx.ext.unit.TestSuite; import io.vertx.ext.unit.report.ReportOptions; public class VertxUnitTest { public static void main(String... args){ new VertxUnitTest().run(); } Vertx vertx; public void run(){ TestOptions options = new TestOptions().addReporter(new ReportOptions().setTo("console")); TestSuite suite = TestSuite.create("com.company.app.VertxUnitTest"); suite.before(context -> { vertx = Vertx.vertx(); vertx.createHttpServer().requestHandler(req -> req.response().end("foo")).listen(8080, context.asyncAssertSuccess()); }); suite.after(context -> { vertx.close(context.asyncAssertSuccess()); }); suite.test("Some_test1", context -> { HttpClient client = vertx.createHttpClient(); Async async = context.async(); client.getNow(8080, "localhost", "/", resp -> { resp.bodyHandler(body -> context.assertEquals("foo", body.toString("UTF-8"))); client.close(); async.complete(); }); }); suite.run(options); } } /* https://github.com/vert-x3/vertx-examples/blob/master/unit-examples/src/test/java/io/vertx/example/unit/test/VertxUnitTest.java 1, run VertxUnitTest.main() */
[ "whan@godaddy.com" ]
whan@godaddy.com
109a13b01611ed90a45865fdb4da8134fd4f7b3c
ff7fd391e454cbf8eb8ef0817f32f7bfc3264a9b
/BookStoreJ/src/main/java/jexxatutorials/bookstorej/domain/businessexception/BookNotInStock.java
7657a53faea33a2b81cb26a733fc3ff2e56a71b9
[]
no_license
Melina1000/JexxaTutorials
2ea7f0f11ac9c9e1a6b9c6b6e15a398e49895b7b
e1f8d25f983045ebdd8683d87a05db62ca92db01
refs/heads/master
2022-12-01T01:54:07.308810
2020-08-21T15:17:15
2020-08-21T15:17:15
284,702,240
0
0
null
null
null
null
UTF-8
Java
false
false
268
java
package jexxatutorials.bookstorej.domain.businessexception; import io.jexxa.addend.applicationcore.BusinessException; /** * Is thrown when trying to sell a book that is currently not in stock */ @BusinessException public class BookNotInStock extends Exception { }
[ "Melina1000@gmx.de" ]
Melina1000@gmx.de
fda342d7032945758b2ff35f39f96cf1b5673db5
731cc03ad465ebd857927d882d52c10ea76dc309
/src/main/java/top/seefly/javase/designpattern/singleton/SimpleSingleton.java
a75c359b6d16a3f5c0ce6155d810599560936947
[]
no_license
gitdoit/JavaSE
13cd643608d5ce17e2ad60253373da79c19cbccf
8c19f8633b8d508209643486db803aae8834f59a
refs/heads/master
2023-03-29T05:01:44.340159
2021-04-02T00:57:20
2021-04-02T00:57:20
92,649,781
1
0
null
2021-03-31T21:26:53
2017-05-28T08:44:09
Java
UTF-8
Java
false
false
734
java
package top.seefly.javase.designpattern.singleton; /** * 简单的单例模式 * <p> * 这种单例模式实现简单,代码易读,性能良好。 但是唯一的缺点是不能控制实例的创建时间。 * * @author liujianxin * @date 2018-11-20 19:51 */ public class SimpleSingleton { /** * 避免被直接引用 */ private static SimpleSingleton instance = new SimpleSingleton(); /** * 单例模式只能有一个实例。构造方法不能被外部访问! */ private SimpleSingleton() { } /** * 通过静态方法获取单例。 * * @return 单例 */ public static SimpleSingleton getInstance() { return instance; } }
[ "seefly@vip.qq.com" ]
seefly@vip.qq.com
96b54d56996d0cdbd630e422714058634b38f276
1385e2c2ea1f157cbbf2d9edde7a92df442e2092
/Platform/src/com/yf/system/back/action/AirflightAction.java
6084f6aac9d66af506bf12c0a2929fb108b53a79
[]
no_license
marc45/kzpw
112b6dd7d5e9317fad343918c48767be32a3c9e3
19c11c2abe37125eb715e8b723df6e87fce7e10e
refs/heads/master
2021-01-22T18:01:45.787156
2015-12-07T08:43:53
2015-12-07T08:43:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
19,028
java
/** * 版权所有, 允风文化 * Author: 允风文化 项目开发组 * copyright: 2012 * */ package com.yf.system.back.action; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; import com.yf.system.back.server.Server; import com.yf.system.base.airflight.Airflight; import com.yf.system.base.customeragent.Customeragent; import com.yf.system.base.flightinfo.CarbinInfo; import com.yf.system.base.flightinfo.FlightInfo; import com.yf.system.base.flightinfo.FlightSearch; import com.yf.system.base.orderinfo.Orderinfo; import com.yf.system.base.passenger.Passenger; import com.yf.system.base.segmentinfo.Segmentinfo; import com.yf.system.base.util.PageInfo; import com.yf.system.base.zrate.Zrate; public class AirflightAction extends B2b2cbackAction { private static final long serialVersionUID = 4247491703275711095L; private List<Airflight> listAirflight; private Airflight airflight = new Airflight(); private List<FlightInfo> listFlightInfoAll; private FlightSearch flightSearch = new FlightSearch(); private List<CarbinInfo>listCarbin=new ArrayList<CarbinInfo>(); private List<Passenger> listPassenger; private List<Segmentinfo> listSegmentinfo; private Orderinfo orderinfo=new Orderinfo(); // 批量操作ID数组 private int[] selectid; // 批量操作选项 private int opt; // search private String s_name; private String depDate;//出发日期 private String StartAirportCode;//出发机场三字码 private String EndAirportCode;//到达三字码 private String AirCompanyCode;//航空公司 private String AgentCode="";//代码 private String FlightNO;//航班号 private String CabinCode;//仓位吗 //下单用参数 private String Flightmodel;//机型 例:380 private String PassName;//乘机人姓名,多人用,分隔 private String IdType;//乘机人证件类型,多人用,分隔 private String IdNo;//乘机人证件号码,多人用,分隔 private String arrtime;//到达日期 例 2012-05-12 07:40:00.000 private String Price;//票面价 private String Portfee;//基建费 private String Fuelfee;//燃油费 private String Linkname;//联系人 private String Linktel;//联系人电话 private String ZrateID;//政策ID private String ZrateValue;//政策返点 //错误信息 public String errManger; public String GetCabinType(Float discont,String cabincode){ System.out.println("discont:"+discont); if(cabincode.equals("P")&&discont>200){ return "豪华头等舱"; } if(cabincode.equals("P")&&discont>0&&discont<100){ return "经济舱"; } if(cabincode.equals("A")&&discont>200){ return "头等舱"; } if(cabincode.equals("A")&&discont>0&&discont<100){ return "经济舱"; } if(cabincode.equals("P")){ return "超值头等舱"; } if(cabincode.equals("Z")&&discont>0&&discont<100){ return "经济舱"; } if(cabincode.equals("F")||cabincode.equals("A")||cabincode.equals("Z")){ return "头等舱"; } if((discont==100)){ return "全价舱"; } if((discont>=40&&discont<100)){ return "经济舱"; } if((discont<40)){ return "特价舱"; } return "经济舱"; } public String CreateOrderBySeginfo() throws Exception { if(AgentCode==null||AgentCode.trim().length()==0){ errManger="代理编号为空"; return "airerr"; } List<Customeragent>listagent=Server.getInstance().getMemberService().findAllCustomeragent(" WHERE 1=1 AND "+Customeragent.COL_agentisenable+" =1 and "+Customeragent.COL_code+" ='"+AgentCode+"'", " ORDER BY ID ", -1, 0); if(listagent.size()==0){ errManger="没有对应的代理"; return "airerr"; } if(StartAirportCode==null||StartAirportCode.trim().length()==0||StartAirportCode.trim().length()!=3){ errManger="出发三字码错误;格式例如:PEK"; return "airerr"; } if(EndAirportCode==null||EndAirportCode.trim().length()==0||EndAirportCode.trim().length()!=3){ errManger="到达三字码错误;格式例如:SHA"; return "airerr"; } if(FlightNO==null||FlightNO.trim().length()==0||FlightNO.trim().length()>7){ errManger="航班号错误;格式例如CA8888"; return "airerr"; } if(depDate==null||depDate.trim().length()==0||depDate.trim().length()!=23){ errManger="起飞时间错误;格式例如XXXX-XX-XX XX:XX:XX.XXX"; return "airerr"; } if(arrtime==null||arrtime.trim().length()==0||arrtime.trim().length()!=23){ errManger="到达时间错误;格式例如XXXX-XX-XX XX:XX:XX.XXX"; return "airerr"; } if(CabinCode==null||CabinCode.trim().length()==0||CabinCode.trim().length()>40){ errManger="仓位码错误;格式例如Y 或者A,B,C,Y"; return "airerr"; } if(Flightmodel==null||Flightmodel.trim().length()==0||Flightmodel.trim().length()>40){ errManger="机型信息错误;格式例如380"; return "airerr"; } if(PassName==null||PassName.trim().length()==0){ errManger="乘机人姓名不能为空"; return "airerr"; } if(IdType==null||IdType.trim().length()==0){ errManger="证件类型不能为空"; return "airerr"; } if(IdNo==null||IdNo.trim().length()==0){ errManger="证件号码不能为空"; return "airerr"; } if(Price==null||Price.trim().length()==0){ errManger="票面价不能为空"; return "airerr"; } if(Portfee==null||Portfee.trim().length()==0){ errManger="基建费不能为空"; return "airerr"; } if(Fuelfee==null||Fuelfee.trim().length()==0){ errManger="燃油费不能为空"; return "airerr"; } if(Linkname==null||Linkname.trim().length()==0){ errManger="联系人不能为空"; return "airerr"; } if(Linktel==null||Linktel.trim().length()==0){ errManger="联系电话不能为空"; return "airerr"; } if(ZrateID==null||ZrateID.trim().length()==0){ errManger="政策ID不能为空"; return "airerr"; } if(ZrateValue==null||ZrateValue.trim().length()==0){ errManger="政策返点不能为空"; return "airerr"; } listPassenger =new ArrayList<Passenger>(); String[] passnames=PassName.split(","); String[] IdTypes=IdType.split(","); String[] IdNos=IdNo.split(","); if(passnames!=null&&passnames.length>0){ for(int p=0;p<passnames.length;p++){ if(passnames[p]!=null&&passnames[p].trim().length()>0){ Passenger passenger=new Passenger(); passenger.setName(passnames[p].trim()); if(IdTypes[p]!=null&&IdTypes[p].trim().length()>0){ passenger.setIdtype(Integer.parseInt(IdTypes[p].trim())); } if(IdNos[p]!=null&&IdNos[p].trim().length()>0){ passenger.setIdnumber(IdNos[p].trim()); } passenger.setPrice(Float.parseFloat(Price)); passenger.setAirportfee(Float.parseFloat(Portfee)); passenger.setFuelprice(Float.parseFloat(Fuelfee)); listPassenger.add(passenger); } } } if(listPassenger.size()==0){ errManger="乘机人为空"; return "airerr"; } if(listPassenger.size()>9){ errManger="一次订单提交乘机人数量不能大于9"; return "airerr"; } listSegmentinfo=new ArrayList<Segmentinfo>(); Segmentinfo segmentinfo=new Segmentinfo(); segmentinfo.setStartairport(StartAirportCode); segmentinfo.setEndairport(EndAirportCode); listSegmentinfo.add(segmentinfo); return ""; } public String SearchAirFlightZrate() throws Exception { if(StartAirportCode==null||StartAirportCode.trim().length()==0||StartAirportCode.trim().length()!=3){ errManger="出发三字码错误;格式例如:PEK"; return "airerr"; } if(EndAirportCode==null||EndAirportCode.trim().length()==0||EndAirportCode.trim().length()!=3){ errManger="到达三字码错误;格式例如:SHA"; return "airerr"; } if(FlightNO==null||FlightNO.trim().length()==0||FlightNO.trim().length()>7){ errManger="航班号错误;格式例如CA8888"; return "airerr"; } if(depDate==null||depDate.trim().length()==0||depDate.trim().length()!=10){ errManger="出发日期错误;格式例如XXXX-XX-XX"; return "airerr"; } if(CabinCode==null||CabinCode.trim().length()==0||CabinCode.trim().length()>40){ errManger="仓位码错误;格式例如Y 或者A,B,C,Y"; return "airerr"; } if(AgentCode==null||AgentCode.trim().length()==0){ errManger="没有对应的代理"; return "airerr"; } List<Customeragent>listagent=Server.getInstance().getMemberService().findAllCustomeragent(" WHERE 1=1 AND "+Customeragent.COL_agentisenable+" =1 and "+Customeragent.COL_code+" ='"+AgentCode+"'", " ORDER BY ID ", -1, 0); if(listagent.size()==0){ errManger="没有对应的代理;"; return "airerr"; } String[] cabins=CabinCode.trim().split(","); if(cabins!=null&&cabins.length>0){ for(int a=0;a<cabins.length;a++){ if(cabins[a]!=null&&cabins[a].trim().length()>0){ CarbinInfo carbinInfo=new CarbinInfo(); Float zratevalue=0f; //匹配政策开始 Calendar cal=Calendar.getInstance(); SimpleDateFormat formatter=new SimpleDateFormat( "HH:mm"); String mDateTime=formatter.format(cal.getTime()); String strSP="[dbo].[sp_GetZrateByFlight] "+ "@chufajichang = N'"+StartAirportCode+"',@daodajichang = N'"+EndAirportCode+"',"+ "@chufariqi = N'"+depDate+"',@dangqianshijian= N'"+mDateTime+"',"+ "@hangkonggongsi= N'"+FlightNO.substring(0, 2).trim()+"',"+ "@cangwei= N'"+cabins[a].trim()+"',@hangbanhao= N'"+FlightNO.trim().substring(2, FlightNO.trim().length())+"',@ismulity=0,@isgaofan=1"; System.out.println(strSP); List listz=Server.getInstance().getSystemService().findMapResultByProcedure(strSP); System.out.println(listz); if(listz.size()>0){ Zrate zrate= new Zrate(); for(int s=0;s<listz.size();s++){ Map map=(Map)listz.get(s); //zrate=Server.getInstance().getAirService().findZrate(Long.parseLong(map.get("zrateid").toString().trim())); zratevalue=Getliudianvalue2(Float.parseFloat(map.get("zratevalue").toString().trim()), listagent.get(0)); carbinInfo.setRatevalue(zratevalue); carbinInfo.setZrateid(Long.parseLong(map.get("zrateid").toString().trim())); carbinInfo.setCabin(cabins[a].trim()); break; } System.out.println("zratevalue:"+zratevalue); } //匹配结束 listCarbin.add(carbinInfo); } } } return "AirFlightZrate"; } public String SearchAirFlight() throws Exception { if(AirCompanyCode==null||AirCompanyCode.length()==0){ AirCompanyCode="ALL"; } if(AgentCode==null||AgentCode.trim().length()==0){ errManger="没有对应的代理"; return "airerr"; } if(StartAirportCode==null||StartAirportCode.trim().length()==0){ errManger="出发三字码为空!"; return "airerr"; } if(EndAirportCode==null||EndAirportCode.trim().length()==0){ errManger="到达三字码为空!"; return "airerr"; } if(depDate==null||depDate.trim().length()==0){ errManger="出发日期为空!"; return "airerr"; } if(depDate.length()!=10){ errManger="出发日期格式错误!准确格式XXXX-XX-XX"; return "airerr"; } List<Customeragent>listagent=Server.getInstance().getMemberService().findAllCustomeragent(" WHERE 1=1 AND "+Customeragent.COL_agentisenable+" =1 and "+Customeragent.COL_code+" ='"+AgentCode+"'", " ORDER BY ID ", -1, 0); if(listagent.size()==0){ errManger="没有对应的代理"; return "airerr"; } flightSearch.setAirCompanyCode(AirCompanyCode); flightSearch.setEndAirportCode(EndAirportCode); flightSearch.setStartAirportCode(StartAirportCode); flightSearch.setFromDate(depDate); //flightSearch.setTravelType(flightSearch.getTravelType()); listFlightInfoAll = Server.getInstance().getTicketSearchService() .findAllFlightinfo(flightSearch); System.out.println(listFlightInfoAll.size()); if(listFlightInfoAll!=null&&listFlightInfoAll.size()>10000){ System.out.println("匹配返点"); for(int a=0;a<listFlightInfoAll.size();a++){ List<CarbinInfo>listCarbinInfo=listFlightInfoAll.get(a).getCarbins(); if(listCarbinInfo!=null&&listCarbinInfo.size()>0){ for(int c=0;c<listCarbinInfo.size();c++){ Float zratevalue=0f; zratevalue=Getliudianvalue2(listCarbinInfo.get(c).getRatevalue(), listagent.get(0)); listCarbinInfo.get(c).setRatevalue(zratevalue); } } } } return "airlist"; } /** * 列表查询航班基础信息表 */ public String execute() throws Exception { String where = " where 1=1 "; // if (s_name!=null && s_name.trim().length()!=0) { // where += " and " + Airflight.COL_name +" like '%" + // s_name.trim()+"%'"; // } if (airflight.getSairportcode() != null && !"".equals(airflight.getSairportcode())) { where += " and " + Airflight.COL_sairportcode + " like '%" + airflight.getSairportcode() + "%'"; } if (airflight.getEairportcode() != null && !"".equals(airflight.getEairportcode())) { where += " and " + Airflight.COL_eairportcode + " like '%" + airflight.getEairportcode() + "%'"; } if (airflight.getAircompanycode() != null && !"".equals(airflight.getAircompanycode())) { where += " and " + Airflight.COL_aircompanycode + " like '%" + airflight.getAircompanycode() + "%'"; } if (airflight.getFlightnumber() != null && !"".equals(airflight.getFlightnumber())) { where += " and " + Airflight.COL_flightnumber + " like '%" + airflight.getFlightnumber() + "%'"; } List list = Server.getInstance().getAirService() .findAllAirflightForPageinfo(where, " ORDER BY ID ", pageinfo); pageinfo = (PageInfo) list.remove(0); listAirflight = list; if (pageinfo.getTotalrow() > 0 && listAirflight.size() == 0) { pageinfo.setPagenum(1); list = Server.getInstance().getAirService() .findAllAirflightForPageinfo(where, " ORDER BY ID ", pageinfo); pageinfo = (PageInfo) list.remove(0); listAirflight = list; } return SUCCESS; } /** * 转向到航班基础信息表添加页面 */ public String toadd() throws Exception { return EDIT; } /** * 转向到航班基础信息表修改页面 */ public String toedit() throws Exception { airflight = Server.getInstance().getAirService().findAirflight( airflight.getId()); return EDIT; } /** * 转向到航班基础信息表审核页面 */ public String docheck() throws Exception { airflight = Server.getInstance().getAirService().findAirflight( airflight.getId()); if (airflight.getIsenable() == 1) { airflight.setIsenable(0); } else { airflight.setIsenable(1); } Server.getInstance().getAirService().updateAirflightIgnoreNull(airflight); return "list2"; } /** * 添加航班基础信息表 */ public String add() throws Exception { airflight.setCreateuser(getLoginUser().getLoginname()); airflight.setCreateusertime(new Timestamp(System.currentTimeMillis())); airflight.setModifyuser(getLoginUser().getLoginname()); airflight.setModifytime(new Timestamp(System.currentTimeMillis())); Server.getInstance().getAirService().createAirflight(airflight); return LIST; } /** * 审核航班基础信息表 */ public String check() throws Exception { airflight.setModifyuser(getLoginUser().getLoginname()); airflight.setModifytime(new Timestamp(System.currentTimeMillis())); Server.getInstance().getAirService().updateAirflightIgnoreNull( airflight); return LIST; } /** * 编辑航班基础信息表 */ public String edit() throws Exception { airflight.setModifyuser(getLoginUser().getLoginname()); airflight.setModifytime(new Timestamp(System.currentTimeMillis())); Server.getInstance().getAirService().updateAirflightIgnoreNull( airflight); return LIST; } /** * 删除航班基础信息表 */ public String delete() throws Exception { Server.getInstance().getAirService().deleteAirflight(airflight.getId()); return LIST; } /** * 批量操作 * * @return * @throws Exception */ public String batch() throws Exception { if (selectid != null && selectid.length > 0) { switch (opt) { case 1: // delete for (int i : selectid) { Server.getInstance().getAirService().deleteAirflight(i); } break; default: break; } } return LIST; } /** * 返回航班基础信息表对象 */ public Object getModel() { return airflight; } public List<Airflight> getListAirflight() { return listAirflight; } public void setListAirflight(List<Airflight> listAirflight) { this.listAirflight = listAirflight; } public Airflight getAirflight() { return airflight; } public void setAirflight(Airflight airflight) { this.airflight = airflight; } public int getOpt() { return opt; } public void setOpt(int opt) { this.opt = opt; } public int[] getSelectid() { return selectid; } public void setSelectid(int[] selectid) { this.selectid = selectid; } public List<FlightInfo> getListFlightInfoAll() { return listFlightInfoAll; } public void setListFlightInfoAll(List<FlightInfo> listFlightInfoAll) { this.listFlightInfoAll = listFlightInfoAll; } public FlightSearch getFlightSearch() { return flightSearch; } public void setFlightSearch(FlightSearch flightSearch) { this.flightSearch = flightSearch; } public String getS_name() { return s_name; } public void setS_name(String s_name) { this.s_name = s_name; } public String getDepDate() { return depDate; } public void setDepDate(String depDate) { this.depDate = depDate; } public String getStartAirportCode() { return StartAirportCode; } public void setStartAirportCode(String startAirportCode) { StartAirportCode = startAirportCode; } public String getEndAirportCode() { return EndAirportCode; } public void setEndAirportCode(String endAirportCode) { EndAirportCode = endAirportCode; } public String getAirCompanyCode() { return AirCompanyCode; } public void setAirCompanyCode(String airCompanyCode) { AirCompanyCode = airCompanyCode; } public static long getSerialVersionUID() { return serialVersionUID; } public String getAgentCode() { return AgentCode; } public void setAgentCode(String agentCode) { AgentCode = agentCode; } public List<CarbinInfo> getListCarbin() { return listCarbin; } public void setListCarbin(List<CarbinInfo> listCarbin) { this.listCarbin = listCarbin; } public String getFlightNO() { return FlightNO; } public void setFlightNO(String flightNO) { FlightNO = flightNO; } public String getCabinCode() { return CabinCode; } public void setCabinCode(String cabinCode) { CabinCode = cabinCode; } public String getErrManger() { return errManger; } public void setErrManger(String errManger) { this.errManger = errManger; } }
[ "dogdog7788@qq.com" ]
dogdog7788@qq.com
8af77872137813e18841b2beac408b17f3c1373b
a77664b62adedf91eb6d83628924c9d2ef8d2b71
/src/test/java/movieApp/CineplexTest.java
cf39813b4d676c30af3f68ed48141acd2cb0e4d7
[]
no_license
AY2021S2-CS2113-T10-3/tp
7733fe44e651d0cfda8f8fb967c60be0381c919c
b08e1279369781ab16ed45522edb4e356c721c43
refs/heads/master
2023-04-04T17:08:27.462975
2021-04-12T13:43:48
2021-04-12T13:43:48
344,321,929
0
5
null
2021-04-12T12:52:37
2021-03-04T02:11:35
Java
UTF-8
Java
false
false
732
java
package movieApp; import org.junit.jupiter.api.Test; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.assertEquals; class CineplexTest { public static ArrayList<Integer> movieList = new ArrayList<>(); public static Cineplex cineplex = new Cineplex(1, "1", movieList); @Test void testGetCineplexID() { assertEquals(1, cineplex.getCineplexID()); } @Test void testGetCineplexName() { assertEquals("1", cineplex.getCineplexName()); } @Test void testGetMovieList() { assertEquals(movieList, cineplex.getMovieList()); } @Test void testGetCinemaList() { assertEquals(new ArrayList<>(), cineplex.getCinemaList()); } }
[ "190060010@qq.com" ]
190060010@qq.com
c30091c624a6435528c17379437d7694db636061
cde60b4fe6eae70fab5e4828508dcf0b90868d5c
/com/createJavaFile/createModel/Model.java
d147be13c9aef4e81416b7257cadfa24905820b9
[]
no_license
shy2850/easyWebSqlBean
fdb3dcfcd5b988951fca94e1bbc13c49dcced6b6
e8e06c6f7e526dd32ee0929936e25d683283b576
refs/heads/master
2016-08-04T18:12:36.753429
2014-10-27T12:28:18
2014-10-27T12:28:18
25,817,822
0
1
null
null
null
null
GB18030
Java
false
false
7,568
java
package com.createJavaFile.createModel; import java.io.IOException; import java.sql.SQLException; import java.util.LinkedList; import com.createJavaFile.connectionSource.ConnectionPool; import com.createJavaFile.myutil.Util; import com.myInterface.Connection; import com.myInterface.ResultSet; import com.myInterface.ResultSetMetaData; import com.myInterface.Statement; import com.shy2850.filter.ApplicationContext; /**</pre> * 通过模块化的拼接字符串 * 创建java文件 * 实现数据库表与java实体对象的映射关系 * </pre> * */ public class Model{ /**表中所有列项的包装类Member类型实例所组成的链表*/ private LinkedList<Member> members = new LinkedList<Member>(); public LinkedList<Member> getMembers() { return members; } /**定义表中字段是否还有Date类型的数据*/ boolean hasDate; /**定义表中字段是否还有Blob类型的数据*/ boolean hasBlob; /**数据库表名*/ String table; /**数据库表名大写*/ String Table; /**生成的java文件的保存地址*/ String url; /**主键所在的索引下标*/ int pkIndex = -1; /**主键字段的名称*/ private String pk; public void setPk(String pk) { this.pk = pk; } public String getPk() { return pk; } /** * @param table 数据库表名 * @param url java文件的保存地址:只允许在src下,如(com.java.util) */ public Model(String table, String url, String pk) { this.table = table; this.Table = Util.upperFirst(table); this.url = url; this.pk = pk; Connection con = ConnectionPool.connectionPoolImpl.getConnection(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from "+table); ResultSetMetaData rsm = rs.getMetaData(); for (int i = 0; i < rsm.getColumnCount(); i++) { String name = rsm.getColumnName(i+1); String type = Util.getType(rsm.getColumnClassName(i+1)); boolean isAutoIncrement = rsm.isAutoIncrement(i+1); if("Date".equals(type))hasDate = true; if("Blob".equals(type))hasBlob = true; System.out.println(name+":"+type); members.add(new Member(name, type, isAutoIncrement)); } } catch (SQLException e) { e.printStackTrace(); } } /**循环声明private成员*/ private String def(){ //声明private成员 StringBuffer sb = new StringBuffer(""); for (int i = 0; i < members.size(); i++) { sb.append(members.get(i).creatMem()+";"); } return sb.toString(); } /**循环生成各个成员的get-set方法*/ private String getSet(){ //生成get-set方法 StringBuffer sb = new StringBuffer(""); for (int i = 0; i < members.size(); i++) { sb.append(members.get(i).creatSetFun()); sb.append(members.get(i).creatGetFun()); } return sb.toString(); } /**<pre> * 生成构造方法: * 包括一个空的构造方法以及全参数的构造方法 * </pre> * */ private String conStructor(){ StringBuffer sb = new StringBuffer("\n\tpublic "+Util.upperFirst(table)+"(){}\n\tpublic "+Util.upperFirst(table)+"("); for (int i = 0; i < members.size(); i++) { sb.append(members.get(i).getType()+" "+members.get(i).getName()); if(i!=members.size()-1)sb.append(", "); } sb.append("){\n\t\tsuper();\n\t\t"); for (int i = 0; i < members.size(); i++) { sb.append("this."+members.get(i).getName()+" = "+members.get(i).getName()+";\n\t\t"); } sb.append("}"); return sb.toString(); } /**重写的equals方法*/ private String Equals(Member member){ StringBuffer sb = new StringBuffer(); sb.append("\n\t@Override\n\tpublic boolean equals(Object o) {\n\t"); sb.append("\treturn (o instanceof "+Table+")&&(("+Table+")o)."+member.get()+"=="+member.get()+";\n\t}"); return sb.toString(); } /**重写的toString方法*/ private String ToString() { //添加toString()方法 StringBuffer sb = new StringBuffer("\n\t@Override\n\tpublic String toString(){\n"); sb.append("\t\treturn \""+Util.upperFirst(table)+" ["); for (int i = 0; i < members.size(); i++) { if(Util.getType(members.get(i).getType()).equals("Date")){ sb.append(members.get(i).getName()+"=\" + DateFormat.format("+members.get(i).getName()+")+\""); } else{ sb.append(members.get(i).getName()+"=\" +"+members.get(i).getName()+"+\""); } if(i!=members.size()-1)sb.append(",");else sb.append("]\";\n\t}"); } return sb.toString(); } /**实现ParseResultable接口方法parseOf的字符串拼接*/ private String ParseOf(){ //实现ParseResultable接口的字符串拼接 StringBuffer sb = new StringBuffer("\n\tpublic Object parseOf(ResultSet rs) throws SQLException{\n\t\tif(null==rs)return null;"); for (int i = 0; i < members.size(); i++) { sb.append("\n\t\t"+members.get(i).getParseResultSet()); } sb.append("\n\t\t"+Util.upperFirst(table)+" "+table+" = new "+Util.upperFirst(table)+"("); for (int i = 0; i < members.size(); i++) { sb.append(members.get(i).getName()); if(i!=members.size()-1)sb.append(", ");else sb.append(");"); } sb.append("\n\t\treturn "+table+";\n\t}"); return sb.toString(); } /**创建成员列表方法*/ private String MemberList(){ StringBuffer sb = new StringBuffer(); sb.append("\n\tpublic static final String[] memberList = {"); for (int i = 0; i < members.size(); i++) { sb.append("\""+members.get(i).getName()+"\""); if(i!=members.size()-1)sb.append(","); else sb.append("};\n"); } sb.append("\tpublic String[] getMemberList(){"); sb.append("\n\t\treturn memberList;\n\t}"); return sb.toString(); } /**创建按序号获得属性值的方法*/ private String Get(){ StringBuffer sb = new StringBuffer(); sb.append("\n\tpublic Object get(int i){"); sb.append("\n\t\tObject[] members = {"); for (int i = 0; i < members.size(); i++) { sb.append(members.get(i).getName()); if(i!=members.size()-1)sb.append(","); else sb.append("};\n"); } sb.append("\t\tif(i<members.length)"); sb.append("return members[i];\n\t\telse \n\t\t\treturn null;\n\t}"); return sb.toString(); } @Override public String toString() { StringBuffer allInfo = new StringBuffer("package "+url+";\n"); if(hasDate)allInfo.append(Util.IMPORT_DATE+"\n"); if(hasBlob)allInfo.append(Util.IMPORT_BLOB+"\n"); allInfo.append("\nimport java.io.Serializable;\nimport com.myInterface.ResultSet;\nimport java.sql.SQLException;\n"); allInfo.append("\nimport com.createJavaFile.createModel.ParseResultSetable;\n\n"); allInfo.append("public class "+Util.upperFirst(table)+" implements ParseResultSetable,Serializable{\n\t"); allInfo.append("\n\tprivate static final long serialVersionUID = 1L;\n\t"); allInfo.append(def()); allInfo.append(conStructor()); allInfo.append(getSet()); for (int i = 0; i < members.size(); i++) { if(members.get(i).getName().equals(pk)){ pkIndex = i; allInfo.append(Equals(members.get(i))); } } allInfo.append(ToString()); allInfo.append(ParseOf()); allInfo.append(MemberList()); allInfo.append(Get()); allInfo.append("\n\tpublic final int primaryKey = "+pkIndex+";"); allInfo.append("\n\tpublic int PrimaryKey(){return primaryKey;}"); allInfo.append("\n}"); return allInfo.toString(); } /**将生成的字符串写入文件*/ public void saveModel(){ try { Util.write(toString(),"src."+url,Table+".java"); System.out.println("实体类:"+Table+".java 已经存入 "+url); ApplicationContext.addProperties(table, url+"."+Table); } catch (IOException e) { e.printStackTrace(); System.out.println("文件写入异常!"); } } }
[ "shy2850@163.com" ]
shy2850@163.com
3d787a1105c285a556b801e67a7f583a8c90bf55
db45bcc53bfb89f98b936f5978dc2ed91c6f472c
/FS2013Web/gensrc/java/fs2013/CurrentRain.java
b8ac631e1bfdc9d1b200ab189b5f70047a179446
[]
no_license
themason/projectrepo
f497cb2af8764109cea138131ea391583e0335ac
ad3a68acbcc06906800a06c16ad29322a75e9967
refs/heads/master
2016-09-03T06:57:07.830399
2014-09-21T16:19:32
2014-09-21T16:19:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,626
java
// // 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.09.20 at 07:42:28 AM BST // package fs2013; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <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;attribute name="isValid" use="required" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "currentRain") public class CurrentRain { @XmlAttribute(name = "isValid", required = true) protected boolean isValid; /** * Gets the value of the isValid property. * */ public boolean isIsValid() { return isValid; } /** * Sets the value of the isValid property. * */ public void setIsValid(boolean value) { this.isValid = value; } }
[ "Rich@Rich-PC.Home" ]
Rich@Rich-PC.Home
37711cca733acf06cc570476216735199351d9e3
0681b0d22a454f06c4554d44c6fe186e17afed4c
/src/main/java/com/project/workshop/resources/exception/ResourceExceptionHandler.java
169a8e0fa89afcfc721751e49c111f72c03ae417
[]
no_license
nakamuraguti/project-spring-boot-mongo
949e2f9eb53f3f8bfc9ddb1bec1bdaf7d8100650
12d9149eeac0f7591461140c90f41856e43511e8
refs/heads/main
2023-04-07T00:45:48.867295
2021-04-11T04:35:08
2021-04-11T04:35:08
356,766,951
0
0
null
null
null
null
UTF-8
Java
false
false
859
java
package com.project.workshop.resources.exception; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import com.project.workshop.services.exception.ObjectNotFoundException; @ControllerAdvice public class ResourceExceptionHandler { @ExceptionHandler(ObjectNotFoundException.class) public ResponseEntity<StandardError> objectNotFound(ObjectNotFoundException e, HttpServletRequest request) { HttpStatus status = HttpStatus.NOT_FOUND; StandardError err = new StandardError(System.currentTimeMillis(), status.value(), "Não encontrado", e.getMessage(), request.getRequestURI()); return ResponseEntity.status(status).body(err); } }
[ "nakamuraguti@gmail.com" ]
nakamuraguti@gmail.com
c4d1e8585e4f84af3d30db3b96aab00118d91f92
3bec55c76c703bd021816ce7bb3294fdb5356599
/app/src/main/java/com/xiaolaogong/test/common/tools/IntentUtils.java
7418507be9b6e39a00053d6fbc4cdd02f56e3704
[]
no_license
xchechi123x/AndroidBegining
8f80c866d6fb3b9cb47ea4f2a2dfef453473721b
19c13b3481ad0369706facc553ea6d01ea3b3077
refs/heads/master
2021-07-19T12:34:58.588299
2017-12-07T16:34:04
2017-12-07T16:34:04
96,279,926
0
0
null
null
null
null
UTF-8
Java
false
false
743
java
package com.xiaolaogong.test.common.tools; import android.content.Context; import android.content.Intent; import android.net.Uri; /** * Created by chechi on 2017/8/27. */ public class IntentUtils { private IntentUtils() { throw new UnsupportedOperationException("This class cannot be instantiated, and its methods must be called directly."); } /** * 跳转到指定url * * @param context 当前上下文 * @param url 网址 */ public static void openUrl(Context context, String url) { Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }
[ "xchechi123x@yeah.net" ]
xchechi123x@yeah.net
cab68583a8ee4494689f9cf03d76d7d2b5b49bbf
5e1870af0822cbfb39fd215fb4a565deb7b89b90
/src/main/java/de/malkusch/whoisServerList/compiler/helper/existingDomain/AggregatedFinder.java
55a9eeada85dea98997a24476590cd7064828545
[ "WTFPL" ]
permissive
wendelas/whois-server-list-maven-plugin
679c48f40b278ef2233d70160d2053aa48e57d01
ae4a8725fd7712f8660e1e7a9c2445258913a231
refs/heads/master
2021-01-15T20:32:55.294081
2016-03-24T21:50:15
2016-03-24T21:50:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
782
java
package de.malkusch.whoisServerList.compiler.helper.existingDomain; import java.util.List; import java.util.Optional; import de.malkusch.whoisServerList.api.v1.model.domain.Domain; final class AggregatedFinder implements FindExistingDomainService { private final List<FindExistingDomainService> services; AggregatedFinder(List<FindExistingDomainService> services) { this.services = services; } @Override public Optional<String> findExistingDomainName(Domain domain) { for (FindExistingDomainService service : services) { Optional<String> existing = service.findExistingDomainName(domain); if (existing.isPresent()) { return existing; } } return Optional.empty(); } }
[ "markus@malkusch.de" ]
markus@malkusch.de
933425157ee3c66981a9ad5df7561ef6f98b372b
ca6599cdb9b295d44453ae9b55629fd0827a5ca6
/Construction Management/src/main/java/com/softsquare/application/common/hibernate/HibernateConfiguration.java
9e705ae45b8e8cb4bae786a688661d2f1bc038c4
[]
no_license
chaisa097/ConstructionProject
971986759d6b04d424edac11812f926f5dfa434d
5b48599d78e49bb0f6ecc177aa359340a0d26b61
refs/heads/master
2021-01-18T03:13:20.373933
2017-11-25T15:08:23
2017-11-25T15:08:23
85,839,672
0
0
null
2017-11-25T15:08:24
2017-03-22T14:45:36
JavaScript
UTF-8
Java
false
false
2,737
java
package com.softsquare.application.common.hibernate; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @PropertySource(value = { "classpath:application.properties" }) public class HibernateConfiguration { @Autowired private Environment environment; @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan(new String[] { "com.softsquare.application.entity" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean public DataSource dataSource() { Properties props = new Properties(); props.setProperty("useUnicode", "true"); props.setProperty("characterEncoding", "utf8"); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName")); dataSource.setUrl(environment.getRequiredProperty("jdbc.url")); dataSource.setUsername(environment.getRequiredProperty("jdbc.username")); dataSource.setPassword(environment.getRequiredProperty("jdbc.password")); dataSource.setConnectionProperties(props); return dataSource; } private Properties hibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect")); properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql")); properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql")); return properties; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory s) { HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(s); return txManager; } }
[ "chaisa097@chai" ]
chaisa097@chai
19461cb74fc6b23648e98dd1187f361444438b9c
6976c0417d0a271dc5ee02ced289eb453d964e8d
/app/src/main/java/com/tvacstudio/quizzapp/FirebaseRepository.java
448b4bfe1b09b2d334c9b6265e6483bae7186393
[]
no_license
januj170398/QuizApp
70e9c4af62da7f148f0dd8d9446b725a3899a338
2eac4f07677c757cfbc805dc1f6dc0b2c56ffe37
refs/heads/master
2022-12-19T00:12:06.187629
2020-09-21T06:46:40
2020-09-21T06:46:40
297,250,707
2
0
null
null
null
null
UTF-8
Java
false
false
1,522
java
package com.tvacstudio.quizzapp; import androidx.annotation.NonNull; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QuerySnapshot; import java.util.List; public class FirebaseRepository { private OnFirestoreTaskComplete onFirestoreTaskComplete; private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance(); private Query quizRef = firebaseFirestore.collection("QuizList").whereEqualTo("visibility", "public"); public FirebaseRepository(OnFirestoreTaskComplete onFirestoreTaskComplete) { this.onFirestoreTaskComplete = onFirestoreTaskComplete; } public void getQuizData() { quizRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ onFirestoreTaskComplete.quizListDataAdded(task.getResult().toObjects(QuizListModel.class)); } else { onFirestoreTaskComplete.onError(task.getException()); } } }); } public interface OnFirestoreTaskComplete { void quizListDataAdded(List<QuizListModel> quizListModelsList); void onError(Exception e); } }
[ "januj170398@gmail.com" ]
januj170398@gmail.com
f4d202af1c3bd64d851fbefb37327d1326767281
eaae18539fef63104faf926e88f4e39721cc313b
/src/Viedienikov/Practice 8.1/n1.java
ca0702f86d4fbe09dc0316c742ec6523cdc0a266
[]
no_license
anneteka/OKAlabs
e83977d9f58f93ce3c985584e45330b7d7d06b2b
44c1215cf90117ea15e8db0035adcab895a0a970
refs/heads/master
2020-04-09T15:10:40.869208
2018-12-20T22:05:53
2018-12-20T22:05:53
160,418,193
2
8
null
null
null
null
UTF-8
Java
false
false
1,307
java
import java.util.Arrays; import java.util.Scanner; public class n1 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); double k = s.nextInt(); M[] arr = new M[n]; for(int i = 0; i < n; i++) {arr[i] = new M(s.nextDouble(), s.nextDouble());} Arrays.sort(arr); for (int i = 0; i < n; i++) { System.out.println(arr[i].points+" "+arr[i].time); } double minP=0; double minTime=0; int j=0; for (int i = 0; i < n; i++) { minP+=arr[j].points; minTime+=arr[j].time; j++; if(minP>=k){ break; } } System.out.println(minTime); } } class M implements Comparable<M> { public double points, time, pointsPerTime; public M(double points, double time) { this.time = time; this.points = points; this.pointsPerTime = points/time; } @Override public int compareTo(M that) { if(this.pointsPerTime > that.pointsPerTime)return -1; if(this.pointsPerTime < that.pointsPerTime)return 1; if(this.time > that.time)return -1; if(this.time < that.time)return 1; return 0; } }
[ "a.karlysheva@ukma.edu.ua" ]
a.karlysheva@ukma.edu.ua
dbbbc59bc086905219eee0db2f302637431700b2
078673c205775c9b6559445cf0137eb9b9765f0e
/src/main/java/annoyaml/IEncryptor.java
865d8c5be94e0d4579df61966b4a8a93a7d710b6
[]
no_license
AnnoYAML/annoyaml
1c37f9eb6e296d107f7fa0e1cc4360a687d19255
a01c23714da370cd03493e811c820a375dd98727
refs/heads/master
2021-01-01T16:30:26.722545
2014-04-29T03:12:47
2014-04-29T03:12:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
91
java
package annoyaml; public interface IEncryptor { public String encrypt(String encrypt); }
[ "jesse.sightler@gmail.com" ]
jesse.sightler@gmail.com
bbe00ec7bc1139eb52beba4ea31d74ca0b3ecd87
e76b41bce2cfcc5baffdf681c4ecdce7f56e7fd5
/app/src/test/java/top/sogrey/httpprocesser/ExampleUnitTest.java
08ef0ebce7a05af09cad02d1e15431d7fd07ba7c
[ "MIT" ]
permissive
Sogrey/HttpProcessor
db0b51468c15d77ce56134cd055e7e06bfc66142
960a0c3b413d46aacd5c484b701739c4e4608bef
refs/heads/master
2020-04-06T16:49:32.974090
2019-04-29T03:33:03
2019-04-29T03:33:03
157,635,782
1
0
null
null
null
null
UTF-8
Java
false
false
402
java
package top.sogrey.httpprocesser; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "suzhaoheng2006@163.com" ]
suzhaoheng2006@163.com
b435ec1768c002369a95459e4d57c2be4ec119c7
65e98c214f8512264f5f33ba0f2dec3c0a6b06e5
/transfuse-api/src/main/java/org/androidtransfuse/listeners/ActivityOnTrackballEventListener.java
25ba5d7e6e59d94813eb2ca52c511fe5bd515482
[ "Apache-2.0" ]
permissive
histone/transfuse
46535168651de5fe60745b3557bba3a3b47fca20
d7b642db063cf8d9d64d06a1ea402a7aecbbe994
refs/heads/master
2021-01-15T20:49:04.801629
2013-02-02T03:11:38
2013-02-02T03:11:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,075
java
/** * Copyright 2013 John Ericksen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.androidtransfuse.listeners; import android.view.MotionEvent; /** * <p> * Defines the Activity onTrackballEvent() Call-Through method. Each defined method represents a method in the corresponding * Activity class.</p> * * <p>Only one Call-Through component per type may be defined per injection graph.</p> * * @author John Ericksen */ public interface ActivityOnTrackballEventListener { @CallThrough boolean onTrackballEvent(MotionEvent event); }
[ "johncarl81@gmail.com" ]
johncarl81@gmail.com
282d386af1feb86642f11a36a45fc36bf7c64861
20867282fea9e78c0671458b0b411ee67d6eeeeb
/api/de/bjoernthalheim/asterixpuzzle/deck/Deck.java
7a3fa872cd57a06bc7ed241c3961037079f2571d
[]
no_license
bjoern-thalheim/AsterixPuzzle
6188424bddb6a000fa23cd04744972dcc4ccd8d5
7ee3bd490a70004bad33ef2b61061619e4b7e33b
refs/heads/master
2021-01-22T09:20:30.468698
2013-03-09T11:20:44
2013-03-09T11:20:44
7,256,821
1
0
null
null
null
null
UTF-8
Java
false
false
758
java
package de.bjoernthalheim.asterixpuzzle.deck; import java.util.List; /** * The deck (a pile of) cards. You can put cards on the deck, take cards off and look at all cards of it. * * @author bjoern */ public interface Deck { /** * Show all the cards of the deck. * * @return All cards of the deck. */ public List<Card> getCards(); /** * Add a card to the deck. * * @param card * The card to be added to the deck. */ public void addCard(Card card); /** * Take a card from the deck. * * @param card * The card which will be taken from the deck. */ public void take(Card card); /** * Create a clone of this deck. * * @return a clone of this deck. */ public Deck defensiveCopy(); }
[ "bjoern.thalheim@gmx.de" ]
bjoern.thalheim@gmx.de
caaac904edbe5de1923d8c3ee40ca0ed42397e64
c39cd9a963aba24c7acd39163824057ff5e2942b
/src/Player/Player.java
21aeea53842412b4b6e00f83357b38274d663ddb
[]
no_license
sezermehmed0/pu-oop-project
af50ca2b7f1719ff03105fc502ffe2f122217e0d
ed32e66b8e43b141185aca265a6495f56268d5aa
refs/heads/main
2023-03-18T02:38:25.901014
2021-03-12T19:21:32
2021-03-12T19:21:32
345,376,064
0
0
null
null
null
null
UTF-8
Java
false
false
455
java
package Player; public class Player { int id; public boolean isActive; int figuresLost; public Player(int id,boolean isActive, int figuresLost) { this.id = id; this.isActive = isActive; this.figuresLost = figuresLost; } public int getFiguresLost() { return figuresLost; } public void setFiguresLost(int figuresLost) { this.figuresLost = figuresLost; } }
[ "noreply@github.com" ]
noreply@github.com
fe14c755711e38c7059e93b6c80fbaab06c049a4
000e9ddd9b77e93ccb8f1e38c1822951bba84fa9
/java/classes2/com/ziroom/ziroomcustomer/flux/b/a.java
8d53f7df053926f15ebce6510d97f35a6dfcfff2
[ "Apache-2.0" ]
permissive
Paladin1412/house
2bb7d591990c58bd7e8a9bf933481eb46901b3ed
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
refs/heads/master
2021-09-17T03:37:48.576781
2018-06-27T12:39:38
2018-06-27T12:41:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,313
java
package com.ziroom.ziroomcustomer.flux.b; import com.ziroom.ziroomcustomer.flux.c; public class a extends c { private String b; public a(Object paramObject) { super(paramObject); } public String getToastMsg() { return this.b; } public void onAction(com.ziroom.ziroomcustomer.flux.a parama) { String str = parama.getType(); int i = -1; switch (str.hashCode()) { } for (;;) { switch (i) { case 0: case 1: case 2: default: return; if (str.equals("type_show_loading")) { i = 0; continue; if (str.equals("type_dismiss_loading")) { i = 1; continue; if (str.equals("type_login")) { i = 2; continue; if (str.equals("type_toast")) { i = 3; } } } } break; } } this.b = ((String)parama.getData()); emitStoreChange(new com.ziroom.ziroomcustomer.flux.a.a(parama.getType(), this.a)); } } /* Location: /Users/gaoht/Downloads/zirom/classes2-dex2jar.jar!/com/ziroom/ziroomcustomer/flux/b/a.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
[ "ght163988@autonavi.com" ]
ght163988@autonavi.com
464e2c795973dbf946272663860dd93f5fb0defb
21bcd1da03415fec0a4f3fa7287f250df1d14051
/sources/com/facebook/internal/FetchedAppSettings.java
4fb3ebbe06a19136b46228435a7509350431737b
[]
no_license
lestseeandtest/Delivery
9a5cc96bd6bd2316a535271ec9ca3865080c3ec8
bc3fae8f30804a2520e6699df92c2e6a4a0a7cfc
refs/heads/master
2022-04-24T12:14:22.396398
2020-04-25T21:50:29
2020-04-25T21:50:29
258,875,870
0
1
null
null
null
null
UTF-8
Java
false
false
7,165
java
package com.facebook.internal; import android.net.Uri; import java.util.EnumSet; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; public final class FetchedAppSettings { private boolean IAPAutomaticLoggingEnabled; private boolean automaticLoggingEnabled; private boolean codelessEventsEnabled; private boolean customTabsEnabled; private Map<String, Map<String, DialogFeatureConfig>> dialogConfigMap; private FacebookRequestErrorClassification errorClassification; private JSONArray eventBindings; private String nuxContent; private boolean nuxEnabled; private String sdkUpdateMessage; private int sessionTimeoutInSeconds; private String smartLoginBookmarkIconURL; private String smartLoginMenuIconURL; private EnumSet<SmartLoginOption> smartLoginOptions; private boolean supportsImplicitLogging; private boolean trackUninstallEnabled; public static class DialogFeatureConfig { private static final String DIALOG_CONFIG_DIALOG_NAME_FEATURE_NAME_SEPARATOR = "\\|"; private static final String DIALOG_CONFIG_NAME_KEY = "name"; private static final String DIALOG_CONFIG_URL_KEY = "url"; private static final String DIALOG_CONFIG_VERSIONS_KEY = "versions"; private String dialogName; private Uri fallbackUrl; private String featureName; private int[] featureVersionSpec; private DialogFeatureConfig(String str, String str2, Uri uri, int[] iArr) { this.dialogName = str; this.featureName = str2; this.fallbackUrl = uri; this.featureVersionSpec = iArr; } public static DialogFeatureConfig parseDialogConfig(JSONObject jSONObject) { String optString = jSONObject.optString("name"); Uri uri = null; if (Utility.isNullOrEmpty(optString)) { return null; } String[] split = optString.split(DIALOG_CONFIG_DIALOG_NAME_FEATURE_NAME_SEPARATOR); if (split.length != 2) { return null; } String str = split[0]; String str2 = split[1]; if (Utility.isNullOrEmpty(str) || Utility.isNullOrEmpty(str2)) { return null; } String optString2 = jSONObject.optString("url"); if (!Utility.isNullOrEmpty(optString2)) { uri = Uri.parse(optString2); } return new DialogFeatureConfig(str, str2, uri, parseVersionSpec(jSONObject.optJSONArray(DIALOG_CONFIG_VERSIONS_KEY))); } private static int[] parseVersionSpec(JSONArray jSONArray) { if (jSONArray == null) { return null; } int length = jSONArray.length(); int[] iArr = new int[length]; for (int i = 0; i < length; i++) { int i2 = -1; int optInt = jSONArray.optInt(i, -1); if (optInt == -1) { String optString = jSONArray.optString(i); if (!Utility.isNullOrEmpty(optString)) { try { i2 = Integer.parseInt(optString); } catch (NumberFormatException e) { Utility.logd("FacebookSDK", (Exception) e); } iArr[i] = i2; } } i2 = optInt; iArr[i] = i2; } return iArr; } public String getDialogName() { return this.dialogName; } public Uri getFallbackUrl() { return this.fallbackUrl; } public String getFeatureName() { return this.featureName; } public int[] getVersionSpec() { return this.featureVersionSpec; } } public FetchedAppSettings(boolean z, String str, boolean z2, boolean z3, int i, EnumSet<SmartLoginOption> enumSet, Map<String, Map<String, DialogFeatureConfig>> map, boolean z4, FacebookRequestErrorClassification facebookRequestErrorClassification, String str2, String str3, boolean z5, boolean z6, JSONArray jSONArray, String str4, boolean z7) { this.supportsImplicitLogging = z; this.nuxContent = str; this.nuxEnabled = z2; this.customTabsEnabled = z3; this.dialogConfigMap = map; this.errorClassification = facebookRequestErrorClassification; this.sessionTimeoutInSeconds = i; this.automaticLoggingEnabled = z4; this.smartLoginOptions = enumSet; this.smartLoginBookmarkIconURL = str2; this.smartLoginMenuIconURL = str3; this.IAPAutomaticLoggingEnabled = z5; this.codelessEventsEnabled = z6; this.eventBindings = jSONArray; this.sdkUpdateMessage = str4; this.trackUninstallEnabled = z7; } public static DialogFeatureConfig getDialogFeatureConfig(String str, String str2, String str3) { if (!Utility.isNullOrEmpty(str2) && !Utility.isNullOrEmpty(str3)) { FetchedAppSettings appSettingsWithoutQuery = FetchedAppSettingsManager.getAppSettingsWithoutQuery(str); if (appSettingsWithoutQuery != null) { Map map = (Map) appSettingsWithoutQuery.getDialogConfigurations().get(str2); if (map != null) { return (DialogFeatureConfig) map.get(str3); } } } return null; } public boolean getAutomaticLoggingEnabled() { return this.automaticLoggingEnabled; } public boolean getCodelessEventsEnabled() { return this.codelessEventsEnabled; } public boolean getCustomTabsEnabled() { return this.customTabsEnabled; } public Map<String, Map<String, DialogFeatureConfig>> getDialogConfigurations() { return this.dialogConfigMap; } public FacebookRequestErrorClassification getErrorClassification() { return this.errorClassification; } public JSONArray getEventBindings() { return this.eventBindings; } public boolean getIAPAutomaticLoggingEnabled() { return this.IAPAutomaticLoggingEnabled; } public String getNuxContent() { return this.nuxContent; } public boolean getNuxEnabled() { return this.nuxEnabled; } public String getSdkUpdateMessage() { return this.sdkUpdateMessage; } public int getSessionTimeoutInSeconds() { return this.sessionTimeoutInSeconds; } public String getSmartLoginBookmarkIconURL() { return this.smartLoginBookmarkIconURL; } public String getSmartLoginMenuIconURL() { return this.smartLoginMenuIconURL; } public EnumSet<SmartLoginOption> getSmartLoginOptions() { return this.smartLoginOptions; } public boolean getTrackUninstallEnabled() { return this.trackUninstallEnabled; } public boolean supportsImplicitLogging() { return this.supportsImplicitLogging; } }
[ "zsolimana@uaedomain.local" ]
zsolimana@uaedomain.local
b059d5b1e02df69f0b7ee5c0c840e0ec21c5e596
35149878c5b0c382d21dbccb524df6ae64e9fe86
/src/main/java/lesson6/task2/generators/PhoneGenerator.java
7887825d2e6b3ce16b9345ac2330d734bf70995f
[]
no_license
MagomedovGadzhi/AutomatizationZero
0d7ad25ff3177aa4058d20d1b0f57a995528ea09
8ebc2bedadbaa54e3521f4844bc4c254380bcaa7
refs/heads/master
2023-07-30T07:02:04.504142
2021-09-16T17:14:20
2021-09-16T17:14:20
361,160,733
0
0
null
null
null
null
UTF-8
Java
false
false
469
java
package lesson6.task2.generators; import java.util.Random; public class PhoneGenerator { public static String generate() { String telefoneNumber = "+7("; for (int i = 0; i < 13; i++) { if (i == 3) telefoneNumber += ")"; else if (i == 7) telefoneNumber += "-"; else if (i == 10) telefoneNumber += "-"; else telefoneNumber += new Random().nextInt(10); } return telefoneNumber; } }
[ "Verhi41AVUg" ]
Verhi41AVUg
555c39324eb1f2dcec24bad54aa185911014fd83
3aa777a1fa7ed1b3ce4cb9b2f14c7934264f13d2
/src/com/kuntsevich/task8/validator/BookValidator.java
84f3275df1a99eec339ce4e5e603ad6b063e15eb
[]
no_license
themuks/jwd-task8
d4e712b3e907ef90e7f7efaae91f7bdd0c3cdfb6
da512e3d09667c1ceb3a61cdf5f15ea4a9eef81f
refs/heads/master
2022-11-27T02:36:25.273594
2020-07-28T17:54:18
2020-07-28T17:54:18
281,070,581
0
0
null
null
null
null
UTF-8
Java
false
false
1,671
java
package com.kuntsevich.task8.validator; import java.util.List; public class BookValidator { public static final int MIN_ID_VALUE = 0; public static final int MAX_ID_VALUE = 10000; public static final int MIN_TITLE_NAME_SIZE = 2; public static final int MAX_TITLE_NAME_SIZE = 200; public static final int MIN_GENRE_NAME_LENGTH = 3; public static final int MAX_GENRE_NAME_LENGTH = 30; public static final int MIN_AUTHOR_NAME_LENGTH = 2; public static final int MAX_AUTHOR_NAME_LENGTH = 400; public static final int MIN_PAGE_COUNT_VALUE = 20; public static final int MAX_PAGE_COUNT_VALUE = 10000; public boolean isIdValid(int id) { return MIN_ID_VALUE <= id && id <= MAX_ID_VALUE; } public boolean isTitleValid(String title) { if (title == null) { return false; } return MIN_TITLE_NAME_SIZE <= title.length() && title.length() <= MAX_TITLE_NAME_SIZE; } public boolean isGenreValid(String genre) { if (genre == null) { return false; } return MIN_GENRE_NAME_LENGTH <= genre.length() && genre.length() <= MAX_GENRE_NAME_LENGTH; } public boolean isPageCountValid(int pageCount) { return MIN_PAGE_COUNT_VALUE <= pageCount && pageCount <= MAX_PAGE_COUNT_VALUE; } public boolean isAuthorsValid(List<String> authors) { if (authors == null) { return false; } for (var author : authors) { if (MIN_AUTHOR_NAME_LENGTH > author.length() || author.length() > MAX_AUTHOR_NAME_LENGTH) { return false; } } return true; } }
[ "max-cun4@yandex.ru" ]
max-cun4@yandex.ru
2111ac02462df36e610c21fd00ff78211b00d735
818ce93d9ce2b3e908d82d6901d7372adc45cf6f
/java/br/com/jonas/salaoDeBeleza/dao/VendaDAO.java
b67bcdc18501fe7bda8ea859e5d4dacd4046a351
[]
no_license
JonasCostaGTI/SalaoDeBeleza
83d9c05327515c7922e34c1a920b07bd1571edf6
2cfd1d30d10fd447f6dee734ddbbf32789ed117c
refs/heads/master
2020-05-21T19:17:12.222748
2016-11-24T23:28:41
2016-11-24T23:28:41
65,505,599
0
0
null
null
null
null
UTF-8
Java
false
false
1,413
java
package br.com.jonas.salaoDeBeleza.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import br.com.jonas.salaoDeBeleza.domain.ItemVenda; import br.com.jonas.salaoDeBeleza.domain.Produto; import br.com.jonas.salaoDeBeleza.domain.Venda; import br.com.jonas.salaoDeBeleza.util.HibernateUtil; public class VendaDAO extends GenericDAO<Venda> { public void salvar(Venda venda, List<ItemVenda> itensVenda){ Session sessao = HibernateUtil.getFabricaDeSessoes().openSession(); Transaction transacao = null; try { transacao = sessao.beginTransaction(); sessao.save(venda); for (int i = 0; i < itensVenda.size(); i++) { ItemVenda itemVenda = itensVenda.get(i); itemVenda.setVenda(venda); sessao.save(itemVenda); Produto produto = itemVenda.getProduto(); int quantidade = produto.getQuantidade() - itemVenda.getQuantidade(); if(quantidade >= 0){ produto.setQuantidade(new Short((produto.getQuantidade() - itemVenda.getQuantidade()) + "")); sessao.update(produto); }else{ //joga este erro para a camada Bean throw new RuntimeException("Quantidade insuficiente em estoque"); } } transacao.commit(); } catch (RuntimeException erro) { if (transacao != null) { transacao.rollback(); } throw erro; } finally { sessao.close(); } } }
[ "jonas.costa@icloud.com" ]
jonas.costa@icloud.com
9f8443cddb9801d65f124c5ea585f34a4e11884f
6891eb2524b57128a17fd5bc0a0cfd0f485048c4
/src/com/mcxtzhang/ejchap4/ConstantInterfaceTest19.java
0e7d68fee70033cfba1676867e21b7639eac6f67
[ "MIT" ]
permissive
mcxtzhang/TJ-notes
d6a0594405ff5ffea0ea7b2c505300e47a25fe12
9454937b53403c70007ba9e0d32c3df61da8bac3
refs/heads/master
2020-05-23T08:01:53.213842
2019-01-22T09:39:44
2019-01-22T09:39:44
80,487,759
2
0
null
null
null
null
UTF-8
Java
false
false
748
java
package com.mcxtzhang.ejchap4; /** * Intro: 19 常量接口 是对接口的错误使用 * Author: zhangxutong * E-mail: mcxtzhang@163.com * Home Page: http://blog.csdn.net/zxt0601 * Created: 2017/4/13. * History: */ public class ConstantInterfaceTest19 { interface A { static final int FINAL_1 = 1; static final int FINAL_2 = 1; } static class B implements A { void method() { System.out.println(FINAL_1); } } static class C extends B { int FINAL_1 = 3; void methodInC() { System.out.println(FINAL_1); } } public static void main(String[] args) { C c = new C(); c.method(); c.methodInC(); } }
[ "zhangxutong@imcoming.cn" ]
zhangxutong@imcoming.cn
508cee1094481d2c8e420df77a1c2e6fb9b2ada6
86854be16ef8f7de1f7d2fbebf82919e0621feb9
/EstibalizAlvarez/src/com/ipartek/ejemplos/estibalizalvarez/dal/ProductosDALColeccion.java
5391058afaf9410c39a703d4f74eedc3fe6a6fd5
[]
no_license
EstibalizAlvarez/EjerciciosServlet
1fae320acc84be6bfee08735c9f38b4762368e9b
ae64e7dfe4c04edb4e032cae9d8041826a698cd6
refs/heads/master
2021-01-20T03:59:46.291253
2017-05-22T16:55:52
2017-05-22T16:55:52
89,617,115
0
0
null
null
null
null
UTF-8
Java
false
false
1,538
java
package com.ipartek.ejemplos.estibalizalvarez.dal; import java.util.HashMap; import java.util.Map; import com.ipartek.ejercicioproductos.Productos1; import com.ipartek.ejercicioproductos.Dal.ProductosDal; public class ProductosDALColeccion implements ProductosDal {// DalColeccion esta obligado a hacer la funciones de ProductosDal. // crear la coleccion (bolsa grande para meter varios productos)llamada productosColeccion: private Map<String, Productos1> productosColeccion = new HashMap<String, Productos1>(); @Override public void alta(Productos1 conjunto) { if (productosColeccion.containsKey(conjunto.getId()))// si en la coleccion"productosColeccion" del conjunto de metodos de "productosDal" el Id que me ponesya esixte: throw new ProductosYAExistenteDALException("El producto ya existe." + conjunto.getId());// sale este mensaje. // me falta esto de hacer. productosColeccion.put(conjunto.getId(), conjunto);// Indice: para el id(clave) de producto que me has metido y te doy toda la informacion. } @Override public void modificar(Productos1 conjunto) { // } @Override public void baja(Productos1 conjunto) { // } @Override public Productos1 buscarPorId(String id) { return productosColeccion.get(id); } @Override public Productos1[] buscarTodos() { // que todos los productos los meta en un array: return productosColeccion.values().toArray(new Productos1[productosColeccion.size()]);// y te mide lo que ocupa procutosColeccion. } }
[ "JAVA@PORT-Z14" ]
JAVA@PORT-Z14
085c057c37286abfd772dda84e419b39df1dcb98
4fca97fc583aeb34b41e21a5a35e7a5535483613
/service-provider/website-provider/src/main/java/cn/qyd/blogroom/website/ueditor/define/State.java
f7ada6dcb1b57b4ab7ad98cdf1f18c242db4b2c1
[]
no_license
qiuyunduo/blogroom
a1d5489bebb52bad61d92364c948e6d7be9bbbb2
3366430ae49824d8ebc9273f79e988b3affdb6f7
refs/heads/master
2022-06-24T16:03:25.089015
2020-04-23T17:56:30
2020-04-23T17:56:30
163,493,568
2
0
null
2022-06-21T03:12:37
2018-12-29T08:38:51
JavaScript
UTF-8
Java
false
false
216
java
package cn.qyd.blogroom.website.ueditor.define; public interface State { boolean isSuccess(); void putInfo(String var1, String var2); void putInfo(String var1, long var2); String toJSONString(); }
[ "qiuyunduo@m-chain.com" ]
qiuyunduo@m-chain.com
a649e87fee2ed932977f2522b552f1c5c38eff0a
02aa2b16ed7e971047421c848a535af01f80b96e
/src/main/java/depends/extractor/ruby/jruby/JRubyVisitor.java
5d39a596f66bb06c33d7d35972bc8fb1a2d43873
[ "MIT" ]
permissive
TiffanyLongjian/depends
eea29ed56feac3396e4c51567659a0af8942b85f
1e1fd70dfc0a05b97d5a41ea1dc407868397d722
refs/heads/master
2022-11-29T01:08:25.831347
2020-08-13T01:36:50
2020-08-13T01:36:50
288,176,665
1
0
MIT
2020-08-17T12:39:13
2020-08-17T12:39:12
null
UTF-8
Java
false
false
10,062
java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG 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 depends.extractor.ruby.jruby; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.ExecutorService; import org.jrubyparser.ast.AliasNode; import org.jrubyparser.ast.ArgumentNode; import org.jrubyparser.ast.ArrayNode; import org.jrubyparser.ast.CallNode; import org.jrubyparser.ast.ClassNode; import org.jrubyparser.ast.ClassVarAsgnNode; import org.jrubyparser.ast.ClassVarDeclNode; import org.jrubyparser.ast.ClassVarNode; import org.jrubyparser.ast.Colon2ConstNode; import org.jrubyparser.ast.Colon3Node; import org.jrubyparser.ast.ConstNode; import org.jrubyparser.ast.DAsgnNode; import org.jrubyparser.ast.DVarNode; import org.jrubyparser.ast.DefnNode; import org.jrubyparser.ast.DefsNode; import org.jrubyparser.ast.FCallNode; import org.jrubyparser.ast.GlobalAsgnNode; import org.jrubyparser.ast.GlobalVarNode; import org.jrubyparser.ast.IArgumentNode; import org.jrubyparser.ast.INameNode; import org.jrubyparser.ast.InstAsgnNode; import org.jrubyparser.ast.InstVarNode; import org.jrubyparser.ast.LocalAsgnNode; import org.jrubyparser.ast.LocalVarNode; import org.jrubyparser.ast.ModuleNode; import org.jrubyparser.ast.Node; import org.jrubyparser.ast.RootNode; import org.jrubyparser.ast.SelfNode; import org.jrubyparser.ast.StrNode; import org.jrubyparser.ast.SymbolNode; import org.jrubyparser.ast.UnaryCallNode; import org.jrubyparser.ast.VCallNode; import org.jrubyparser.util.NoopVisitor; import depends.entity.ContainerEntity; import depends.entity.Entity; import depends.entity.GenericName; import depends.entity.VarEntity; import depends.entity.repo.EntityRepo; import depends.extractor.ParserCreator; import depends.extractor.ruby.IncludedFileLocator; import depends.extractor.ruby.RubyHandlerContext; import depends.relations.Inferer; public class JRubyVisitor extends NoopVisitor { private RubyHandlerContext context; RubyParserHelper helper = RubyParserHelper.getInst(); private ExpressionUsage expressionUsage; public JRubyVisitor(String fileFullPath, EntityRepo entityRepo, IncludedFileLocator includedFileLocator, ExecutorService executorService, Inferer inferer, ParserCreator parserCreator) { this.context = new RubyHandlerContext(entityRepo, includedFileLocator, executorService, inferer, parserCreator); expressionUsage = new ExpressionUsage(context, entityRepo, helper, inferer); context.startFile(fileFullPath); } @Override public Object visitAliasNode(AliasNode node) { context.foundNewAlias(node.getNewNameString(), node.getOldNameString()); return super.visitAliasNode(node); } @Override public Object visitModuleNode(ModuleNode node) { String name = helper.getName(node.getCPath()); context.foundNamespace(name); super.visitModuleNode(node); context.exitLastedEntity(); return null; } @Override public Object visitClassNode(ClassNode node) { context.foundNewType(helper.getName(node.getCPath())); Node superNode = node.getSuper(); if (superNode instanceof ConstNode || superNode instanceof SymbolNode || superNode instanceof Colon2ConstNode || superNode instanceof Colon3Node) { String superName = helper.getName(superNode); context.foundExtends(superName); }else{ if (superNode != null) { System.err.println("cannot support the super node style" + superNode.toString()); } } super.visitClassNode(node); context.exitLastedEntity(); return null; } @Override public Object visitRootNode(RootNode node) { return super.visitRootNode(node); } @Override public Object visitFCallNode(FCallNode node) { String fname = helper.getName(node); Collection<String> params = getParams(node); context.processSpecialFuncCall(fname, params); return super.visitFCallNode(node); } private Collection<String> getParams(IArgumentNode node) { Node args = node.getArgs(); Collection<String> params = new ArrayList<>(); if (args instanceof ArrayNode) { ArrayNode argArray = (ArrayNode) args; for (Node arg : argArray.childNodes()) { if (arg instanceof StrNode) { params.add(((StrNode) arg).getValue()); } else if (arg instanceof ConstNode) { params.add(((ConstNode) arg).getName()); } } } return params; } @Override public Object visitCallNode(CallNode node) { String fname = helper.getName(node); Collection<String> params = getParams(node); addCallToReceiverVar(node, fname); context.processSpecialFuncCall(fname, params); return super.visitCallNode(node); } private void addCallToReceiverVar(CallNode node, String fname) { if (helper.isCommonOperator(fname))return; Node varNode = node.getReceiver(); GenericName varName = GenericName.build(helper.getName(varNode)); if (varName==null) return; Entity var = context.foundEntityWithName(varName); if (var != null && var instanceof VarEntity) { VarEntity varEntity = (VarEntity) var; varEntity.addFunctionCall(GenericName.build(fname)); } } @Override public Object visitUnaryCallNode(UnaryCallNode node) { String fname = helper.getName(node); Collection<String> params = new ArrayList<>(); context.processSpecialFuncCall(fname, params); return super.visitUnaryCallNode(node); } /** * VCallNode is just a function call without parameter */ @Override public Object visitVCallNode(VCallNode node) { return super.visitVCallNode(node); } @Override public Object visitDefnNode(DefnNode node) { context.foundMethodDeclarator(node.getName()); super.visitDefnNode(node); context.exitLastedEntity(); return null; } @Override public Object visitDefsNode(DefsNode node) { boolean handled = false; Node varNode = node.getReceiver(); if (varNode instanceof SelfNode) { //will be handled by context.foundMethodDeclarator(node.getName(), null, new ArrayList<>()); } else if (varNode instanceof ConstNode) { String className = ((INameNode) varNode).getName(); Entity entity = context.foundEntityWithName(GenericName.build(className)); if (entity != null && entity instanceof ContainerEntity) { context.foundMethodDeclarator(((ContainerEntity) entity), node.getName()); handled = true; } } else if (varNode instanceof INameNode) { String varName = ((INameNode) varNode).getName(); Entity var = context.foundEntityWithName(GenericName.build(varName)); if (var != null && var instanceof ContainerEntity) { context.foundMethodDeclarator(((ContainerEntity) var), node.getName()); handled = true; } } if (!handled) { // fallback to add it to last container context.foundMethodDeclarator(node.getName()); } super.visitDefsNode(node); context.exitLastedEntity(); return null; } @Override public Object visitGlobalVarNode(GlobalVarNode node) { context.foundVarDefinition(context.globalScope(), node.getName()); return super.visitGlobalVarNode(node); } @Override public Object visitInstVarNode(InstVarNode node) { context.foundVarDefinition(context.currentType(), node.getName()); return super.visitInstVarNode(node); } @Override public Object visitClassVarAsgnNode(ClassVarAsgnNode node) { context.foundVarDefinition(helper.getScopeOfVar(node,context), node.getName()); return super.visitClassVarAsgnNode(node); } @Override public Object visitClassVarDeclNode(ClassVarDeclNode node) { context.foundVarDefinition(context.currentType(), node.getName()); return super.visitClassVarDeclNode(node); } @Override public Object visitClassVarNode(ClassVarNode node) { context.foundVarDefinition(context.currentType(), node.getName()); return super.visitClassVarNode(node); } @Override public Object visitLocalVarNode(LocalVarNode node) { return super.visitLocalVarNode(node); } @Override public Object visitDVarNode(DVarNode node) { context.foundVarDefinition(context.lastContainer(), node.getName()); return super.visitDVarNode(node); } @Override public Object visitDAsgnNode(DAsgnNode node) { context.foundVarDefinition(helper.getScopeOfVar(node,context), node.getName()); return super.visitDAsgnNode(node); } @Override public Object visitGlobalAsgnNode(GlobalAsgnNode node) { context.foundVarDefinition(helper.getScopeOfVar(node,context), node.getName()); return super.visitGlobalAsgnNode(node); } @Override public Object visitInstAsgnNode(InstAsgnNode node) { context.foundVarDefinition(helper.getScopeOfVar(node,context), node.getName()); return super.visitInstAsgnNode(node); } @Override public Object visitArgumentNode(ArgumentNode node) { String paramName = node.getName(); context.addMethodParameter(paramName); return super.visitArgumentNode(node); } @Override public Object visitLocalAsgnNode(LocalAsgnNode node) { context.foundVarDefinition(helper.getScopeOfVar(node,context), node.getName()); return super.visitLocalAsgnNode(node); } @Override protected Object visit(Node node) { expressionUsage.foundExpression(node); return super.visit(node); } public void done() { context.done(); } }
[ "gangz@emergentdesign.cn" ]
gangz@emergentdesign.cn
0a1f3f8f097e0f08793bf4878b21849f6d762f6d
3f037202b1f3fb5d98c74b59db734e6d1eb50a5d
/JAVAReview Week1/2019.10.02/part03-control_statement/src/com/koreait/test/Test06.java
6654ab15805516d1a109d71aff8354e88ca89d64
[]
no_license
KLS13/yiseong
50f1876b306933e2539b43202bf9fd494a6084a6
8784212735cc12bf7318721fc0c765ed31290751
refs/heads/master
2020-07-17T22:29:29.304407
2020-04-23T13:55:46
2020-04-23T13:55:46
206,112,955
1
0
null
null
null
null
UHC
Java
false
false
592
java
//알파벳 하나 입력 --> 대문자는 소문자로, 소문자는 대문자로, 나머지는 그대로 package com.koreait.test; import java.util.Scanner; public class Test06 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("입력 : "); int str = input.nextLine().charAt(0); if(str >= 65 && str <=90) { System.out.println((char)(str+32)); }else if(str >=91 && str <=122) { System.out.println((char)(str-32)); }else { System.out.println((char)str); } input.close(); } }
[ "noreply@github.com" ]
noreply@github.com
fea67add083493c2522110642e7060cf2e436dbf
e40b85a61a04dfaeebcb212cdeb104041eb5713d
/dev/workspace/sistJavaStudy/src/date181120/TestFor10.java
54cabd3b71cc13ed8d8f366d0e6c2896753db047
[]
no_license
younggeun0/SSangYoung
d4e6081ac3ce8b69b725d89098d9d0a1ece4fded
1d00893c85004d2d3243cebb375ee754817649f5
refs/heads/master
2020-04-01T22:19:34.191490
2019-05-15T06:29:08
2019-05-15T06:29:08
153,702,136
1
0
null
2018-12-02T14:35:44
2018-10-18T23:58:55
Java
UHC
Java
false
false
994
java
package date181120; /** * 다양한 for 형태 * */ public class TestFor10 { public static void main(String[] args) { // 무한루프 /*for(;;) { System.out.println("무한루프"); }*/ // System.out.println("무한루프 다음코드"); // Unreachable code error발생 // 증가하는 수를 세는 무한 LOOP /*for (int i=0;;i++) { System.out.println("무한루프" + i); // 다중 for의 경우 break는 가장 가까이 있는 for만 나감 if (i==50) break; }*/ /*// 여러개의 초기값을 사용하는 for for(int i=0, j=10, k=30; i<10; i++, j++, k--) { System.out.println(i+" "+j+" "+k); }*/ /*// 조건식을 잘못 설정하면 무한루프 for(int i=0; i < 10; i--) { System.out.println("무한루프 " + i); }*/ // for문 뒤에 ;가 있는 경우 한번 실행됨 // for문 수행 후 sysout 한번 수행 /*int i = 0; for(i=0; i< 10; i++); { System.out.println("반복문"+i); }*/ } }
[ "34850791+younggeun0@users.noreply.github.com" ]
34850791+younggeun0@users.noreply.github.com
76777d50c8a8015275d02b6be88fda31c0497fbd
dc4123f422b4cbbdca4a07db961535270caebe66
/src/frc/team4951/subsystems/Intake.java
cacb04ce390c3f97626070d1c0443d04108f01f4
[]
no_license
4951Robotics/2018Robot
d612076628784ecc5ea47ceb716d3acb75b66db1
e41d4d509d3614963bcadb707a09d9ea593fb793
refs/heads/master
2020-04-01T22:26:01.918574
2018-10-19T01:16:47
2018-10-19T01:16:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,588
java
package frc.team4951.subsystems; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Spark; import edu.wpi.first.wpilibj.command.Subsystem; import frc.team4951.RobotMap; public class Intake extends Subsystem { // Motor controller running wheels private Spark wheels = new Spark(RobotMap.INTAKE_SPARK); // Motor controller running wrist joint private Spark wrist = new Spark(RobotMap.WRIST_SPARK); // Solenoid for piston private DoubleSolenoid solenoid = new DoubleSolenoid(RobotMap.SOLENOID_F, RobotMap.SOLENOID_R); // Speed for wheels private static final double IN_SPEED = 0.8; private static final double OUT_SPEED = -0.5; // Speed for wrist joint private static final double WRIST_SPEED = 0.6; private static Intake instance; public static Intake getInstance() { if (instance == null) instance = new Intake(); return instance; } public void in() {wheels.set(IN_SPEED);} public void out() {wheels.set(OUT_SPEED);} public void stop() {wheels.set(0);} public void open() {solenoid.set(DoubleSolenoid.Value.kForward);} public void close() {solenoid.set(DoubleSolenoid.Value.kReverse);} public void wristUp() {wrist.set(-WRIST_SPEED);} public void wristDown() {wrist.set(WRIST_SPEED);} public void wristStop() {wrist.set(0);} public boolean isOpen() {return solenoid.get() == DoubleSolenoid.Value.kForward;} public void initDefaultCommand() {} }
[ "cartermoore8@gmail.com" ]
cartermoore8@gmail.com
0f72ed0dd05eb641c485d47871ed299fcd770015
29c5c5d7225abe3ce068d4cc819803747c47b3e7
/test/wchar_tao_interop/jacorb/Client.java
dd149bb20bddc0f3b08a7274bdaec7e27c1d19ac
[]
no_license
wolfc/jacorb
308a770016586ce3e8f902507ba1bde295df78c1
40e0ec34c36fdcfe67b67a9ceba729e1d4581899
refs/heads/master
2020-05-02T12:50:56.097066
2010-05-25T22:23:05
2010-05-25T22:23:05
686,203
0
1
null
null
null
null
UTF-8
Java
false
false
1,752
java
import org.omg.CORBA.*; import java.io.*; /** * Client.java * * * Created: Mon Sep 3 19:28:34 2001 * * @author Nicolas Noffke * @version $Id: Client.java,v 1.2 2006-06-14 12:05:00 alphonse.bendt Exp $ */ public class Client { public static void main( String[] args ) throws Exception { if( args.length != 1 ) { System.out.println( "Usage: jaco Client <ior_file>" ); System.exit( 1 ); } File f = new File( args[ 0 ] ); //check if file exists if( ! f.exists() ) { System.out.println("File " + args[0] + " does not exist."); System.exit( -1 ); } //check if args[0] points to a directory if( f.isDirectory() ) { System.out.println("File " + args[0] + " is a directory."); System.exit( -1 ); } // initialize the ORB. org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init( args, null ); BufferedReader br = new BufferedReader( new FileReader( f )); // get object reference from command-line argument file org.omg.CORBA.Object obj = orb.string_to_object( br.readLine() ); br.close(); GoodDay gd = GoodDayHelper.narrow( obj ); System.out.println( "hello_simple(): " + gd.hello_simple()); System.out.println( "hello_wide(): " + gd.hello_wide( "daß dödelt und dödelt")); try { gd.test(); } catch( GoodDayPackage.WStringException wse ) { System.out.println("Exception: " + wse.why ); } } }// Client
[ "cdewolf@redhat.com" ]
cdewolf@redhat.com
b67931d0ae6ac4bea008725a31e6f9b64f067d70
d0bd4f949e38ae242ca3e5216b2c610ba5326776
/cayenne-dbsync/src/main/java/org/apache/cayenne/dbsync/merge/token/db/AddProcedureToDb.java
1481888e47491e136aa3ae0a156aa943037f1d8a
[ "Apache-2.0" ]
permissive
apache/cayenne
f6844e75807bd1db02e30d7e1ce3fdbb26296fb5
983c51cd1f322ccbaa0468afe693adf938c3c1fe
refs/heads/master
2023-08-31T03:09:20.919712
2023-08-23T19:32:01
2023-08-23T19:32:01
206,350
333
161
null
2023-08-09T12:43:35
2009-05-21T01:05:37
Java
UTF-8
Java
false
false
1,892
java
/***************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ****************************************************************/ package org.apache.cayenne.dbsync.merge.token.db; import java.util.List; import org.apache.cayenne.dba.DbAdapter; import org.apache.cayenne.dbsync.merge.factory.MergerTokenFactory; import org.apache.cayenne.dbsync.merge.token.MergerToken; import org.apache.cayenne.map.Procedure; /** * @since 4.2 */ public class AddProcedureToDb extends AbstractToDbToken { private Procedure procedure; public AddProcedureToDb(Procedure procedure) { super("Add procedure to db", 120); this.procedure = procedure; } @Override public List<String> createSql(DbAdapter adapter) { throw new UnsupportedOperationException("Can't generate SQL for procedure"); } @Override public String getTokenValue() { return procedure.getName(); } @Override public MergerToken createReverse(MergerTokenFactory factory) { return factory.createDropProcedureToModel(procedure); } }
[ "ancarseni@gmail.com" ]
ancarseni@gmail.com
020e48e296613e5823f21cd0ce60a297663fca0b
f9c5cbedbbcc3716d9e8315a7a1139d1052da7d8
/app/src/main/java/com/example/daksh/aero_trial/GPSTracker.java
09babfc3c568a6c6e9547f3d8584814faaf38672
[]
no_license
divynshh/AERO
d9296539f52b4d31e22a6385ea2d873ca74b8642
d9018ea5b32c538e1ca56750bb23313461c734ee
refs/heads/master
2022-02-12T08:26:17.990094
2022-01-23T14:16:15
2022-01-23T14:16:15
148,790,834
0
0
null
null
null
null
UTF-8
Java
false
false
6,432
java
package com.example.daksh.aero_trial; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.util.Log; public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status boolean isGPSEnabled = false; // flag for network status boolean isNetworkEnabled = false; // flag for GPS status boolean canGetLocation = false; Location location; // location double latitude; // latitude double longitude; // longitude // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters // The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute // Declaring a Location Manager protected LocationManager locationManager; public GPSTracker(Context context) { this.mContext = context; getLocation(); } public Location getLocation() { try { locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { // no network provider is enabled } else { this.canGetLocation = true; // First get location from Network Provider if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { e.printStackTrace(); } return location; } /** * Stop using GPS listener * Calling this function will stop using GPS in your app * */ public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GPSTracker.this); } } /** * Function to get latitude * */ public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } // return latitude return latitude; } /** * Function to get longitude * */ public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } // return longitude return longitude; } /** * Function to check GPS/wifi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog * On pressing Settings button will lauch Settings Options * */ public void showSettingsAlert(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); // Setting Dialog Title alertDialog.setTitle("GPS is settings"); // Setting Dialog Message alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); // On pressing Settings button alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(intent); } }); // on pressing cancel button alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } @Override public void onLocationChanged(Location location) { } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } }
[ "iamakshatchauhan@gmail.com" ]
iamakshatchauhan@gmail.com
1c4e54d458a0e7f4a94fb2701967f6850cd093da
796a7ac06c9bd747323b05d7b4194b479df7c862
/src/main/java/org/sense/flink/examples/stream/tpch/udf/LineItemSource.java
676e4983b84ff91b0d730a811e222616fa8497a9
[]
no_license
fafg/explore-flink
056a6f1f4ff1563c44d0be904c91d5ff5c85d2d6
c74d5cb906d6f1e48c68e95b4f1526b302636e23
refs/heads/master
2022-11-14T10:01:56.661153
2020-07-02T14:50:16
2020-07-02T14:50:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,416
java
package org.sense.flink.examples.stream.tpch.udf; import static org.sense.flink.util.MetricLabels.TPCH_DATA_LINE_ITEM; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.functions.source.RichSourceFunction; import org.sense.flink.examples.stream.tpch.pojo.LineItem; import org.sense.flink.util.DataRateListener; public class LineItemSource extends RichSourceFunction<LineItem> { private static final long serialVersionUID = 1L; public static final transient DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); private final String dataFilePath; private DataRateListener dataRateListener; private boolean running; private transient BufferedReader reader; private transient InputStream stream; public LineItemSource() { this(TPCH_DATA_LINE_ITEM); } public LineItemSource(String dataFilePath) { this.running = true; this.dataFilePath = dataFilePath; } @Override public void open(Configuration parameters) throws Exception { super.open(parameters); this.dataRateListener = new DataRateListener(); this.dataRateListener.start(); } @Override public void run(SourceContext<LineItem> sourceContext) throws Exception { while (running) { generateLineItemArray(sourceContext); } this.reader.close(); this.reader = null; this.stream.close(); this.stream = null; } private void generateLineItemArray(SourceContext<LineItem> sourceContext) { try { stream = new FileInputStream(dataFilePath); reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); String line; LineItem lineItem; long startTime; while (reader.ready() && (line = reader.readLine()) != null) { startTime = System.nanoTime(); lineItem = getLineItem(line); sourceContext.collectWithTimestamp(lineItem, getEventTime(lineItem)); // sleep in nanoseconds to have a reproducible data rate for the data source this.dataRateListener.busySleep(startTime); } } catch (FileNotFoundException e) { System.err.println("Please make sure they are available at [" + dataFilePath + "]."); System.err.println( " Follow the instructions at [https://docs.deistercloud.com/content/Databases.30/TPCH%20Benchmark.90/Data%20generation%20tool.30.xml?embedded=true] in order to download and create them."); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private LineItem getLineItem(String line) { String[] tokens = line.split("\\|"); if (tokens.length != 16) { throw new RuntimeException("Invalid record: " + line); } LineItem lineItem; try { long rowNumber = Long.parseLong(tokens[0]); long orderKey = Long.parseLong(tokens[1]); long partKey = Long.parseLong(tokens[2]); long supplierKey = Long.parseLong(tokens[2]); int lineNumber = Integer.parseInt(tokens[3]); long quantity = Long.parseLong(tokens[4]); long extendedPrice = (long) Double.parseDouble(tokens[5]); long discount = (long) Double.parseDouble(tokens[6]); long tax = (long) Double.parseDouble(tokens[7]); String returnFlag = tokens[8]; String status = tokens[9]; int shipDate = Integer.parseInt(tokens[10].replace("-", "")); int commitDate = Integer.parseInt(tokens[11].replace("-", "")); int receiptDate = Integer.parseInt(tokens[12].replace("-", "")); String shipInstructions = tokens[13]; String shipMode = tokens[14]; String comment = tokens[15]; lineItem = new LineItem(rowNumber, orderKey, partKey, supplierKey, lineNumber, quantity, extendedPrice, discount, tax, returnFlag, status, shipDate, commitDate, receiptDate, shipInstructions, shipMode, comment); } catch (NumberFormatException nfe) { throw new RuntimeException("Invalid record: " + line, nfe); } catch (Exception e) { throw new RuntimeException("Invalid record: " + line, e); } return lineItem; } public long getEventTime(LineItem value) { return value.getTimestamp(); } public List<LineItem> getLineItems() { String line = null; InputStream s = null; BufferedReader r = null; List<LineItem> lineItemsList = new ArrayList<LineItem>(); try { s = new FileInputStream(TPCH_DATA_LINE_ITEM); r = new BufferedReader(new InputStreamReader(s, StandardCharsets.UTF_8)); while (r.ready() && (line = r.readLine()) != null) { lineItemsList.add(getLineItem(line)); } } catch (NumberFormatException nfe) { throw new RuntimeException("Invalid record: " + line, nfe); } catch (Exception e) { throw new RuntimeException("Invalid record: " + line, e); } finally { } try { r.close(); r = null; s.close(); s = null; } catch (IOException e) { e.printStackTrace(); } return lineItemsList; } @Override public void cancel() { try { this.running = false; if (this.reader != null) { this.reader.close(); } if (this.stream != null) { this.stream.close(); } } catch (IOException ioe) { throw new RuntimeException("Could not cancel SourceFunction", ioe); } finally { this.reader = null; this.stream = null; } } }
[ "felipe.gutierrez@tu-berlin.de" ]
felipe.gutierrez@tu-berlin.de
6ce2fe9542febd569b06ebdd47432344d67b8476
f3e86482794a77ea9116f567c1b9e0abca98db69
/ecsite/src/com/internousdev/ecsite/action/package-info.java
e8a4612d6b1cc0dfc9ad77658cd26e4a146a7baa
[]
no_license
Fukudaharutaka/test
4e1066397bc58440882602c441cb243ed4e69e15
5e7ad1fe584c4b562ffd056d5311a83c58251299
refs/heads/master
2020-03-20T03:25:43.006361
2018-12-03T12:39:17
2018-12-03T12:39:17
137,145,859
0
0
null
null
null
null
UTF-8
Java
false
false
89
java
/** * */ /** * @author Little Busters! * */ package com.internousdev.ecsite.action;
[ "vqnraikko@yahoo.co.jp" ]
vqnraikko@yahoo.co.jp
4636ac4ff3dbc3f670e91168e2b14a52807aa373
795aee65d188ec90f963373ca14fba92d528cbc5
/src/main/java/ly/study/cy/config/BeanConfig.java
579625d78da97ad863836f4a1004395d327e1669
[]
no_license
liuyushihao123/springboot-DuGuYu
ef722ff41842184aa17a693747f1ca9ef6c1eb98
fb997bfa1f243287ac57abcb8bcd4c972c57ad96
refs/heads/master
2022-12-03T02:56:08.838912
2020-08-07T11:20:44
2020-08-07T11:20:44
285,802,017
1
0
null
null
null
null
UTF-8
Java
false
false
2,144
java
package ly.study.cy.config; import java.util.concurrent.CountDownLatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.listener.PatternTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import org.springframework.web.client.RestTemplate; import ly.study.cy.queue.Receiver; @Configuration public class BeanConfig { private static final Logger LOGGER = LoggerFactory.getLogger(BeanConfig.class); @Bean Receiver receiver(CountDownLatch latch) { return new Receiver(latch); } @Bean CountDownLatch latch() { return new CountDownLatch(1); } @Bean StringRedisTemplate template(RedisConnectionFactory connectionFactory) { return new StringRedisTemplate(connectionFactory); } @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(listenerAdapter, new PatternTopic("chat")); return container; } @Bean MessageListenerAdapter listenerAdapter(Receiver receiver) { return new MessageListenerAdapter(receiver, "receiveMessage"); } @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } @Bean public CommandLineRunner run(RestTemplate restTemplate) throws Exception { return args -> { String quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", String.class); LOGGER.info(quote.toString()); }; } }
[ "783148832@qq.com" ]
783148832@qq.com
66e8995beb77875b6dcb343de885022e141940aa
8ee71b460e6cd2d1098c9694bacfbfd00e2fb14e
/bootstrap-ui/src/main/java/com/dncomponents/bootstrap/client/autocomplete/multiselect/AutocompleteMultiSelectItemViewImpl.java
ddf272de617dfa572e87a4dc1d3b592cafa2a53f
[ "Apache-2.0" ]
permissive
dncomponents/dncomponents
359310dfa45fc408a5f024f251e28d991ee66d7b
acca539797b24ed55b6c04566f774003a8f04469
refs/heads/master
2023-07-08T16:06:12.918150
2023-07-03T07:55:32
2023-07-03T07:55:32
225,630,575
26
1
Apache-2.0
2023-03-26T12:23:45
2019-12-03T13:46:36
Java
UTF-8
Java
false
false
2,006
java
/* * Copyright 2023 dncomponents * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dncomponents.bootstrap.client.autocomplete.multiselect; import com.dncomponents.UiField; import com.dncomponents.client.components.core.HtmlBinder; import com.dncomponents.client.dom.handlers.ClickHandler; import com.dncomponents.client.views.MainViewSlots; import com.dncomponents.client.views.core.ui.autocomplete.multiselect.AutocompleteMultiSelectItemView; import elemental2.dom.HTMLElement; import elemental2.dom.HTMLTemplateElement; /** * @author nikolasavic */ public class AutocompleteMultiSelectItemViewImpl implements AutocompleteMultiSelectItemView { @UiField HTMLElement root; @UiField HTMLElement mainPanel; @UiField HTMLElement removeBtn; HtmlBinder uiBinder = HtmlBinder.create(AutocompleteMultiSelectItemViewImpl.class, this); public AutocompleteMultiSelectItemViewImpl(String template) { uiBinder.setTemplateContent(template); uiBinder.bind(); } public AutocompleteMultiSelectItemViewImpl(HTMLTemplateElement templateElement) { uiBinder.setTemplateElement(templateElement); uiBinder.bind(); } @Override public void addRemoveClickHandler(ClickHandler clickHandler) { clickHandler.addTo(removeBtn); } @Override public HTMLElement asElement() { return root; } @Override public MainViewSlots getViewSlots() { return () -> mainPanel; } }
[ "nikolasav@gmail.com" ]
nikolasav@gmail.com
94ea088292d2cc9bf10efe5b8da310b5043690aa
38a801324c4e4f85486f50513f18dc90551307e2
/src/main/java/je/backit/utils/Passwords.java
e2d8753228cc0acd02cdde467f0a95249bfd72f4
[]
no_license
atheedom/backit.je
184d70e3cad14e6b22c59fea63a83f31cf4e4136
fa64e85afa74f2ae84c095ff253fc69fcf549dc8
refs/heads/master
2020-04-14T14:01:18.012822
2015-03-15T12:05:26
2015-03-15T12:05:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,056
java
/* * Copyright 2014 Yann Le Tallec. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package je.backit.utils; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import java.util.Random; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; /** * A utility class to hash passwords and check passwords vs hashed values. It uses a combination of hashing and unique * salt. The algorithm used is PBKDF2WithHmacSHA1 which, although not the best for hashing password (vs. bcrypt) is * still considered robust and <a href="http://security.stackexchange.com/a/6415/12614"> recommended by NIST </a>. * The hashed value has 256 bits. */ public final class Passwords { private static final Random RANDOM = new SecureRandom(); private static final int ITERATIONS = 10000; private static final int KEY_LENGTH = 256; private Passwords() { } /** * Returns a random salt to be used to hash a password. * * @return a 16 bytes random salt */ public static byte[] getNextSalt() { byte[] salt = new byte[16]; RANDOM.nextBytes(salt); return salt; } /** * Returns a salted and hashed password using the provided hash.<br> * Note - side effect: the password is destroyed (the char[] is filled with zeros) * * @param password the password to be hashed * @param salt a 16 bytes salt, ideally obtained with the getNextSalt method * * @return the hashed password with a pinch of salt */ public static byte[] hash(char[] password, byte[] salt) { PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH); Arrays.fill(password, Character.MIN_VALUE); try { SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); return skf.generateSecret(spec).getEncoded(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new AssertionError("Error while hashing a password: " + e.getMessage(), e); } finally { spec.clearPassword(); } } /** * Returns true if the given password and salt match the hashed value, false otherwise.<br> * Note - side effect: the password is destroyed (the char[] is filled with zeros) * * @param password the password to check * @param salt the salt used to hash the password * @param expectedHash the expected hashed value of the password * * @return true if the given password and salt match the hashed value, false otherwise */ public static boolean isExpectedPassword(char[] password, byte[] salt, byte[] expectedHash) { byte[] pwdHash = hash(password, salt); Arrays.fill(password, Character.MIN_VALUE); if (pwdHash.length != expectedHash.length) return false; for (int i = 0; i < pwdHash.length; i++) { if (pwdHash[i] != expectedHash[i]) return false; } return true; } /** * Generates a random password of a given length, using letters and digits. * * @param length the length of the password * * @return a random password */ public static String generateRandomPassword(int length) { StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { int c = RANDOM.nextInt(62); if (c <= 9) { sb.append(String.valueOf(c)); } else if (c < 36) { sb.append((char) ('a' + c - 10)); } else { sb.append((char) ('A' + c - 36)); } } return sb.toString(); } }
[ "yann@assylias.com" ]
yann@assylias.com
010ee59725767edd8c6bf99c2ece9e9e5d7aeb27
221747493d21434b060a8d3db95ec01a15d5e156
/Java/ShopPro/src/service/impl/UserServiceImpl.java
7bde37a36e275f82a9e30ccb4cc2a10cd0367e8f
[]
no_license
CZY12/Java
cd8eb36acb4a4667daa8c53fcca98f07417aa48d
66f173651def9d3ba4cff1cc775b1aa5cd066163
refs/heads/master
2020-06-09T13:18:28.100658
2019-08-24T02:42:49
2019-08-24T02:42:49
193,443,596
1
0
null
null
null
null
UTF-8
Java
false
false
1,840
java
package service.impl; import dao.UserDao; import dao.impl.UserDaoImpl; import entity.Page; import entity.User; import service.UserService; import java.util.List; /** * @ClassName UserServiceImpl * @Description TODO * @Author czy61 * @Date 2019/8/10 16:42 * @Version 1.0 */ public class UserServiceImpl implements UserService { private UserDao userDao = new UserDaoImpl(); @Override public User checkUserNameExits(String username) { return userDao.checkUserExits(username); } @Override public int regist(User user) { return userDao.regist(user); } @Override public int modifeRegistInfo(User user) { return userDao.modifeRegistInfo(user); } @Override public User checkLogin(User user) { return userDao.checkLogin(user); } @Override public User backlogin(User user) { return userDao.checkBackLogin(user); } @Override public Page queryAllUserInfo(Page page) { int totalCount = userDao.getUserCount(); int totalPage = totalCount%page.getPageSize()==0?totalCount/page.getPageSize():totalCount/page.getPageSize()+1; List<User> list = userDao.getList((page.getCurrentPage()-1)*page.getPageSize(),page.getPageSize()); page.setTotalCount(totalCount); page.setTotalPage(totalPage); page.setList(list); return page; } @Override public int add(User user) { return userDao.add(user); } @Override public User findById(Integer id) { return userDao.findById(id); } @Override public void update(User user) { userDao.update(user); } @Override public void dongjie(Integer id) { userDao.dongjie(id); } @Override public void delete(Integer id) { userDao.delete(id); } }
[ "610175932@qq.com" ]
610175932@qq.com
d2521ab8ca8d4f22403d995b60481c0076e60fd6
bb0a5331f70165533db51b07b990a7d02d0b9c9d
/src/IC/Parser/Token.java
eb5f0c677669a0c6f43e58de1d1a86f2d33f4b88
[]
no_license
shaychoo/Compiler
080bf7a9df58b22e954301cc04f34901cfacad62
ed61befc9eba3b729b8a175b805d942109906977
refs/heads/master
2016-09-05T10:51:34.539701
2015-03-29T21:51:02
2015-03-29T21:51:02
32,567,432
0
0
null
null
null
null
UTF-8
Java
false
false
3,635
java
package IC.Parser; public class Token extends java_cup.runtime.Symbol { private int id; private int line; private int column; private String IDName; public Token(int id, int line) { super(id, null); this.id = id; this.line = line+1; } public Token(int id, int line,String value) { super(id, null); this.id = id; this.line = line +1; this.value = value; } public Token(int id, int line,int column, String value) { super(id,null); this.id = id; this.line = line +1; this.column = column; this.value = value; } public String toString() { return value + "\t" + getTag(this.id) +"\t"+ line + ":" + this.column; } public int getLine() { return line; } public int getVal() { return this.id; } public String getTokenValue () { return this.value.toString(); } public String getTag(int tagId) { switch (tagId) { case IC.Parser.sym.LP: return "LP"; case IC.Parser.sym.IF: return "IF"; case IC.Parser.sym.RP: return "RP"; case IC.Parser.sym.PLUS: return "PLUS"; case IC.Parser.sym.MINUS: return "MINUS"; case IC.Parser.sym.IDENT: return "IDENT"; case IC.Parser.sym.ASSIGN: return "ASSIGN"; case IC.Parser.sym.BOOLEAN: return "BOOLEAN"; case IC.Parser.sym.BREAK: return "BREAK"; case IC.Parser.sym.CLASS: return "CLASS"; case IC.Parser.sym.CLASS_ID: return "CLASS_ID"; case IC.Parser.sym.COMMA: return "COMMA"; case IC.Parser.sym.CONTINUE: return "CONTINUE"; case IC.Parser.sym.DIVIDE: return "DIVIDE"; case IC.Parser.sym.EQUAL: return "EQUAL"; case IC.Parser.sym.EXTENDS: return "EXTENDS"; case IC.Parser.sym.ELSE: return "ELSE"; case IC.Parser.sym.INT: return "INT"; case IC.Parser.sym.FALSE: return "FALSE"; case IC.Parser.sym.GT: return "GT"; case IC.Parser.sym.GTE: return "GTE"; case IC.Parser.sym.INTEGER: return "INTEGER"; case IC.Parser.sym.LAND: return "LAND"; case IC.Parser.sym.LB: return "LB"; case IC.Parser.sym.LCBR: return "LCBR"; case IC.Parser.sym.LENGTH: return "LENGTH"; case IC.Parser.sym.NEW: return "NEW"; case IC.Parser.sym.LNEG: return "LNEG"; case IC.Parser.sym.LOR: return "LOR"; case IC.Parser.sym.LT: return "LT"; case IC.Parser.sym.LTE: return "LTE"; case IC.Parser.sym.MOD: return "MOD"; case IC.Parser.sym.MULTIPLY: return "MULTIPLY"; case IC.Parser.sym.NEQUAL: return "NEQUAL"; case IC.Parser.sym.NULL: return "NULL"; case IC.Parser.sym.RB: return "RB"; case IC.Parser.sym.RCBR: return "RCBR"; case IC.Parser.sym.RETURN: return "RETURN"; case IC.Parser.sym.SEMI: return "SEMI"; case IC.Parser.sym.STRING: return "STRING"; case IC.Parser.sym.QUOTE: return "QUOTE"; case IC.Parser.sym.THIS: return "THIS"; case IC.Parser.sym.TRUE: return "TRUE"; case IC.Parser.sym.VOID: return "VOID"; case IC.Parser.sym.WHILE: return "WHILE"; case IC.Parser.sym.EOF: return "EOF"; case IC.Parser.sym.STATIC: return "STATIC"; case IC.Parser.sym.DOT: return "DOT"; default: return null; } } }
[ "shaytrjmn@gmail.com" ]
shaytrjmn@gmail.com
f52314bdb736054fa8cad3f9cd4602e2e5305339
265bc87527b654cd67279e6d39704b11795fd4f5
/src/main/java/com/example/spring/demo/person/PersonController.java
aed75c04465b74e7cc99df7112ede53910cc21ed
[]
no_license
drachno/Spring1
ff70c15d7d94443393649cd14356a4cbb826c03f
894ac300e3a65c2b2e87452515783d57b99075c9
refs/heads/main
2023-03-06T19:44:06.374051
2021-02-18T09:26:49
2021-02-18T09:26:49
339,168,041
0
1
null
null
null
null
UTF-8
Java
false
false
5,757
java
package com.example.spring.demo.person; import com.example.spring.demo.group.Group; import com.example.spring.demo.group.GroupService; import com.example.spring.demo.group.exception.GroupNotFoundException; import com.example.spring.demo.person.exception.PersonNotFoundException; import com.example.spring.demo.pet.Pet; import com.example.spring.demo.pet.PetService; import com.example.spring.demo.pet.exception.PetNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Collection; import java.util.List; import java.util.Set; @RestController @RequestMapping("api/persons") public class PersonController { PersonService personService; GroupService groupService; PetService petService; @Autowired public PersonController(PersonService personService, GroupService groupService, PetService petService) { this.personService = personService; this.groupService = groupService; this.petService = petService; } @GetMapping(produces = "application/json") public ResponseEntity<List<Person>> getPersons() { List<Person> list = personService.getAll(); return new ResponseEntity<List<Person>>(list, HttpStatus.OK); } @GetMapping(path = "/{pid}", produces = "application/json") public ResponseEntity<Person> getPersonByPid(@PathVariable("pid") Long pid) { Person person = personService.getById(pid); return new ResponseEntity<Person>(person, HttpStatus.OK); } @PostMapping(consumes = "application/json") public ResponseEntity<Void> addPerson(@RequestBody Person person) { personService.addPerson(person); return ResponseEntity.ok().build(); } @DeleteMapping("/{pid}") public ResponseEntity<Void> deletePerson(@PathVariable("pid") Long pid) { personService.deleteById(pid); return ResponseEntity.ok().build(); } @PutMapping(path = "/{pid}", consumes = "application/json") public ResponseEntity<Void> updatePerson(@RequestBody Person person, @PathVariable("pid") long pid) { personService.updatePerson(person, pid); return ResponseEntity.ok().build(); } @GetMapping("{pid}/groups") public ResponseEntity<Collection<Group>> getPersonGroups(@PathVariable("pid") Long pid) { try { Person person = personService.getById(pid); return new ResponseEntity<Collection<Group>>(person.getGroups(), HttpStatus.OK); } catch (PersonNotFoundException ex) { return ResponseEntity.notFound().build(); } } @PatchMapping("{pid}/groups/{id}") public ResponseEntity<?> setGroup(@PathVariable("pid") long pid, @PathVariable("id") long id) { try { Person person = personService.getById(pid); Group group = groupService.findById(id); Set<Group> groups = person.getGroups(); groups.add(group); person.setGroups(groups); personService.saveAndFlush(person); return ResponseEntity.ok().build(); } catch (GroupNotFoundException | PersonNotFoundException ex) { return ResponseEntity.notFound().build(); } } @DeleteMapping("{pid}/groups/{id}") public ResponseEntity<?> removeFromGroup(@PathVariable("pid") long pid, @PathVariable("id") long id) { try { Person person = personService.getById(pid); Group group = groupService.findById(id); Set<Group> groups = person.getGroups(); if (groups.contains(group)) { groups.remove(group); person.setGroups(groups); personService.saveAndFlush(person); } return ResponseEntity.ok().build(); } catch (GroupNotFoundException | PersonNotFoundException ex) { //log.error("setGroup", ex); return ResponseEntity.notFound().build(); } } @GetMapping("{pid}/pets") public ResponseEntity<Collection<Pet>> getPets(@PathVariable("pid") Long pid) { try { Person person = personService.getById(pid); return new ResponseEntity<Collection<Pet>>(person.getPets(), HttpStatus.OK); } catch (PetNotFoundException ex) { return ResponseEntity.notFound().build(); } } @PatchMapping("{pid}/pets/{id}") public ResponseEntity<?> setPet(@PathVariable("pid") long pid, @PathVariable("id") long id) { try { Person person = personService.getById(pid); Pet pet = petService.getById(id); Set<Pet> pets = person.getPets(); pets.add(pet); person.setPets(pets); personService.saveAndFlush(person); return ResponseEntity.ok().build(); } catch (PetNotFoundException | PersonNotFoundException ex) { return ResponseEntity.notFound().build(); } } @DeleteMapping("{pid}/pets/{id}") public ResponseEntity<?> removeFromPets(@PathVariable("pid") long pid, @PathVariable("id") long id) { try { Person person = personService.getById(pid); Pet pet = petService.getById(id); Set<Pet> pets = person.getPets(); if (pets.contains(pet)) { pets.remove(pet); person.setPets(pets); personService.saveAndFlush(person); } return ResponseEntity.ok().build(); } catch (PetNotFoundException | PersonNotFoundException ex) { return ResponseEntity.notFound().build(); } } }
[ "andrius.drachneris@gmail.com" ]
andrius.drachneris@gmail.com
f5e133dafc8211266923982551f08679635a8683
cff7e8d2c1f9073947d40b08c64c47d5e0f25278
/app/src/main/java/com/example/ertan/roomfinder/RequestHandler.java
9fe63eabdeff3ce2911399c5f72902cddb64e358
[]
no_license
ErtanS/RoomFinder
6db7706f8450eb99c989e69239d0394606000906
8a69c8bd60cb5e6454bfa8b79bf172b1c1644e32
refs/heads/master
2021-01-20T15:10:10.059707
2017-02-22T12:04:28
2017-02-22T12:04:28
82,799,645
0
0
null
null
null
null
UTF-8
Java
false
false
3,882
java
package com.example.ertan.roomfinder; import android.os.AsyncTask; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import javax.net.ssl.HttpsURLConnection; /** * The type Request handler. */ public class RequestHandler { private final HashMap<String, String> phpVars = new HashMap<>(); private String url = "http://192.168.0.52/smart/createLayout.php"; /** * Methode zum Senden von httpPostRequest * * @param requestURL URL zur Phpdatei * @param postDataParams Parameter hashmap * @return Rückgabe der Phpdatei */ private String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) { URL url; StringBuilder sb = new StringBuilder(); try { url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); String response; while ((response = br.readLine()) != null) { sb.append(response); } } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } /** * Verarbeitung der Übergabeparameter * * @param params Übergabeparameter * @return rückgabe der Phpdatei * @throws UnsupportedEncodingException Fehlerhandling */ private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } /** * Hinzufügen zusätzlicher Php Paramter * * @param key Php Identifikations String * @param value Wert */ private void addPhpVar(String key, String value) { phpVars.put(key, value); } public String transferData(String value) { addPhpVar("room", value); return sendPostRequest(); } private String sendPostRequest() { SelectAsyncPost s = new SelectAsyncPost(); try { return s.execute().get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return null; } private class SelectAsyncPost extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { return sendPostRequest(url, phpVars); } } }
[ "ertansamgam@gmail.com" ]
ertansamgam@gmail.com
d915fc86b1cd15a7af2aba872e72820f5cb91717
b73c10db211b833ed4e67dcd9e9a9bfa57dd8634
/src/a3/ProcesamientoImagen.java
fb1e2770b75bbba96387eca75b4f0453aaaf1535
[]
no_license
David7852/A3
ebddd0f994c73757fd90cb321f5ad18ad28dc24c
7c47c4e652b6af9d5665f92e77e3c1d91ef17647
refs/heads/master
2016-08-13T01:11:16.406047
2016-04-06T22:08:32
2016-04-06T22:08:32
55,643,670
0
0
null
null
null
null
UTF-8
Java
false
false
11,189
java
package a3; import java.awt.Color; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.filechooser.FileNameExtensionFilter; public class ProcesamientoImagen { //Imagen actual que se ha cargado public BufferedImage imgoriginal, imageActual; String Name,Format; public double entropyR() { double P[]=new double[256]; for(int i=0;i<256;i++) P[i]=0; for(int i = 0; i < imageActual.getWidth(); i++) for( int j = 0; j < imageActual.getHeight(); j++ ) { Color x=new Color(imageActual.getRGB(i, j)); int e=(int)x.getRed(); P[e]=(++P[e])/(imageActual.getWidth()*imageActual.getHeight()); } double H=0.0; for(int i=0;i<256;i++) if(P[i]!=0) H+=P[i]*(Math.log(1.0/P[i])/Math.log(2)); return H; } public double entropyG() { double P[]=new double[256]; for(int i=0;i<256;i++) P[i]=0; for(int i = 0; i < imageActual.getWidth(); i++) for( int j = 0; j < imageActual.getHeight(); j++ ) { Color x=new Color(imageActual.getRGB(i, j)); int e=(int)x.getGreen(); P[e]=(++P[e])/(imageActual.getWidth()*imageActual.getHeight()); } double H=0.0; for(int i=0;i<256;i++) if(P[i]!=0) H+=P[i]*(Math.log(1.0/P[i])/Math.log(2)); return H; } public double entropyB() { double P[]=new double[256]; for(int i=0;i<256;i++) P[i]=0; for(int i = 0; i < imageActual.getWidth(); i++) for( int j = 0; j < imageActual.getHeight(); j++ ) { Color x=new Color(imageActual.getRGB(i, j)); int e=(int)x.getBlue(); P[e]=(++P[e])/(imageActual.getWidth()*imageActual.getHeight()); } double H=0.0; for(int i=0;i<256;i++) if(P[i]!=0) H+=P[i]*(Math.log(1.0/P[i])/Math.log(2)); return H; } public double CCV(int M) { double Ex,Ey,Dx,Dy,Co,sum; Point px[]=new Point[M]; Point py[]=new Point[M]; Random r=new Random(); for(int i=0;i<M;i++) { int x=r.nextInt(imageActual.getWidth()), y=r.nextInt(imageActual.getHeight()-1); px[i]=new Point(x,y); py[i]=new Point(x,y+1); } sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(px[i].x, px[i].y)); sum+=(int)((c.getRed()+c.getGreen()+c.getBlue())/3); } Ex=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(py[i].x, py[i].y)); sum+=(int)((c.getRed()+c.getGreen()+c.getBlue())/3); } Ey=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(px[i].x, px[i].y)); sum+=Math.pow(((c.getRed()+c.getGreen()+c.getBlue())/3)-Ex,2); } Dx=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(py[i].x, py[i].y)); sum+=Math.pow(((c.getRed()+c.getGreen()+c.getBlue())/3)-Ey,2); } Dy=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color cy=new Color(imageActual.getRGB(py[i].x, py[i].y)); Color cx=new Color(imageActual.getRGB(px[i].x, px[i].y)); sum+=(((cx.getRed()+cx.getGreen()+cx.getBlue())/3)-Ex)*(((cy.getRed()+cy.getGreen()+cy.getBlue())/3)-Ey); } Co=(1.0/M)*sum; return Co/(Math.sqrt(Dx)*Math.sqrt(Dy)); } public double CCH(int M) { double Ex,Ey,Dx,Dy,Co,sum; Point px[]=new Point[M]; Point py[]=new Point[M]; Random r=new Random(); for(int i=0;i<M;i++) { int x=r.nextInt(imageActual.getWidth()-1), y=r.nextInt(imageActual.getHeight()); px[i]=new Point(x,y); py[i]=new Point(x+1,y); } sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(px[i].x, px[i].y)); sum+=(int)((c.getRed()+c.getGreen()+c.getBlue())/3); } Ex=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(py[i].x, py[i].y)); sum+=(int)((c.getRed()+c.getGreen()+c.getBlue())/3); } Ey=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(px[i].x, px[i].y)); sum+=Math.pow(((c.getRed()+c.getGreen()+c.getBlue())/3)-Ex,2); } Dx=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(py[i].x, py[i].y)); sum+=Math.pow(((c.getRed()+c.getGreen()+c.getBlue())/3)-Ey,2); } Dy=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color cy=new Color(imageActual.getRGB(py[i].x, py[i].y)); Color cx=new Color(imageActual.getRGB(px[i].x, px[i].y)); sum+=(((cx.getRed()+cx.getGreen()+cx.getBlue())/3)-Ex)*(((cy.getRed()+cy.getGreen()+cy.getBlue())/3)-Ey); } Co=(1.0/M)*sum; return Co/(Math.sqrt(Dx)*Math.sqrt(Dy)); } public double CCD(int M) { double Ex,Ey,Dx,Dy,Co,sum; Point px[]=new Point[M]; Point py[]=new Point[M]; Random r=new Random(); for(int i=0;i<M;i++) { int x=r.nextInt(imageActual.getWidth()-1), y=r.nextInt(imageActual.getHeight()-1); px[i]=new Point(x,y); py[i]=new Point(x+1,y+1); } sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(px[i].x, px[i].y)); sum+=(int)((c.getRed()+c.getGreen()+c.getBlue())/3); } Ex=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(py[i].x, py[i].y)); sum+=(int)((c.getRed()+c.getGreen()+c.getBlue())/3); } Ey=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(px[i].x, px[i].y)); sum+=Math.pow(((c.getRed()+c.getGreen()+c.getBlue())/3)-Ex,2); } Dx=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color c=new Color(imageActual.getRGB(py[i].x, py[i].y)); sum+=Math.pow(((c.getRed()+c.getGreen()+c.getBlue())/3)-Ey,2); } Dy=(1.0/M)*sum; sum=0; for(int i=0;i<M;i++) { Color cy=new Color(imageActual.getRGB(py[i].x, py[i].y)); Color cx=new Color(imageActual.getRGB(px[i].x, px[i].y)); sum+=(((cx.getRed()+cx.getGreen()+cx.getBlue())/3)-Ex)*(((cy.getRed()+cy.getGreen()+cy.getBlue())/3)-Ey); } Co=(1.0/M)*sum; return Co/(Math.sqrt(Dx)*Math.sqrt(Dy)); } public ProcesamientoImagen() { abrirImagen(); } public int getm() { return imageActual.getWidth(); } public int getn() { return imageActual.getHeight(); } public void abrirImagen() { //Creamos la variable que será devuelta (la creamos como null) BufferedImage bmp=null; //Creamos un nuevo cuadro de diálogo para seleccionar imagen JFileChooser selector=new JFileChooser(); //Le damos un título selector.setDialogTitle("Seleccione una imagen"); //Filtramos los tipos de archivos FileNameExtensionFilter filtroImagen = new FileNameExtensionFilter("JPG & GIF & BMP", "jpg", "gif", "bmp"); selector.setFileFilter(filtroImagen); //Abrimos el cuadro de diálog int flag=selector.showOpenDialog(null); //Comprobamos que pulse en aceptar if(flag==JFileChooser.APPROVE_OPTION) try { //Devuelve el fichero seleccionado File imagenSeleccionada=selector.getSelectedFile(); Name=imagenSeleccionada.getName(); Format=Name.substring(Name.lastIndexOf(".")+1); //Asignamos a la variable bmp la imagen leida bmp = ImageIO.read(imagenSeleccionada); }catch (Exception e){final JPanel panel = new JPanel();JOptionPane.showMessageDialog(panel, "Could not open file", "Error", JOptionPane.ERROR_MESSAGE);} //Asignamos la imagen cargada a la propiedad imageActual imageActual=bmp; } public Cell[][] cargarImagen() { Cell[][] C=new Cell[imageActual.getWidth()][imageActual.getHeight()]; for( int i = 0; i < imageActual.getWidth(); i++ ) for( int j = 0; j < imageActual.getHeight(); j++ ) C[i][j]=new Cell(new Color(imageActual.getRGB(i, j))); return C; } public void sobreEscribirImagen(Cell[][] C,int m,int n) throws IOException { File result=new File("./"+Name); for( int i = 0; i <m; i++ ) for( int j = 0; j <n; j++ ) { //Asignamos el nuevo valor al BufferedImage imageActual.setRGB(i, j,C[i][j].value.getRGB()); } ImageIO.write(imageActual, Format, result); Grafica.graficarhistograma(imageActual, Name); JOptionPane.showMessageDialog(null, "La entropia en los rojos es: "+entropyR()+"\r\n"+"La entropia en los verdes es: "+entropyG()+"\r\n"+"La entropia en los azules es: "+entropyB()); JOptionPane.showMessageDialog(null, "Coeficiente de corelacion vertical: "+CCV(3000)+"\r\n"+"Coeficiente de corelacion horizontal: "+CCH(3000)+"\r\n"+"Coeficiente de corelacion diagonal: "+CCD(3000)); } public void sobreEscribirImagen(Cell[][] C,int m,int n,String name) throws IOException { File result=new File("./"+name+"."+Format); for( int i = 0; i <m; i++ ) for( int j = 0; j <n; j++ ) { //Asignamos el nuevo valor al BufferedImage imageActual.setRGB(i, j,C[i][j].value.getRGB()); } ImageIO.write(imageActual, Format, result); Grafica.graficarhistograma(imageActual, Name); JOptionPane.showMessageDialog(null, "La entropia en los rojos es: "+entropyR()+"\r\n"+"La entropia en los verdes es: "+entropyG()+"\r\n"+"La entropia en los azules es: "+entropyB()); JOptionPane.showMessageDialog(null, "Coeficiente de corelacion vertical: "+CCV(3000)+"\r\n"+"Coeficiente de corelacion horizontal: "+CCH(3000)+"\r\n"+"Coeficiente de corelacion diagonal: "+CCD(3000)); } }
[ "dyd785265@hotmail.com" ]
dyd785265@hotmail.com
38be76fa68ce0036148dfb9f8803e444933b4202
bc2968aae05b40e0cf6887d558a3b4b611a3e5da
/src/com/wlz/dao/HouseDaoImpl.java
0f7959374ca1553894fab20dc0f037d03976df5c
[]
no_license
1026674574/xiaoquguanli
17d7beb105fc4b01d880b9ec8b7311d3b4850ade
9e56050f6834a3ac70f915fdec99e6168ac9ed72
refs/heads/master
2023-02-08T04:29:52.474295
2021-01-03T07:15:57
2021-01-03T07:15:57
322,760,132
0
0
null
null
null
null
UTF-8
Java
false
false
3,844
java
package com.wlz.dao; import com.wlz.dao.impl.HouseDao; import com.wlz.db.DBConnection; import com.wlz.model.House; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class HouseDaoImpl implements HouseDao { DBConnection db= new DBConnection(); @Override public House getHouse(int id) { House house = new House(); Connection connection = db.getConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { preparedStatement = connection.prepareStatement("select * from house where ho_id = ? "); preparedStatement.setInt(1,id); resultSet=preparedStatement.executeQuery(); if (resultSet.next()) { house.setHo_id(resultSet.getInt("ho_id")); house.setHo_dan(resultSet.getInt("ho_dan")); house.setHo_dong(resultSet.getInt("ho_dong")); house.setHo_hao(resultSet.getInt("ho_hao")); house.setHo_area(resultSet.getInt("ho_area")); house.setHo_state(resultSet.getInt("ho_state")); house.setHo_type(resultSet.getString("ho_type")); } resultSet.close(); preparedStatement.close(); connection.close(); return house; } catch (SQLException e) { e.printStackTrace(); } return null; } @Override public ArrayList<House> getList() { Connection connection = db.getConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; ArrayList<House> houses = new ArrayList<>(); try { preparedStatement = connection.prepareStatement("select * from house "); resultSet=preparedStatement.executeQuery(); while (resultSet.next()) { House house = new House(); house.setHo_id(resultSet.getInt("ho_id")); house.setHo_dan(resultSet.getInt("ho_dan")); house.setHo_dong(resultSet.getInt("ho_dong")); house.setHo_hao(resultSet.getInt("ho_hao")); house.setHo_area(resultSet.getInt("ho_area")); house.setHo_state(resultSet.getInt("ho_state")); house.setHo_type(resultSet.getString("ho_type")); houses.add(house); } resultSet.close(); preparedStatement.close(); connection.close(); return houses; } catch (SQLException e) { e.printStackTrace(); } return null; } @Override public void updateHouse(House house) { Connection connection = db.getConnection(); PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement("update house set ho_hao = ? , ho_dong = ?, ho_dan = ?, ho_area = ?,ho_state= ?,ho_type = ? WHERE ho_id = ?"); preparedStatement.setInt(1,house.getHo_hao()); preparedStatement.setInt(2,house.getHo_dong()); preparedStatement.setInt(3,house.getHo_dan()); preparedStatement.setInt(4,house.getHo_area()); preparedStatement.setInt(5,house.getHo_state()); preparedStatement.setString(6,house.getHo_type()); preparedStatement.setInt(7,house.getHo_id()); preparedStatement.executeUpdate(); preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } public void deleteHouse(int id){ } }
[ "1026674574@qq.com" ]
1026674574@qq.com
71162da9391861d30099dd7238588de72920d6d5
0d2f5d51e4c576b9c34dcb1477528960dfb51c51
/driver.java
0091f46b3c34a6c439a00ec7b78274322ff1a7ad
[]
no_license
kjaf/arrayClassJava
6a23d04b6aaa58a1152e00ffd8a6f9c9d9b2f6e2
4634e6607c2ffdb5bdcd22154107f5440a049908
refs/heads/master
2021-04-15T07:51:11.698934
2017-06-16T17:10:35
2017-06-16T17:10:35
94,565,122
0
0
null
null
null
null
UTF-8
Java
false
false
349
java
package ArrayClass; //import Array.java; public class driver { public static void main(String[] args){ Array array = new Array(5, 'b'); Array a = new Array(); a = a.setArrayEqual(array); a.resize(10); try{ char index = a.get(2); System.out.println(index); }catch(Exception e){ System.out.println(e); } } }
[ "kfetterm@iupui.edu" ]
kfetterm@iupui.edu
4796c9ed7dac6cd9d4f997ed4be5213dade275f7
e58aa29e079404cbf0b4a178135838acb65d58d6
/trunk/cwb/v2/src/main/java/lig/steamer/cwb/util/wsclient/overpass/exception/MalformedOverpassURLException.java
849c8a4e0d424e0c73df2a39e400947cada718f7
[]
no_license
anthonyhombiat/CWB
1a5f1a5991adc93607ae01126f9cf97948170f6c
ce5a8278cf3aecb202e3ed60babb992841d003fb
refs/heads/master
2021-01-01T03:53:08.816265
2015-03-03T10:24:27
2015-03-03T10:24:27
58,721,800
0
0
null
null
null
null
UTF-8
Java
false
false
295
java
package lig.steamer.cwb.util.wsclient.overpass.exception; public class MalformedOverpassURLException extends Exception { private static final long serialVersionUID = 1L; public MalformedOverpassURLException(Throwable e){ super("Malformed Overpass web service URL.", e); } }
[ "anthonyhombiat@51e108a9-9e07-433b-b235-c056ae316712" ]
anthonyhombiat@51e108a9-9e07-433b-b235-c056ae316712
0362c4e2c2ea0679c9f1aab67e88f0120ea3ecfb
3b0f58acd7c4e656d095a294801320c2ab111ca7
/src/es/uc3m/eda/bstree/bs/AvlTree.java
2093e2333d91dbbbf4f7f23063078e6b4c1d81fe
[]
no_license
kosmasK/RecordPlayer
982385a6ec24a616ca8b5056354f33340720d8ed
a7c6997160ab4adafde09e8ebe70043430d49c86
refs/heads/master
2021-01-23T11:20:17.323621
2012-05-09T22:32:05
2012-05-09T22:32:05
3,530,482
0
1
null
null
null
null
UTF-8
Java
false
false
5,454
java
package es.uc3m.eda.bstree.bs; public class AvlTree<K extends Comparable<K>, E> extends BsTree<K, E> { @Override public AvlNode<K, E> getRootNode() { return (AvlNode<K, E>) this.rootNode; } @Override public void add(K key, E elem) { this.rootNode = addRec((AvlNode<K, E>) this.rootNode, key, elem); } /* * Recursive AVL insertion, (deletion not implemented as AVL) */ private AvlNode<K, E> addRec(AvlNode<K, E> node, K key, E elem) { if (node == null) { AvlNode<K, E> newNode = new AvlNode<K, E>(key, elem); return newNode; } else { int cmp = key.compareTo(node.getKey()); if (cmp > 0) { node.rightNode = addRec(node.getRightNode(), key, elem); node.updateHeight(); node = balanceRight(node); } else if (cmp < 0) { node.leftNode = addRec(node.getLeftNode(), key, elem); node.updateHeight(); node = balanceLeft(node); } else { // throw new Exception("key already exists"); } return node; } } private AvlNode<K, E> balanceLeft(AvlNode<K, E> node) { AvlNode<K, E> leftNode = (AvlNode<K, E>) node.leftNode; AvlNode<K, E> rightNode = (AvlNode<K, E>) node.rightNode; int leftHeight = (leftNode == null) ? 0 : leftNode.height; int rightHeight = (rightNode == null) ? 0 : rightNode.height; if (leftHeight > rightHeight + 1) { AvlNode<K, E> leftLeftNode = (AvlNode<K, E>) leftNode.leftNode; AvlNode<K, E> leftRightNode = (AvlNode<K, E>) leftNode.rightNode; int leftLeftHeight = (leftLeftNode == null) ? 0 : leftLeftNode.height; int leftRightHeight = (leftRightNode == null) ? 0 : leftRightNode.height; if (leftLeftHeight > leftRightHeight) { node = balanceLeftLeft(node); } else { node = balanceLeftRight(node); } } return node; } private AvlNode<K, E> balanceRight(AvlNode<K, E> node) { AvlNode<K, E> leftNode = (AvlNode<K, E>) node.leftNode; AvlNode<K, E> rightNode = (AvlNode<K, E>) node.rightNode; int leftHeight = (leftNode == null) ? 0 : leftNode.height; int rightHeight = (rightNode == null) ? 0 : rightNode.height; if (rightHeight > leftHeight + 1) { AvlNode<K, E> rightLeftNode = (AvlNode<K, E>) rightNode.leftNode; AvlNode<K, E> rightRightRight = (AvlNode<K, E>) rightNode.rightNode; int rightLeftHeight = (rightLeftNode == null) ? 0 : rightLeftNode.height; int rightRightHeight = (rightRightRight == null) ? 0 : rightRightRight.height; if (rightLeftHeight > rightRightHeight) { node = balanceRightLeft(node); } else { node = balanceRightRight(node); } } return node; } private AvlNode<K, E> balanceLeftLeft(AvlNode<K, E> node) { AvlNode<K, E> node6 = node; AvlNode<K, E> node4 = (AvlNode<K, E>) node6.leftNode; AvlNode<K, E> node2 = (AvlNode<K, E>) node4.leftNode; AvlNode<K, E> node7 = (AvlNode<K, E>) node6.rightNode; AvlNode<K, E> node5 = (AvlNode<K, E>) node4.rightNode; AvlNode<K, E> node3 = (AvlNode<K, E>) node2.rightNode; AvlNode<K, E> node1 = (AvlNode<K, E>) node2.leftNode; node2.leftNode = node1; node2.rightNode = node3; node2.updateHeight(); node6.leftNode = node5; node6.rightNode = node7; node6.updateHeight(); node4.leftNode = node2; node4.rightNode = node6; node4.updateHeight(); return node4; } private AvlNode<K, E> balanceLeftRight(AvlNode<K, E> node) { AvlNode<K, E> node6 = node; AvlNode<K, E> node2 = (AvlNode<K, E>) node6.leftNode; AvlNode<K, E> node4 = (AvlNode<K, E>) node2.rightNode; AvlNode<K, E> node7 = (AvlNode<K, E>) node6.rightNode; AvlNode<K, E> node5 = (AvlNode<K, E>) node4.rightNode; AvlNode<K, E> node3 = (AvlNode<K, E>) node4.leftNode; AvlNode<K, E> node1 = (AvlNode<K, E>) node2.leftNode; node2.leftNode = node1; node2.rightNode = node3; node2.updateHeight(); node6.leftNode = node5; node6.rightNode = node7; node6.updateHeight(); node4.leftNode = node2; node4.rightNode = node6; node4.updateHeight(); return node4; } private AvlNode<K, E> balanceRightLeft(AvlNode<K, E> node) { AvlNode<K, E> node2 = node; AvlNode<K, E> node6 = (AvlNode<K, E>) node2.rightNode; AvlNode<K, E> node4 = (AvlNode<K, E>) node6.leftNode; AvlNode<K, E> node1 = (AvlNode<K, E>) node2.leftNode; AvlNode<K, E> node3 = (AvlNode<K, E>) node4.leftNode; AvlNode<K, E> node5 = (AvlNode<K, E>) node4.rightNode; AvlNode<K, E> node7 = (AvlNode<K, E>) node6.rightNode; node2.leftNode = node1; node2.rightNode = node3; node2.updateHeight(); node6.leftNode = node5; node6.rightNode = node7; node6.updateHeight(); node4.leftNode = node2; node4.rightNode = node6; node4.updateHeight(); return node4; } private AvlNode<K, E> balanceRightRight(AvlNode<K, E> node) { AvlNode<K, E> node2 = node; AvlNode<K, E> node4 = (AvlNode<K, E>) node2.rightNode; AvlNode<K, E> node6 = (AvlNode<K, E>) node4.rightNode; AvlNode<K, E> node1 = (AvlNode<K, E>) node2.leftNode; AvlNode<K, E> node3 = (AvlNode<K, E>) node4.leftNode; AvlNode<K, E> node5 = (AvlNode<K, E>) node6.leftNode; AvlNode<K, E> node7 = (AvlNode<K, E>) node6.rightNode; node2.leftNode = node1; node2.rightNode = node3; node2.updateHeight(); node6.leftNode = node5; node6.rightNode = node7; node6.updateHeight(); node4.leftNode = node2; node4.rightNode = node6; node4.updateHeight(); return node4; } }
[ "kosmas.kritsis@gmail.com" ]
kosmas.kritsis@gmail.com
3839546b0ace5ade4a92516744974be6e5468971
a77f13e3163ae097574b84578600bcc957094778
/src/com/xocs/ap/relaties/Klant.java
27b0d65bcf1686f3cf2488956279af4bae75e205
[]
no_license
robertxocs/hu_ap_voorbeelden
0c183e7a7253ba616be9fb30d305c56cd23ed795
ca7195f4fc34be769b506b830db9c019dedc5cf7
refs/heads/main
2023-04-29T13:43:10.527071
2021-05-17T12:13:38
2021-05-17T12:13:38
356,585,891
0
2
null
null
null
null
UTF-8
Java
false
false
667
java
package com.xocs.ap.relaties; import java.util.HashMap; import java.util.Map; public class Klant { private Map<String,Rekening> rekeningen = new HashMap<>(); public void addRekening(Rekening rekening) { rekeningen.put(rekening.getId(),rekening); } public double getTotaalSaldo() { return rekeningen.values().stream() .mapToDouble(r -> r.getSaldo()) .sum(); } public int getAantalRekeningen() { return rekeningen.size(); } public double getSaldo(String rekeningId) { return rekeningen.containsKey(rekeningId) ? rekeningen.get(rekeningId).getSaldo() : 0.0; } }
[ "robert@xocs.com" ]
robert@xocs.com
4db0b0b334d9a44bbb854c99ca62f8ce32dec64a
78479864badf6f2bc7c5abeb2412c73b7113bda2
/plugin/topologychannels/TopologyEditor.java
1fd4b28769bee1bea2dfcbda29a9ee62ab439cb7
[]
no_license
remenska/Charmy
8784bb2101a12badb25b44cddc0b9cb11769ec6d
d77092c6637127166a2eecab13b6430316cc89e7
refs/heads/master
2020-06-04T11:34:18.392901
2013-07-18T19:21:48
2013-07-18T19:21:48
null
0
0
null
null
null
null
ISO-8859-1
Java
false
false
33,809
java
/* Charmy (CHecking Architectural Model consistencY) * Copyright (C) 2004 Patrizio Pelliccione <pellicci@di.univaq.it>, * Henry Muccini <muccini@di.univaq.it>, Paola Inverardi <inverard@di.univaq.it>. * Computer Science Department, University of L'Aquila. SEA Group. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package plugin.topologychannels; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Stroke; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.geom.Rectangle2D; import java.util.LinkedList; import java.util.Vector; import javax.swing.JPanel; import plugin.charmyui.extensionpoint.editor.GenericHostEditor; import plugin.topologychannels.data.ElementoCanale; import plugin.topologychannels.data.ElementoProcesso; import plugin.topologychannels.data.ListaCanale; import plugin.topologychannels.data.ListaProcesso; import plugin.topologychannels.data.PlugData; import plugin.topologychannels.dialog.FinestraElementoBoxTesto; import plugin.topologychannels.dialog.FinestraGraficoLinkTopology; import plugin.topologychannels.dialog.FinestraGraphEditor; import plugin.topologychannels.general.edcp.CopyCutPasteTopology; import plugin.topologychannels.general.undo.UndoRedoTopology; import plugin.topologychannels.resource.utility.ListMovedObjects; import core.internal.plugin.file.FileManager; import core.internal.ui.PlugDataWin; import core.resources.jpeg.JpegImage; /** Classe per la creazione e gestione del pannello su cui verrà disegnato il S_A_ Topology Diagram_ La classe controlla gli eventi del mouse (clicked, released, dragged), esegue le classiche operazioni di editing (del, copy, paste, undo) e di zoom, implementa le operazioni associate ai pulsanti della TopologyToolBar, etc. */ public class TopologyEditor extends GenericHostEditor{ public FileManager fileManager; /** Numero di Processi. */ private long numProcessi; private int spiazzamentoX = 0, spiazzamentoY = 0; /** Costante per lo stato di attesa dell'input dell'utente. */ public static final int ATTESA = 0; /** Costante per lo stato in cui l'utente sta introducendo un nuovo processo. */ public static final int DISEGNA_PROCESSO = 1; /** Costante per lo stato in cui l'utente sta inserendo un nuovo canale di comunicazione tra processi. */ public static final int INSERIMENTO_CANALE = 2; /** Costante per lo stato in cui si sta tracciando una linea relativa ad un canale di collegamento. */ public static final int DISEGNA_CANALE = 3; /** Costante per lo stato in cui l'utente sta spostando un processo. */ public static final int SPOSTA_PROCESSO = 4; /** Costante per lo stato in cui l'utente seleziona più oggetti tramite trascinamento del mouse. */ public static final int MULTISELEZIONE = 5; /** Costante per lo stato in cui l'utente sposta più oggetti_ Ci sono tre modi per attivare questo stato: 1) Rilascio mouse nello stato MULTISELEZIONE; 2) Trascinamento del mouse con pressione del tasto "MAIUSC" nello stato ATTESA; 3) Operazione di paste. */ public static final int SPOSTA_MULTISELEZIONE = 6; /** Costante per lo stato in cui l'utente ha già iniziato l'operazione di spostamento di più oggetti_ Questo stato viene attivato solo tramite trascinamento del mouse nello stato SPOSTA_MULTISELEZIONE. */ public static final int SPOSTA_MULTISELEZIONE_FASE2 = 7; public static final int TEMPATTESA = 8; /** Riferimento alla toolbar. */ //private TopologyToolBar localTopologyToolBar; /** Riferimento alla toolbar. */ //private EditToolBar localEditToolBar; /** Lista dei processi disegnati. */ private ListaProcesso ListaDeiProcessi; /** Lista dei canali disegnati. */ private ListaCanale ListaDeiCanali; /** Riferimento al processo corrente.*/ private ElementoProcesso ProcessoCorrente; /** Processo di partenza nell'operazione di inserimento di un nuovo canale. */ private ElementoProcesso ProcessFrom; /** Processo di arrivo nell'operazione di inserimento di un nuovo canale. */ private ElementoProcesso ProcessTo; /** Riferimento al canale corrente.*/ private ElementoCanale CanaleCorrente; /** Memorizza lo stato dell'editor (ATTESA, DISEGNA_PROCESSO, INSERIMENTO_CANALE, DISEGNA_CANALE, SPOSTA_PROCESSO, etc.) */ private int ClassEditorStatus = ATTESA; /** Memorizza il tipo di processo per una successiva operazione di inserimento. */ private int TipoProcesso = 0; /** Memorizza se il processo è di tipo dummy per una successiva operazione di inserimento. */ private boolean ctrlDummy; /** Assume il valore 'true' quando uno dei pulsanti di inserimento processo (PROCESS, STORE, DUMMY) o quello di inserimento canale risulta bloccato. */ private boolean BloccoPulsante = false; /** Finestra di dialogo per impostare le proprietà di un processo. */ private FinestraElementoBoxTesto FinestraProprietaProcesso; /** Finestra di dialogo per impostare le proprietà di un canale. */ private FinestraGraficoLinkTopology FinestraProprietaCanale; /** Finestra di dialogo per impostare le proprietà dell'editor. */ private FinestraGraphEditor FinestraProprietaEditor; /** Necessaria per l'implementazione. */ private Graphics2D g2; /** Utilizzata per le operazioni di copy e paste su processi. */ private LinkedList tmpListaProcessi = null; /** Utilizzata per le operazioni di copy e paste su canali. */ private LinkedList tmpListaCanali = null; /** Utilizzata per memorizzare la lista dei processi nelle operazioni interessate da multiselezione_ Forse potrebbe essere eliminata, riutilizzando tmpListaProcessi. */ private ListMovedObjects spostaListaProcessi = null; /** Riferimento all'editor del S_A_ Topology Diagram, ovvero alla classe stessa_ E' usato all'interno delle classi nidificate ClassEditorClickAdapter e ClassEditorMotionAdapter. */ private TopologyEditor rifEditor; /** Punto di partenza in un'operazione di multiselezione tramite trascinamento del mouse. */ private Point startPoint; /** Punto di arrivo in un'operazione di multiselezione tramite trascinamento del mouse. */ private Point endPoint; /** Punto di posizionamento del mouse nello spostamento contemporaneo di più oggetti. */ private Point trackPoint; /** Punto di riferimento per lo spostamento contemporaneo di più oggetti. */ private Point rifPoint; /** Rettangolo visualizzato durante un'operazione di trascinamento del mouse nello stato MULTISELEZIONE. */ private Rectangle2D rectMultiSelection = null; /** Memorizza il più piccolo rettangolo contenente tutti i processi selezionati (multiselezione). */ private Rectangle2D externalRect = null; /** * riferimenti alle finestre principali del programme */ private PlugDataWin plugDataWin; /** * riferimento alla struttura dati del programma */ private PlugData plugData; /** * riferimento alla TopologyWindow */ private TopologyWindow topologyWindow; /** * riferimento al sistema di undo redo */ private UndoRedoTopology undoRedoManager; private CopyCutPasteTopology ccpTopology; /** Costruttore_ Prende in ingresso un riferimento alla barra di stato. */ public TopologyEditor() { super(null); /* plugDataWin = pdw; plugData = (PlugData)pd; topologyWindow = tw; addMouseListener(new ClassEditorClickAdapter()); addMouseMotionListener(new ClassEditorMotionAdapter()); ListaDeiProcessi = plugData.getListaProcesso(); ListaDeiCanali = plugData.getListaCanale(); undoRedoManager = new UndoRedoTopology(); undoRedoManager.setDati(plugDataWin, plugData); rifEditor = this; ccpTopology = new CopyCutPasteTopology(plugData);*/ } public void setDati(TopologyWindow tw, PlugDataWin pdw, PlugData pd){ this.fileManager=pdw.getFileManager(); plugDataWin = pdw; plugData = (PlugData)pd; topologyWindow = tw; addMouseListener(new ClassEditorClickAdapter()); addMouseMotionListener(new ClassEditorMotionAdapter()); ListaDeiProcessi = plugData.getListaProcesso(); ListaDeiCanali = plugData.getListaCanale(); undoRedoManager = new UndoRedoTopology(); undoRedoManager.setDati(plugDataWin, plugData); rifEditor = this; ccpTopology = new CopyCutPasteTopology(plugData); } public PlugData getPlugData(){ return plugData; } /** Imposta il riferimento alle toolbar. */ /*public void setToolBar(TopologyToolBar ctbar) { localTopologyToolBar = ctbar; localEditToolBar = plugDataWin.getEditToolBar(); localEditToolBar.setButtonEnabled("Copy", true); localEditToolBar.setButtonEnabled("Paste", true); localEditToolBar.setButtonEnabled("Del", true); localEditToolBar.setButtonEnabled("Cut", true); localEditToolBar.setButtonEnabled("Undo", true); localEditToolBar.setButtonEnabled("Redo", true); }*/ /** Restituisce lo stato dell'editor. */ public int getEditorStatus() { return ClassEditorStatus; } /** Imposta lo stato dell'editor_ Si osservi che solo alcuni stati possono essere assegnati dall'esterno: DISEGNA_PROCESSO, INSERIMENTO_CANALE, DISEGNA_CANALE. */ public void setEditorStatus( int j, int tipoprc, boolean isDummy, boolean ctrlpulsante) { BloccoPulsante = ctrlpulsante; TipoProcesso = tipoprc; ctrlDummy = isDummy; switch (j) { case DISEGNA_PROCESSO : ClassEditorStatus = DISEGNA_PROCESSO; break; case INSERIMENTO_CANALE : ClassEditorStatus = INSERIMENTO_CANALE; break; case DISEGNA_CANALE : ClassEditorStatus = DISEGNA_CANALE; break; default : ClassEditorStatus = ATTESA; break; } } /** "Stampa" l'editor con processi e canali. */ public void paintComponent(Graphics g) { super.paintComponent(g); g2 = (Graphics2D) g; g2.scale(scaleX, scaleY); Stroke tmpstroke = g2.getStroke(); g2.setStroke(bstroke); g2.draw(rettangolo); g2.setStroke(tmpstroke); if (rectMultiSelection != null) { g2.draw(rectMultiSelection); } ListaDeiCanali.paintLista(g2); ListaDeiProcessi.paintLista(g2); } /** Classe per la gestione della pressione dei tasti del mouse. */ private final class ClassEditorClickAdapter extends MouseAdapter { /** Rilascio del mouse. */ public void mouseReleased(MouseEvent e) { if (rettangolo.contains(updateGetPoint(e.getPoint()))) { switch (ClassEditorStatus) { case DISEGNA_PROCESSO : ListaDeiProcessi.noSelected(); ListaDeiCanali.noSelected(); ProcessoCorrente = new ElementoProcesso( updateGetPoint(e.getPoint()), ElementoProcesso.GLOBALE, TipoProcesso, ctrlDummy, "process" + (ElementoProcesso.getNumIstanze() + 1)); // Aggiornamento della barra di stato. plugDataWin.getStatusBar().setText( "Process " + ProcessoCorrente.getName() + " inserted."); if (!BloccoPulsante) { ClassEditorStatus = TEMPATTESA; rifEditor.setAllButtonNoPressed(); } ListaDeiProcessi.addElement(ProcessoCorrente); repaint(); //plugDataWin.getFileManager().setModificata(true); //core.internal.plugin.file.FileManager.setModificata(true); fileManager.setChangeWorkset(TopologyWindow.idPluginFileCharmy,true); break; case INSERIMENTO_CANALE : // Selezionato solo il processo di partenza del nuovo canale. ListaDeiCanali.noSelected(); ListaDeiProcessi.noSelected(); ProcessFrom = (ElementoProcesso) (ListaDeiProcessi .getElement(updateGetPoint(e.getPoint()))); if (ProcessFrom != null) { plugDataWin.getStatusBar().setText( "Process " + ProcessFrom.getName() + " selected." + " Click over another process to insert a channel."); ProcessFrom.setSelected(true); ClassEditorStatus = DISEGNA_CANALE; } repaint(); break; case DISEGNA_CANALE : // Creazione ed inserimento di un nuovo canale. ProcessTo = (ElementoProcesso) (ListaDeiProcessi .getElement(updateGetPoint(e.getPoint()))); if ((ProcessTo != null) && (!(ProcessTo.equals(ProcessFrom)))) { ElementoCanale.incNumCanale(); CanaleCorrente = new ElementoCanale(ProcessFrom, ProcessTo, null); ListaDeiCanali.addElement(CanaleCorrente); // Aggiornamento della barra di stato. plugDataWin.getStatusBar().setText( "Channel " + CanaleCorrente.getName() + " inserted."); // core.internal.plugin.file.FileManager.setModificata(true); fileManager.setChangeWorkset(TopologyWindow.idPluginFileCharmy,true); } else { plugDataWin.getStatusBar().setText( "Channel not inserted. Topology ready."); } ProcessTo = null; ProcessFrom.setSelected(false); ProcessFrom = null; ClassEditorStatus = INSERIMENTO_CANALE; if (!BloccoPulsante) { ClassEditorStatus = TEMPATTESA; rifEditor.setAllButtonNoPressed(); } repaint(); break; case SPOSTA_PROCESSO : ClassEditorStatus = ATTESA; //riabilita la lista dei il send dei messaggi //il sistema scritto qui potrebbe essere eliminato //gestendo l'evento ad un livello più basso. if(ProcessoCorrente!=null){ ProcessoCorrente.enabled(); ProcessoCorrente.informPostUpdate(); } plugDataWin.getStatusBar().setText( "Process " + ProcessoCorrente.getName() + " selected. Topology ready."); break; case MULTISELEZIONE : endPoint = updateGetPoint(e.getPoint()); // Per selezionare gli oggetti il trascinamento del mouse deve // avvenire da sinistra verso destra e dall'alto verso il basso. if ((endPoint.x > startPoint.x) && (endPoint.y > startPoint.y)) { // Selezione degli oggetti contenuti nel rettangolo rectMultiSelection. rectMultiSelection = new Rectangle2D.Double( startPoint.x, startPoint.y, endPoint.x - startPoint.x, endPoint.y - startPoint.y); ListaDeiProcessi.setSelectedIfInRectangle( rectMultiSelection); ListaDeiCanali.setSelectedIfInRectangle(); rectMultiSelection = null; spostaListaProcessi = ListaDeiProcessi.listSelectedProcess(); if (!spostaListaProcessi.isEmpty()) { ClassEditorStatus = SPOSTA_MULTISELEZIONE; plugDataWin.getStatusBar().setText( "Selection ok."); externalRect = spostaListaProcessi.getExternalBounds(); } else // Non è stato selezionato alcun processo. { ClassEditorStatus = ATTESA; plugDataWin.getStatusBar().setText( "Topology ready."); } repaint(); } else { ClassEditorStatus = ATTESA; plugDataWin.getStatusBar().setText( "Topology ready."); } break; case SPOSTA_MULTISELEZIONE_FASE2 : // Con queste istruzioni, per spostare ancora gli oggetti // selezionati, l'utente è obbligato a passare con il // trascinamento del mouse all'interno della selezione. ClassEditorStatus = SPOSTA_MULTISELEZIONE; externalRect = spostaListaProcessi.getExternalBounds(); //plugDataWin.getFileManager().setModificata(true); // core.internal.plugin.file.FileManager.setModificata(true); fileManager.setChangeWorkset(TopologyWindow.idPluginFileCharmy,true); break; default : ClassEditorStatus = ATTESA; break; } } } /** Gestione del click sul mouse. */ public void mouseClicked(MouseEvent e) { if (rettangolo.contains(updateGetPoint(e.getPoint()))){ switch (ClassEditorStatus){ case TEMPATTESA: ClassEditorStatus = ATTESA; break; case ATTESA: if (!e.isShiftDown()){ // Non è stato premuto il tasto "MAIUSC", pertanto // devo eliminare qualunque precedente selezione. ListaDeiCanali.noSelected(); ListaDeiProcessi.noSelected(); } ProcessoCorrente = (ElementoProcesso)(ListaDeiProcessi.getElement(updateGetPoint(e.getPoint()))); if (ProcessoCorrente != null){ // E' stato selezionato un processo. if (!e.isShiftDown()){ Point p = e.getPoint(); spiazzamentoX=ProcessoCorrente.getTopX()-p.x; spiazzamentoY=ProcessoCorrente.getTopY()-p.y; ProcessoCorrente.setSelected(true); plugDataWin.getStatusBar().setText("Process " + ProcessoCorrente.getName() + " selected."); } else{ // Avendo premuto il tasto "MAIUSC", devo selezionare (deselezionare) // un processo se deselezionato (selezionato). ProcessoCorrente.invSelected(); } repaint(); if (!ProcessoCorrente.isDummy()){ if (e.getClickCount()>1){ // Gestione del doppio click su un processo non dummy. FinestraProprietaProcesso = new FinestraElementoBoxTesto(ProcessoCorrente,g2,null,"Process Properties",0,plugData.getPlugDataManager()); } } } else { // Non è stato selezionato alcun processo. CanaleCorrente = (ElementoCanale)(ListaDeiCanali.getElementSelected(updateGetPoint(e.getPoint()))); if (CanaleCorrente != null){ // E' stato selezionato un canale. if (!e.isShiftDown()){ CanaleCorrente.setSelected(true); plugDataWin.getStatusBar().setText("Channel " + CanaleCorrente.getName() + " selected."); } else{ // Avendo premuto il tasto "MAIUSC", devo selezionare (deselezionare) // un canale se deselezionato (selezionato). CanaleCorrente.invSelected(); plugDataWin.getStatusBar().setText("Clicked over " + CanaleCorrente.getName() + "."); } repaint(); if (e.getClickCount()>1){ // Gestione del doppio click su un canale. FinestraProprietaCanale = new FinestraGraficoLinkTopology(CanaleCorrente,null,"Channel Properties",0,plugData.getPlugDataManager()); } } else{ // Non è stato selezionato né un processo né un canale. if (e.getClickCount()>1){ // Gestione del doppio click sull'editor. FinestraProprietaEditor = new FinestraGraphEditor(rifEditor,null,"Editor Properties"); } } } repaint(); break; case DISEGNA_PROCESSO: break; case INSERIMENTO_CANALE: break; case DISEGNA_CANALE: break; default: // Si entra qui con lo stato SPOSTA_PROCESSO, MULTISELEZIONE, // SPOSTA_MULTISELEZIONE, SPOSTA_MULTISELEZIONE_FASE2 oppure, // al limite, con uno stato non previsto. // Tornare nello stato di attesa. ListaDeiProcessi.noSelected(); ListaDeiCanali.noSelected(); spostaListaProcessi = null; ClassEditorStatus = ATTESA; plugDataWin.getStatusBar().setText("Topology ready."); repaint(); break; } } } } /** Gestione del movimento del mouse. */ private final class ClassEditorMotionAdapter extends MouseMotionAdapter { /** Trascinamento del mouse. */ public void mouseDragged(MouseEvent e) { Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1); ((JPanel)e.getSource()).scrollRectToVisible(r); // Gestione degli eventi di trascinamento solo se // interni all'area di editing (delimitata da rettangolo). if (rettangolo.contains(updateGetPoint(e.getPoint()))) { switch (ClassEditorStatus) { case ATTESA : if (!e.isShiftDown()) { // Non è stato premuto il tasto "MAIUSC". ListaDeiCanali.noSelected(); ListaDeiProcessi.noSelected(); ProcessoCorrente = (ElementoProcesso) (ListaDeiProcessi .getElement(updateGetPoint(e.getPoint()))); if (ProcessoCorrente != null) { Point p = e.getPoint(); spiazzamentoX = ProcessoCorrente.getTopX() - p.x; spiazzamentoY = ProcessoCorrente.getTopY() - p.y; ProcessoCorrente.setSelected(true); plugDataWin.getStatusBar().setText( "Process " + ProcessoCorrente.getName() + " selected and moved."); ListaDeiCanali.updateListaCanalePosizione(ProcessoCorrente); ClassEditorStatus = SPOSTA_PROCESSO; //plugDataWin.getFileManager().setModificata(true); // core.internal.plugin.file.FileManager.setModificata(true); fileManager.setChangeWorkset(TopologyWindow.idPluginFileCharmy,true); repaint(); } else { // Nessun processo selezionato. startPoint = updateGetPoint(e.getPoint()); ClassEditorStatus = MULTISELEZIONE; } } else { // E' stato premuto il tasto "MAIUSC". // Creazione della lista dei processi selezionati. spostaListaProcessi = ListaDeiProcessi.listSelectedProcess(); if (!spostaListaProcessi.isEmpty()) { // E' stato selezionato almento un processo. ClassEditorStatus = SPOSTA_MULTISELEZIONE; externalRect = spostaListaProcessi.getExternalBounds(); //plugDataWin.getFileManager().setModificata(true); // core.internal.plugin.file.FileManager.setModificata(true); fileManager.setChangeWorkset(TopologyWindow.idPluginFileCharmy,true); } else { ClassEditorStatus = ATTESA; } repaint(); } break; case DISEGNA_CANALE : break; case SPOSTA_PROCESSO : // Aggiornamento della posizione del processo selezionato. Point p = e.getPoint(); p.x = p.x + spiazzamentoX; p.y = p.y + spiazzamentoY; //unisco gli eventi di modifica if (ProcessoCorrente.getStato()) { ProcessoCorrente.informPreUpdate(); } ProcessoCorrente.disable(); ProcessoCorrente.setPoint(updateGetPoint(p)); ListaDeiCanali.updateListaCanalePosizione( ProcessoCorrente); repaint(); break; case MULTISELEZIONE : endPoint = updateGetPoint(e.getPoint()); // Per selezionare gli oggetti il trascinamento del mouse deve // avvenire da sinistra verso destra e dall'alto verso il basso. if ((endPoint.x > startPoint.x) && (endPoint.y > startPoint.y)) { rectMultiSelection = new Rectangle2D.Double( startPoint.x, startPoint.y, endPoint.x - startPoint.x, endPoint.y - startPoint.y); repaint(); } break; case SPOSTA_MULTISELEZIONE : // Inizia lo spostamento contemporaneo di più oggetti. // Durante il trascinamento lo stato SPOSTA_MULTISELEZIONE // viene attivato una sola volta. trackPoint = updateGetPoint(e.getPoint()); if (externalRect.contains(trackPoint)) { // Punto di riferimento rispetto al quale calcolare lo spostamento. rifPoint = spostaListaProcessi.getRifPoint(); ClassEditorStatus = SPOSTA_MULTISELEZIONE_FASE2; } else { ProcessoCorrente = (ElementoProcesso) (ListaDeiProcessi .getElement(updateGetPoint(e.getPoint()))); if (ProcessoCorrente != null) { // E' stato selezionato un processo esterno alla selezione, pertanto // si suppone che l'utente voglia muovere solo quel processo. ListaDeiCanali.noSelected(); ListaDeiProcessi.noSelected(); ProcessoCorrente.setSelected(true); ProcessoCorrente.setPoint(updateGetPoint(e.getPoint())); plugDataWin.getStatusBar().setText( "Process " + ProcessoCorrente.getName() + " selected and moved."); ListaDeiCanali.updateListaCanalePosizione(ProcessoCorrente); ClassEditorStatus = SPOSTA_PROCESSO; //plugDataWin.getFileManager().setModificata(true); // core.internal.plugin.file.FileManager.setModificata(true); fileManager.setChangeWorkset(TopologyWindow.idPluginFileCharmy,true); repaint(); } } break; case SPOSTA_MULTISELEZIONE_FASE2 : // Spostamento contemporaneo di più oggetti. // Durante il trascinamento rimane attivato lo stato // SPOSTA_MULTISELEZIONE_FASE2; ad ogni passaggio si aggiorna // la posizione di tutti gli oggetti interessati dallo spostamento. trackPoint = updateGetPoint(e.getPoint()); spostaListaProcessi.updatePosition( rifPoint, trackPoint, ListaDeiCanali); rifPoint = trackPoint; plugDataWin.getStatusBar().setText("Selection moved."); //plugDataWin.getFileManager().setModificata(true); // core.internal.plugin.file.FileManager.setModificata(true); fileManager.setChangeWorkset(TopologyWindow.idPluginFileCharmy,true); repaint(); break; default : // Si entra qui con lo stato DISEGNA_PROCESSO o INSERIMENTO_CANALE // oppure, al limite, con uno stato non previsto. break; } } } } /** Restituisce un punto le cui coordinate sono quelle del punto in ingresso aggiornate tenendo conto dei fattori di scala per l'asse X e per l'asse Y. */ private Point updateGetPoint(Point pnt) { Point pp = new Point(roundToInt(pnt.x / scaleX), roundToInt(pnt.y / scaleY)); return pp; } /** Operazione di copy su processi e canali. */ public void opCopy() { // ccpTopology.copy(); // plugDataWin.getStatusBar().setText("<Copy> ok!! Topology ready."); } /** Operazione di paste su processi e canali. */ public void opPaste() { // int j; // boolean tmpboolean; // boolean listevuote = true; // String NomeProcesso; // String NomeCanale; // ElementoProcesso PasteProcesso; // ElementoCanale PasteCanale; // ccpTopology.paste(); // repaint(); } /** Operazione di cut. */ public void opCut() { // LinkedList delListaCanali = null; // LinkedList delListaProcessi = null; // ListaCanale delextraListaCanali = null; // // Lista dei canali da eliminare. // delListaCanali = ListaDeiCanali.listSelectedChannel(); // if ((delListaCanali != null) && (!delListaCanali.isEmpty())) { // // Eliminazione canali. // ListaDeiCanali.removeListeSelected(delListaCanali); // } // // Lista dei processi da eliminare. // delListaProcessi = ListaDeiProcessi.listSelectedProcess(); // if ((delextraListaCanali != null) // && (!delextraListaCanali.isEmpty())) { // // Eliminazione di canali per la precedente eliminazione di processi. // ListaDeiCanali.removeListeSelected(delextraListaCanali); // } // ClassEditorStatus = ATTESA; // tmpListaProcessi = delListaProcessi; // tmpListaCanali = delListaCanali; // plugDataWin.getStatusBar().setText("<Cut> ok!! Topology ready."); // repaint(); } /** Operazione di redo. */ public void opRedo() { undoRedoManager.redo(scaleX, scaleY); ClassEditorStatus = ATTESA; rifEditor.setAllButtonNoPressed(); plugDataWin.getStatusBar().setText("<Redo> ok!! Ready."); repaint(); } /** Operazione di undo sull'ultima operazione di del (per processi e canali). */ public void opUndo() { undoRedoManager.undo(scaleX, scaleY); ClassEditorStatus = ATTESA; rifEditor.setAllButtonNoPressed(); plugDataWin.getStatusBar().setText("<Undo> ok!! Ready."); repaint(); } /** Operazione di cancellazione (del) di processi e/o canali. */ public void opDel() { //plugData.getListaProcesso().removeAllSelected(); //plugData.getListaCanale().removeAllSelected(); //ClassEditorStatus = ATTESA; //plugDataWin.getStatusBar().setText("<Delete> ok!! Topology ready."); //repaint(); } /** Creazione dell'immagine jpeg del S_A_ Topology Diagram. */ public void opImg() { boolean ctrlImage; JpegImage Immagine; Graphics2D imgG2D; Immagine = new JpegImage(0, 0, rWidth, rHeight, scaleX, scaleY, editorColor); imgG2D = Immagine.getImageGraphics2D(); if (imgG2D != null) { ListaDeiCanali.paintLista(imgG2D); ListaDeiProcessi.paintLista(imgG2D); plugDataWin.getStatusBar().setText("Select file and wait."); ctrlImage = Immagine.saveImageFile((Frame) getTopLevelAncestor()); if (ctrlImage) { plugDataWin.getStatusBar().setText( "Image saved. Topology ready."); } else { plugDataWin.getStatusBar().setText( "Image not saved. Topology ready."); } } } /** Restituisce il vettore contenente i nomi di tutti i processi definiti_ Nel vettore non sono inclusi i nomi dei processi 'dummy'. */ public Vector getAllProcessName() { return ListaDeiProcessi.getAllProcessName(); } /** Restituisce la lista di tutti i processi definiti nel S_A_ Topology Diagram. */ public LinkedList getListaProcessi() { return ListaDeiProcessi.getListProcessNoDummy(); } /** Restituisce la lista dei processi privata di quelli di tipo dummy. */ public ListaProcesso getListaProcessoSenzaDummy() { return ListaDeiProcessi.getListaProcessoSenzaDummy(); } /** Ripristina la scala del pannello al 100%. */ public void resetScale() { super.resetScale(); plugDataWin.getStatusBar().setText( "<Zoom Reset> ok!! Topology ready."); } /** Operazione di zoom sull'asse X. */ public void incScaleX() { super.incScaleX(); plugDataWin.getStatusBar().setText( "<Stretch Horizontal> ok!! Topology ready."); } /** Operazione di zoom negativo sull'asse X. */ public void decScaleX() { super.decScaleX(); plugDataWin.getStatusBar().setText( "<Compress Horizontal> ok!! Topology ready."); } /** Operazione di zoom sull'asse Y. */ public void incScaleY() { super.incScaleY(); plugDataWin.getStatusBar().setText( "<Stretch Vertical> ok!!. Topology ready."); } /** Operazione di zoom negativo sull'asse Y. */ public void decScaleY() { super.decScaleY(); plugDataWin.getStatusBar().setText( "<Compress Vertical> ok!!. Topology ready."); } /** Restituisce la lista dei processi inseriti nel Topology Diagram. */ public ListaProcesso getListaDeiProcessi() { return ListaDeiProcessi; } /** Imposta la lista dei processi del Topology Diagram. */ public void setListaDeiProcessi(ListaProcesso lp) { ListaDeiProcessi = lp; } /** Restituisce la lista dei canali inseriti nel Topology Diagram. */ public ListaCanale getListaDeiCanali() { return ListaDeiCanali; } /** Imposta la lista dei canali del Topology Diagram. */ public void setListaDeiCanali(ListaCanale lc) { ListaDeiCanali = lc; } /** Metodo per svuotare la lista dei processi e dei canali_ E' usato, ad esempio, dalle operazioni relative all'item "New" del menu "File". */ public void resetForNewFile() { ListaDeiProcessi.removeAll(); ListaDeiCanali.removeAll(); ClassEditorStatus = ATTESA; CanaleCorrente = null; ProcessoCorrente = null; ProcessFrom = null; ProcessTo = null; BloccoPulsante = false; //rifEditor.setAllButtonNoPressed(); repaint(); } public void restoreFromFile() { super.restoreFromFile(); } /** Restituisce il nome di un canale se ne esiste almeno uno, altrimenti null. */ public String getAnyNameChannel() { if (ListaDeiCanali == null) return null; if (ListaDeiCanali.isEmpty()) return null; return ((ElementoCanale) (ListaDeiCanali.getElement(0))).getName(); } public void setDeselectedAll(){ rifEditor.getListaDeiProcessi().setUnselected(); rifEditor.getListaDeiCanali().setUnselected(); repaint(); } /* (non-Javadoc) * @see plugin.charmyui.extensionpoint.editor.IHostEditor#editorActive() */ public void editorActive() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see plugin.charmyui.extensionpoint.editor.IHostEditor#editorInactive() */ public void editorInactive() { // TODO Auto-generated method stub } public void notifyMessage(Object callerObject, int status, String message) { // TODO Auto-generated method stub } }
[ "remenska@gmail.com" ]
remenska@gmail.com
b9acda59e22cb74353f8db9bdeb0fe515808278d
af9dd869576d106e348809dd27a3cd92087c6b3d
/wallpaper/src/com/bn/fbx/core/nonormal/BNThreadGroupNoNormal.java
72887784b3373f3ab595fa363689525507cd51c7
[]
no_license
Ritchielambda/graphics-algorithm
b86c7f3e13d1099383e874655f45163bd7763a34
8c160e0a1c58a9d637ba21e712a73520e6384050
refs/heads/master
2022-12-20T15:50:39.731735
2020-10-08T06:20:41
2020-10-08T06:20:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,032
java
package com.bn.fbx.core.nonormal; public class BNThreadGroupNoNormal { //线程数量 private static final int THREAD_COUNT=3; //执行任务的线程组 private static TaskThreadNoNormal[] threadGroup=new TaskThreadNoNormal[THREAD_COUNT]; //任务分配锁 public static Object lock=new Object(); //静态成员初始化 static { for(int i=0;i<THREAD_COUNT;i++) { threadGroup[i]=new TaskThreadNoNormal(i); threadGroup[i].start(); } } //添加任务 public static void addTask(BnggdhDrawNoNormal bd) { synchronized(lock) { int min=Integer.MAX_VALUE; int curr=-1; for(int i=0;i<THREAD_COUNT;i++) { TaskThreadNoNormal tt=threadGroup[i]; if(tt.taskGroup.size()<min) { min=tt.taskGroup.size(); curr=i; } } threadGroup[curr].addTask(bd); } } //移除任务 public static void removeTask(BnggdhDrawNoNormal bd) { synchronized(lock) { for(int i=0;i<THREAD_COUNT;i++) { TaskThreadNoNormal tt=threadGroup[i]; tt.removeTask(bd); } } } }
[ "yindou97@163.com" ]
yindou97@163.com
744cd3b69333d238f48cea20c2d08aeda0a10285
bb4d1db93eadae6ab7ba36f9f184e68d1b7dd298
/app/src/main/java/com/tiyujia/homesport/common/homepage/activity/HomePageDateActivity.java
1ed6a2ba79ca75c03b93f59e8eea0a21a1b4ef67
[]
no_license
ZyxServices/zyx-android-2.0
e487d221fb0cf3ac16c6bf8724e4428f030f7952
e785e8272142f12976eda629d9e6bc734627b926
refs/heads/master
2021-01-19T15:30:20.305995
2016-11-28T04:08:11
2016-11-28T04:08:13
74,929,396
0
0
null
null
null
null
UTF-8
Java
false
false
2,569
java
package com.tiyujia.homesport.common.homepage.activity; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bigkoo.convenientbanner.ConvenientBanner; import com.tiyujia.homesport.ImmersiveActivity; import com.tiyujia.homesport.R; import com.tiyujia.homesport.common.personal.adapter.TestAdapter; import com.tiyujia.homesport.entity.ActiveModel; import java.util.ArrayList; import butterknife.Bind; import butterknife.ButterKnife; /** * 作者: Cymbi on 2016/11/17 15:03.1 * 邮箱:928902646@qq.com */ public class HomePageDateActivity extends ImmersiveActivity implements View.OnClickListener ,SwipeRefreshLayout.OnRefreshListener{ @Bind(R.id.ivMenu) ImageView ivMenu; @Bind(R.id.ivBack) ImageView ivBack; @Bind(R.id.tvTitle) TextView tvTitle; @Bind(R.id.cbDateBanner) ConvenientBanner cbDateBanner; @Bind(R.id.recyclerView) RecyclerView recyclerView; @Bind(R.id.srlRefresh) SwipeRefreshLayout srlRefresh; private ArrayList<ActiveModel> mDatas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.homepage_date); ButterKnife.bind(this); setView(); initData(); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); //保证recycleView不卡顿 recyclerView.setLayoutManager(layoutManager); layoutManager.setAutoMeasureEnabled(true); recyclerView.setLayoutManager(layoutManager); recyclerView.setHasFixedSize(true); recyclerView.setNestedScrollingEnabled(false); recyclerView.setAdapter(new TestAdapter(this,mDatas)); } private void initData() { mDatas = new ArrayList<>(); for (int i = 0; i < 10; i++) { ActiveModel activeModel= new ActiveModel(); mDatas.add(activeModel); } } private void setView() { ivMenu.setOnClickListener(this); ivBack.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.ivBack: finish(); break; case R.id.ivMenu: break; } } @Override public void onRefresh() { } }
[ "928902646@qq.com" ]
928902646@qq.com
bbfdc1591ed499e076b8a30b8822f4a21ab5fb46
015508176d0d136d4b642e84e326c8a7b8ceb199
/backend/java/com/devsuperior/dsdeliver/repositories/OrderRepository.java
2c0eca9c223b639bcc57c8ac27430286f8dbc60b
[]
no_license
Douglas-Cezaro/dsdeliver-sds2
f13677db8f424a6a9b93117774892ea4e87b83ff
70554519f45dc1cc3623697dcf0f2198db4fc200
refs/heads/master
2023-02-12T02:50:32.989788
2021-01-10T18:59:46
2021-01-10T18:59:46
327,464,112
1
0
null
null
null
null
UTF-8
Java
false
false
478
java
package com.devsuperior.dsdeliver.repositories; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.devsuperior.dsdeliver.entities.Order; public interface OrderRepository extends JpaRepository<Order, Long> { @Query("SELECT DISTINCT obj FROM Order obj JOIN FETCH obj.products " + " WHERE obj.status = 0 ORDER BY obj.moment ASC") List<Order> findOrdersWithProducts(); }
[ "cezarodouglas@gmail.com" ]
cezarodouglas@gmail.com
31c6329da23eb05d0daa6f1cb1ab1d9e939dad02
7579e5fc92a549baae3591e1d7af08799bcc0341
/PhonePe/src/main/java/booking/service/I_BookingService.java
0190dd0b06fc2a468ab0eb5251e86605ba550472
[]
no_license
ansraj91/phonepe_cabmgmt
b2e0d7ae2c4d7384c4ddd1a33bda292cc551dc80
064a5f3fb258e4ceda05ccaaa6ce5781d56b639c
refs/heads/main
2023-07-12T20:53:48.323583
2021-08-30T07:47:48
2021-08-30T07:47:48
401,257,541
1
0
null
null
null
null
UTF-8
Java
false
false
444
java
package booking.service; import booking.model.Booking; import exceptions.BookingException; import exceptions.RiderException; import exceptions.VehicleException; import java.util.List; public interface I_BookingService { Booking book(Long riderUserId, Long cityId) throws VehicleException; List<Booking> history(Long riderUserId) throws RiderException; Boolean endTrip(Long timeStamp, String bookingId) throws BookingException; }
[ "noreply@github.com" ]
noreply@github.com
36eeadddb1959cff0339c09fc57cb1cbefa3d702
6e7c2a197db7761787ab8a129df922b0cad3795d
/app/src/main/java/com/prography/prography_androidstudy/src/add_edit/interfaces/AddEditActivityView.java
44bcba5dd54b24c30bf4bb2514f9827160bf3312
[]
no_license
Ssioo/Prography_AndroidStudy
ba07e6434b6fe86064e29ae2998b4da539cd90a5
d395c84ea5a59009d822b145052d7a8a824709f1
refs/heads/master
2020-08-05T23:25:35.614476
2019-11-15T20:51:59
2019-11-15T20:51:59
212,754,194
1
0
null
null
null
null
UTF-8
Java
false
false
246
java
package com.prography.prography_androidstudy.src.add_edit.interfaces; import android.view.View; import android.widget.CompoundButton; public interface AddEditActivityView extends View.OnClickListener, CompoundButton.OnCheckedChangeListener { }
[ "wooisso@naver.com" ]
wooisso@naver.com
d4361bad3e421513f4bbe28dd37d66f92274440b
a54d078e6177236d1e5c96db5c0f24905ff09d87
/src/main/java/com/bonc/staff/service/PerAddServiceImpl.java
24f56c0ac5f3bb00a281522700ff85a1c99144bf
[]
no_license
punisherj/staff
4329a1f6e5eba2960a22416bd16d79ff03ccab06
68212b87c543b25f540a8e7fd394101172f7a6a4
refs/heads/master
2020-03-20T09:22:50.520022
2018-06-28T09:06:49
2018-06-28T09:06:49
137,335,358
0
0
null
null
null
null
UTF-8
Java
false
false
859
java
package com.bonc.staff.service; import com.bonc.staff.entity.PerAddEntity; import com.bonc.staff.repository.PerAddRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author xukj */ @Service public class PerAddServiceImpl implements PerAddService{ @Autowired private PerAddRepository perAddRepository; @Override public PerAddEntity findByPersonidAndAddressid(String personId, String addressId) { return perAddRepository.findByPersonidAndAddressid(personId, addressId); } @Override public void save(PerAddEntity pe) { perAddRepository.save(pe); } @Override public Integer countPerAdd(String personPhone, String addressId) { return perAddRepository.countByPersonPhoneAndAddressId(personPhone, addressId); } }
[ "xukuijian@bonc.com.cn" ]
xukuijian@bonc.com.cn
a79cc7b84ec978765f2714c3b0bb4e12c8daf0fa
80623a1a73c16d2b70ace95ec320bc9d9bcc2c24
/chatroom_clientside/src/friendManage/SingleChatDialog.java
3633930342a26ee797517c598fc6b456902264eb
[]
no_license
Jimmy9507/chatroom
bb87cd0464716165979ae2a9c8b434a69cbe540d
f1696141198496ee3622d64fd4abe3907dbea4d8
refs/heads/master
2020-03-29T00:32:00.726239
2018-09-18T19:52:19
2018-09-18T19:52:19
149,343,963
0
0
null
null
null
null
UTF-8
Java
false
false
3,948
java
package friendManage; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import client.Client; public class SingleChatDialog extends JDialog implements ActionListener{ JButton sendMessageButton; JButton exitButton; JScrollPane showMessagePane; JTextArea showMessageArea; FriendChatThread friendChatThread; JTextField messageInput; JPanel buttonPanel; JPanel showMessagePanel; String otherSideUsername; String thisSideUsername; /*设置对话框的大小尺寸*/ Dimension dimension=Toolkit.getDefaultToolkit().getScreenSize(); final int WINDOW_X=dimension.width/3; final int WINDOW_Y=dimension.height/3; final int WINDOW_WIDTH=dimension.width/3; final int WINDOW_HEIGHT=dimension.height/4; public SingleChatDialog(String thisSideUsername,String otherSideUsername) { friendChatThread=new FriendChatThread(thisSideUsername,otherSideUsername,this); friendChatThread.start(); initView(); this.setBounds(WINDOW_X,WINDOW_Y,WINDOW_WIDTH,WINDOW_HEIGHT); this.setVisible(true); this.otherSideUsername=otherSideUsername; this.thisSideUsername=thisSideUsername; this.setTitle("与"+otherSideUsername+"的聊天"); this.addWindowListener(new MyWindowListener(this)); } public void initView() { Container container=this.getContentPane(); container.setLayout(null); //配置消息面板 showMessagePanel=new JPanel(); showMessagePanel.setLayout(new BorderLayout()); showMessageArea=new JTextArea(); showMessagePane=new JScrollPane(); showMessagePane.getViewport().add(showMessageArea); showMessagePanel.add(showMessagePane,BorderLayout.CENTER); showMessagePanel.setBounds(0,0,WINDOW_WIDTH,(int)(WINDOW_HEIGHT*4/6.0)); //按钮面板 messageInput=new JTextField(25); buttonPanel=new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); buttonPanel.setBounds(0,(int)(WINDOW_HEIGHT*4/6.0),WINDOW_WIDTH,(int)(WINDOW_HEIGHT*2/6.0)); sendMessageButton=new JButton("发送"); sendMessageButton.addActionListener(this); exitButton=new JButton("退出"); exitButton.addActionListener(this); buttonPanel.add(messageInput); buttonPanel.add(sendMessageButton); buttonPanel.add(exitButton); this.getContentPane().add(showMessagePanel); this.getContentPane().add(buttonPanel); } public void actionPerformed(ActionEvent e) { if((JButton)e.getSource()==sendMessageButton) { String message=messageInput.getText().trim(); friendChatThread.sendMessage(Client.userInfo.getUserNickname(),message); messageInput.setText(""); } if((JButton)e.getSource()==exitButton) { friendChatThread.interrupt(); this.dispose(); } //消息类 } private static class MyWindowListener extends WindowAdapter{ SingleChatDialog singleChatDialog; public MyWindowListener(SingleChatDialog singleChatDialog) { this.singleChatDialog=singleChatDialog; } public void WindowClosing(WindowEvent e) { singleChatDialog.friendChatThread.interrupt(); singleChatDialog.dispose(); } } }
[ "406403730@qq.com" ]
406403730@qq.com
26c6b27d432341940a5c221cb078a851f77f2c2a
941b50f71c949e27b029c2f3450f39719ddfe4fa
/SpringBoot-RabbitMQ/src/test/java/com/SpringBoot/RabbitMq/SpringBootRabbitMQ/SpringBootRabbitMqApplicationTests.java
5b806d5fcc51a2690c921faea1fb03f5994998fc
[]
no_license
anshujainb/Springboot-rabbitMQ
b5f62c2a086ece9627171b482b5cd1d91edda9d7
cdf1f2525202127d25f93b8b2332c83c3c3c57f9
refs/heads/master
2020-04-28T20:52:37.293779
2019-03-14T06:21:41
2019-03-14T06:21:41
175,560,313
0
0
null
null
null
null
UTF-8
Java
false
false
371
java
package com.SpringBoot.RabbitMq.SpringBootRabbitMQ; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootRabbitMqApplicationTests { @Test public void contextLoads() { } }
[ "noreply@github.com" ]
noreply@github.com
361608c591b8217dc9dcdefb74220de6147ccf30
f2d21e008f281e4d8c0b66bc314ba57a6ea6ff89
/RobbieRobotShop/src/GUI/GUIPanel.java
d989c0dce27788573b31525768cb38454ddbafa3
[]
no_license
kallippso/CSE-J1613
c44c8c5adcc32f280b8b32f87f000a11c94a609a
15d33fd22d16e0ae621530c628fef2a334655559
refs/heads/master
2021-01-10T09:38:44.129523
2016-04-21T10:36:40
2016-04-21T10:36:40
55,388,314
0
2
null
2016-04-07T13:58:13
2016-04-04T05:56:19
Java
UTF-8
Java
false
false
1,245
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package GUI; /** * * @author christian */ import javax.swing.BoxLayout; import static javax.swing.BoxLayout.Y_AXIS; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JTextField; public class GUIPanel extends JFrame { String[] labels = {"Part Name: ", "Fax: ", "Email: ", "Address: "}; int numPairs = labels.length; public GUIPanel(JFrame currFrame) { JLayeredPane testPanel = new JLayeredPane(); BoxLayout layout = new BoxLayout(testPanel, Y_AXIS); testPanel.setLayout(layout); for (int i = 0; i < numPairs; i++) { JLabel l = new JLabel(labels[i], JLabel.TRAILING); testPanel.add(l); JTextField textField = new JTextField(10); l.setLabelFor(textField); testPanel.add(textField); } currFrame.setLayeredPane(testPanel); testPanel.setSize(50, 25); currFrame.setVisible(true); } }
[ "christian.gross1016@gmail.com" ]
christian.gross1016@gmail.com
e9736858be23b2b2e998811560f3af74f1685ae8
1bc22704be60052162520ea32cbc19a042d33996
/src/jsquidmodel/SquidDefaultVector.java
7b834c0103251f769c96757d4d22968021d85192
[]
no_license
xv1t/SquidModel.GUI
2531c1a0c4579ad7117778111affb5e21c2f6d24
8dd42aa2c93e67fb2c058989aa6f1cfb4c77d00e
refs/heads/master
2020-04-02T09:20:02.993907
2011-09-14T17:01:48
2011-09-14T17:01:48
2,386,129
1
1
null
null
null
null
UTF-8
Java
false
false
1,493
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsquidmodel; import java.util.Vector; /** * * @author xvit */ public class SquidDefaultVector extends Vector<DefaultSquidObject> { String group_name; int prioritet; boolean sorting = true; public SquidDefaultVector() { } public SquidDefaultVector(String _group_name) { group_name = _group_name; prioritet = 5; } public SquidDefaultVector(String _group_name, int _prioritet) { group_name = _group_name; prioritet = _prioritet; } // @Override public boolean removeByName(String name){ int index = getIndexByName(name); if (index == -1) return false; removeElementAt(index); return true; } public int getIndexByName(String name){ for (int i =0; i < size(); i++) if (get(i).name.equals(name)) return i; return -1; } public DefaultSquidObject get(String name){ return get(getIndexByName(name)); } public void moveObject(int index, int new_index){ } public boolean addOrReplaceObject(DefaultSquidObject object){ object.group_name = group_name; int index = getIndexByName(object.name); if (index == -1) { if (sorting) { /*SORTING is NOT AVIALABLE*/ add(object); } else add(object); return false; } get(index).value = object.value; return true; } }
[ "xv1t@yandex.ru" ]
xv1t@yandex.ru
71728ca8c4441b78d3666a66420bfcdd66e7fabb
58fc6a6e559b4755dd5b7e8cd5a6081e8893dbe4
/spring-jpa/sample/src/main/java/com/test/hibernate/model/User.java
d521f6d7befff3d6ec38c8da0a0378a92d1fa187
[]
no_license
sambit-pani/study
2afe74615e7ca510928acf1c675c84620c489832
1cb88d35519b15f55f16c4751f50fb29ce7d593f
refs/heads/master
2020-04-13T15:22:17.701908
2019-03-21T09:11:20
2019-03-21T09:11:20
163,288,983
0
0
null
null
null
null
UTF-8
Java
false
false
3,139
java
package com.test.hibernate.model; import java.util.Date; import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; @Entity @Table(name = "user") @Cacheable @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public class User { public static enum SEX { MALE, FEMALE } public User(String name, Date dob, boolean isActive, double salary, SEX sex, Date date1, Date date2, Date created, Date modified) { super(); this.name = name; this.dob = dob; this.isActive = isActive; this.salary = salary; this.sex = sex; this.date1 = date1; this.date2 = date2; this.created = created; this.modified = modified; } public User() { } @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column(nullable=false,length=50) private String name; @Column @Temporal(TemporalType.DATE) private Date dob; private boolean isActive; @Column(precision=2) private double salary; @Enumerated(EnumType.STRING) private SEX sex; @Column @Temporal(TemporalType.TIME) private Date date1; @Column @Temporal(TemporalType.TIMESTAMP) private Date date2; @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) private Date created; @UpdateTimestamp @Temporal(TemporalType.TIMESTAMP) private Date modified; private Religion religion; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } public boolean isActive() { return isActive; } public void setActive(boolean isActive) { this.isActive = isActive; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public SEX getSex() { return sex; } public void setSex(SEX sex) { this.sex = sex; } public Date getDate1() { return date1; } public void setDate1(Date date1) { this.date1 = date1; } public Date getDate2() { return date2; } public void setDate2(Date date2) { this.date2 = date2; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Date getModified() { return modified; } public void setModified(Date modified) { this.modified = modified; } public Religion getReligion() { return religion; } public void setReligion(Religion religion) { this.religion = religion; } @Override public String toString() { return "User [id=" + id + ", name=" + name + "]"; } }
[ "sambitpani16@gmail.com" ]
sambitpani16@gmail.com
38ecc2f8b167cca112f2344cfd02991f27c54d5f
0d754b8abe5702f40a6024f56a1ca45a05e5db8a
/app/src/main/java/project/yidun/com/yidun/utils/SPUtil.java
e72a9d8f26c8c23e10eb23031fcea01734cc32ba
[]
no_license
jackyhezhenguo/hezhenguo
b138a78f2bb9eac2f976de026668f32b35622d1e
0906185068fe272e9e95d5bde953297fcbf8bf77
refs/heads/master
2021-01-23T03:59:06.383238
2017-04-05T06:56:46
2017-04-05T06:56:46
86,140,047
0
0
null
null
null
null
UTF-8
Java
false
false
5,677
java
package project.yidun.com.yidun.utils; import android.content.Context; import android.content.SharedPreferences; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; /** * 简化SharedPreferences的帮助类. * * 用法:直接SPUtil.putAndApply() * @author shicaiD * */ public class SPUtil { /** * SharedPreferences存储在sd卡中的文件名字 */ private static String getSpName(Context context) { return context.getPackageName() + "_preferences"; } /** * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 */ public static void putAndApply(Context context, String key, Object object) { SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); if (object instanceof String) { editor.putString(key, (String) object); } else if (object instanceof Integer) { editor.putInt(key, (Integer) object); } else if (object instanceof Boolean) { editor.putBoolean(key, (Boolean) object); } else if (object instanceof Float) { editor.putFloat(key, (Float) object); } else if (object instanceof Long) { editor.putLong(key, (Long) object); } else { editor.putString(key, object.toString()); } SharedPreferencesCompat.apply(editor); } /** * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 */ public static Object get(Context context, String key, Object defaultObject) { SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE); if (defaultObject instanceof String) { return sp.getString(key, (String) defaultObject); } else if (defaultObject instanceof Integer) { return sp.getInt(key, (Integer) defaultObject); } else if (defaultObject instanceof Boolean) { return sp.getBoolean(key, (Boolean) defaultObject); } else if (defaultObject instanceof Float) { return sp.getFloat(key, (Float) defaultObject); } else if (defaultObject instanceof Long) { return sp.getLong(key, (Long) defaultObject); } else { return null; } } public static Object get(Context context ,String paName, String key, Object defaultObject) { SharedPreferences sp = context.getSharedPreferences(paName, Context.MODE_PRIVATE); if (defaultObject instanceof String) { return sp.getString(key, (String) defaultObject); } else if (defaultObject instanceof Integer) { return sp.getInt(key, (Integer) defaultObject); } else if (defaultObject instanceof Boolean) { return sp.getBoolean(key, (Boolean) defaultObject); } else if (defaultObject instanceof Float) { return sp.getFloat(key, (Float) defaultObject); } else if (defaultObject instanceof Long) { return sp.getLong(key, (Long) defaultObject); } else { return null; } } /** * 移除某个key值已经对应的值 */ public static void remove(Context context, String key) { SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); SharedPreferencesCompat.apply(editor); } /** * 清除所有数据 */ public static void clear(Context context) { SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.clear(); SharedPreferencesCompat.apply(editor); } /** * 查询某个key是否已经存在 */ public static boolean contains(Context context, String key) { SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE); return sp.contains(key); } /** * 返回所有的键值对 */ public static Map<String, ?> getAll(Context context) { SharedPreferences sp = context.getSharedPreferences(getSpName(context), Context.MODE_PRIVATE); return sp.getAll(); } /** * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类 * @author zhy */ private static class SharedPreferencesCompat { private static final Method sApplyMethod = findApplyMethod(); /** * 反射查找apply的方法 */ @SuppressWarnings({"unchecked", "rawtypes"}) private static Method findApplyMethod() { try { Class clz = SharedPreferences.Editor.class; return clz.getMethod("apply"); } catch (NoSuchMethodException e) { } return null; } /** * 如果找到则使用apply执行,否则使用commit */ public static void apply(SharedPreferences.Editor editor) { try { if (sApplyMethod != null) { sApplyMethod.invoke(editor); return; } } catch (IllegalArgumentException expected) { } catch (IllegalAccessException expected) { } catch (InvocationTargetException expected) { } editor.commit(); } } }
[ "938517869@qq.com" ]
938517869@qq.com
23ce4241fcc5e75e29270ad76d3bb505fd023f73
3e3d78daf567d88e940a88b982c1b22a916e5151
/jpa05/src/main/java/com/indusfo/spc/pojo/Blyy.java
bb934114e462b316dbdc1da23bfdde33729a3dcc
[]
no_license
RongHaoLou/SingleBatch_Boot
536961377102e7f26dcf05b7aecc80f720413b50
a602ddccbc4ce031fd1bf02f7bbae7d22a9761b4
refs/heads/master
2020-07-26T18:09:18.791294
2019-09-16T06:49:32
2019-09-16T06:49:32
208,726,443
0
0
null
null
null
null
UTF-8
Java
false
false
2,204
java
package com.indusfo.spc.pojo; import com.indusfo.spc.common.pojo.BasePojo; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; /** * @ProjectName: IEIS2 * @Package: com.indusfo.spc.pojo * @ClassName: Blyy * @Author: 熊冰 * @Description: ${description} * @Date: 2019/8/8 15:41 * @Version: 1.0 * 不良原因pojo类 */ @Table(name = "T_B77_BLYY") public class Blyy extends BasePojo { @Id @Column(name = "BLYY_ID",insertable=false) //不良原因编号 private Integer blyyId; //不良原因名称 private String blyyName; //不良原因类型 private Integer blyytypeId; //不良原因类型名称 private String blyytypeName; //备注 private String remark; //数据状态 1 启用 2 删除 3停用 private Integer dataState=1; public Integer getBlyyId() { return blyyId; } public void setBlyyId(Integer blyyId) { this.blyyId = blyyId; } public String getBlyyName() { return blyyName; } public void setBlyyName(String blyyName) { this.blyyName = blyyName; } public Integer getBlyytypeId() { return blyytypeId; } public void setBlyytypeId(Integer blyytypeId) { this.blyytypeId = blyytypeId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Integer getDataState() { return dataState; } public void setDataState(Integer dataState) { this.dataState = dataState; } public String getBlyytypeName() { return blyytypeName; } public void setBlyytypeName(String blyytypeName) { this.blyytypeName = blyytypeName; } @Override public String toString() { return "Blyy{" + "blyyId=" + blyyId + ", blyyName='" + blyyName + '\'' + ", blyytypeId=" + blyytypeId + ", remark='" + remark + '\'' + ", dataState=" + dataState + '}'; } public String BasePojoToString() { return super.toString(); } }
[ "1370293157@qq.com" ]
1370293157@qq.com
1e8649ab0ded7188c39e8a43eb190928d6b7f5f5
40dd609c6b24ca91045f5bb6cdd69ac04e5b0391
/app/src/main/java/com/beemindz/miyotee/util/ToastUtils.java
168a892c8c9077e15fd5c400d9f86c6d9746e89a
[]
no_license
beemindz/miyotee
3671cd1043d60107df703d4b03d148ef306dba8a
4e9c687532c38b0dcf870a9ca01f5b986b61240f
refs/heads/master
2021-01-22T10:13:50.814123
2014-08-18T10:06:29
2014-08-18T10:06:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
804
java
package com.beemindz.miyotee.util; import android.content.Context; import android.widget.Toast; /** * This utility for toast message. Using to show message on screen activity. */ public class ToastUtils { /** * Displays a Toast notification for a short duration. * * @param context * activity screen. * @param resId * '@string' id. */ public static void toast(Context context, int resId) { Toast.makeText(context, resId, Toast.LENGTH_SHORT).show(); } /** * Displays a Toast notification for a short duration. * * @param context * activity screen. * @param message * message need show. */ public static void toast(Context context, String message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } }
[ "hungmutsu@gmail.com" ]
hungmutsu@gmail.com
bd00c8d15006f3bc141e950526149c39c1932004
5d220b8cbe0bcab98414349ac79b449ec2a5bdcf
/src/com/ufgov/zc/server/zc/dao/IZcSuppleMentPProMakeDao.java
eb7a18075033597e8de0611ce5fbce2ad38eee15
[]
no_license
jielen/puer
fd18bdeeb0d48c8848dc2ab59629f9bbc7a5633e
0f56365e7bb8364f3d1b4daca0591d0322f7c1aa
refs/heads/master
2020-04-06T03:41:08.173645
2018-04-15T01:31:56
2018-04-15T01:31:56
63,419,454
0
1
null
null
null
null
UTF-8
Java
false
false
1,077
java
/** * @(#) project: zcxa * @(#) file: IZcSuppleMentPProMake.java * * Copyright 2010 UFGOV, Inc. All rights reserved. * UFGOV PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * */ package com.ufgov.zc.server.zc.dao; import java.util.List; import com.ufgov.zc.common.system.dto.ElementConditionDto; import com.ufgov.zc.common.zc.model.ZcSupplementPProMake; /** * @ClassName: 追加资金业务层 * @Description: TCJLODO(这里用一句话描述这个类的作用) * @date: 2010-7-29 下午04:07:12 * @version: V1.0 * @since: 1.0 * @author: Administrator * @modify: */ public interface IZcSuppleMentPProMakeDao { public ZcSupplementPProMake insertZcSupplementPProMake(ZcSupplementPProMake zcSuppleMentPProMake); public ZcSupplementPProMake updateZcSupplementPProMake(ZcSupplementPProMake zcSuppleMentPProMake); public ZcSupplementPProMake getZcSupplementPProMake(String zcMakeCode); public void deleteZcSupplementPProMake(String zcMakeCode); public List getZcSupplementPProMakeList(ElementConditionDto elementConditionDto); }
[ "jielenzghsy1@163.com" ]
jielenzghsy1@163.com
9c928466b696e88479d17a7869bc5912189bc57b
c07eff890584e1885be5f3c8dec58c4727c0f4fb
/src/Tree/NumberOfIslands200.java
ed735573b96d6c45de80ef5644c65cbecd6e7c55
[]
no_license
XinliYu/Java_Leetcode
e0c966568e0686cdf44f0bbb90816c8de674e071
12a802d78f467da9fc7d531d29734776d84c2135
refs/heads/master
2020-09-22T16:30:34.714108
2019-12-02T03:24:27
2019-12-02T03:24:27
225,273,799
0
0
null
null
null
null
UTF-8
Java
false
false
2,712
java
package Tree; import java.util.LinkedList; import java.util.Queue; //Input: //11000 //11000 //00100 //00011 // //Output: 3 public class NumberOfIslands200 { //BFS public int numIslands(char[][] grid) { if (grid == null || grid.length == 0) { return 0; } int nr = grid.length; int nc = grid[0].length; int num_islands = 0; for (int r = 0; r < nr; ++r) { for (int c = 0; c < nc; ++c) { if (grid[r][c] == '1') { ++num_islands; grid[r][c] = '0'; // mark as visited Queue<Integer> neighbors = new LinkedList<>(); neighbors.add(r * nc + c); while (!neighbors.isEmpty()) { int id = neighbors.remove(); int row = id / nc; int col = id % nc; if (row - 1 >= 0 && grid[row-1][col] == '1') { neighbors.add((row-1) * nc + col); grid[row-1][col] = '0'; } if (row + 1 < nr && grid[row+1][col] == '1') { neighbors.add((row+1) * nc + col); grid[row+1][col] = '0'; } if (col - 1 >= 0 && grid[row][col-1] == '1') { neighbors.add(row * nc + col-1); grid[row][col-1] = '0'; } if (col + 1 < nc && grid[row][col+1] == '1') { neighbors.add(row * nc + col+1); grid[row][col+1] = '0'; } } } } } return num_islands; } //dfs void dfs(char[][] grid, int r, int c) { int nr = grid.length; int nc = grid[0].length; if (r < 0 || c < 0 || r >= nr || c >= nc || grid[r][c] == '0') { return; } grid[r][c] = '0'; dfs(grid, r - 1, c); dfs(grid, r + 1, c); dfs(grid, r, c - 1); dfs(grid, r, c + 1); } public int numIslands2(char[][] grid) { if (grid == null || grid.length == 0) { return 0; } int nr = grid.length; int nc = grid[0].length; int num_islands = 0; for (int r = 0; r < nr; ++r) { for (int c = 0; c < nc; ++c) { if (grid[r][c] == '1') { ++num_islands; dfs(grid, r, c); } } } return num_islands; } }
[ "xyu350@gatech.edu" ]
xyu350@gatech.edu
efd62313fa4e2531b9237c9f4c20b5965233d648
312cca920c3cde9c582b4913e9432eab0f69e507
/build/sqflite/generated/source/buildConfig/profile/com/tekartik/sqflite/BuildConfig.java
341d59f3247297b986ae85c7cc5b1a8b271ac568
[]
no_license
Navneet-chaurasia/Quacker
f87852361bb30904ec1f607f70a3396a286baa9a
cf96238c2da09e9741b07ca6207a98d29ae6d631
refs/heads/master
2021-04-11T12:50:30.452044
2020-04-05T14:45:56
2020-04-05T14:45:56
249,389,689
1
0
null
null
null
null
UTF-8
Java
false
false
663
java
/** * Automatically generated file. DO NOT MODIFY */ package com.tekartik.sqflite; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String LIBRARY_PACKAGE_NAME = "com.tekartik.sqflite"; /** * @deprecated APPLICATION_ID is misleading in libraries. For the library package name use LIBRARY_PACKAGE_NAME */ @Deprecated public static final String APPLICATION_ID = "com.tekartik.sqflite"; public static final String BUILD_TYPE = "profile"; public static final String FLAVOR = ""; public static final int VERSION_CODE = -1; public static final String VERSION_NAME = ""; }
[ "navneetc486@gmail.com" ]
navneetc486@gmail.com
c538ae3a9a4f4715561a01469dca7e403b8bdc9f
74b47b895b2f739612371f871c7f940502e7165b
/aws-java-sdk-chimesdkmessaging/src/main/java/com/amazonaws/services/chimesdkmessaging/model/DeleteChannelResult.java
9e98c92cda9bf2b77acf9c1cbce57c5cea136dec
[ "Apache-2.0" ]
permissive
baganda07/aws-sdk-java
fe1958ed679cd95b4c48f971393bf03eb5512799
f19bdb30177106b5d6394223a40a382b87adf742
refs/heads/master
2022-11-09T21:55:43.857201
2022-10-24T21:08:19
2022-10-24T21:08:19
221,028,223
0
0
Apache-2.0
2019-11-11T16:57:12
2019-11-11T16:57:11
null
UTF-8
Java
false
false
2,344
java
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.chimesdkmessaging.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/chime-sdk-messaging-2021-05-15/DeleteChannel" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteChannelResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteChannelResult == false) return false; DeleteChannelResult other = (DeleteChannelResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public DeleteChannelResult clone() { try { return (DeleteChannelResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
[ "" ]
278ee080be74e929d103ff6931fe8fb8cd8bdad4
adac48930222d0ed92b352f9a0da0d17f0efc225
/src/main/java/com/rumakin/universityschedule/validation/validator/BusyGroupsConstraintValidator.java
ce940832506058ba02cc9017ef35ab9de94a8386
[]
no_license
Khilarian/universitySchedule
64d421eb1f7f119ff2c6d465507dcefd48d75714
140d15df4584a5846ffdd8378fb3393ac2e8edcd
refs/heads/master
2023-02-24T10:44:20.697956
2021-01-24T18:27:32
2021-01-24T18:27:32
305,832,368
0
0
null
2021-01-24T18:27:33
2020-10-20T21:00:05
Java
UTF-8
Java
false
false
2,463
java
package com.rumakin.universityschedule.validation.validator; import java.time.LocalDate; import java.util.*; import java.util.stream.Collectors; import javax.validation.*; import org.springframework.beans.factory.annotation.Autowired; import com.rumakin.universityschedule.dto.GroupDto; import com.rumakin.universityschedule.dto.LessonDto; import com.rumakin.universityschedule.service.*; import com.rumakin.universityschedule.validation.annotation.*; public class BusyGroupsConstraintValidator implements ConstraintValidator<BusyGroups, LessonDto> { @Autowired private LessonService lessonService; @Autowired private GroupService groupService; @Override public boolean isValid(LessonDto lessonDto, ConstraintValidatorContext context) { if (lessonDto.getLessonTypeId() == null || lessonDto.getTimeSlotId() == null) { return false; } String usedGroupsNames = getBusyGroupsName(lessonDto); boolean result = Objects.equals(usedGroupsNames, ""); if (!result) { String message; context.disableDefaultConstraintViolation(); if (usedGroupsNames.contains(", ")) { message = "Groups '%s' are busy at this time"; } else { message = "Group '%s' is busy at this time"; } context.buildConstraintViolationWithTemplate(String.format(message, usedGroupsNames)) .addPropertyNode("groups").addConstraintViolation(); } return result; } private String getBusyGroupsName(LessonDto lessonDto) { Set<Integer> usedGroupsId = getBusyGroupsId(lessonDto); Set<Integer> lessonGroupsId = getGroupsId(lessonDto); usedGroupsId.retainAll(lessonGroupsId); return getGroupsNames(usedGroupsId); } private Set<Integer> getBusyGroupsId(LessonDto lessonDto) { Integer lessonId = lessonDto.getId(); LocalDate date = lessonDto.getDate(); int timeSlotId = lessonDto.getTimeSlotId(); return lessonService.getBusyGroupsId(lessonId, date, timeSlotId); } private Set<Integer> getGroupsId(LessonDto lessonDto) { return lessonDto.getGroups().stream().map(GroupDto::getId).collect(Collectors.toSet()); } private String getGroupsNames(Set<Integer> groupsId) { return groupsId.stream().map(g -> groupService.findById(g).getName()).collect(Collectors.joining(", ")); } }
[ "donnorvator@gmail.com" ]
donnorvator@gmail.com
5b8cd7294037c61509d09f494576d45559d0852b
5ee1585a7ce0d1628c9696bd7d7527990f8734dc
/src/main/java/com/zxl/seckill/entity/SeckillOrder.java
eaaa7e88ee3b685e8712d33f4c92879781c52f1b
[]
no_license
zxlSoftHouse/seckill
380a0c80900a2f42b68da115cb32e5344c8a46b1
d3a4d92bbd3adaba2eee5a90e393bef180e5b584
refs/heads/master
2020-11-27T00:01:18.392700
2020-01-20T07:27:04
2020-01-20T07:27:04
229,236,776
0
0
null
null
null
null
UTF-8
Java
false
false
1,263
java
package com.zxl.seckill.entity; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableName; import com.zxl.seckill.util.BaseModel; import lombok.Data; import java.util.Date; /** * 秒杀订单表 */ @TableName("seckill_order") @Data public class SeckillOrder extends BaseModel { // 商品ID @TableField("product_id") private Long productId; // 支付金额 @TableField("pay_amount") private Float payAmount; // 用户ID @TableField("user_id") private Long userId; // 商家ID @TableField("business_id") private Long businessId; // 开始时间 @TableField("create_time") private Date createTime; // 支付时间 @TableField("pay_time") private Date payTime; // 审核状态,1-待支付,2-已支付,3-取消支付 @TableField("pay_status") private String payStatus; // 收货人 @TableField("receiver") private String receiver; // 收货人地址 @TableField("receiver_address") private String receiverAddress; // 收货人电话 @TableField("receiver_num") private String receiverNum; // 交易流水号 @TableField("serial_num") private String serialNum; }
[ "953519816@qq.com" ]
953519816@qq.com
8e5eedccb3f533fc39dafb03e8232ec7389d8a87
9b75d8540ff2e55f9ff66918cc5676ae19c3bbe3
/cab.snapp.passenger.play_184.apk-decompiled/sources/com/yandex/metrica/impl/ob/dt.java
0fd1f9ae29e650cc8d953f3f78effdcd791ec906
[]
no_license
BaseMax/PopularAndroidSource
a395ccac5c0a7334d90c2594db8273aca39550ed
bcae15340907797a91d39f89b9d7266e0292a184
refs/heads/master
2020-08-05T08:19:34.146858
2019-10-06T20:06:31
2019-10-06T20:06:31
212,433,298
2
0
null
null
null
null
UTF-8
Java
false
false
247
java
package com.yandex.metrica.impl.ob; import java.util.List; public class dt extends dh<cm> { public dt(Cdo doVar) { super(doVar); } public void a(List<cm> list) { list.add(a().f()); list.add(a().a()); } }
[ "MaxBaseCode@gmail.com" ]
MaxBaseCode@gmail.com
0adb57dabf12b9841d6c4206a9608151fddd3967
17e74ecab72d7d98f78805dd71b3f79e3dfef394
/chapitre1-2/chapitre1-2-samples/src/main/java/org/kearis/formation/javaee7/chapitre1_2/ex04/CardValidator04.java
c8845fa9fa71efee5e05daa3bb41090104c25fdf
[]
no_license
Droopy06/javaee7
37be5467851023fbd26b1db39b00f480ab1d718f
9790145777cac57ac820a5e5e9c7dfa8a2f92fd6
refs/heads/master
2021-01-12T13:55:32.851125
2016-09-30T14:52:48
2016-09-30T14:52:48
68,922,813
0
0
null
2016-09-22T13:15:12
2016-09-22T13:15:12
null
UTF-8
Java
false
false
1,585
java
package org.kearis.formation.javaee7.chapitre1_2.ex04; import javax.validation.Valid; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.Future; import javax.validation.constraints.NotNull; import java.util.Date; public class CardValidator04 { private ValidationAlgorithm validationAlgorithm; // ====================================== // = Constructors = // ====================================== public CardValidator04() { } public CardValidator04(ValidationAlgorithm validationAlgorithm) { this.validationAlgorithm = validationAlgorithm; } // ====================================== // = Public Methods = // ====================================== // @AssertTrue public Boolean validate(CreditCard04 creditCard) { String lastDigit = validationAlgorithm.validate(creditCard.getNumber(), creditCard.getControlNumber()); if (Integer.parseInt(lastDigit.toString()) % 2 == 0) { return true; } else { return false; } } @AssertTrue public Boolean validate(String number, Date expiryDate, Integer controlNumber, String type) { String lastDigit = validationAlgorithm.validate(number, controlNumber); if (Integer.parseInt(lastDigit.toString()) % 2 == 0) { return true; } else { return false; } } private class ValidationAlgorithm { public String validate(String number, Integer controlNumber) { Character lastDigit = number.charAt(number.length() - 1); return lastDigit.toString(); } } }
[ "poutsjr@gmail.com" ]
poutsjr@gmail.com
f353efd31134f0cf3484d150ee7b0bde482dc9c7
06270ea86a1b265128959bbf42082e70f6fed376
/src/main/java/com/meti/lib/util/Action.java
15ddab7c548eb60c8a4ab92979c0a0a79a0e2371
[ "MIT" ]
permissive
Sgt-Tesla/Nexus
d6988b1ad04b5e83126a2ed8b0a5d06f319dc5db
2a7893415310bd7a6c060ba3ea5160a9577e904c
refs/heads/master
2021-08-31T20:59:07.979897
2017-12-22T22:19:19
2017-12-22T22:19:19
110,032,712
0
0
MIT
2017-12-22T22:22:06
2017-11-08T21:30:53
Java
UTF-8
Java
false
false
156
java
package com.meti.lib.util; /** * @author SirMathhman * @version 0.0.0 * @since 12/18/2017 */ public interface Action<P, R> { R act(P... params); }
[ "minecraftmathhman@gmail.com" ]
minecraftmathhman@gmail.com
43e0bca36246b0ec53c5596971bcc6e52f0a81bf
4f94294ab4aca7e28c6ad09ca5bc59729c5c8113
/eureka-http-server8000/src/main/java/com/hust/springcloud/controller/AccountFeignController.java
4f05d8033607c01fb31d72d2fcb8eb082ce1771f
[]
no_license
YzwWh9327/hehe
d3376570333ee3e5d5870d228afe62a5df17fd4d
bb83f784adcbdc0c91f5c989fc83e6e67f52ba27
refs/heads/master
2023-06-22T21:49:10.464731
2021-07-15T12:08:12
2021-07-15T12:08:12
385,605,307
1
0
null
null
null
null
UTF-8
Java
false
false
2,460
java
package com.hust.springcloud.controller; import com.hust.springcloud.common.Result; import com.hust.springcloud.service.AccountFeignService; import com.hust.springcloud.utils.CsvImporExporttUtil; import feign.Response; import lombok.extern.slf4j.Slf4j; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; @RestController @Slf4j @RequestMapping("consumer") public class AccountFeignController { @Resource private AccountFeignService accountFeignService; @PostMapping(value = "upload") public Result upload(@RequestPart(value = "file") MultipartFile file){ return accountFeignService.upload(file); } @GetMapping("list") public Result list(@RequestParam("accountName")String accountName){ return accountFeignService.list(accountName); } @GetMapping("download") public void download(@RequestParam("min_create_date")String min_create_date, @RequestParam("max_create_date")String max_create_date, HttpServletResponse response){ String fName = "AccountInfo_"; try { CsvImporExporttUtil.responseSetProperties(fName,response); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Response rs = accountFeignService.download(min_create_date, max_create_date, response); InputStream inputStream = null; ServletOutputStream outputStream =null; try { inputStream = rs.body().asInputStream(); outputStream = response.getOutputStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); }finally { try { outputStream.flush(); outputStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
[ "zhengwu.yang@shopee.com" ]
zhengwu.yang@shopee.com
cc02cd7b3771543a93e6c99bc6526d8273623054
129f3c9dbce3f11e6ab75878a2e02963b90f576a
/src/test/java/hello/core/scan/filter/ComponentFilterAppConfigTest.java
51821c02536b6312e7cb4af01a3c35dd4b8c3cd0
[]
no_license
oksusutea/core
7eb7663a80ab84f85fe04fa00599c898ef54a5bd
59573d1edec2aa7e0b72181e94df8d46f8f85a82
refs/heads/master
2023-03-12T01:37:00.359631
2021-03-01T05:56:46
2021-03-01T05:56:46
341,596,077
0
0
null
null
null
null
UTF-8
Java
false
false
1,418
java
package hello.core.scan.filter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.context.annotation.ComponentScan.*; public class ComponentFilterAppConfigTest { @Test void filterScan(){ AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ComponentFilterAppConfig.class); BeanA beanA = ac.getBean("beanA", BeanA.class); assertThat(beanA).isNotNull(); //BeanB beanB = ac.getBean("beanB",BeanB.class); //assertThat(beanB).isNull(); Assertions.assertThrows( NoSuchBeanDefinitionException.class, () -> ac.getBean("beanB",BeanB.class)); } @Configuration @ComponentScan( includeFilters = @Filter(type = FilterType.ANNOTATION, classes = MyIncludeComponent.class), excludeFilters = @Filter(type = FilterType.ANNOTATION, classes = MyExcludeComponent.class) ) static class ComponentFilterAppConfig{ } }
[ "chanjukim118@gmail.com" ]
chanjukim118@gmail.com
c45551d3e51ff4f3a163eafcfd93ce62bb30e90d
b8823ac1e0e5613a06213e3359513fa9481914e9
/hyracks/hyracks-storage-am-lsm-common/src/main/java/edu/uci/ics/hyracks/storage/am/lsm/common/impls/AbstractMemoryLSMComponent.java
ce4817b906b580e9bac5c0e536320565f2a49d91
[]
no_license
uci-cbcl/genomix
21ae2c8414a1982826477545dae8b783ccd74c6a
42a8f09a0f2b4ed907f94228115a97d5469c94cb
refs/heads/genomix/fullstack_genomix
2021-01-18T18:12:25.430452
2016-02-22T17:38:51
2016-02-22T17:38:51
13,568,234
2
1
null
2019-02-12T00:10:16
2013-10-14T17:35:48
Java
UTF-8
Java
false
false
6,297
java
/* * Copyright 2009-2013 by The Regents of the University of California * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * you may obtain a copy of the License from * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.hyracks.storage.am.lsm.common.impls; import java.util.concurrent.atomic.AtomicBoolean; import edu.uci.ics.hyracks.api.exceptions.HyracksDataException; import edu.uci.ics.hyracks.storage.am.lsm.common.api.IVirtualBufferCache; public abstract class AbstractMemoryLSMComponent extends AbstractLSMComponent { private int writerCount; private final IVirtualBufferCache vbc; private final AtomicBoolean isModified; private boolean requestedToBeActive; public AbstractMemoryLSMComponent(IVirtualBufferCache vbc, boolean isActive) { super(); this.vbc = vbc; writerCount = 0; if (isActive) { state = ComponentState.READABLE_WRITABLE; } else { state = ComponentState.INACTIVE; } isModified = new AtomicBoolean(); } @Override public boolean threadEnter(LSMOperationType opType, boolean isMutableComponent) throws HyracksDataException { if (state == ComponentState.INACTIVE && requestedToBeActive) { state = ComponentState.READABLE_WRITABLE; requestedToBeActive = false; } switch (opType) { case FORCE_MODIFICATION: if (isMutableComponent) { if (state == ComponentState.READABLE_WRITABLE || state == ComponentState.READABLE_UNWRITABLE) { writerCount++; } else { return false; } } else { if (state == ComponentState.READABLE_UNWRITABLE || state == ComponentState.READABLE_UNWRITABLE_FLUSHING) { readerCount++; } else { return false; } } break; case MODIFICATION: if (isMutableComponent) { if (state == ComponentState.READABLE_WRITABLE) { writerCount++; } else { return false; } } else { if (state == ComponentState.READABLE_UNWRITABLE || state == ComponentState.READABLE_UNWRITABLE_FLUSHING) { readerCount++; } else { return false; } } break; case SEARCH: if (state == ComponentState.READABLE_WRITABLE || state == ComponentState.READABLE_UNWRITABLE || state == ComponentState.READABLE_UNWRITABLE_FLUSHING) { readerCount++; } else { return false; } break; case FLUSH: if (state == ComponentState.READABLE_WRITABLE || state == ComponentState.READABLE_UNWRITABLE) { assert writerCount == 0; state = ComponentState.READABLE_UNWRITABLE_FLUSHING; readerCount++; } else { return false; } break; default: throw new UnsupportedOperationException("Unsupported operation " + opType); } return true; } @Override public void threadExit(LSMOperationType opType, boolean failedOperation, boolean isMutableComponent) throws HyracksDataException { switch (opType) { case FORCE_MODIFICATION: case MODIFICATION: if (isMutableComponent) { writerCount--; if (state == ComponentState.READABLE_WRITABLE && isFull()) { state = ComponentState.READABLE_UNWRITABLE; } } else { readerCount--; if (state == ComponentState.UNREADABLE_UNWRITABLE && readerCount == 0) { state = ComponentState.INACTIVE; } } break; case SEARCH: readerCount--; if (state == ComponentState.UNREADABLE_UNWRITABLE && readerCount == 0) { state = ComponentState.INACTIVE; } break; case FLUSH: assert state == ComponentState.READABLE_UNWRITABLE_FLUSHING; readerCount--; if (readerCount == 0) { state = ComponentState.INACTIVE; } else { state = ComponentState.UNREADABLE_UNWRITABLE; } break; default: throw new UnsupportedOperationException("Unsupported operation " + opType); } assert readerCount > -1 && writerCount > -1; } public boolean isReadable() { if (state == ComponentState.INACTIVE || state == ComponentState.UNREADABLE_UNWRITABLE) { return false; } return true; } @Override public LSMComponentType getType() { return LSMComponentType.MEMORY; } @Override public ComponentState getState() { return state; } public void setActive() { requestedToBeActive = true; } public void setIsModified() { isModified.set(true); } public boolean isModified() { return isModified.get(); } public boolean isFull() { return vbc.isFull(); } protected void reset() throws HyracksDataException { isModified.set(false); } }
[ "salsubaiee@gmail.com" ]
salsubaiee@gmail.com
eb20a2f466cd3a825dc1e9bf377b3fb870400ea1
3ac425d82933d34187413e2c912e49bced9ad206
/kline/src/main/java/com/season/example/fragment/DealFragment.java
9f3f95d661680241b936880ea19c28a866d6327b
[]
no_license
Seasonallan/KLineChart
f03e02b71eb1214157b53eb05ecaf4ca8124733d
c31edc2bd9fa0aea2e2df507d06b66d96a32fbb6
refs/heads/master
2023-07-03T14:33:45.259012
2021-08-13T02:35:58
2021-08-13T02:35:58
389,884,442
2
0
null
null
null
null
UTF-8
Java
false
false
5,247
java
package com.season.example.fragment; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.season.example.util.CoinCodeDecimalUtil; import com.season.klinechart.ColorStrategy; import com.season.mylibrary.R; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class DealFragment extends Fragment { RecyclerView recycler_view; private List<DealRecord> items = new ArrayList<>(); private DealRecordAdapter myAdapter; public static DealFragment getInstance() { Bundle args = new Bundle(); DealFragment fragment = new DealFragment(); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View parent = inflater.inflate(R.layout.kc_fragment_deal, null); recycler_view = parent.findViewById(R.id.recycler_view); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); recycler_view.setLayoutManager(linearLayoutManager); for (int i = 0; i < 20; i++) { items.add(new DealRecord()); } myAdapter = new DealRecordAdapter(getContext(), items); recycler_view.setAdapter(myAdapter); return parent; } public String coinCode = ""; @Override public void onDestroy() { super.onDestroy(); } public void onRecordChange(List<DealRecord> list) { for (int i = 0; i < list.size(); i++) { items.add(0, list.get(i)); items.remove(items.size() - 1); } myAdapter.notifyDataSetChanged(); } public class DealRecordAdapter extends RecyclerView.Adapter<DealRecordAdapter.DealHolder> { List<DealRecord> list; Context context; private DecimalFormat dfCoinNumber;//币种数量小数位限制 private DecimalFormat dfCoinPrice;//币种价格小数位限制 DealRecordAdapter(Context context, List<DealRecord> list) { this.list = list; this.context = context; this.dfCoinPrice = new DecimalFormat(CoinCodeDecimalUtil.getDecimalFormatPrice(coinCode));//币种价格小数位限制 this.dfCoinNumber = new DecimalFormat(CoinCodeDecimalUtil.getDecimalFormatNumber(coinCode));//币种数量小数位限制 } @Override public int getItemViewType(int position) { return position == 0 ? 0 : 1; } @Override public DealHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(ColorStrategy.getStrategy().isBlackTheme()?(viewType == 0 ? R.layout.kc_item_deal_record0 : R.layout.kc_item_deal_record):(viewType == 0 ? R.layout.kc_item_deal_record0_white : R.layout.kc_item_deal_record_white), parent, false); DealHolder holder = new DealHolder(view); return holder; } @Override public void onBindViewHolder(DealRecordAdapter.DealHolder holder, int position) { if (position == 0) { return; } DealRecord item = list.get(position - 1); if (item.getId() == -1) { holder.timeView.setText(""); holder.directionView.setText(""); holder.priceView.setText(""); holder.numView.setText(""); } else { holder.timeView.setText(new SimpleDateFormat("HH:mm:ss").format(new Date(item.getTime() * 1000L))); holder.directionView.setText(context.getResources().getString(item.getDirection() == 1 ? R.string.buy : R.string.sale)); holder.directionView.setTextColor(context.getResources().getColor(item.getDirection() == 1 ? ColorStrategy.getStrategy().getRiseColor() : ColorStrategy.getStrategy().getFallColor())); holder.priceView.setText(dfCoinPrice.format(Double.parseDouble(item.getPrice()))); holder.numView.setText(dfCoinNumber.format(item.getAmount())); } } @Override public int getItemCount() { return list.size() + 1; } class DealHolder extends RecyclerView.ViewHolder { public TextView timeView, directionView, priceView, numView; public DealHolder(@NonNull View itemView) { super(itemView); timeView = itemView.findViewById(R.id.time_list); directionView = itemView.findViewById(R.id.direction_list); priceView = itemView.findViewById(R.id.price_list); numView = itemView.findViewById(R.id.num_list); } } } }
[ "451360508@qq.com" ]
451360508@qq.com
3cd245ab88c6605c2036b08842b06a8a3b4bf3c2
c63344105ced320b5a015836a1a5315af7f8ec80
/atcrowdfunding-bean/src/main/java/com/atguigu/atcrowdfunding/bean/RolePermission.java
daa1241e224daf46108760bbc735aa1160c3d395
[]
no_license
rokumon/AtCrowdFunding
ace80fc955c818d939b36f2433c46c8e84d59d37
1008bf6713bc7863068b2ca853196415e31072c5
refs/heads/master
2020-03-21T14:33:51.653304
2018-06-30T04:33:15
2018-06-30T04:33:15
138,663,496
0
0
null
null
null
null
UTF-8
Java
false
false
607
java
package com.atguigu.atcrowdfunding.bean; public class RolePermission { private Integer id; private Integer roleid; private Integer permissionid; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getRoleid() { return roleid; } public void setRoleid(Integer roleid) { this.roleid = roleid; } public Integer getPermissionid() { return permissionid; } public void setPermissionid(Integer permissionid) { this.permissionid = permissionid; } }
[ "rokumon@163.com" ]
rokumon@163.com
67442d205419dc61002f87b4bfbbeb7f2c2d7595
c9323b8e577261a8adb0740fee2ab3b6fb63f40d
/Week_01/id_41/LeetCode_441_41.java
f384d1a654322482c1b919fdcdc1282f47e4ca7f
[]
no_license
mikejicken/algorithm
15ea83f34a2dd8fede636c9be6902cf1db104763
8244e0cb73f8ad9a159469c16e63b1628f24ba66
refs/heads/master
2020-05-14T14:09:43.241029
2019-05-12T15:57:22
2019-05-12T15:57:22
181,827,289
0
0
null
2019-04-17T06:05:12
2019-04-17T06:05:08
Java
UTF-8
Java
false
false
286
java
class LeetCode_441_41 { public int arrangeCoins(int n) { int i=1; while(n>0){ n-=i; i++; if(n<i){ return i-1; } } return 0; } }
[ "wq123456" ]
wq123456
5026c9fd8831cd490dd026e896d00847b4ad7e55
80552d844f54667b4d6f00845a667026d656e1ba
/zip/spring-framework-3.2.x/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java
c6ada1f25f0e96592d8fade1d9fa769c4cdb80e9
[ "Apache-2.0" ]
permissive
13266764646/spring-framewrok3.2.x
e662e4d633adec91fcfca6d66e15a7555044429d
84c238239ebd8cebdddee540c0fefa8e4755eac8
refs/heads/master
2020-05-03T15:38:25.422211
2019-08-26T02:44:12
2019-08-26T02:44:12
178,707,063
1
0
null
null
null
null
UTF-8
Java
false
false
60,158
java
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.propertyeditors; import static org.junit.Assert.*; import java.beans.PropertyEditor; import java.beans.PropertyEditorSupport; import java.beans.PropertyVetoException; import java.io.File; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import java.util.regex.Pattern; import org.junit.Test; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.tests.sample.beans.BooleanTestBean; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.IndexedTestBean; import org.springframework.tests.sample.beans.NumberTestBean; import org.springframework.tests.sample.beans.TestBean; /** * Unit tests for the various PropertyEditors in Spring. * * @author Juergen Hoeller * @author Rick Evans * @author Rob Harrop * @author Arjen Poutsma * @author Chris Beams * @since 10.06.2003 */ public class CustomEditorTests { @Test public void testComplexObject() { TestBean tb = new TestBean(); String newName = "Rod"; String tbString = "Kerry_34"; BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(ITestBean.class, new TestBeanEditor()); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("age", new Integer(55))); pvs.addPropertyValue(new PropertyValue("name", newName)); pvs.addPropertyValue(new PropertyValue("touchy", "valid")); pvs.addPropertyValue(new PropertyValue("spouse", tbString)); bw.setPropertyValues(pvs); assertTrue("spouse is non-null", tb.getSpouse() != null); assertTrue("spouse name is Kerry and age is 34", tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34); } @Test public void testComplexObjectWithOldValueAccess() { TestBean tb = new TestBean(); String newName = "Rod"; String tbString = "Kerry_34"; BeanWrapper bw = new BeanWrapperImpl(tb); bw.setExtractOldValueForEditor(true); bw.registerCustomEditor(ITestBean.class, new OldValueAccessingTestBeanEditor()); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("age", new Integer(55))); pvs.addPropertyValue(new PropertyValue("name", newName)); pvs.addPropertyValue(new PropertyValue("touchy", "valid")); pvs.addPropertyValue(new PropertyValue("spouse", tbString)); bw.setPropertyValues(pvs); assertTrue("spouse is non-null", tb.getSpouse() != null); assertTrue("spouse name is Kerry and age is 34", tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34); ITestBean spouse = tb.getSpouse(); bw.setPropertyValues(pvs); assertSame("Should have remained same object", spouse, tb.getSpouse()); } @Test public void testCustomEditorForSingleProperty() { TestBean tb = new TestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(String.class, "name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("prefix" + text); } }); bw.setPropertyValue("name", "value"); bw.setPropertyValue("touchy", "value"); assertEquals("prefixvalue", bw.getPropertyValue("name")); assertEquals("prefixvalue", tb.getName()); assertEquals("value", bw.getPropertyValue("touchy")); assertEquals("value", tb.getTouchy()); } @Test public void testCustomEditorForAllStringProperties() { TestBean tb = new TestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(String.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("prefix" + text); } }); bw.setPropertyValue("name", "value"); bw.setPropertyValue("touchy", "value"); assertEquals("prefixvalue", bw.getPropertyValue("name")); assertEquals("prefixvalue", tb.getName()); assertEquals("prefixvalue", bw.getPropertyValue("touchy")); assertEquals("prefixvalue", tb.getTouchy()); } @Test public void testCustomEditorForSingleNestedProperty() { TestBean tb = new TestBean(); tb.setSpouse(new TestBean()); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(String.class, "spouse.name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("prefix" + text); } }); bw.setPropertyValue("spouse.name", "value"); bw.setPropertyValue("touchy", "value"); assertEquals("prefixvalue", bw.getPropertyValue("spouse.name")); assertEquals("prefixvalue", tb.getSpouse().getName()); assertEquals("value", bw.getPropertyValue("touchy")); assertEquals("value", tb.getTouchy()); } @Test public void testCustomEditorForAllNestedStringProperties() { TestBean tb = new TestBean(); tb.setSpouse(new TestBean()); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(String.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("prefix" + text); } }); bw.setPropertyValue("spouse.name", "value"); bw.setPropertyValue("touchy", "value"); assertEquals("prefixvalue", bw.getPropertyValue("spouse.name")); assertEquals("prefixvalue", tb.getSpouse().getName()); assertEquals("prefixvalue", bw.getPropertyValue("touchy")); assertEquals("prefixvalue", tb.getTouchy()); } @Test public void testDefaultBooleanEditorForPrimitiveType() { BooleanTestBean tb = new BooleanTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.setPropertyValue("bool1", "true"); assertTrue("Correct bool1 value", Boolean.TRUE.equals(bw.getPropertyValue("bool1"))); assertTrue("Correct bool1 value", tb.isBool1()); bw.setPropertyValue("bool1", "false"); assertTrue("Correct bool1 value", Boolean.FALSE.equals(bw.getPropertyValue("bool1"))); assertTrue("Correct bool1 value", !tb.isBool1()); bw.setPropertyValue("bool1", " true "); assertTrue("Correct bool1 value", tb.isBool1()); bw.setPropertyValue("bool1", " false "); assertTrue("Correct bool1 value", !tb.isBool1()); bw.setPropertyValue("bool1", "on"); assertTrue("Correct bool1 value", tb.isBool1()); bw.setPropertyValue("bool1", "off"); assertTrue("Correct bool1 value", !tb.isBool1()); bw.setPropertyValue("bool1", "yes"); assertTrue("Correct bool1 value", tb.isBool1()); bw.setPropertyValue("bool1", "no"); assertTrue("Correct bool1 value", !tb.isBool1()); bw.setPropertyValue("bool1", "1"); assertTrue("Correct bool1 value", tb.isBool1()); bw.setPropertyValue("bool1", "0"); assertTrue("Correct bool1 value", !tb.isBool1()); try { bw.setPropertyValue("bool1", "argh"); fail("Should have thrown BeansException"); } catch (BeansException ex) { // expected } } @Test public void testDefaultBooleanEditorForWrapperType() { BooleanTestBean tb = new BooleanTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.setPropertyValue("bool2", "true"); assertTrue("Correct bool2 value", Boolean.TRUE.equals(bw.getPropertyValue("bool2"))); assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "false"); assertTrue("Correct bool2 value", Boolean.FALSE.equals(bw.getPropertyValue("bool2"))); assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "on"); assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "off"); assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "yes"); assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "no"); assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "1"); assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "0"); assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", ""); assertNull("Correct bool2 value", tb.getBool2()); } @Test public void testCustomBooleanEditorWithAllowEmpty() { BooleanTestBean tb = new BooleanTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(Boolean.class, new CustomBooleanEditor(true)); bw.setPropertyValue("bool2", "true"); assertTrue("Correct bool2 value", Boolean.TRUE.equals(bw.getPropertyValue("bool2"))); assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "false"); assertTrue("Correct bool2 value", Boolean.FALSE.equals(bw.getPropertyValue("bool2"))); assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "on"); assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "off"); assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "yes"); assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "no"); assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "1"); assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", "0"); assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); bw.setPropertyValue("bool2", ""); assertTrue("Correct bool2 value", bw.getPropertyValue("bool2") == null); assertTrue("Correct bool2 value", tb.getBool2() == null); } @Test public void testCustomBooleanEditorWithSpecialTrueAndFalseStrings() throws Exception { String trueString = "pechorin"; String falseString = "nash"; CustomBooleanEditor editor = new CustomBooleanEditor(trueString, falseString, false); editor.setAsText(trueString); assertTrue(((Boolean) editor.getValue()).booleanValue()); assertEquals(trueString, editor.getAsText()); editor.setAsText(falseString); assertFalse(((Boolean) editor.getValue()).booleanValue()); assertEquals(falseString, editor.getAsText()); editor.setAsText(trueString.toUpperCase()); assertTrue(((Boolean) editor.getValue()).booleanValue()); assertEquals(trueString, editor.getAsText()); editor.setAsText(falseString.toUpperCase()); assertFalse(((Boolean) editor.getValue()).booleanValue()); assertEquals(falseString, editor.getAsText()); try { editor.setAsText(null); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } } @Test public void testDefaultNumberEditor() { NumberTestBean tb = new NumberTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.setPropertyValue("short1", "1"); bw.setPropertyValue("short2", "2"); bw.setPropertyValue("int1", "7"); bw.setPropertyValue("int2", "8"); bw.setPropertyValue("long1", "5"); bw.setPropertyValue("long2", "6"); bw.setPropertyValue("bigInteger", "3"); bw.setPropertyValue("float1", "7.1"); bw.setPropertyValue("float2", "8.1"); bw.setPropertyValue("double1", "5.1"); bw.setPropertyValue("double2", "6.1"); bw.setPropertyValue("bigDecimal", "4.5"); assertTrue("Correct short1 value", new Short("1").equals(bw.getPropertyValue("short1"))); assertTrue("Correct short1 value", tb.getShort1() == 1); assertTrue("Correct short2 value", new Short("2").equals(bw.getPropertyValue("short2"))); assertTrue("Correct short2 value", new Short("2").equals(tb.getShort2())); assertTrue("Correct int1 value", new Integer("7").equals(bw.getPropertyValue("int1"))); assertTrue("Correct int1 value", tb.getInt1() == 7); assertTrue("Correct int2 value", new Integer("8").equals(bw.getPropertyValue("int2"))); assertTrue("Correct int2 value", new Integer("8").equals(tb.getInt2())); assertTrue("Correct long1 value", new Long("5").equals(bw.getPropertyValue("long1"))); assertTrue("Correct long1 value", tb.getLong1() == 5); assertTrue("Correct long2 value", new Long("6").equals(bw.getPropertyValue("long2"))); assertTrue("Correct long2 value", new Long("6").equals(tb.getLong2())); assertTrue("Correct bigInteger value", new BigInteger("3").equals(bw.getPropertyValue("bigInteger"))); assertTrue("Correct bigInteger value", new BigInteger("3").equals(tb.getBigInteger())); assertTrue("Correct float1 value", new Float("7.1").equals(bw.getPropertyValue("float1"))); assertTrue("Correct float1 value", new Float("7.1").equals(new Float(tb.getFloat1()))); assertTrue("Correct float2 value", new Float("8.1").equals(bw.getPropertyValue("float2"))); assertTrue("Correct float2 value", new Float("8.1").equals(tb.getFloat2())); assertTrue("Correct double1 value", new Double("5.1").equals(bw.getPropertyValue("double1"))); assertTrue("Correct double1 value", tb.getDouble1() == 5.1); assertTrue("Correct double2 value", new Double("6.1").equals(bw.getPropertyValue("double2"))); assertTrue("Correct double2 value", new Double("6.1").equals(tb.getDouble2())); assertTrue("Correct bigDecimal value", new BigDecimal("4.5").equals(bw.getPropertyValue("bigDecimal"))); assertTrue("Correct bigDecimal value", new BigDecimal("4.5").equals(tb.getBigDecimal())); } @Test public void testCustomNumberEditorWithoutAllowEmpty() { NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN); NumberTestBean tb = new NumberTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(short.class, new CustomNumberEditor(Short.class, nf, false)); bw.registerCustomEditor(Short.class, new CustomNumberEditor(Short.class, nf, false)); bw.registerCustomEditor(int.class, new CustomNumberEditor(Integer.class, nf, false)); bw.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, nf, false)); bw.registerCustomEditor(long.class, new CustomNumberEditor(Long.class, nf, false)); bw.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, nf, false)); bw.registerCustomEditor(BigInteger.class, new CustomNumberEditor(BigInteger.class, nf, false)); bw.registerCustomEditor(float.class, new CustomNumberEditor(Float.class, nf, false)); bw.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, false)); bw.registerCustomEditor(double.class, new CustomNumberEditor(Double.class, nf, false)); bw.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, nf, false)); bw.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, nf, false)); bw.setPropertyValue("short1", "1"); bw.setPropertyValue("short2", "2"); bw.setPropertyValue("int1", "7"); bw.setPropertyValue("int2", "8"); bw.setPropertyValue("long1", "5"); bw.setPropertyValue("long2", "6"); bw.setPropertyValue("bigInteger", "3"); bw.setPropertyValue("float1", "7,1"); bw.setPropertyValue("float2", "8,1"); bw.setPropertyValue("double1", "5,1"); bw.setPropertyValue("double2", "6,1"); bw.setPropertyValue("bigDecimal", "4,5"); assertTrue("Correct short1 value", new Short("1").equals(bw.getPropertyValue("short1"))); assertTrue("Correct short1 value", tb.getShort1() == 1); assertTrue("Correct short2 value", new Short("2").equals(bw.getPropertyValue("short2"))); assertTrue("Correct short2 value", new Short("2").equals(tb.getShort2())); assertTrue("Correct int1 value", new Integer("7").equals(bw.getPropertyValue("int1"))); assertTrue("Correct int1 value", tb.getInt1() == 7); assertTrue("Correct int2 value", new Integer("8").equals(bw.getPropertyValue("int2"))); assertTrue("Correct int2 value", new Integer("8").equals(tb.getInt2())); assertTrue("Correct long1 value", new Long("5").equals(bw.getPropertyValue("long1"))); assertTrue("Correct long1 value", tb.getLong1() == 5); assertTrue("Correct long2 value", new Long("6").equals(bw.getPropertyValue("long2"))); assertTrue("Correct long2 value", new Long("6").equals(tb.getLong2())); assertTrue("Correct bigInteger value", new BigInteger("3").equals(bw.getPropertyValue("bigInteger"))); assertTrue("Correct bigInteger value", new BigInteger("3").equals(tb.getBigInteger())); assertTrue("Correct float1 value", new Float("7.1").equals(bw.getPropertyValue("float1"))); assertTrue("Correct float1 value", new Float("7.1").equals(new Float(tb.getFloat1()))); assertTrue("Correct float2 value", new Float("8.1").equals(bw.getPropertyValue("float2"))); assertTrue("Correct float2 value", new Float("8.1").equals(tb.getFloat2())); assertTrue("Correct double1 value", new Double("5.1").equals(bw.getPropertyValue("double1"))); assertTrue("Correct double1 value", tb.getDouble1() == 5.1); assertTrue("Correct double2 value", new Double("6.1").equals(bw.getPropertyValue("double2"))); assertTrue("Correct double2 value", new Double("6.1").equals(tb.getDouble2())); assertTrue("Correct bigDecimal value", new BigDecimal("4.5").equals(bw.getPropertyValue("bigDecimal"))); assertTrue("Correct bigDecimal value", new BigDecimal("4.5").equals(tb.getBigDecimal())); } @Test(expected = IllegalArgumentException.class) public void testCustomNumberEditorCtorWithNullNumberType() throws Exception { new CustomNumberEditor(null, true); } @Test public void testCustomNumberEditorWithAllowEmpty() { NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN); NumberTestBean tb = new NumberTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(long.class, new CustomNumberEditor(Long.class, nf, true)); bw.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, nf, true)); bw.setPropertyValue("long1", "5"); bw.setPropertyValue("long2", "6"); assertTrue("Correct long1 value", new Long("5").equals(bw.getPropertyValue("long1"))); assertTrue("Correct long1 value", tb.getLong1() == 5); assertTrue("Correct long2 value", new Long("6").equals(bw.getPropertyValue("long2"))); assertTrue("Correct long2 value", new Long("6").equals(tb.getLong2())); bw.setPropertyValue("long2", ""); assertTrue("Correct long2 value", bw.getPropertyValue("long2") == null); assertTrue("Correct long2 value", tb.getLong2() == null); try { bw.setPropertyValue("long1", ""); fail("Should have thrown BeansException"); } catch (BeansException ex) { // expected assertTrue("Correct long1 value", new Long("5").equals(bw.getPropertyValue("long1"))); assertTrue("Correct long1 value", tb.getLong1() == 5); } } @Test public void testCustomNumberEditorWithFrenchBigDecimal() throws Exception { NumberFormat nf = NumberFormat.getNumberInstance(Locale.FRENCH); NumberTestBean tb = new NumberTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, nf, true)); bw.setPropertyValue("bigDecimal", "1000"); assertEquals(1000.0f, tb.getBigDecimal().floatValue(), 0f); bw.setPropertyValue("bigDecimal", "1000,5"); assertEquals(1000.5f, tb.getBigDecimal().floatValue(), 0f); bw.setPropertyValue("bigDecimal", "1 000,5"); assertEquals(1000.5f, tb.getBigDecimal().floatValue(), 0f); } @Test public void testParseShortGreaterThanMaxValueWithoutNumberFormat() { try { CustomNumberEditor editor = new CustomNumberEditor(Short.class, true); editor.setAsText(String.valueOf(Short.MAX_VALUE + 1)); fail(Short.MAX_VALUE + 1 + " is greater than max value"); } catch (NumberFormatException ex) { // expected } } @Test public void testByteArrayPropertyEditor() { PrimitiveArrayBean bean = new PrimitiveArrayBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.setPropertyValue("byteArray", "myvalue"); assertEquals("myvalue", new String(bean.getByteArray())); } @Test public void testCharArrayPropertyEditor() { PrimitiveArrayBean bean = new PrimitiveArrayBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.setPropertyValue("charArray", "myvalue"); assertEquals("myvalue", new String(bean.getCharArray())); } @Test public void testCharacterEditor() { CharBean cb = new CharBean(); BeanWrapper bw = new BeanWrapperImpl(cb); bw.setPropertyValue("myChar", new Character('c')); assertEquals('c', cb.getMyChar()); bw.setPropertyValue("myChar", "c"); assertEquals('c', cb.getMyChar()); bw.setPropertyValue("myChar", "\u0041"); assertEquals('A', cb.getMyChar()); bw.setPropertyValue("myChar", "\\u0022"); assertEquals('"', cb.getMyChar()); CharacterEditor editor = new CharacterEditor(false); editor.setAsText("M"); assertEquals("M", editor.getAsText()); } @Test public void testCharacterEditorWithAllowEmpty() { CharBean cb = new CharBean(); BeanWrapper bw = new BeanWrapperImpl(cb); bw.registerCustomEditor(Character.class, new CharacterEditor(true)); bw.setPropertyValue("myCharacter", new Character('c')); assertEquals(new Character('c'), cb.getMyCharacter()); bw.setPropertyValue("myCharacter", "c"); assertEquals(new Character('c'), cb.getMyCharacter()); bw.setPropertyValue("myCharacter", "\u0041"); assertEquals(new Character('A'), cb.getMyCharacter()); bw.setPropertyValue("myCharacter", " "); assertEquals(new Character(' '), cb.getMyCharacter()); bw.setPropertyValue("myCharacter", ""); assertNull(cb.getMyCharacter()); } @Test(expected = IllegalArgumentException.class) public void testCharacterEditorSetAsTextWithStringLongerThanOneCharacter() throws Exception { PropertyEditor charEditor = new CharacterEditor(false); charEditor.setAsText("ColdWaterCanyon"); } @Test public void testCharacterEditorGetAsTextReturnsEmptyStringIfValueIsNull() throws Exception { PropertyEditor charEditor = new CharacterEditor(false); assertEquals("", charEditor.getAsText()); charEditor = new CharacterEditor(true); charEditor.setAsText(null); assertEquals("", charEditor.getAsText()); charEditor.setAsText(""); assertEquals("", charEditor.getAsText()); charEditor.setAsText(" "); assertEquals(" ", charEditor.getAsText()); } @Test(expected = IllegalArgumentException.class) public void testCharacterEditorSetAsTextWithNullNotAllowingEmptyAsNull() throws Exception { PropertyEditor charEditor = new CharacterEditor(false); charEditor.setAsText(null); } @Test public void testClassEditor() { PropertyEditor classEditor = new ClassEditor(); classEditor.setAsText(TestBean.class.getName()); assertEquals(TestBean.class, classEditor.getValue()); assertEquals(TestBean.class.getName(), classEditor.getAsText()); classEditor.setAsText(null); assertEquals("", classEditor.getAsText()); classEditor.setAsText(""); assertEquals("", classEditor.getAsText()); classEditor.setAsText("\t "); assertEquals("", classEditor.getAsText()); } @Test(expected = IllegalArgumentException.class) public void testClassEditorWithNonExistentClass() throws Exception { PropertyEditor classEditor = new ClassEditor(); classEditor.setAsText("hairdresser.on.Fire"); } @Test public void testClassEditorWithArray() { PropertyEditor classEditor = new ClassEditor(); classEditor.setAsText("org.springframework.tests.sample.beans.TestBean[]"); assertEquals(TestBean[].class, classEditor.getValue()); assertEquals("org.springframework.tests.sample.beans.TestBean[]", classEditor.getAsText()); } /* * SPR_2165 - ClassEditor is inconsistent with multidimensional arrays */ @Test public void testGetAsTextWithTwoDimensionalArray() throws Exception { String[][] chessboard = new String[8][8]; ClassEditor editor = new ClassEditor(); editor.setValue(chessboard.getClass()); assertEquals("java.lang.String[][]", editor.getAsText()); } /* * SPR_2165 - ClassEditor is inconsistent with multidimensional arrays */ @Test public void testGetAsTextWithRidiculousMultiDimensionalArray() throws Exception { String[][][][][] ridiculousChessboard = new String[8][4][0][1][3]; ClassEditor editor = new ClassEditor(); editor.setValue(ridiculousChessboard.getClass()); assertEquals("java.lang.String[][][][][]", editor.getAsText()); } @Test public void testFileEditor() { PropertyEditor fileEditor = new FileEditor(); fileEditor.setAsText("file:myfile.txt"); assertEquals(new File("myfile.txt"), fileEditor.getValue()); assertEquals((new File("myfile.txt")).getPath(), fileEditor.getAsText()); } @Test public void testFileEditorWithRelativePath() { PropertyEditor fileEditor = new FileEditor(); try { fileEditor.setAsText("myfile.txt"); } catch (IllegalArgumentException ex) { // expected: should get resolved as class path resource, // and there is no such resource in the class path... } } @Test public void testFileEditorWithAbsolutePath() { PropertyEditor fileEditor = new FileEditor(); // testing on Windows if (new File("C:/myfile.txt").isAbsolute()) { fileEditor.setAsText("C:/myfile.txt"); assertEquals(new File("C:/myfile.txt"), fileEditor.getValue()); } // testing on Unix if (new File("/myfile.txt").isAbsolute()) { fileEditor.setAsText("/myfile.txt"); assertEquals(new File("/myfile.txt"), fileEditor.getValue()); } } @Test public void testLocaleEditor() { PropertyEditor localeEditor = new LocaleEditor(); localeEditor.setAsText("en_CA"); assertEquals(Locale.CANADA, localeEditor.getValue()); assertEquals("en_CA", localeEditor.getAsText()); localeEditor = new LocaleEditor(); assertEquals("", localeEditor.getAsText()); } @Test public void testPatternEditor() { final String REGEX = "a.*"; PropertyEditor patternEditor = new PatternEditor(); patternEditor.setAsText(REGEX); assertEquals(Pattern.compile(REGEX).pattern(), ((Pattern) patternEditor.getValue()).pattern()); assertEquals(REGEX, patternEditor.getAsText()); patternEditor = new PatternEditor(); assertEquals("", patternEditor.getAsText()); patternEditor = new PatternEditor(); patternEditor.setAsText(null); assertEquals("", patternEditor.getAsText()); } @Test public void testCustomBooleanEditor() { CustomBooleanEditor editor = new CustomBooleanEditor(false); editor.setAsText("true"); assertEquals(Boolean.TRUE, editor.getValue()); assertEquals("true", editor.getAsText()); editor.setAsText("false"); assertEquals(Boolean.FALSE, editor.getValue()); assertEquals("false", editor.getAsText()); editor.setValue(null); assertEquals(null, editor.getValue()); assertEquals("", editor.getAsText()); try { editor.setAsText(null); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } } @Test public void testCustomBooleanEditorWithEmptyAsNull() { CustomBooleanEditor editor = new CustomBooleanEditor(true); editor.setAsText("true"); assertEquals(Boolean.TRUE, editor.getValue()); assertEquals("true", editor.getAsText()); editor.setAsText("false"); assertEquals(Boolean.FALSE, editor.getValue()); assertEquals("false", editor.getAsText()); editor.setValue(null); assertEquals(null, editor.getValue()); assertEquals("", editor.getAsText()); } @Test public void testCustomDateEditor() { CustomDateEditor editor = new CustomDateEditor(null, false); editor.setValue(null); assertEquals(null, editor.getValue()); assertEquals("", editor.getAsText()); } @Test public void testCustomDateEditorWithEmptyAsNull() { CustomDateEditor editor = new CustomDateEditor(null, true); editor.setValue(null); assertEquals(null, editor.getValue()); assertEquals("", editor.getAsText()); } @Test public void testCustomDateEditorWithExactDateLength() { int maxLength = 10; String validDate = "01/01/2005"; String invalidDate = "01/01/05"; assertTrue(validDate.length() == maxLength); assertFalse(invalidDate.length() == maxLength); CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true, maxLength); try { editor.setAsText(validDate); } catch (IllegalArgumentException ex) { fail("Exception shouldn't be thrown because this is a valid date"); } try { editor.setAsText(invalidDate); fail("Exception should be thrown because this is an invalid date"); } catch (IllegalArgumentException ex) { // expected assertTrue(ex.getMessage().contains("10")); } } @Test public void testCustomNumberEditor() { CustomNumberEditor editor = new CustomNumberEditor(Integer.class, false); editor.setAsText("5"); assertEquals(new Integer(5), editor.getValue()); assertEquals("5", editor.getAsText()); editor.setValue(null); assertEquals(null, editor.getValue()); assertEquals("", editor.getAsText()); } @Test public void testCustomNumberEditorWithHex() { CustomNumberEditor editor = new CustomNumberEditor(Integer.class, false); editor.setAsText("0x" + Integer.toHexString(64)); assertEquals(new Integer(64), editor.getValue()); } @Test public void testCustomNumberEditorWithEmptyAsNull() { CustomNumberEditor editor = new CustomNumberEditor(Integer.class, true); editor.setAsText("5"); assertEquals(new Integer(5), editor.getValue()); assertEquals("5", editor.getAsText()); editor.setAsText(""); assertEquals(null, editor.getValue()); assertEquals("", editor.getAsText()); editor.setValue(null); assertEquals(null, editor.getValue()); assertEquals("", editor.getAsText()); } @Test public void testStringTrimmerEditor() { StringTrimmerEditor editor = new StringTrimmerEditor(false); editor.setAsText("test"); assertEquals("test", editor.getValue()); assertEquals("test", editor.getAsText()); editor.setAsText(" test "); assertEquals("test", editor.getValue()); assertEquals("test", editor.getAsText()); editor.setAsText(""); assertEquals("", editor.getValue()); assertEquals("", editor.getAsText()); editor.setValue(null); assertEquals("", editor.getAsText()); editor.setAsText(null); assertEquals("", editor.getAsText()); } @Test public void testStringTrimmerEditorWithEmptyAsNull() { StringTrimmerEditor editor = new StringTrimmerEditor(true); editor.setAsText("test"); assertEquals("test", editor.getValue()); assertEquals("test", editor.getAsText()); editor.setAsText(" test "); assertEquals("test", editor.getValue()); assertEquals("test", editor.getAsText()); editor.setAsText(" "); assertEquals(null, editor.getValue()); assertEquals("", editor.getAsText()); editor.setValue(null); assertEquals("", editor.getAsText()); } @Test public void testStringTrimmerEditorWithCharsToDelete() { StringTrimmerEditor editor = new StringTrimmerEditor("\r\n\f", false); editor.setAsText("te\ns\ft"); assertEquals("test", editor.getValue()); assertEquals("test", editor.getAsText()); editor.setAsText(" test "); assertEquals("test", editor.getValue()); assertEquals("test", editor.getAsText()); editor.setAsText(""); assertEquals("", editor.getValue()); assertEquals("", editor.getAsText()); editor.setValue(null); assertEquals("", editor.getAsText()); } @Test public void testStringTrimmerEditorWithCharsToDeleteAndEmptyAsNull() { StringTrimmerEditor editor = new StringTrimmerEditor("\r\n\f", true); editor.setAsText("te\ns\ft"); assertEquals("test", editor.getValue()); assertEquals("test", editor.getAsText()); editor.setAsText(" test "); assertEquals("test", editor.getValue()); assertEquals("test", editor.getAsText()); editor.setAsText(" \n\f "); assertEquals(null, editor.getValue()); assertEquals("", editor.getAsText()); editor.setValue(null); assertEquals("", editor.getAsText()); } @Test public void testIndexedPropertiesWithCustomEditorForType() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(String.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("prefix" + text); } }); TestBean tb0 = bean.getArray()[0]; TestBean tb1 = bean.getArray()[1]; TestBean tb2 = ((TestBean) bean.getList().get(0)); TestBean tb3 = ((TestBean) bean.getList().get(1)); TestBean tb4 = ((TestBean) bean.getMap().get("key1")); TestBean tb5 = ((TestBean) bean.getMap().get("key2")); assertEquals("name0", tb0.getName()); assertEquals("name1", tb1.getName()); assertEquals("name2", tb2.getName()); assertEquals("name3", tb3.getName()); assertEquals("name4", tb4.getName()); assertEquals("name5", tb5.getName()); assertEquals("name0", bw.getPropertyValue("array[0].name")); assertEquals("name1", bw.getPropertyValue("array[1].name")); assertEquals("name2", bw.getPropertyValue("list[0].name")); assertEquals("name3", bw.getPropertyValue("list[1].name")); assertEquals("name4", bw.getPropertyValue("map[key1].name")); assertEquals("name5", bw.getPropertyValue("map[key2].name")); assertEquals("name4", bw.getPropertyValue("map['key1'].name")); assertEquals("name5", bw.getPropertyValue("map[\"key2\"].name")); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0].name", "name5"); pvs.add("array[1].name", "name4"); pvs.add("list[0].name", "name3"); pvs.add("list[1].name", "name2"); pvs.add("map[key1].name", "name1"); pvs.add("map['key2'].name", "name0"); bw.setPropertyValues(pvs); assertEquals("prefixname5", tb0.getName()); assertEquals("prefixname4", tb1.getName()); assertEquals("prefixname3", tb2.getName()); assertEquals("prefixname2", tb3.getName()); assertEquals("prefixname1", tb4.getName()); assertEquals("prefixname0", tb5.getName()); assertEquals("prefixname5", bw.getPropertyValue("array[0].name")); assertEquals("prefixname4", bw.getPropertyValue("array[1].name")); assertEquals("prefixname3", bw.getPropertyValue("list[0].name")); assertEquals("prefixname2", bw.getPropertyValue("list[1].name")); assertEquals("prefixname1", bw.getPropertyValue("map[\"key1\"].name")); assertEquals("prefixname0", bw.getPropertyValue("map['key2'].name")); } @Test public void testIndexedPropertiesWithCustomEditorForProperty() { IndexedTestBean bean = new IndexedTestBean(false); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(String.class, "array.name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("array" + text); } }); bw.registerCustomEditor(String.class, "list.name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("list" + text); } }); bw.registerCustomEditor(String.class, "map.name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("map" + text); } }); bean.populate(); TestBean tb0 = bean.getArray()[0]; TestBean tb1 = bean.getArray()[1]; TestBean tb2 = ((TestBean) bean.getList().get(0)); TestBean tb3 = ((TestBean) bean.getList().get(1)); TestBean tb4 = ((TestBean) bean.getMap().get("key1")); TestBean tb5 = ((TestBean) bean.getMap().get("key2")); assertEquals("name0", tb0.getName()); assertEquals("name1", tb1.getName()); assertEquals("name2", tb2.getName()); assertEquals("name3", tb3.getName()); assertEquals("name4", tb4.getName()); assertEquals("name5", tb5.getName()); assertEquals("name0", bw.getPropertyValue("array[0].name")); assertEquals("name1", bw.getPropertyValue("array[1].name")); assertEquals("name2", bw.getPropertyValue("list[0].name")); assertEquals("name3", bw.getPropertyValue("list[1].name")); assertEquals("name4", bw.getPropertyValue("map[key1].name")); assertEquals("name5", bw.getPropertyValue("map[key2].name")); assertEquals("name4", bw.getPropertyValue("map['key1'].name")); assertEquals("name5", bw.getPropertyValue("map[\"key2\"].name")); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0].name", "name5"); pvs.add("array[1].name", "name4"); pvs.add("list[0].name", "name3"); pvs.add("list[1].name", "name2"); pvs.add("map[key1].name", "name1"); pvs.add("map['key2'].name", "name0"); bw.setPropertyValues(pvs); assertEquals("arrayname5", tb0.getName()); assertEquals("arrayname4", tb1.getName()); assertEquals("listname3", tb2.getName()); assertEquals("listname2", tb3.getName()); assertEquals("mapname1", tb4.getName()); assertEquals("mapname0", tb5.getName()); assertEquals("arrayname5", bw.getPropertyValue("array[0].name")); assertEquals("arrayname4", bw.getPropertyValue("array[1].name")); assertEquals("listname3", bw.getPropertyValue("list[0].name")); assertEquals("listname2", bw.getPropertyValue("list[1].name")); assertEquals("mapname1", bw.getPropertyValue("map[\"key1\"].name")); assertEquals("mapname0", bw.getPropertyValue("map['key2'].name")); } @Test public void testIndexedPropertiesWithIndividualCustomEditorForProperty() { IndexedTestBean bean = new IndexedTestBean(false); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(String.class, "array[0].name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("array0" + text); } }); bw.registerCustomEditor(String.class, "array[1].name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("array1" + text); } }); bw.registerCustomEditor(String.class, "list[0].name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("list0" + text); } }); bw.registerCustomEditor(String.class, "list[1].name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("list1" + text); } }); bw.registerCustomEditor(String.class, "map[key1].name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("mapkey1" + text); } }); bw.registerCustomEditor(String.class, "map[key2].name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("mapkey2" + text); } }); bean.populate(); TestBean tb0 = bean.getArray()[0]; TestBean tb1 = bean.getArray()[1]; TestBean tb2 = ((TestBean) bean.getList().get(0)); TestBean tb3 = ((TestBean) bean.getList().get(1)); TestBean tb4 = ((TestBean) bean.getMap().get("key1")); TestBean tb5 = ((TestBean) bean.getMap().get("key2")); assertEquals("name0", tb0.getName()); assertEquals("name1", tb1.getName()); assertEquals("name2", tb2.getName()); assertEquals("name3", tb3.getName()); assertEquals("name4", tb4.getName()); assertEquals("name5", tb5.getName()); assertEquals("name0", bw.getPropertyValue("array[0].name")); assertEquals("name1", bw.getPropertyValue("array[1].name")); assertEquals("name2", bw.getPropertyValue("list[0].name")); assertEquals("name3", bw.getPropertyValue("list[1].name")); assertEquals("name4", bw.getPropertyValue("map[key1].name")); assertEquals("name5", bw.getPropertyValue("map[key2].name")); assertEquals("name4", bw.getPropertyValue("map['key1'].name")); assertEquals("name5", bw.getPropertyValue("map[\"key2\"].name")); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0].name", "name5"); pvs.add("array[1].name", "name4"); pvs.add("list[0].name", "name3"); pvs.add("list[1].name", "name2"); pvs.add("map[key1].name", "name1"); pvs.add("map['key2'].name", "name0"); bw.setPropertyValues(pvs); assertEquals("array0name5", tb0.getName()); assertEquals("array1name4", tb1.getName()); assertEquals("list0name3", tb2.getName()); assertEquals("list1name2", tb3.getName()); assertEquals("mapkey1name1", tb4.getName()); assertEquals("mapkey2name0", tb5.getName()); assertEquals("array0name5", bw.getPropertyValue("array[0].name")); assertEquals("array1name4", bw.getPropertyValue("array[1].name")); assertEquals("list0name3", bw.getPropertyValue("list[0].name")); assertEquals("list1name2", bw.getPropertyValue("list[1].name")); assertEquals("mapkey1name1", bw.getPropertyValue("map[\"key1\"].name")); assertEquals("mapkey2name0", bw.getPropertyValue("map['key2'].name")); } @Test public void testNestedIndexedPropertiesWithCustomEditorForProperty() { IndexedTestBean bean = new IndexedTestBean(); TestBean tb0 = bean.getArray()[0]; TestBean tb1 = bean.getArray()[1]; TestBean tb2 = ((TestBean) bean.getList().get(0)); TestBean tb3 = ((TestBean) bean.getList().get(1)); TestBean tb4 = ((TestBean) bean.getMap().get("key1")); TestBean tb5 = ((TestBean) bean.getMap().get("key2")); tb0.setNestedIndexedBean(new IndexedTestBean()); tb1.setNestedIndexedBean(new IndexedTestBean()); tb2.setNestedIndexedBean(new IndexedTestBean()); tb3.setNestedIndexedBean(new IndexedTestBean()); tb4.setNestedIndexedBean(new IndexedTestBean()); tb5.setNestedIndexedBean(new IndexedTestBean()); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(String.class, "array.nestedIndexedBean.array.name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("array" + text); } @Override public String getAsText() { return ((String) getValue()).substring(5); } }); bw.registerCustomEditor(String.class, "list.nestedIndexedBean.list.name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("list" + text); } @Override public String getAsText() { return ((String) getValue()).substring(4); } }); bw.registerCustomEditor(String.class, "map.nestedIndexedBean.map.name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("map" + text); } @Override public String getAsText() { return ((String) getValue()).substring(4); } }); assertEquals("name0", tb0.getName()); assertEquals("name1", tb1.getName()); assertEquals("name2", tb2.getName()); assertEquals("name3", tb3.getName()); assertEquals("name4", tb4.getName()); assertEquals("name5", tb5.getName()); assertEquals("name0", bw.getPropertyValue("array[0].nestedIndexedBean.array[0].name")); assertEquals("name1", bw.getPropertyValue("array[1].nestedIndexedBean.array[1].name")); assertEquals("name2", bw.getPropertyValue("list[0].nestedIndexedBean.list[0].name")); assertEquals("name3", bw.getPropertyValue("list[1].nestedIndexedBean.list[1].name")); assertEquals("name4", bw.getPropertyValue("map[key1].nestedIndexedBean.map[key1].name")); assertEquals("name5", bw.getPropertyValue("map['key2'].nestedIndexedBean.map[\"key2\"].name")); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0].nestedIndexedBean.array[0].name", "name5"); pvs.add("array[1].nestedIndexedBean.array[1].name", "name4"); pvs.add("list[0].nestedIndexedBean.list[0].name", "name3"); pvs.add("list[1].nestedIndexedBean.list[1].name", "name2"); pvs.add("map[key1].nestedIndexedBean.map[\"key1\"].name", "name1"); pvs.add("map['key2'].nestedIndexedBean.map[key2].name", "name0"); bw.setPropertyValues(pvs); assertEquals("arrayname5", tb0.getNestedIndexedBean().getArray()[0].getName()); assertEquals("arrayname4", tb1.getNestedIndexedBean().getArray()[1].getName()); assertEquals("listname3", ((TestBean) tb2.getNestedIndexedBean().getList().get(0)).getName()); assertEquals("listname2", ((TestBean) tb3.getNestedIndexedBean().getList().get(1)).getName()); assertEquals("mapname1", ((TestBean) tb4.getNestedIndexedBean().getMap().get("key1")).getName()); assertEquals("mapname0", ((TestBean) tb5.getNestedIndexedBean().getMap().get("key2")).getName()); assertEquals("arrayname5", bw.getPropertyValue("array[0].nestedIndexedBean.array[0].name")); assertEquals("arrayname4", bw.getPropertyValue("array[1].nestedIndexedBean.array[1].name")); assertEquals("listname3", bw.getPropertyValue("list[0].nestedIndexedBean.list[0].name")); assertEquals("listname2", bw.getPropertyValue("list[1].nestedIndexedBean.list[1].name")); assertEquals("mapname1", bw.getPropertyValue("map['key1'].nestedIndexedBean.map[key1].name")); assertEquals("mapname0", bw.getPropertyValue("map[key2].nestedIndexedBean.map[\"key2\"].name")); } @Test public void testNestedIndexedPropertiesWithIndexedCustomEditorForProperty() { IndexedTestBean bean = new IndexedTestBean(); TestBean tb0 = bean.getArray()[0]; TestBean tb1 = bean.getArray()[1]; TestBean tb2 = ((TestBean) bean.getList().get(0)); TestBean tb3 = ((TestBean) bean.getList().get(1)); TestBean tb4 = ((TestBean) bean.getMap().get("key1")); TestBean tb5 = ((TestBean) bean.getMap().get("key2")); tb0.setNestedIndexedBean(new IndexedTestBean()); tb1.setNestedIndexedBean(new IndexedTestBean()); tb2.setNestedIndexedBean(new IndexedTestBean()); tb3.setNestedIndexedBean(new IndexedTestBean()); tb4.setNestedIndexedBean(new IndexedTestBean()); tb5.setNestedIndexedBean(new IndexedTestBean()); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(String.class, "array[0].nestedIndexedBean.array[0].name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("array" + text); } }); bw.registerCustomEditor(String.class, "list.nestedIndexedBean.list[1].name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("list" + text); } }); bw.registerCustomEditor(String.class, "map[key1].nestedIndexedBean.map.name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("map" + text); } }); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0].nestedIndexedBean.array[0].name", "name5"); pvs.add("array[1].nestedIndexedBean.array[1].name", "name4"); pvs.add("list[0].nestedIndexedBean.list[0].name", "name3"); pvs.add("list[1].nestedIndexedBean.list[1].name", "name2"); pvs.add("map[key1].nestedIndexedBean.map[\"key1\"].name", "name1"); pvs.add("map['key2'].nestedIndexedBean.map[key2].name", "name0"); bw.setPropertyValues(pvs); assertEquals("arrayname5", tb0.getNestedIndexedBean().getArray()[0].getName()); assertEquals("name4", tb1.getNestedIndexedBean().getArray()[1].getName()); assertEquals("name3", ((TestBean) tb2.getNestedIndexedBean().getList().get(0)).getName()); assertEquals("listname2", ((TestBean) tb3.getNestedIndexedBean().getList().get(1)).getName()); assertEquals("mapname1", ((TestBean) tb4.getNestedIndexedBean().getMap().get("key1")).getName()); assertEquals("name0", ((TestBean) tb5.getNestedIndexedBean().getMap().get("key2")).getName()); } @Test public void testIndexedPropertiesWithDirectAccessAndPropertyEditors() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(TestBean.class, "array", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(new TestBean("array" + text, 99)); } @Override public String getAsText() { return ((TestBean) getValue()).getName(); } }); bw.registerCustomEditor(TestBean.class, "list", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(new TestBean("list" + text, 99)); } @Override public String getAsText() { return ((TestBean) getValue()).getName(); } }); bw.registerCustomEditor(TestBean.class, "map", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(new TestBean("map" + text, 99)); } @Override public String getAsText() { return ((TestBean) getValue()).getName(); } }); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0]", "a"); pvs.add("array[1]", "b"); pvs.add("list[0]", "c"); pvs.add("list[1]", "d"); pvs.add("map[key1]", "e"); pvs.add("map['key2']", "f"); bw.setPropertyValues(pvs); assertEquals("arraya", bean.getArray()[0].getName()); assertEquals("arrayb", bean.getArray()[1].getName()); assertEquals("listc", ((TestBean) bean.getList().get(0)).getName()); assertEquals("listd", ((TestBean) bean.getList().get(1)).getName()); assertEquals("mape", ((TestBean) bean.getMap().get("key1")).getName()); assertEquals("mapf", ((TestBean) bean.getMap().get("key2")).getName()); } @Test public void testIndexedPropertiesWithDirectAccessAndSpecificPropertyEditors() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(TestBean.class, "array[0]", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(new TestBean("array0" + text, 99)); } @Override public String getAsText() { return ((TestBean) getValue()).getName(); } }); bw.registerCustomEditor(TestBean.class, "array[1]", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(new TestBean("array1" + text, 99)); } @Override public String getAsText() { return ((TestBean) getValue()).getName(); } }); bw.registerCustomEditor(TestBean.class, "list[0]", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(new TestBean("list0" + text, 99)); } @Override public String getAsText() { return ((TestBean) getValue()).getName(); } }); bw.registerCustomEditor(TestBean.class, "list[1]", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(new TestBean("list1" + text, 99)); } @Override public String getAsText() { return ((TestBean) getValue()).getName(); } }); bw.registerCustomEditor(TestBean.class, "map[key1]", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(new TestBean("mapkey1" + text, 99)); } @Override public String getAsText() { return ((TestBean) getValue()).getName(); } }); bw.registerCustomEditor(TestBean.class, "map[key2]", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(new TestBean("mapkey2" + text, 99)); } @Override public String getAsText() { return ((TestBean) getValue()).getName(); } }); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0]", "a"); pvs.add("array[1]", "b"); pvs.add("list[0]", "c"); pvs.add("list[1]", "d"); pvs.add("map[key1]", "e"); pvs.add("map['key2']", "f"); bw.setPropertyValues(pvs); assertEquals("array0a", bean.getArray()[0].getName()); assertEquals("array1b", bean.getArray()[1].getName()); assertEquals("list0c", ((TestBean) bean.getList().get(0)).getName()); assertEquals("list1d", ((TestBean) bean.getList().get(1)).getName()); assertEquals("mapkey1e", ((TestBean) bean.getMap().get("key1")).getName()); assertEquals("mapkey2f", ((TestBean) bean.getMap().get("key2")).getName()); } @Test public void testIndexedPropertiesWithListPropertyEditor() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(List.class, "list", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { List<TestBean> result = new ArrayList<TestBean>(); result.add(new TestBean("list" + text, 99)); setValue(result); } }); bw.setPropertyValue("list", "1"); assertEquals("list1", ((TestBean) bean.getList().get(0)).getName()); bw.setPropertyValue("list[0]", "test"); assertEquals("test", bean.getList().get(0)); } @Test public void testConversionToOldCollections() throws PropertyVetoException { OldCollectionsBean tb = new OldCollectionsBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(Vector.class, new CustomCollectionEditor(Vector.class)); bw.registerCustomEditor(Hashtable.class, new CustomMapEditor(Hashtable.class)); bw.setPropertyValue("vector", new String[] {"a", "b"}); assertEquals(2, tb.getVector().size()); assertEquals("a", tb.getVector().get(0)); assertEquals("b", tb.getVector().get(1)); bw.setPropertyValue("hashtable", Collections.singletonMap("foo", "bar")); assertEquals(1, tb.getHashtable().size()); assertEquals("bar", tb.getHashtable().get("foo")); } @Test public void testUninitializedArrayPropertyWithCustomEditor() { IndexedTestBean bean = new IndexedTestBean(false); BeanWrapper bw = new BeanWrapperImpl(bean); PropertyEditor pe = new CustomNumberEditor(Integer.class, true); bw.registerCustomEditor(null, "list.age", pe); TestBean tb = new TestBean(); bw.setPropertyValue("list", new ArrayList<Object>()); bw.setPropertyValue("list[0]", tb); assertEquals(tb, bean.getList().get(0)); assertEquals(pe, bw.findCustomEditor(int.class, "list.age")); assertEquals(pe, bw.findCustomEditor(null, "list.age")); assertEquals(pe, bw.findCustomEditor(int.class, "list[0].age")); assertEquals(pe, bw.findCustomEditor(null, "list[0].age")); } @Test public void testArrayToArrayConversion() throws PropertyVetoException { IndexedTestBean tb = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(TestBean.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(new TestBean(text, 99)); } }); bw.setPropertyValue("array", new String[] {"a", "b"}); assertEquals(2, tb.getArray().length); assertEquals("a", tb.getArray()[0].getName()); assertEquals("b", tb.getArray()[1].getName()); } @Test public void testArrayToStringConversion() throws PropertyVetoException { TestBean tb = new TestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(String.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("-" + text + "-"); } }); bw.setPropertyValue("name", new String[] {"a", "b"}); assertEquals("-a,b-", tb.getName()); } @Test public void testClassArrayEditorSunnyDay() throws Exception { ClassArrayEditor classArrayEditor = new ClassArrayEditor(); classArrayEditor.setAsText("java.lang.String,java.util.HashMap"); Class<?>[] classes = (Class<?>[]) classArrayEditor.getValue(); assertEquals(2, classes.length); assertEquals(String.class, classes[0]); assertEquals(HashMap.class, classes[1]); assertEquals("java.lang.String,java.util.HashMap", classArrayEditor.getAsText()); // ensure setAsText can consume the return value of getAsText classArrayEditor.setAsText(classArrayEditor.getAsText()); } @Test public void testClassArrayEditorSunnyDayWithArrayTypes() throws Exception { ClassArrayEditor classArrayEditor = new ClassArrayEditor(); classArrayEditor.setAsText("java.lang.String[],java.util.Map[],int[],float[][][]"); Class<?>[] classes = (Class<?>[]) classArrayEditor.getValue(); assertEquals(4, classes.length); assertEquals(String[].class, classes[0]); assertEquals(Map[].class, classes[1]); assertEquals(int[].class, classes[2]); assertEquals(float[][][].class, classes[3]); assertEquals("java.lang.String[],java.util.Map[],int[],float[][][]", classArrayEditor.getAsText()); // ensure setAsText can consume the return value of getAsText classArrayEditor.setAsText(classArrayEditor.getAsText()); } @Test public void testClassArrayEditorSetAsTextWithNull() throws Exception { ClassArrayEditor editor = new ClassArrayEditor(); editor.setAsText(null); assertNull(editor.getValue()); assertEquals("", editor.getAsText()); } @Test public void testClassArrayEditorSetAsTextWithEmptyString() throws Exception { ClassArrayEditor editor = new ClassArrayEditor(); editor.setAsText(""); assertNull(editor.getValue()); assertEquals("", editor.getAsText()); } @Test public void testClassArrayEditorSetAsTextWithWhitespaceString() throws Exception { ClassArrayEditor editor = new ClassArrayEditor(); editor.setAsText("\n"); assertNull(editor.getValue()); assertEquals("", editor.getAsText()); } @Test public void testCharsetEditor() throws Exception { CharsetEditor editor = new CharsetEditor(); String name = "UTF-8"; editor.setAsText(name); Charset charset = Charset.forName(name); assertEquals("Invalid Charset conversion", charset, editor.getValue()); editor.setValue(charset); assertEquals("Invalid Charset conversion", name, editor.getAsText()); } private static class TestBeanEditor extends PropertyEditorSupport { @Override public void setAsText(String text) { TestBean tb = new TestBean(); StringTokenizer st = new StringTokenizer(text, "_"); tb.setName(st.nextToken()); tb.setAge(Integer.parseInt(st.nextToken())); setValue(tb); } } private static class OldValueAccessingTestBeanEditor extends PropertyEditorSupport { @Override public void setAsText(String text) { TestBean tb = new TestBean(); StringTokenizer st = new StringTokenizer(text, "_"); tb.setName(st.nextToken()); tb.setAge(Integer.parseInt(st.nextToken())); if (!tb.equals(getValue())) { setValue(tb); } } } @SuppressWarnings("unused") private static class PrimitiveArrayBean { private byte[] byteArray; private char[] charArray; public byte[] getByteArray() { return byteArray; } public void setByteArray(byte[] byteArray) { this.byteArray = byteArray; } public char[] getCharArray() { return charArray; } public void setCharArray(char[] charArray) { this.charArray = charArray; } } @SuppressWarnings("unused") private static class CharBean { private char myChar; private Character myCharacter; public char getMyChar() { return myChar; } public void setMyChar(char myChar) { this.myChar = myChar; } public Character getMyCharacter() { return myCharacter; } public void setMyCharacter(Character myCharacter) { this.myCharacter = myCharacter; } } @SuppressWarnings("unused") private static class OldCollectionsBean { private Vector<?> vector; private Hashtable<?, ?> hashtable; public Vector<?> getVector() { return vector; } public void setVector(Vector<?> vector) { this.vector = vector; } public Hashtable<?, ?> getHashtable() { return hashtable; } public void setHashtable(Hashtable<?, ?> hashtable) { this.hashtable = hashtable; } } }
[ "972181522@qq.com" ]
972181522@qq.com
53b5aade80fe9a37ae2b3e4b6bdba6bba59d060d
9956302c325ffc5546aee71aad0e92d2b1bc9fcd
/src/main/java/push/apns/ApnsShouYueVerticle.java
aff15987928030e4b39dbb81728d8f135c4087fb
[]
no_license
sdmjhca/vertx-http2-apns
c3f76ebec939d52cc2a966ac592dae1a6ded2f8f
718de03274bb5ae2f5dca166ccf336fe4e895262
refs/heads/master
2021-07-20T01:33:50.973344
2017-10-27T06:50:27
2017-10-27T06:50:27
108,406,548
3
2
null
null
null
null
UTF-8
Java
false
false
4,856
java
package push.apns; import io.vertx.core.AbstractVerticle; import io.vertx.core.buffer.Buffer; import io.vertx.core.eventbus.EventBus; import io.vertx.core.http.HttpVersion; import io.vertx.core.json.Json; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.core.net.PfxOptions; import io.vertx.ext.web.client.HttpRequest; import io.vertx.ext.web.client.HttpResponse; import io.vertx.ext.web.client.WebClient; import io.vertx.ext.web.client.WebClientOptions; import org.apache.commons.lang.StringUtils; import push.apns.data.Payload; import push.apns.header.ApnsHeader; /** * @author jhmi * 通过服务证书向APNS请求消息推送服务 * 另一种方式:通过服务Token向APNS请求,为确保安全性,APN需要定期生成新的令牌 */ public class ApnsShouYueVerticle extends AbstractVerticle { private static final Logger logger = LoggerFactory.getLogger(ApnsShouYueVerticle.class); private static final String APNS_KEYSTORE_PWD = "01zhuanche"; private EventBus eb; /** * 定义HTTP请求客户端 */ private WebClient webClient; /** * 定义APNS的开发环境URL */ private static final String APNS_REQ_URL_DEV = "api.development.push.apple.com"; /** * 定义APNS密钥的存放路径 */ private static final String KEY_STORE_PATH = "dev/apns_developer.p12"; //private static final String KEY_STORE_PATH = "D:/apnsCert/apns_developer.p12"; @Override public void start() throws Exception { super.start(); //初始化webclient this.initWebClient(); eb = vertx.eventBus(); eb.<JsonObject>consumer(ApnsShouYueVerticle.class.getName() + "local", res -> { String action = res.headers().get("action"); if (StringUtils.isNotEmpty(action)) { JsonObject body = res.body(); switch (action) { case "apnsSend": ApnsMsg msg = Json.decodeValue(body.encode(), ApnsMsg.class); if (msg != null && StringUtils.isNotEmpty(msg.getDeviceToken())) { apnsSend(msg.getDeviceToken(), msg.getTitle(), msg.getBody(), msg.getExtend()); } else { logger.warn("apnsSend, device token is null."); } break; default: break; } } }); } /** * 向APNS服务发送推送请求 * @param deviceToken 设备token * @param title 消息标题 * @param content 消息内容 * @param extend 其他 */ private void apnsSend(String deviceToken, String title, String content, Extend extend) { if(webClient == null){ this.initWebClient(); } //设置请求报文体 JsonObject reqJson = Payload.newPayload() .alertBody(content)//设置alert内容 .alerTitle(title)//设置通知的标题,建议使用默认的应用标题 .sound() .build(); //设置请求的路径URL+TOKEN HttpRequest<Buffer> request = webClient.post(443,APNS_REQ_URL_DEV,"/3/device/"+deviceToken); //设置请求的报文头 request.putHeader("apnsID", ApnsHeader.getApnsID()); request.putHeader("apnsExpiration", ApnsHeader.getApnsExpiration()); //发送请求 request.sendJsonObject(reqJson,res->{ if(res.succeeded()){ HttpResponse response = res.result(); int stausCode = response.statusCode(); if(stausCode == 200){ logger.info("请求APNS服务器成功,结果="+stausCode); }else{ logger.error("请求APNS服务器成功,推送失败code={},msg={},body={}", response.statusCode(),response.statusMessage(),response.body()); } }else{ res.result(); res.cause().printStackTrace(); logger.info("请求APNS服务器失败,失败原因={}",res.cause().getMessage()); } }); } /** * 初始化webclient */ public void initWebClient(){ WebClientOptions webClientOptions = new WebClientOptions(); webClientOptions.setProtocolVersion(HttpVersion.HTTP_2); webClientOptions.setSsl(true); /** * implementations that support HTTP/2 over TLS * MUST use protocol negotiation in TLS [TLS-ALPN]. * 标准的Java 8不支持ALPN,所以ALPN应该通过其他方式启用: * OpenSSL支持 * Jetty-ALPN支持 */ webClientOptions.setUseAlpn(true); //webClientOptions.setSslEngineOptions(new OpenSSLEngineOptions()); //PKCS#12格式的密钥/证书(http://en.wikipedia.org/wiki/PKCS_12),通常使用.pfx 或.p12 PfxOptions pfxOptions = new PfxOptions(); //设置密钥和路径 pfxOptions.setPath(KEY_STORE_PATH); pfxOptions.setPassword(APNS_KEYSTORE_PWD); //设置客户端信任证书 webClientOptions.setPfxKeyCertOptions(pfxOptions); //另一种方式读取密钥 /* Buffer buffer = Buffer.buffer(bytes);*/ /*Buffer buffer = vertx.fileSystem().readFileBlocking("d://apnsCert/apns_developer.p12"); pfxOptions.setValue(buffer);*/ //创建webclient webClient = WebClient.create(vertx,webClientOptions); } }
[ "sdmjhca@foxmail.com" ]
sdmjhca@foxmail.com