text
stringlengths
10
2.72M
package LimpBiscuit.Demo.Repository; import LimpBiscuit.Demo.Entity.RequestOperatingSystem; import org.springframework.data.repository.CrudRepository; public interface RequestOperatingSystemRepository extends CrudRepository<RequestOperatingSystem, Long> { <S extends RequestOperatingSystemRepository> S save(S entity); RequestOperatingSystem findByNameAndAndFamily(String name, String family); }
/* ------------------------------------------------------------------------------ * 软件名称:他秀手机版 * 公司名称:多宝科技 * 开发作者:Yongchao.Yang * 开发时间:2014年7月15日/2014 * All Rights Reserved 2012-2015 * ------------------------------------------------------------------------------ * 注意:本内容均来自多宝科技研发部,仅限内部交流使用,未经过公司许可 禁止转发 * ------------------------------------------------------------------------------ * prj-name:com.duobao.video.logic * fileName:UserDaoImpl.java * ------------------------------------------------------------------------------- */ package com.ace.database.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.ace.database.ds.DBReleaser; import com.rednovo.ace.constant.Constant; import com.rednovo.ace.constant.Constant.OperaterStatus; import com.rednovo.ace.entity.ExchangeBindInfo; import com.rednovo.ace.entity.ExchangeDetail; import com.rednovo.tools.DateUtil; /** * @author yongchao.Yang/2014年7月15日 */ public class ExchangeDao extends BasicDao { /** * */ public ExchangeDao(Connection connection) { super(connection); } public ExchangeBindInfo getBindInfo(String userId) { PreparedStatement ps = null; ResultSet res = null; String sql = "select userId,weChatId,mobileId,updateTime,createTime from exchange_bind_info where userId=?"; try { ps = this.getConnnection().prepareStatement(sql); ps.setString(1, userId); res = ps.executeQuery(); if (res != null && res.next()) { ExchangeBindInfo bind = new ExchangeBindInfo(); bind.setUserId(userId); bind.setWeChatId(res.getString("weChatId"));; bind.setMobileId(res.getString("mobileId")); bind.setUpdateTime(res.getString("updateTime")); bind.setCreateTime(res.getString("createTime")); return bind; } } catch (Exception e) { this.getLogger().error("[根据用户(" + userId + ")获取用户兑点绑定信息失败]", e); } finally { DBReleaser.release(ps, res); } return null; } /** * 获取账户余额 * * @param userId * @return * @author Yongchao.Yang * @since 2016年3月4日上午12:51:53 */ public String bind(ExchangeBindInfo bindInfo) { PreparedStatement ps = null; boolean isExist = true; String sql = "update exchange_bind_info set weChatId=?,mobileId=?,schemaId=? where userId=? "; if (this.getBindInfo(bindInfo.getUserId()) == null) { isExist = false; sql = "insert into exchange_bind_info (userId,weChatId,mobileId,updateTime,createTime,schemaId) values (?,?,?,?,?,?)"; } try { ps = this.getConnnection().prepareStatement(sql); if (isExist) { ps.setString(1, bindInfo.getWeChatId()); ps.setString(2, bindInfo.getMobileId()); ps.setString(3, DateUtil.getTimeInMillis()); ps.setString(4, bindInfo.getUserId()); } else { ps.setString(1, bindInfo.getUserId()); ps.setString(2, bindInfo.getWeChatId()); ps.setString(3, bindInfo.getMobileId()); ps.setString(4, DateUtil.getStringDate()); ps.setString(5, DateUtil.getStringDate()); ps.setString(6, DateUtil.getTimeInMillis()); } if (ps.executeUpdate() > 0) { return Constant.OperaterStatus.SUCESSED.getValue(); } } catch (Exception e) { this.getLogger().error("[修改用户(" + bindInfo.getUserId() + ")兑点捆绑信息失败]", e); } finally { DBReleaser.release(ps); } return OperaterStatus.FAILED.getValue(); } public String addRequest(ExchangeDetail detail) { PreparedStatement ps = null; String sql = "insert into exchange_detail (userId,userName,weChatId,mobileId,coinAmount,rmbAmount,status,payerId,payerName,updateTime,createTime) values (?,?,?,?,?,?,?,?,?,?,?)"; try { ps = this.getConnnection().prepareStatement(sql); ps.setString(1, detail.getUserId()); ps.setString(2, detail.getUserName()); ps.setString(3, detail.getWeChatId()); ps.setString(4, detail.getMobileId()); ps.setBigDecimal(5, detail.getCoinAmount()); ps.setBigDecimal(6, detail.getRmbAmount()); ps.setString(7, detail.getStatus()); ps.setString(8, detail.getPayerId()); ps.setString(9, detail.getPayerName()); ps.setString(10, DateUtil.getStringDate()); ps.setString(11, DateUtil.getStringDate()); if (ps.executeUpdate() > 0) { return Constant.OperaterStatus.SUCESSED.getValue(); } } catch (Exception e) { this.getLogger().error("[用户(" + detail.getUserId() + ")添加兑点申请失败]", e); } finally { DBReleaser.release(ps); } return OperaterStatus.FAILED.getValue(); } public String applyRequest(String requestId, String status, String payerId, String payerName) { PreparedStatement ps = null; String sql = "update exchange_detail set payerId=?,payerName=?, status=?,updateTime=? where id=?"; try { ps = this.getConnnection().prepareStatement(sql); ps.setString(1, payerId); ps.setString(2, payerName); ps.setString(3, status); ps.setString(4, DateUtil.getStringDate()); ps.setString(5, requestId); if (ps.executeUpdate() > 0) { return Constant.OperaterStatus.SUCESSED.getValue(); } } catch (Exception e) { this.getLogger().error("[修改兑点申请(" + requestId + ")失败]", e); } finally { DBReleaser.release(ps); } return OperaterStatus.FAILED.getValue(); } }
package com.git.support.sdo.impl; public class BodyDO extends DataObject { private static final long serialVersionUID = 1L; private BodyDO() { } public static BodyDO CreateBodyDO() { return new BodyDO(); } }
package model; public class dayForecast { private String date; // not edit private Long dayIcon; private Long nightIcon; private String minTemperature; // not edit private String maxTemperature; // not edit private String dayWind; // edit private String nightWind; private String uVIndex; // not edit private String airQualityCategory; // not edit private String dayRainProbability; private String nightRainProbability; private String daySnowProbability; private String nightSnowProbability; private String dayIceProbability; private String nightIceProbability; private String dayRain; private String nightRain; private String daySnow; private String nightSnow; private String dayIce; private String nightIce; public dayForecast() { super(); // TODO Auto-generated constructor stub } public dayForecast(String date, Long dayIcon, Long nightIcon, String minTemperature, String maxTemperature, String dayWind, String nightWind, String uVIndex, String airQualityCategory, String dayRainProbability, String nightRainProbability, String daySnowProbability, String nightSnowProbability, String dayIceProbability, String nightIceProbability, String dayRain, String nightRain, String daySnow, String nightSnow, String dayIce, String nightIce) { super(); this.date = date; this.dayIcon = dayIcon; this.nightIcon = nightIcon; this.minTemperature = minTemperature; this.maxTemperature = maxTemperature; this.dayWind = dayWind; this.nightWind = nightWind; this.uVIndex = uVIndex; this.airQualityCategory = airQualityCategory; this.dayRainProbability = dayRainProbability; this.nightRainProbability = nightRainProbability; this.daySnowProbability = daySnowProbability; this.nightSnowProbability = nightSnowProbability; this.dayIceProbability = dayIceProbability; this.nightIceProbability = nightIceProbability; this.dayRain = dayRain; this.nightRain = nightRain; this.daySnow = daySnow; this.nightSnow = nightSnow; this.dayIce = dayIce; this.nightIce = nightIce; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Long getDayIcon() { return dayIcon; } public void setDayIcon(Long dayIcon) { this.dayIcon = dayIcon; } public Long getNightIcon() { return nightIcon; } public void setNightIcon(Long nightIcon) { this.nightIcon = nightIcon; } public String getMinTemperature() { return minTemperature; } public void setMinTemperature(String minTemperature) { this.minTemperature = minTemperature; } public String getMaxTemperature() { return maxTemperature; } public void setMaxTemperature(String maxTemperature) { this.maxTemperature = maxTemperature; } public String getDayWind() { return dayWind; } public void setDayWind(String dayWind) { this.dayWind = dayWind; } public String getNightWind() { return nightWind; } public void setNightWind(String nightWind) { this.nightWind = nightWind; } public String getuVIndex() { return uVIndex; } public void setuVIndex(String uVIndex) { this.uVIndex = uVIndex; } public String getAirQualityCategory() { return airQualityCategory; } public void setAirQualityCategory(String airQualityCategory) { this.airQualityCategory = airQualityCategory; } public String getDayRainProbability() { return dayRainProbability; } public void setDayRainProbability(String dayRainProbability) { this.dayRainProbability = dayRainProbability; } public String getNightRainProbability() { return nightRainProbability; } public void setNightRainProbability(String nightRainProbability) { this.nightRainProbability = nightRainProbability; } public String getDaySnowProbability() { return daySnowProbability; } public void setDaySnowProbability(String daySnowProbability) { this.daySnowProbability = daySnowProbability; } public String getNightSnowProbability() { return nightSnowProbability; } public void setNightSnowProbability(String nightSnowProbability) { this.nightSnowProbability = nightSnowProbability; } public String getDayIceProbability() { return dayIceProbability; } public void setDayIceProbability(String dayIceProbability) { this.dayIceProbability = dayIceProbability; } public String getNightIceProbability() { return nightIceProbability; } public void setNightIceProbability(String nightIceProbability) { this.nightIceProbability = nightIceProbability; } public String getDayRain() { return dayRain; } public void setDayRain(String dayRain) { this.dayRain = dayRain; } public String getNightRain() { return nightRain; } public void setNightRain(String nightRain) { this.nightRain = nightRain; } public String getDaySnow() { return daySnow; } public void setDaySnow(String daySnow) { this.daySnow = daySnow; } public String getNightSnow() { return nightSnow; } public void setNightSnow(String nightSnow) { this.nightSnow = nightSnow; } public String getDayIce() { return dayIce; } public void setDayIce(String dayIce) { this.dayIce = dayIce; } public String getNightIce() { return nightIce; } public void setNightIce(String nightIce) { this.nightIce = nightIce; } }
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { /* * Ensure an inlined static invoke explicitly triggers the * initialization check of the called method's declaring class, and * that the corresponding load class instruction does not get * removed before register allocation & code generation. */ /// CHECK-START: void Main.invokeStaticInlined() builder (after) /// CHECK-DAG: <<LoadClass:l\d+>> LoadClass gen_clinit_check:false /// CHECK-DAG: <<ClinitCheck:l\d+>> ClinitCheck [<<LoadClass>>] /// CHECK-DAG: InvokeStaticOrDirect [{{([ij]\d+,)?}}<<ClinitCheck>>] /// CHECK-START: void Main.invokeStaticInlined() inliner (after) /// CHECK-DAG: <<LoadClass:l\d+>> LoadClass gen_clinit_check:false /// CHECK-DAG: <<ClinitCheck:l\d+>> ClinitCheck [<<LoadClass>>] /// CHECK-START: void Main.invokeStaticInlined() inliner (after) /// CHECK-NOT: InvokeStaticOrDirect // The following checks ensure the clinit check instruction added by // the builder is pruned by the PrepareForRegisterAllocation, while // the load class instruction is preserved. As the control flow // graph is not dumped after (nor before) this step, we check the // CFG as it is before the next pass (liveness analysis) instead. /// CHECK-START: void Main.invokeStaticInlined() liveness (before) /// CHECK-DAG: LoadClass gen_clinit_check:true /// CHECK-START: void Main.invokeStaticInlined() liveness (before) /// CHECK-NOT: ClinitCheck /// CHECK-NOT: InvokeStaticOrDirect static void invokeStaticInlined() { ClassWithClinit1.$opt$inline$StaticMethod(); } static class ClassWithClinit1 { static { System.out.println("Main$ClassWithClinit1's static initializer"); } static void $opt$inline$StaticMethod() { } } /* * Ensure a non-inlined static invoke eventually has an implicit * initialization check of the called method's declaring class. */ /// CHECK-START: void Main.invokeStaticNotInlined() builder (after) /// CHECK: <<LoadClass:l\d+>> LoadClass gen_clinit_check:false /// CHECK: <<ClinitCheck:l\d+>> ClinitCheck [<<LoadClass>>] /// CHECK: InvokeStaticOrDirect [{{([ij]\d+,)?}}<<ClinitCheck>>] /// CHECK-START: void Main.invokeStaticNotInlined() inliner (after) /// CHECK: <<LoadClass:l\d+>> LoadClass gen_clinit_check:false /// CHECK: <<ClinitCheck:l\d+>> ClinitCheck [<<LoadClass>>] /// CHECK: InvokeStaticOrDirect [{{([ij]\d+,)?}}<<ClinitCheck>>] // The following checks ensure the clinit check and load class // instructions added by the builder are pruned by the // PrepareForRegisterAllocation. As the control flow graph is not // dumped after (nor before) this step, we check the CFG as it is // before the next pass (liveness analysis) instead. /// CHECK-START: void Main.invokeStaticNotInlined() liveness (before) /// CHECK: InvokeStaticOrDirect clinit_check:implicit /// CHECK-START: void Main.invokeStaticNotInlined() liveness (before) /// CHECK-NOT: LoadClass /// CHECK-NOT: ClinitCheck static void invokeStaticNotInlined() { ClassWithClinit2.$noinline$staticMethod(); } static class ClassWithClinit2 { static { System.out.println("Main$ClassWithClinit2's static initializer"); } static boolean staticField = false; static void $noinline$staticMethod() { } } /* * Ensure an inlined call from a static method to a static method * of the same class does not require an explicit clinit check * (already initialized or initializing in the same thread). */ /// CHECK-START: void Main$ClassWithClinit3Static.invokeStaticInlined() builder (after) /// CHECK-DAG: InvokeStaticOrDirect /// CHECK-START: void Main$ClassWithClinit3Static.invokeStaticInlined() builder (after) /// CHECK-NOT: LoadClass /// CHECK-NOT: ClinitCheck /// CHECK-START: void Main$ClassWithClinit3Static.invokeStaticInlined() inliner (after) /// CHECK-NOT: LoadClass /// CHECK-NOT: ClinitCheck /// CHECK-NOT: InvokeStaticOrDirect static class ClassWithClinit3Static { static void invokeStaticInlined() { // The invocation of invokeStaticInlined happens only after a clinit check // of ClassWithClinit3Static, meaning that the hereinbelow call to // $opt$inline$StaticMethod does not need another clinit check. $opt$inline$StaticMethod(); } static { System.out.println("Main$ClassWithClinit3Static's static initializer"); } static void $opt$inline$StaticMethod() { } } /* * Ensure an inlined call from an instance method to a static method * of the same class actually requires an explicit clinit check when * the class has a non-trivial initialization as we could be executing * the instance method on an escaped object of an erroneous class. b/62478025 */ /// CHECK-START: void Main$ClassWithClinit3Instance.invokeStaticInlined() builder (after) /// CHECK-DAG: LoadClass /// CHECK-DAG: ClinitCheck /// CHECK-DAG: InvokeStaticOrDirect /// CHECK-START: void Main$ClassWithClinit3Instance.invokeStaticInlined() inliner (after) /// CHECK-DAG: LoadClass /// CHECK-DAG: ClinitCheck /// CHECK-START: void Main$ClassWithClinit3Instance.invokeStaticInlined() inliner (after) /// CHECK-NOT: InvokeStaticOrDirect static class ClassWithClinit3Instance { void invokeStaticInlined() { // ClinitCheck required. $opt$inline$StaticMethod(); } static { System.out.println("Main$ClassWithClinit3Instance's static initializer"); } static void $opt$inline$StaticMethod() { } } /* * Ensure a non-inlined call from a static method to a static method * of the same class does not require an explicit clinit check * (already initialized or initializing in the same thread). */ /// CHECK-START: void Main$ClassWithClinit4Static.invokeStaticNotInlined() builder (after) /// CHECK-DAG: InvokeStaticOrDirect /// CHECK-START: void Main$ClassWithClinit4Static.invokeStaticNotInlined() builder (after) /// CHECK-NOT: LoadClass /// CHECK-NOT: ClinitCheck /// CHECK-START: void Main$ClassWithClinit4Static.invokeStaticNotInlined() inliner (after) /// CHECK-DAG: InvokeStaticOrDirect /// CHECK-START: void Main$ClassWithClinit4Static.invokeStaticNotInlined() inliner (after) /// CHECK-NOT: LoadClass /// CHECK-NOT: ClinitCheck static class ClassWithClinit4Static { static void invokeStaticNotInlined() { // The invocation of invokeStaticNotInlined triggers the // initialization of ClassWithClinit4Static, meaning that the // call to staticMethod below does not need a clinit // check. $noinline$staticMethod(); } static { System.out.println("Main$ClassWithClinit4Static's static initializer"); } static void $noinline$staticMethod() { } } /* * Ensure a non-inlined call from an instance method to a static method * of the same class actually requires an explicit clinit check when * the class has a non-trivial initialization as we could be executing * the instance method on an escaped object of an erroneous class. b/62478025 */ /// CHECK-START: void Main$ClassWithClinit4Instance.invokeStaticNotInlined() builder (after) /// CHECK-DAG: LoadClass /// CHECK-DAG: ClinitCheck /// CHECK-DAG: InvokeStaticOrDirect /// CHECK-START: void Main$ClassWithClinit4Instance.invokeStaticNotInlined() inliner (after) /// CHECK-DAG: LoadClass /// CHECK-DAG: ClinitCheck /// CHECK-DAG: InvokeStaticOrDirect // The following checks ensure the clinit check and load class // instructions added by the builder are pruned by the // PrepareForRegisterAllocation. As the control flow graph is not // dumped after (nor before) this step, we check the CFG as it is // before the next pass (liveness analysis) instead. /// CHECK-START: void Main$ClassWithClinit4Instance.invokeStaticNotInlined() liveness (before) /// CHECK: InvokeStaticOrDirect clinit_check:implicit /// CHECK-START: void Main$ClassWithClinit4Instance.invokeStaticNotInlined() liveness (before) /// CHECK-NOT: LoadClass /// CHECK-NOT: ClinitCheck static class ClassWithClinit4Instance { void invokeStaticNotInlined() { // ClinitCheck required. $noinline$staticMethod(); } static { System.out.println("Main$ClassWithClinit4Instance's static initializer"); } static void $noinline$staticMethod() { } } /* * We used to remove clinit check for calls to static methods in a superclass. However, this * is not a valid optimization when instances of erroneous classes can escape, therefore * we avoid this optimization for classes with non-trivial initialization. b/62478025 */ /// CHECK-START: void Main$SubClassOfClassWithClinit5.invokeStaticInlined() builder (after) /// CHECK-DAG: LoadClass /// CHECK-DAG: ClinitCheck /// CHECK-DAG: InvokeStaticOrDirect /// CHECK-START: void Main$SubClassOfClassWithClinit5.invokeStaticInlined() inliner (after) /// CHECK-DAG: LoadClass /// CHECK-DAG: ClinitCheck /// CHECK-NOT: InvokeStaticOrDirect static class ClassWithClinit5 { static void $opt$inline$StaticMethod() { } static { System.out.println("Main$ClassWithClinit5's static initializer"); } } static class SubClassOfClassWithClinit5 extends ClassWithClinit5 { static void invokeStaticInlined() { ClassWithClinit5.$opt$inline$StaticMethod(); } } /* * Ensure an inlined call to a static method whose declaring class is a super class * of the caller's class does not require an explicit clinit check if the declaring * class has a trivial initialization. b/62478025 */ /// CHECK-START: void Main$SubClassOfClassWithoutClinit5.invokeStaticInlined() builder (after) /// CHECK-DAG: InvokeStaticOrDirect /// CHECK-START: void Main$SubClassOfClassWithoutClinit5.invokeStaticInlined() builder (after) /// CHECK-NOT: LoadClass /// CHECK-NOT: ClinitCheck /// CHECK-START: void Main$SubClassOfClassWithoutClinit5.invokeStaticInlined() inliner (after) /// CHECK-NOT: LoadClass /// CHECK-NOT: ClinitCheck /// CHECK-NOT: InvokeStaticOrDirect static class ClassWithoutClinit5 { // Mimicks ClassWithClinit5 but without the <clinit>. static void $opt$inline$StaticMethod() { } } static class SubClassOfClassWithoutClinit5 extends ClassWithoutClinit5 { static { System.out.println("Main$SubClassOfClassWithoutClinit5's static initializer"); } static void invokeStaticInlined() { ClassWithoutClinit5.$opt$inline$StaticMethod(); } } /* * We used to remove clinit check for calls to static methods in a superclass. However, this * is not a valid optimization when instances of erroneous classes can escape, therefore * we avoid this optimization for classes with non-trivial initialization. b/62478025 */ /// CHECK-START: void Main$SubClassOfClassWithClinit6.invokeStaticNotInlined() builder (after) /// CHECK-DAG: InvokeStaticOrDirect /// CHECK-START: void Main$SubClassOfClassWithClinit6.invokeStaticNotInlined() builder (after) /// CHECK-DAG: LoadClass /// CHECK-DAG: ClinitCheck /// CHECK-START: void Main$SubClassOfClassWithClinit6.invokeStaticNotInlined() inliner (after) /// CHECK-DAG: LoadClass /// CHECK-DAG: ClinitCheck /// CHECK-DAG: InvokeStaticOrDirect static class ClassWithClinit6 { static void $noinline$staticMethod() { } static { System.out.println("Main$ClassWithClinit6's static initializer"); } } static class SubClassOfClassWithClinit6 extends ClassWithClinit6 { static void invokeStaticNotInlined() { ClassWithClinit6.$noinline$staticMethod(); } } /* * Ensure a non-inlined call to a static method whose declaring class is a super class * of the caller's class does not require an explicit clinit check if the declaring * class has a trivial initialization. b/62478025 */ /// CHECK-START: void Main$SubClassOfClassWithoutClinit6.invokeStaticNotInlined() builder (after) /// CHECK-DAG: InvokeStaticOrDirect /// CHECK-START: void Main$SubClassOfClassWithoutClinit6.invokeStaticNotInlined() builder (after) /// CHECK-NOT: LoadClass /// CHECK-NOT: ClinitCheck /// CHECK-START: void Main$SubClassOfClassWithoutClinit6.invokeStaticNotInlined() inliner (after) /// CHECK-DAG: InvokeStaticOrDirect /// CHECK-START: void Main$SubClassOfClassWithoutClinit6.invokeStaticNotInlined() inliner (after) /// CHECK-NOT: LoadClass /// CHECK-NOT: ClinitCheck static class ClassWithoutClinit6 { // Mimicks ClassWithClinit6 but without the <clinit>. static void $noinline$staticMethod() { } } static class SubClassOfClassWithoutClinit6 extends ClassWithoutClinit6 { static { System.out.println("Main$SubClassOfClassWithoutClinit6's static initializer"); } static void invokeStaticNotInlined() { ClassWithoutClinit6.$noinline$staticMethod(); } } /* * Verify that if we have a static call immediately after the load class * we don't do generate a clinit check. */ /// CHECK-START: void Main.noClinitBecauseOfInvokeStatic() liveness (before) /// CHECK-DAG: <<IntConstant:i\d+>> IntConstant 0 /// CHECK-DAG: <<LoadClass:l\d+>> LoadClass gen_clinit_check:false /// CHECK-DAG: InvokeStaticOrDirect clinit_check:implicit /// CHECK-DAG: StaticFieldSet [<<LoadClass>>,<<IntConstant>>] /// CHECK-START: void Main.noClinitBecauseOfInvokeStatic() liveness (before) /// CHECK-NOT: ClinitCheck static void noClinitBecauseOfInvokeStatic() { ClassWithClinit2.$noinline$staticMethod(); ClassWithClinit2.staticField = false; } /* * Verify that if the static call is after a field access, the load class * will generate a clinit check. */ /// CHECK-START: void Main.clinitBecauseOfFieldAccess() liveness (before) /// CHECK-DAG: <<IntConstant:i\d+>> IntConstant 0 /// CHECK-DAG: <<LoadClass:l\d+>> LoadClass gen_clinit_check:true /// CHECK-DAG: StaticFieldSet [<<LoadClass>>,<<IntConstant>>] /// CHECK-DAG: InvokeStaticOrDirect clinit_check:none /// CHECK-START: void Main.clinitBecauseOfFieldAccess() liveness (before) /// CHECK-NOT: ClinitCheck static void clinitBecauseOfFieldAccess() { ClassWithClinit2.staticField = false; ClassWithClinit2.$noinline$staticMethod(); } /* * Verify that LoadClass from const-class is not merged with * later invoke-static (or it's ClinitCheck). */ /// CHECK-START: void Main.constClassAndInvokeStatic(java.lang.Iterable) liveness (before) /// CHECK: LoadClass gen_clinit_check:false /// CHECK: InvokeStaticOrDirect clinit_check:implicit /// CHECK-START: void Main.constClassAndInvokeStatic(java.lang.Iterable) liveness (before) /// CHECK-NOT: ClinitCheck static void constClassAndInvokeStatic(Iterable<?> it) { $opt$inline$ignoreClass(ClassWithClinit7.class); ClassWithClinit7.$noinline$someStaticMethod(it); } static void $opt$inline$ignoreClass(Class<?> c) { } static class ClassWithClinit7 { static { System.out.println("Main$ClassWithClinit7's static initializer"); } static void $noinline$someStaticMethod(Iterable<?> it) { it.iterator(); } } /* * Verify that LoadClass from sget is not merged with later invoke-static. */ /// CHECK-START: void Main.sgetAndInvokeStatic(java.lang.Iterable) liveness (before) /// CHECK: LoadClass gen_clinit_check:true /// CHECK: InvokeStaticOrDirect clinit_check:none /// CHECK-START: void Main.sgetAndInvokeStatic(java.lang.Iterable) liveness (before) /// CHECK-NOT: ClinitCheck static void sgetAndInvokeStatic(Iterable<?> it) { $opt$inline$ignoreInt(ClassWithClinit8.value); ClassWithClinit8.$noinline$someStaticMethod(it); } static void $opt$inline$ignoreInt(int i) { } static class ClassWithClinit8 { public static int value = 0; static { System.out.println("Main$ClassWithClinit8's static initializer"); } static void $noinline$someStaticMethod(Iterable<?> it) { it.iterator(); } } /* * Verify that LoadClass from const-class, ClinitCheck from sget and * InvokeStaticOrDirect from invoke-static are not merged. */ /// CHECK-START: void Main.constClassSgetAndInvokeStatic(java.lang.Iterable) liveness (before) /// CHECK: LoadClass gen_clinit_check:false /// CHECK: ClinitCheck /// CHECK: InvokeStaticOrDirect clinit_check:none static void constClassSgetAndInvokeStatic(Iterable<?> it) { $opt$inline$ignoreClass(ClassWithClinit9.class); $opt$inline$ignoreInt(ClassWithClinit9.value); ClassWithClinit9.$noinline$someStaticMethod(it); } static class ClassWithClinit9 { public static int value = 0; static { System.out.println("Main$ClassWithClinit9's static initializer"); } static void $noinline$someStaticMethod(Iterable<?> it) { it.iterator(); } } /* * Verify that LoadClass from a fully-inlined invoke-static is not merged * with InvokeStaticOrDirect from a later invoke-static to the same method. */ /// CHECK-START: void Main.inlinedInvokeStaticViaNonStatic(java.lang.Iterable) liveness (before) /// CHECK: LoadClass gen_clinit_check:true /// CHECK: InvokeStaticOrDirect clinit_check:none /// CHECK-START: void Main.inlinedInvokeStaticViaNonStatic(java.lang.Iterable) liveness (before) /// CHECK-NOT: ClinitCheck static void inlinedInvokeStaticViaNonStatic(Iterable<?> it) { if (it != null) { inlinedInvokeStaticViaNonStaticHelper(null); inlinedInvokeStaticViaNonStaticHelper(it); } } static void inlinedInvokeStaticViaNonStaticHelper(Iterable<?> it) { ClassWithClinit10.inlinedForNull(it); } static class ClassWithClinit10 { public static int value = 0; static { System.out.println("Main$ClassWithClinit10's static initializer"); } static void inlinedForNull(Iterable<?> it) { if (it != null) { it.iterator(); // We're not inlining methods that always throw. throw new Error(""); } } } /* * Check that the LoadClass from an invoke-static C.foo() doesn't get merged with * an invoke-static inside C.foo(). This would mess up the stack walk in the * resolution trampoline where we would have to load C (if C isn't loaded yet) * which is not permitted there. * * Note: In case of failure, we would get an failed assertion during compilation, * so we wouldn't really get to the checker tests below. */ /// CHECK-START: void Main.inlinedInvokeStaticViaStatic(java.lang.Iterable) liveness (before) /// CHECK: LoadClass gen_clinit_check:true /// CHECK: InvokeStaticOrDirect clinit_check:none /// CHECK-START: void Main.inlinedInvokeStaticViaStatic(java.lang.Iterable) liveness (before) /// CHECK-NOT: ClinitCheck static void inlinedInvokeStaticViaStatic(Iterable<?> it) { if (it != null) { ClassWithClinit11.callInlinedForNull(it); } } static class ClassWithClinit11 { public static int value = 0; static { System.out.println("Main$ClassWithClinit11's static initializer"); } static void callInlinedForNull(Iterable<?> it) { inlinedForNull(it); } static void inlinedForNull(Iterable<?> it) { it.iterator(); if (it != null) { // We're not inlining methods that always throw. throw new Error(""); } } } /* * A test similar to inlinedInvokeStaticViaStatic() but doing the indirect invoke * twice with the first one to be fully inlined. */ /// CHECK-START: void Main.inlinedInvokeStaticViaStaticTwice(java.lang.Iterable) liveness (before) /// CHECK: LoadClass gen_clinit_check:true /// CHECK: InvokeStaticOrDirect clinit_check:none /// CHECK-START: void Main.inlinedInvokeStaticViaStaticTwice(java.lang.Iterable) liveness (before) /// CHECK-NOT: ClinitCheck static void inlinedInvokeStaticViaStaticTwice(Iterable<?> it) { if (it != null) { ClassWithClinit12.callInlinedForNull(null); ClassWithClinit12.callInlinedForNull(it); } } static class ClassWithClinit12 { public static int value = 0; static { System.out.println("Main$ClassWithClinit12's static initializer"); } static void callInlinedForNull(Iterable<?> it) { inlinedForNull(it); } static void inlinedForNull(Iterable<?> it) { if (it != null) { // We're not inlining methods that always throw. throw new Error(""); } } } static class ClassWithClinit13 { static { System.out.println("Main$ClassWithClinit13's static initializer"); } public static void $inline$forwardToGetIterator(Iterable<?> it) { $noinline$getIterator(it); } public static void $noinline$getIterator(Iterable<?> it) { it.iterator(); } } // TODO: Write checker statements. static Object $noinline$testInliningAndNewInstance(Iterable<?> it) { ClassWithClinit13.$inline$forwardToGetIterator(it); return new ClassWithClinit13(); } // TODO: Add a test for the case of a static method whose declaring // class type index is not available (i.e. when `storage_index` // equals `dex::kDexNoIndex` in // art::HGraphBuilder::BuildInvoke). public static void main(String[] args) { invokeStaticInlined(); invokeStaticNotInlined(); ClassWithClinit3Static.invokeStaticInlined(); new ClassWithClinit3Instance().invokeStaticInlined(); ClassWithClinit4Static.invokeStaticNotInlined(); new ClassWithClinit4Instance().invokeStaticNotInlined(); SubClassOfClassWithClinit5.invokeStaticInlined(); SubClassOfClassWithoutClinit5.invokeStaticInlined(); SubClassOfClassWithClinit6.invokeStaticNotInlined(); SubClassOfClassWithoutClinit6.invokeStaticNotInlined(); Iterable it = new Iterable() { public java.util.Iterator iterator() { return null; } }; constClassAndInvokeStatic(it); sgetAndInvokeStatic(it); constClassSgetAndInvokeStatic(it); try { inlinedInvokeStaticViaNonStatic(it); } catch (Error e) { // Expected } try { inlinedInvokeStaticViaStatic(it); } catch (Error e) { // Expected } try{ inlinedInvokeStaticViaStaticTwice(it); } catch (Error e) { // Expected } $noinline$testInliningAndNewInstance(it); } }
package application; import com.jme3.app.SimpleApplication; import com.jme3.input.KeyInput; import com.jme3.input.MouseInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.AnalogListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseAxisTrigger; import com.jme3.material.Material; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.CameraNode; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.control.CameraControl.ControlDirection; import com.jme3.scene.shape.*; import com.jme3.system.AppSettings; import com.jme3.texture.Texture; import com.jme3.texture.Texture.WrapMode; import com.jme3.util.SkyFactory; public class Main extends SimpleApplication { float speed = 10; Node player = new Node("Player"); AnalogListener analogListener = new AnalogListener() { public void onAnalog(String name, float value, float tpf) { Spatial camNode = player.getChild("Camera Node"); speed = camNode.getLocalTranslation().z; if (name.equals("Left")) { player.move(value*-(speed+10)/2, 0, 0); } if (name.equals("Right")) { player.move(value*(speed+10)/2, 0, 0); } if (name.equals("Up")) { player.move(0, value*(speed+10)/2, 0); } if (name.equals("Down")) { player.move(0, value*-(speed+10)/2, 0); } } }; private ActionListener actionListener = new ActionListener() { public void onAction(String name, boolean keyPressed, float tpf) { Spatial camNode = player.getChild("Camera Node"); if (name.equals("Zoom In") && camNode.getLocalTranslation().z > 3) { camNode.move(0, 0, -1); } if (name.equals("Zoom Out")) { camNode.move(0, 0, 1); } } }; public static void main(String[] args) { Main app = new Main(); AppSettings settings = new AppSettings(false); settings.setTitle("Risky Strats"); app.setSettings(settings); app.start(); } @Override public void simpleInitApp() { initCamera(); initInput(); createSkybox(); Quad s = new Quad(32, 32); Geometry g = new Geometry("Plane", s); Material m = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); Texture grass = assetManager.loadTexture("assets/textures/grass_1300.png"); grass.setWrap(WrapMode.Repeat); s.scaleTextureCoordinates(new Vector2f(5, 5)); m.setTexture("ColorMap", grass); g.setMaterial(m); g.setLocalTranslation(-16, -16, 0); rootNode.attachChild(g); // DirectionalLight sun = new DirectionalLight(new Vector3f(-0.5f, -0.5f, -0.5f).normalizeLocal(), ColorRGBA.White); // rootNode.addLight(sun); } public void initCamera() { rootNode.attachChild(player); flyCam.setEnabled(false); CameraNode camNode = new CameraNode("Camera Node", cam); camNode.setControlDir(ControlDirection.SpatialToCamera); player.attachChild(camNode); camNode.setLocalTranslation(0, 0, speed); camNode.lookAt(player.getLocalTranslation(), Vector3f.UNIT_Y); } public void initInput() { inputManager.addMapping("Left", new KeyTrigger(KeyInput.KEY_A), new KeyTrigger(KeyInput.KEY_LEFT)); inputManager.addMapping("Right", new KeyTrigger(KeyInput.KEY_D), new KeyTrigger(KeyInput.KEY_RIGHT)); inputManager.addMapping("Up", new KeyTrigger(KeyInput.KEY_W), new KeyTrigger(KeyInput.KEY_UP)); inputManager.addMapping("Down", new KeyTrigger(KeyInput.KEY_S), new KeyTrigger(KeyInput.KEY_DOWN)); inputManager.addMapping("Zoom In", new MouseAxisTrigger(MouseInput.AXIS_WHEEL,false)); inputManager.addMapping("Zoom Out", new MouseAxisTrigger(MouseInput.AXIS_WHEEL,true)); inputManager.addListener(analogListener, "Left", "Right", "Up", "Down"); inputManager.addListener(actionListener, "Zoom In", "Zoom Out"); } public void createSkybox() { Texture[] lagoon = new Texture[] { assetManager.loadTexture("Textures/Sky/Lagoon/lagoon_west.jpg"), assetManager.loadTexture("Textures/Sky/Lagoon/lagoon_east.jpg"), assetManager.loadTexture("Textures/Sky/Lagoon/lagoon_north.jpg"), assetManager.loadTexture("Textures/Sky/Lagoon/lagoon_south.jpg"), assetManager.loadTexture("Textures/Sky/Lagoon/lagoon_up.jpg"), assetManager.loadTexture("Textures/Sky/Lagoon/lagoon_down.jpg") }; int i = 0; getRootNode().attachChild(SkyFactory.createSky(assetManager, lagoon[i++], lagoon[i++], lagoon[i++], lagoon[i++], lagoon[i++], lagoon[i++])); } @Override public void simpleUpdate(float tpf) { } }
package ua.com.hibernate.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ua.com.hibernate.model.User; import ua.com.hibernate.repository.UserRepository; import ua.com.hibernate.repository.impl.UserRepositoryImpl; import ua.com.hibernate.service.UserService; import javax.transaction.Transactional; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Transactional @Override public void addUser(User user) { userRepository.addUser(user); } @Transactional @Override public void updateUser(User user) { userRepository.updateUser(user); } @Transactional @Override public void deleteUser(User user) { userRepository.deleteUser(user); } @Transactional @Override public User findById(int id) { return userRepository.findById(id); } @Transactional @Override public List<User> findAll() { return userRepository.findAll(); } }
package com.stackflow.pageObjects; import java.util.List; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; public class GmailLogin extends BasePage{ @FindBy(how=How.XPATH, xpath="//input[@id='identifierId']") WebElement emailfield; @FindBy(how=How.XPATH, xpath="//*[@id='password']/div[1]/div/div[1]/input") WebElement passwordfield; @FindBy(how=How.XPATH, xpath="//span[@class='bqe']") List<WebElement> emailThreads; @FindBy(how=How.XPATH, xpath="//span[@class='gb_ya gbii']") WebElement profilelogo; @FindBy(how=How.CSS, css="input.gb_3e") @CacheLookup WebElement searchBox; @FindBy(how=How.LINK_TEXT, linkText="Click here to complete your registration") @CacheLookup WebElement activatelink; @FindBy(how=How.LINK_TEXT, linkText= "Anmelden") @CacheLookup WebElement loginLink; @FindBy(how=How.XPATH, xpath= "//*[contains(text(),'Produktiver arbeiten mit Gmail')]") @CacheLookup WebElement googleProductTxt; public GmailLogin(WebDriver driver) { super(driver); } public void enterEmailID(String emailID) throws Exception { waitForVisible(driver, emailfield, 25); Thread.sleep(2000); Actions actions=new Actions(driver); actions.moveToElement(emailfield); actions.click(); actions.sendKeys(emailID + Keys.ENTER); actions.build().perform(); } public void enterPassword(String password) throws Exception { waitForVisible(driver, passwordfield, 25); Thread.sleep(2000); Actions actions=new Actions(driver); actions.moveToElement(passwordfield); actions.click(); actions.sendKeys(password + Keys.ENTER); actions.build().perform(); } public void clickEmail(String emailSubject) { waitForVisible(driver, profilelogo, 25); for (int i = 0; i < emailThreads.size(); i++) { if (emailThreads.get(i).getText().contains(emailSubject)) { emailThreads.get(i).click(); break; } } } public void searchEmail(String emailIdChild) { waitForVisible(driver, searchBox, 25); searchBox.sendKeys("to:"+emailIdChild + Keys.ENTER); } public StackFlowHomePage openLink() throws Exception { waitForVisible(driver, activatelink, 25); activatelink.click(); return new StackFlowHomePage(driver); } public void loginGmailLink() { loginLink.click(); } public boolean googleProductText() { return googleProductTxt.isDisplayed(); } }
package newlang4; import newlang3.LexicalType; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class EndNode extends Node { static final Set<LexicalType> first = new HashSet<LexicalType>(Arrays.asList( LexicalType.END)); private EndNode(Environment env){ super(env); type = NodeType.END; } public static boolean isMatch(LexicalType type) { return first.contains(type); } public static Node getHandler(LexicalType type, Environment env) throws Exception { env.getInput().get(); if(type != LexicalType.END) return null; System.out.println("Program END"); return new EndNode(env); } @Override public String toString(){ return "END"; } }
package ru.skillfactory.actions; import ru.skillfactory.*; /** * Класс для реализации действия "Перевести средства", используется в StartUI. */ public class TransferToAction implements UserAction { @Override public String getTitle() { return "Перевести средства"; } /** * Перевести средства - также общаетесь в этом методе с пользователем и передаёте информацию, * так как операция важная желательно ещё раз заставлять вводить пароль/логин и передавать информацию * в BankService. Exceptions пользователю печатать не надо (как и в других методах этого класса), * вводите подсказки или написанные вами сообщения об ошибках. * * @param bankService BankService объект. * @param input Input объект. * @param requisite Строка в произвольной форме, используется для поиска пользователя. * @return возвращает всегда true, приложение продолжает работать. */ @Override public boolean execute(BankService bankService, Input input, String requisite) { return true; } }
package f.star.iota.milk.ui.gacha; import f.star.iota.milk.base.BaseBean; class GachaBean extends BaseBean { private String preview; private String url; private String avatar; private String author; private String rank; public GachaBean() { } public String getPreview() { return preview; } public void setPreview(String preview) { this.preview = preview; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } }
package com.pwq.sort; /** * @Author:WenqiangPu * @Description * @Date:Created in 20:13 2017/8/2 * @Modified By: */ public class User implements Comparable<User>{ private String name; private Integer order; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getOrder() { return order; } public void setOrder(Integer order) { this.order = order; } @Override public int compareTo(User o) { if(this.getOrder()<o.getOrder()){ return -1; }else { return 1; } } }
/* * 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 logica; import java.sql.SQLException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import persistencia.PersistenciaPersonal; import persistencia.PersonalAlmacen; /** * Clase que administra el personal. * * @author marai */ public class InventarioPersonal implements InventarioPersonalInterface { private PersistenciaPersonal almacen = new PersonalAlmacen(); public InventarioPersonal() { } /** * comprueba si existe el persona. * @param usuario Ide del personal * @return si existe o no el personal * @throws SQLException Por si causa problemas la base */ @Override public boolean comprobarIdPersonal(int usuario) throws SQLException { return this.almacen.buscarUsuario(usuario); } /** * comprieba la contraseña . * @param contrasenia es la contraseña dek usuario * @return si la contraseña conicide y es correcta. * @throws SQLException Por si causa problemas la base */ @Override public boolean comprobarContrasenia(String contrasenia) throws SQLException { return false; } /** * obtiene el registro del personal. * @param numeroDePersonal id del personal * @return objeto personal * @throws SQLException Por si causa problemas la base */ @Override public Personal obtenerPersonal(int numeroDePersonal) throws SQLException { return this.almacen.obtenerPersonal(numeroDePersonal); } /** * comprueba si los datos del usuario estan correctos. * @param numeroDePersonal numero del personal * @param contrasenia contraseña del usuario. * @return regresa si los datos si existe y son correctos */ @Override public boolean comprobarPersonal(int numeroDePersonal, String contrasenia) { return this.almacen.buscarPersonal(numeroDePersonal, contrasenia); } /** * obtiene el puesto del personal indicado. * @param usuario id del personal * @return regresa el puesto del personal */ @Override public String obtenerPuesto(int usuario) { try { return this.almacen.obteberPuesto(usuario); } catch (SQLException ex) { return null; } } /** * obtiene todos los registros del personal. * @return lista de objetos personal. * @throws SQLException Por si causa problemas la base */ @Override public List<Personal> verPersonal() throws SQLException { return this.almacen.obternerTodoPersonal(); } /** * registra un nuevo objeto personal. * @param personal objeto personal. * @throws SQLException Por si causa problemas la base */ @Override public void registrarNuevoPersonal(Personal personal) throws SQLException { try { this.almacen.registrarPersonal(personal); this.almacen.registrarContrasenia(personal); } catch (SQLException ex) { throw new SQLException(); } } /** * comprueba si el correo existe. * @param correo correo del personal * @return si existe el correo * @throws SQLException Por si causa problemas la base */ @Override public boolean comprobarCorreo(String correo) throws SQLException { return this.almacen.buscarCorreo(correo); } /** * comprueba si el telefono no es repedido. * @param telefono telefono del personal. * @return regresa si existe el telefono. * @throws SQLException Por si causa problemas la base */ @Override public boolean comprobarTelefono(String telefono) throws SQLException { return this.almacen.buscarTelefono(telefono); } /** * edita un registro de un personal. * @param personal recibe un objeto personal */ @Override public void editarPersonal(Personal personal) { try { this.almacen.actualizarPersonal(personal); } catch (SQLException ex) { Logger.getLogger(InventarioPersonal.class.getName()).log(Level.SEVERE, null, ex); } try { this.almacen.actualizarContrasenia(personal); } catch (SQLException ex) { Logger.getLogger(InventarioPersonal.class.getName()).log(Level.SEVERE, null, ex); } } }
/* * Copyright 2002-2019 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.context; import java.util.Locale; import org.springframework.lang.Nullable; /** * Strategy interface for resolving messages, with support for the parameterization * and internationalization of such messages. * * <p>Spring provides two out-of-the-box implementations for production: * <ul> * <li>{@link org.springframework.context.support.ResourceBundleMessageSource}: built * on top of the standard {@link java.util.ResourceBundle}, sharing its limitations. * <li>{@link org.springframework.context.support.ReloadableResourceBundleMessageSource}: * highly configurable, in particular with respect to reloading message definitions. * </ul> * * @author Rod Johnson * @author Juergen Hoeller * @see org.springframework.context.support.ResourceBundleMessageSource * @see org.springframework.context.support.ReloadableResourceBundleMessageSource */ public interface MessageSource { /** * Try to resolve the message. Return default message if no message was found. * @param code the message code to look up, e.g. 'calculator.noRateSet'. * MessageSource users are encouraged to base message names on qualified class * or package names, avoiding potential conflicts and ensuring maximum clarity. * @param args an array of arguments that will be filled in for params within * the message (params look like "{0}", "{1,date}", "{2,time}" within a message), * or {@code null} if none * @param defaultMessage a default message to return if the lookup fails * @param locale the locale in which to do the lookup * @return the resolved message if the lookup was successful, otherwise * the default message passed as a parameter (which may be {@code null}) * @see #getMessage(MessageSourceResolvable, Locale) * @see java.text.MessageFormat */ @Nullable String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale); /** * Try to resolve the message. Treat as an error if the message can't be found. * @param code the message code to look up, e.g. 'calculator.noRateSet'. * MessageSource users are encouraged to base message names on qualified class * or package names, avoiding potential conflicts and ensuring maximum clarity. * @param args an array of arguments that will be filled in for params within * the message (params look like "{0}", "{1,date}", "{2,time}" within a message), * or {@code null} if none * @param locale the locale in which to do the lookup * @return the resolved message (never {@code null}) * @throws NoSuchMessageException if no corresponding message was found * @see #getMessage(MessageSourceResolvable, Locale) * @see java.text.MessageFormat */ String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException; /** * Try to resolve the message using all the attributes contained within the * {@code MessageSourceResolvable} argument that was passed in. * <p>NOTE: We must throw a {@code NoSuchMessageException} on this method * since at the time of calling this method we aren't able to determine if the * {@code defaultMessage} property of the resolvable is {@code null} or not. * @param resolvable the value object storing attributes required to resolve a message * (may include a default message) * @param locale the locale in which to do the lookup * @return the resolved message (never {@code null} since even a * {@code MessageSourceResolvable}-provided default message needs to be non-null) * @throws NoSuchMessageException if no corresponding message was found * (and no default message was provided by the {@code MessageSourceResolvable}) * @see MessageSourceResolvable#getCodes() * @see MessageSourceResolvable#getArguments() * @see MessageSourceResolvable#getDefaultMessage() * @see java.text.MessageFormat */ String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException; }
package com.isg.ifrend.wrapper.mli.request.customer; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="GetAddress") public class GetAddress { private String customerNumber; private String cardNumber; private String applicationNumber; public String getCustomerNumber() { return customerNumber; } public void setCustomerNumber(String customerNumber) { this.customerNumber = customerNumber; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public String getApplicationNumber() { return applicationNumber; } public void setApplicationNumber(String applicationNumber) { this.applicationNumber = applicationNumber; } }
/** * 湖北安式软件有限公司 * Hubei Anssy Software Co., Ltd. * FILENAME : HeadVo.java * PACKAGE : com.anssy.inter.base.vo * CREATE DATE : 2016-8-20 * AUTHOR : make it * MODIFIED BY : * DESCRIPTION : */ package com.anssy.inter.base.vo; /** * @author make it * @version SVN #V1# #2016-8-20# */ public class HeadVo { /** * 头像 */ private String headImage; public String getHeadImage() { return headImage; } public void setHeadImage(String headImage) { this.headImage = headImage; } }
package com.message; import oa.sys.*; import oa.data.*; import java.util.*; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; /** **************************************************** *类名称: Read<br> *类功能: 读站内信息<br> **************************************************** */ public class Read extends HttpServlet{ private int news; private int accepter; private int sender; private String time; private int messageid; private HttpSession session=null; private ResultSet rs=null; private Statement stmt=null; private String title,content,sqls; private int temp=0,id,count; public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{ request.setCharacterEncoding("gb2312"); response.setContentType("text/html; charset=gb2312"); Str str=new Str(); Db db=new Db(); Collection coll=new ArrayList(); PrintWriter out=response.getWriter(); session=request.getSession(); try{ id=Integer.parseInt(session.getAttribute("id").toString()); }catch(Exception e){ e.printStackTrace(); } try{ messageid=Integer.parseInt(request.getParameter("messageid").toString()); }catch(Exception e){ e.printStackTrace(); } sqls="SELECT * FROM message WHERE accepter="+id+" AND messageid ="+messageid; out.print(sqls); try { stmt=db.getStmtread(); rs=stmt.executeQuery(sqls); if(rs.next()){ messageid=rs.getInt(1); title=rs.getString(2); time=rs.getString(3); sender=rs.getInt(4); accepter=rs.getInt(5); content=rs.getString(6); news=rs.getInt(7); Message info=new Message(); info.setId(messageid); info.setTitle(title); info.setTime(time); info.setSender(sender); info.setAccepter(accepter); info.setContent(content); info.setNews(news); coll.add(info); rs.close(); stmt.close(); stmt=db.getStmt(); stmt.executeUpdate("UPDATE message SET new=1 WHERE messageid="+messageid); } request.setAttribute("msg",coll); } catch (SQLException e) { e.printStackTrace(); }finally{ db.close(); RequestDispatcher dispatcher=request.getRequestDispatcher("read.jsp"); dispatcher.forward(request,response); } } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{ doPost(request,response); } }
package br.com.zup.kafka.consumer.typetests; import br.com.zup.kafka.config.props.ConsumerProperties; import br.com.zup.kafka.config.props.OffsetReset; import br.com.zup.kafka.config.props.ProducerProperties; import br.com.zup.kafka.config.props.PropertyBuilder; import br.com.zup.kafka.consumer.ConsumerRunner; import br.com.zup.kafka.consumer.GenericConsumerHandler; import br.com.zup.kafka.consumer.TestConfigs; import br.com.zup.kafka.producer.KafkaProducer; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; public class ZupKafkaStringTest { private static final String TOPIC = "zup_kafka_string_topic"; private static final Logger LOGGER = LoggerFactory.getLogger(ZupKafkaStringTest.class); private static KafkaProducer<String, String> producer; private static ExecutorService consumerExecutorService; private static GenericConsumerHandler<String> stringConsumerHandler = new GenericConsumerHandler<>(); @BeforeClass public static void beforeClass() { ProducerProperties props = PropertyBuilder.producer(TestConfigs.KAFKA_BOOTSTRAP_SERVERS); producer = new KafkaProducer<>(props); ConsumerProperties<String, String> consumerProperties = PropertyBuilder .consumer(stringConsumerHandler) .withTopics(Collections.singletonList(TOPIC)) .withServers(TestConfigs.KAFKA_BOOTSTRAP_SERVERS) .withGroupId(TestConfigs.KAFKA_DEFAULT_GROUP_ID) .withDeserializerClass(String.class) .withAutoOffsetReset(OffsetReset.EARLIEST); consumerExecutorService = ConsumerRunner.execute(TestConfigs.KAFKA_DEFAULT_CONSUMER_POOL_SIZE, consumerProperties); } @AfterClass public static void afterClass() throws InterruptedException { producer.close(); consumerExecutorService.shutdown(); consumerExecutorService.awaitTermination(10, TimeUnit.SECONDS); } @Test public void stringTest() throws ExecutionException, InterruptedException { stringConsumerHandler.setCountDown(1); producer.send(TOPIC, "stringTestMsg").get(); Assert.assertEquals(stringConsumerHandler.await(), true); } }
package dev.nowalk.app; import dev.nowalk.models.Movie; import dev.nowalk.repositories.MovieRepo; import dev.nowalk.repositories.MovieRepoDBImpl; public class RepoDBTest { public static void main(String[] args) { MovieRepo mr = new MovieRepoDBImpl(); Movie m = mr.getMovie(4); //if we print out a movie that means that we have successfully used JDBC to get a movie from our database System.out.println(m); System.out.println(mr.getAllMovies()); Movie newMovie = new Movie("Guardians of the Galaxy: vol 1", 11, true, 0); newMovie = mr.addMovie(newMovie); System.out.println(newMovie); } }
package com.github.mistertea.html5animator.service; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.apache.thrift.TException; import com.github.mistertea.html5animator.rpc.NotAuthorizedException; import com.github.mistertea.html5animator.rpc.AnimatorRpc; import com.github.mistertea.html5animator.thrift.ClientErrorInfo; import com.github.mistertea.html5animator.thrift.Movie; import com.github.mistertea.html5animator.thrift.User; import com.github.mistertea.html5animator.thrift.UserData; import com.github.mistertea.html5animator.thrift.UserInternal; import com.github.mistertea.html5animator.thrift.UserSession; import com.github.mistertea.html5animator.thrift.coreConstants; public class AnimatorRpcImpl extends ServerRpcBase implements AnimatorRpc.Iface { private final static Logger logger = Logger.getLogger(AnimatorRpcImpl.class .getName()); private EmailSender emailSender; public AnimatorRpcImpl() { super(); emailSender = new EmailSender(); } @Override public User getMyself(String token) throws TException { UserSession userSession = getSession(token); if (userSession == null) { // System.out.println("User session " + token + " not found"); return new User(); } // System.out.println("User session found"); try { User player = databaseEngine.get(User.class, userSession.userId); return player; } catch (IOException e) { throw new TException(e); } } @Override public void logout(String token) throws NotAuthorizedException, TException { try { String id = getSession(token).userId; User user = databaseEngine.get(User.class, id); user.loggedIn = false; databaseEngine.upsert(user); databaseEngine.deleteFromId(UserSession.class, token); } catch (IOException e) { throw new TException(e); } } @Override public int ping() throws TException { return coreConstants.VERSION; } @Override public boolean changePassword(String token, String oldPassword, String newPassword) throws NotAuthorizedException, TException { String uid = getSession(token).userId; try { UserInternal pip = databaseEngine.get(UserInternal.class, uid); if (!pip.password.equals(oldPassword)) { return false; } pip.password = newPassword; databaseEngine.upsert(pip); } catch (IOException e) { throw new TException(e); } return false; } @Override public boolean changeUsername(String token, String newUsername) throws NotAuthorizedException, TException { try { User p = getSessionUser(token); if (!databaseEngine.secondaryGet(User.class, "name", newUsername) .isEmpty()) { return false; } p.name = newUsername; databaseEngine.upsert(p); return true; } catch (IOException e) { throw new TException(e); } } private static String sanitizeEmail(String email) { return email.toLowerCase(); } @Override public boolean emailPassword(String email) throws TException { email = sanitizeEmail(email); try { ArrayList<UserInternal> usersWithEmail; usersWithEmail = databaseEngine.secondaryGet(UserInternal.class, "emailAddress", email); if (usersWithEmail.size() > 1) { logger.severe("Somehow got too many users with email address " + email); throw new TException("Server email error"); } if (usersWithEmail.isEmpty()) { return false; } emailSender.sendEmailFromGmail(email, "Your password reminder", "Your password is: " + usersWithEmail.get(0).password); return true; } catch (IOException e) { throw new TException(e); } } @Override public String login(String token, String email, String password) throws TException { if (token == null) { throw new TException("No Token found."); } email = sanitizeEmail(email); ArrayList<UserInternal> usersWithEmail; try { usersWithEmail = databaseEngine.secondaryGet(UserInternal.class, "emailAddress", email); } catch (IOException e) { throw new TException(e); } if (usersWithEmail.size() > 1) { logger.severe("Somehow got too many users with email address " + email); throw new TException("Server email error"); } if (usersWithEmail.isEmpty()) { return "No user with email " + email + " found."; } if (!usersWithEmail.get(0).password.equals(password)) { return "Incorrect Password"; } // If we got here, authentication is complete try { AuthHandler.authComplete(databaseEngine, usersWithEmail.get(0).id, token, request.getRemoteAddr(), 0); } catch (IOException e) { throw new TException(e); } logger.info(usersWithEmail.get(0).id + " logged in using internal login"); return ""; } @Override public String createAccount(String token, String email, String name, String password) throws TException { // Sanitize the email email = sanitizeEmail(email); try { if (!databaseEngine.secondaryGet(UserInternal.class, "emailAddress", email).isEmpty()) { return "No user with email " + email + " found."; } User player = new User().setId(null).setName(name) .setIpAddress(request.getRemoteAddr()); databaseEngine.create(player); UserInternal pip = new UserInternal().setId(player.id) .setPassword(password).setEmailAddress(email); databaseEngine.createWithId(pip); databaseEngine.commit(); // If we got here, authentication is complete AuthHandler.authComplete(databaseEngine, player.id, token, request.getRemoteAddr(), 0); logger.info(player.id + " logged in using internal login"); return ""; } catch (IOException e) { throw new TException(e); } } @Override public UserData getMyData(String token) throws TException { UserSession userSession = getSession(token); if (userSession == null) { System.out.println("User session " + token + " not found"); return new UserData(); } try { UserData player = databaseEngine.get(UserData.class, userSession.userId); return player; } catch (IOException e) { throw new TException(e); } } @Override public boolean validateToken(String token) throws TException { return (getSession(token) != null); } @Override public void sendClientError(ClientErrorInfo errorInfo) throws TException { try { databaseEngine.create(errorInfo); } catch (IOException e) { // Don't throw or we could have an infinite loop of error reports. e.printStackTrace(); } } @Override public Movie loadMovie(String id) throws TException { try { return databaseEngine.get(Movie.class, id); } catch (IOException e) { throw new TException(e); } } @Override public void saveMovie(Movie movie) throws TException { try { databaseEngine.upsert(movie); } catch (IOException e) { throw new TException(e); } } }
package com.cqut.dto; import java.math.BigDecimal; public class UserProfitDTO { private String id; private String userId; private double shoppingBalance;//购物优惠余额 private double accoutBalance;//账s户余额 private double rechargeBalance;//充值余额 public String getId() { return id; } public String getUserId() { return userId; } public double getShoppingBalance() { return shoppingBalance; } public double getAccoutBalance() { return accoutBalance; } public double getRechargeBalance() { return rechargeBalance; } public void setId(String id) { this.id = id; } public void setUserId(String userId) { this.userId = userId; } public void setShoppingBalance(double shoppingBalance) { this.shoppingBalance = shoppingBalance; } public void setAccoutBalance(double newBalance) { this.accoutBalance = newBalance; } public void setRechargeBalance(double rechargeBalance) { this.rechargeBalance = rechargeBalance; } }
package com.cn.service; import com.cn.pojo.Orders; import java.util.List; public interface IOrderService { public List<Orders> findAll() throws Exception; public Orders findById(Integer id) throws Exception; public void deleteById(Integer id) throws Exception; public void addOrder(Orders orders) throws Exception; public Integer findAllMoney() throws Exception; public Integer findAllOrders() throws Exception; }
package edu.fudan.ml.types; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Map.Entry; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; import edu.fudan.util.exception.LoadModelException; public class Dictionary { private int MAX_LEN = 7; private int MIN_LEN = 2; /** * 字典 */ private TreeSet<String> dict = new TreeSet<String>(); private TreeMap<String, String[]> dictPOS = new TreeMap<String, String[]>(); private TreeMap<String, int[]> index = new TreeMap<String, int[]>(); private int indexLen = 2; private boolean isAmbiguity = false; TreeMap<String, TreeSet<String>> dp; public static ArrayList<String[]> format(ArrayList<String> al) { ArrayList<String[]> list = new ArrayList<String[]>(); for(String s: al) { list.add(new String[]{s}); } return list; } public Dictionary(){ MAX_LEN = Integer.MIN_VALUE; MIN_LEN = Integer.MAX_VALUE; dp = new TreeMap<String, TreeSet<String>>(); } /** * * @param b 是否模糊处理 */ public Dictionary(boolean b) { this(); this.setAmbiguity(b); } /** * * @param path * @throws IOException */ public Dictionary(String path) throws IOException { this(path,false); } /** * * @param path * @param b 使用模糊处理 * @throws IOException */ public Dictionary(String path, boolean b) throws IOException { this(); this.setAmbiguity(b); ArrayList<String[]> al = loadDict(path); addDict(al); indexLen = MIN_LEN; createIndex(); } /** * 加入不带词性的字典 * @param al */ public void addSegDict(ArrayList<String> al) { ArrayList<String[]> al1 = Dictionary.format(al); add(al1); } /** * * @param al 字典 ArrayList<String[]> * 每一个元素为一个单元String[]. * String[] 第一个元素为单词,后面为对应的词性 * @return */ public void add(ArrayList<String[]> al) { addDict(al); indexLen = MIN_LEN; createIndex(); } /** * 在目前词典中增加新的词典信息 * @param path * @throws FileNotFoundException */ public void addFile(String path) throws LoadModelException{ try { ArrayList<String[]> al = loadDict(path); addDict(al); indexLen = MIN_LEN; createIndex(); } catch (IOException e) { throw new LoadModelException("加载词典错误"+e.toString()); } } /** * 通过字典文件建立字典 * @param path * @return * @throws FileNotFoundException */ private ArrayList<String[]> loadDict(String path) throws IOException { Scanner scanner = new Scanner(new FileInputStream(path), "utf-8"); ArrayList<String[]> al = new ArrayList<String[]>(); while(scanner.hasNext()) { String line = scanner.nextLine().trim(); if(line.length() > 0) { String[] s = line.split("\\s"); al.add(s); } } scanner.close(); return al; } /** * 增加词典信息 * @param al */ private void addDict(ArrayList<String[]> al) { for(int i = 0; i < al.size(); i++) { String[] s = al.get(i); if(s[0].length() > MAX_LEN) MAX_LEN = s[0].length(); if(s[0].length() < MIN_LEN) MIN_LEN = s[0].length(); dict.add(s[0]); for(int j = 1; j < s.length; j++) { if(dp.containsKey(s[0]) == false) { TreeSet<String> set = new TreeSet<String>(); set.add(s[j]); dp.put(s[0], set); } else { dp.get(s[0]).add(s[j]); } } } if(dp.size() > 0) for(Entry<String, TreeSet<String>> entry: dp.entrySet()) { String key = entry.getKey(); TreeSet<String> set = entry.getValue(); String[] sa = new String[set.size()]; set.toArray(sa); dictPOS.put(key, sa); } // for(Entry<String, String[]> entry: dictPOS.entrySet()) { // String key = entry.getKey(); // String[] set = entry.getValue(); // System.out.print(key); // for(int i = 0; i < set.length; i++) // System.out.print("/" + set[i]); // System.out.println(); // } } private void createIndex() { // System.out.println("indexLen: " + indexLen); TreeMap<String, TreeSet<Integer>> indexT = new TreeMap<String, TreeSet<Integer>>(); for(String s: dict) { if(s.length() < indexLen) continue; String temp = s.substring(0, indexLen); //System.out.println(temp); if(indexT.containsKey(temp) == false) { TreeSet<Integer> set = new TreeSet<Integer>(); set.add(s.length()); indexT.put(temp, set); } else { indexT.get(temp).add(s.length()); } } for(Entry<String, TreeSet<Integer>> entry: indexT.entrySet()) { String key = entry.getKey(); TreeSet<Integer> set = entry.getValue(); int[] ia = new int[set.size()]; int i = set.size(); // System.out.println(key); for(Integer integer: set) { ia[--i] = integer; } // for(int j = 0; j < ia.length; j++) // System.out.println(ia[j]); index.put(key, ia); } // System.out.println(indexT); } public int getMaxLen() { return MAX_LEN; } public int getMinLen() { return MIN_LEN; } public boolean contains(String s) { return dict.contains(s); } public int[] getIndex(String s) { return index.get(s); } public String[] getPOS(String s) { return dictPOS.get(s); } public int getDictSize() { return dict.size(); } public int getIndexLen() { return indexLen; } public boolean isAmbiguity() { return isAmbiguity; } private void setAmbiguity(boolean isAmbiguity) { this.isAmbiguity = isAmbiguity; } public TreeSet<String> getDict() { return dict; } public TreeMap<String, String[]> getPOSDict() { return dictPOS; } public TreeMap<String, int[]> getIndex() { return index; } public int size(){ return dict.size(); } }
/* * Copyright 2002-2022 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.web.servlet.theme; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ThemeResolver; import org.springframework.web.servlet.support.RequestContextUtils; /** * Interceptor that allows for changing the current theme on every request, * via a configurable request parameter (default parameter name: "theme"). * * @author Juergen Hoeller * @since 20.06.2003 * @see org.springframework.web.servlet.ThemeResolver * @deprecated as of 6.0 in favor of using CSS, without direct replacement */ @Deprecated(since = "6.0") public class ThemeChangeInterceptor implements HandlerInterceptor { /** * Default name of the theme specification parameter: "theme". */ public static final String DEFAULT_PARAM_NAME = "theme"; private String paramName = DEFAULT_PARAM_NAME; /** * Set the name of the parameter that contains a theme specification * in a theme change request. Default is "theme". */ public void setParamName(String paramName) { this.paramName = paramName; } /** * Return the name of the parameter that contains a theme specification * in a theme change request. */ public String getParamName() { return this.paramName; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException { String newTheme = request.getParameter(this.paramName); if (newTheme != null) { ThemeResolver themeResolver = RequestContextUtils.getThemeResolver(request); if (themeResolver == null) { throw new IllegalStateException("No ThemeResolver found: not in a DispatcherServlet request?"); } themeResolver.setThemeName(request, response, newTheme); } // Proceed in any case. return true; } }
package fr.skytasul.quests.utils.compatibility; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.permission.Permission; public class Vault { private static Economy eco; private static Permission vperm = Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class).getProvider(); static { RegisteredServiceProvider<Economy> ecoReg = Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (ecoReg != null) eco = ecoReg.getProvider(); RegisteredServiceProvider<Permission> permReg = Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permReg != null) vperm = permReg.getProvider(); } public static Economy getEconomy(){ return eco; } public static Permission getVaultPermission(){ return vperm; } public static void depositPlayer(Player p, double money) { if (eco != null) eco.depositPlayer(p, money); } public static void withdrawPlayer(Player p, double money) { if (eco != null) eco.withdrawPlayer(p, money); } public static boolean has(Player p, double money) { if (eco == null) return false; return eco.has(p, money); } public static String format(double money) { if (eco == null) return "" + money; return eco.format(money); } public static void changePermission(Player p, String perm, boolean remove, String world) { //boolean has = vperm.playerHas(world, p, perm); if (remove) { /*if (has) */vperm.playerRemove(world, p, perm); }else /*if (!has)*/ vperm.playerAdd(world, p, perm); } public static void changeGroup(Player p, String group, boolean remove, String world) { //boolean has = vperm.playerInGroup(world, p, group); if (remove) { /*if (has) */vperm.playerRemoveGroup(world, p, group); }else /*if (!has)*/ vperm.playerAddGroup(world, p, group); } }
package com.geeknews.web; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class ReleaseViewController { @GetMapping("/newsview") public String Index(){ return "release-n"; } }
package com.hzero.order.app.service.impl; import com.hzero.order.app.service.SoLineService; import com.hzero.order.domain.entity.SoLine; import com.hzero.order.infra.mapper.SoLineMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 应用服务默认实现 **/ @Service public class SoLineServiceImpl implements SoLineService { @Autowired private SoLineMapper soLineMapper; @Override public List<SoLine> selectById(Long soHeaderId) { return soLineMapper.selectById(soHeaderId); } }
package com.icanit.app; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.json.JSONObject; import android.app.Application; import android.util.Log; import com.icanit.app.entity.CartItem; import com.icanit.app.exception.AppException; import com.icanit.app.service.DataService; import com.icanit.app.util.AppUtil; public class MapApplication extends Application { private Map<String,Object> map=new HashMap<String,Object>(); public Map<Integer,CartItem> shoppingCartMap; public Set<Integer> reservedProdIdSet; public List<CartItem> shoppingCartList; public void put(String key,Object value){ map.put(key,value); } public Object get(String key){ return map.get(key); } public void remove(String key){ map.remove(key); } @Override public void onCreate() { super.onCreate(); AppUtil.appContext=this; try { shoppingCartList=AppUtil.getServiceFactory().getShoppingCartDaoInstance(this). findAllItemsByPhone(AppUtil.getLoginPhoneNum()); shoppingCartMap=listToMap(shoppingCartList); reservedProdIdSet=new HashSet(shoppingCartMap.keySet()); Log.w("appInfo","shoppingCart="+shoppingCartMap+"\nprodIdSet="+reservedProdIdSet+" @MapApplication onCreate"); } catch (AppException e) { e.printStackTrace(); } } private Map<Integer,CartItem> listToMap(List<CartItem> items){ Map<Integer,CartItem> map = new HashMap<Integer,CartItem>(); CartItem item; for(int i=0;i<items.size();i++){ item = items.get(i); map.put(item.prod_id, item); } return map; } }
package serve.serveup.views.order; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import serve.serveup.R; import serve.serveup.dataholder.apistatus.ApiStatus; import serve.serveup.dataholder.apistatus.ApiStatusType; import serve.serveup.dataholder.order.Order; import serve.serveup.dataholder.session.Session; import serve.serveup.dataholder.session.SessionContent; import serve.serveup.utils.ContentStore; import serve.serveup.utils.Utils; import serve.serveup.webservices.RestManagement; public class ProcessingPaymentActivity extends AppCompatActivity { private ContentStore cntStore; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_processing_payment); cntStore = new ContentStore(getApplicationContext()); Order myOrder = createNewOrder(); Intent myIntent = getIntent(); if(myIntent != null) { String casPrevzema = myIntent.getStringExtra("payment_order_time"); myOrder.setCasPrevzema(casPrevzema); RestManagement.createNewOrderByUser(myOrder).enqueue(new Callback<ApiStatus>() { @Override public void onResponse(Call<ApiStatus> call, Response<ApiStatus> response) { ApiStatus myStatus = response.body(); if(myStatus.getStatus() == ApiStatusType.OK_STATUS.getStatus()) { Utils.logInfo("order created by user"); orderFinishedDelayAndClearBasketSession(); } else Utils.logInfo("error with creating new order :/"); } @Override public void onFailure(Call<ApiStatus> call, Throwable t) { Utils.logInfo("api 'orders/new_order/' failed"); } }); } } private Order createNewOrder() { Order newOrder = new Order(); Session currentSesh = cntStore.getSession(); newOrder.setCasNarocila(Utils.createDateTimeString()); if (currentSesh.mealsNotEmpty() && currentSesh.userIsSet() && currentSesh.restaurantIsSet()) { newOrder.setRestavracijaID(currentSesh.getCurrentRestaurant().getIdRestavracija()); newOrder.setUporabnikID(currentSesh.getCurrentUser()); newOrder.setMeals(currentSesh.getAllMeals()); } return newOrder; } public void orderFinishedDelayAndClearBasketSession() { Handler myHandler = new Handler(); myHandler.postDelayed(new Runnable() { @Override public void run() { Utils.showToast(getApplicationContext(), "Naročilo uspešno opravljeno"); cntStore.deleteFromSession(SessionContent.RESTUANRANT); cntStore.deleteFromSession(SessionContent.MEALS); finish(); }}, 4000); } }
package com.hhdb.csadmin.plugin.table_operate.handle; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.DefaultCellEditor; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import com.hh.frame.swingui.swingcontrol.displayTable.TablePanelUtil; import com.hh.frame.swingui.swingcontrol.displayTable.basis.BaseTable; import com.hhdb.csadmin.common.util.HHSqlUtil.ITEM_TYPE; import com.hhdb.csadmin.plugin.cmd.console.CommonsHelper; import com.hhdb.csadmin.plugin.table_operate.TableEditPanel; import com.hhdb.csadmin.plugin.table_operate.bean.TableForeignBean; import com.hhdb.csadmin.plugin.table_operate.component.ComboBoxCellEditor; import com.hhdb.csadmin.plugin.table_operate.component.CreateTableSQLSyntax; import com.hhdb.csadmin.plugin.table_operate.component.TextCellEditor; import com.hhdb.csadmin.plugin.table_operate.component.listcombox.MulitCellEditor; /** * * @Description: 表格外键 * @Copyright: Copyright (c) 2017年10月25日 * @Company:H2 Technology * @author zhipeng.zhang * @version 1.0 */ public class HandleForeignPanel extends JPanel implements TableModelListener, CreateTableSQLSyntax { private static final long serialVersionUID = 1L; private TableEditPanel tabp; private TablePanelUtil tablePanel; private HandleTablePanel tabPanel; private ComboBoxCellEditor ftable; private ComboBoxCellEditor deltable; private ComboBoxCellEditor updtable; private String[] values; private BaseTable baseTable; private Map<String, TableForeignBean> map = new HashMap<String, TableForeignBean>(); private static Map<String, String> mtype = new HashMap<String, String>(); private List<String> dels = new ArrayList<String>(); private JTextField zs; private int prerow = -1; private static List<String> lists = new ArrayList<String>(); static { lists.add("名"); lists.add("栏位"); lists.add("外键表"); lists.add("外键表栏位"); lists.add("删除时"); lists.add("更新时"); lists.add("oid"); lists.add("comment"); mtype.put("n", "SET NULL"); mtype.put("d", "SET DEFAULT"); mtype.put("r", "RESTRICT"); mtype.put("a", "NO ACTION"); mtype.put("c", "CASCADE"); } public HandleForeignPanel(TableEditPanel tableeditpanel,HandleTablePanel tabsPanel) throws Exception { this.tabp = tableeditpanel; this.tabPanel = tabsPanel; setBackground(Color.WHITE); tablePanel = new TablePanelUtil(true); tablePanel.setPreferredSize(new Dimension(680, 210)); tablePanel.setBackground(Color.WHITE); tablePanel.getViewport().setBackground(Color.WHITE); tablePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); baseTable = tablePanel.getBaseTable(); baseTable.setBackground(new Color(220, 255, 220)); editForeign(); setLayout(new GridBagLayout()); zs = new JTextField(); zs.setPreferredSize(new Dimension(300, 20)); inputSetup(false); add(tablePanel, new GridBagConstraints(0, 0, 2, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); add(new JLabel("注释:"), new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(50, 10, 0, 0), 0, 0)); add(zs, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(50, 10, 0, 0), 0, 0)); JPanel jpl = new JPanel(); jpl.setBackground(Color.WHITE); add(jpl, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); tablePanel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { tablePanel.requestFocus(); } }); baseTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { rowClicked(); } }); } /** * 初始化单元格控件 * * @throws Exception */ public void initCellEditor() throws Exception { TextCellEditor textcell = new TextCellEditor(); MulitCellEditor mulitcell = new MulitCellEditor(values); MulitCellEditor fcell = new MulitCellEditor(values); ftable = new ComboBoxCellEditor(); deltable = new ComboBoxCellEditor(); updtable = new ComboBoxCellEditor(); setComboBoxDefault(); tablePanel.getTableDataModel().addTableModelListener(this); tablePanel.getBaseTable().getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(textcell)); tablePanel.getBaseTable().getColumnModel().getColumn(1).setCellEditor(mulitcell); tablePanel.getBaseTable().getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(ftable)); tablePanel.getBaseTable().getColumnModel().getColumn(3).setCellEditor(fcell); tablePanel.getBaseTable().getColumnModel().getColumn(4).setCellEditor(new DefaultCellEditor(deltable)); tablePanel.getBaseTable().getColumnModel().getColumn(5).setCellEditor(new DefaultCellEditor(updtable)); setColumnWidth(new int[] { 1, 3 }); } /** * 设置表格列的宽度 * * @param column * @param table */ private void setColumnWidth(int[] column) { for (int i = 0; i < baseTable.getColumnCount(); i++) { TableColumn firsetColumn = baseTable.getColumnModel().getColumn(i); firsetColumn.setPreferredWidth(80); firsetColumn.setMaxWidth(200); if (i == column[0] || i == column[1]) { firsetColumn.setPreferredWidth(230); firsetColumn.setMaxWidth(230); } firsetColumn.setMinWidth(80); } hideColumn(new int[] { 6, 7 }); } /** * 隐藏列 * @param cols */ private void hideColumn(int[] cols) { for (int c : cols) { TableColumn coln = baseTable.getColumnModel().getColumn(c); coln.setMinWidth(0); coln.setMaxWidth(0); coln.setWidth(0); coln.setPreferredWidth(0); } } /** * combox赋值 将索引类型加载到comboBox * * @throws Exception */ private void setComboBoxDefault() throws Exception { List<Map<String, Object>> list = tabp.sqls.getListBySql(ITEM_TYPE.TABLE, "prop_coll", new String[] { "'"+tabp.getSchemaName()+"'" }); for (int i = 0; i < list.size(); i++) { ftable.addItem(list.get(i).get("name").toString()); } String[] combox = new String[] { "", "RESTRICT", "NO ACTION", "CASCADE", "SET NULL", "SET DEFAULT" }; for (String str : combox) { deltable.addItem(str); updtable.addItem(str); } } /** * 添加一行 */ public void addRows() { Object[] object = new Object[] { null, null, null, null, null, null }; tablePanel.getTableDataModel().addRow(object); } /** * 删除一行 */ public void delRow() { int row = baseTable.getSelectedRow(); int sum = baseTable.getRowCount(); if (row != -1) { int result = JOptionPane.showConfirmDialog(null, "是否删除当前行", "提示信息", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { if (baseTable.getValueAt(baseTable.getSelectedRow(), 6) != null) { dels.add(baseTable.getValueAt(baseTable.getSelectedRow(), 0).toString()); } //获取下一行的下面输入框的值填入,防止自动赋值时将已删除的赋予下行 if(row+1<sum){ //不能是最后一行 zs.setText((String) baseTable.getModel().getValueAt(row+1, 7)); }else{ zs.setText(""); } tablePanel.getTableDataModel().removeRow(row); } } } @Override public void tableChanged(TableModelEvent e) { int rows = tabPanel.getBaseTable().getRowCount(); try { if (baseTable.getSelectedRow() != -1) { if (baseTable.getValueAt(baseTable.getSelectedRow(), 2) != null && !"".equals(baseTable.getValueAt(baseTable.getSelectedRow(), 2))) { MulitCellEditor cell = (MulitCellEditor) baseTable.getCellEditor(0, 3); List<Map<String, Object>> lic = tabp.sqls.getListBySql(ITEM_TYPE.TABLE, "columnsbyname", new String[] { tabp.getSchemaName(), baseTable.getValueAt(baseTable.getSelectedRow(), 2).toString() }); String[] vals = new String[lic.size()]; for (int i = 0; i < lic.size(); i++) { Map<String, Object> m = lic.get(i); vals[i] = m.get("名称").toString(); } cell.getCellEditor().setData(vals); } } String columns = ""; for (int i = 0; i < rows; i++) { if (tabPanel.getBaseTable().getValueAt(i, 0) != null) { columns += tabPanel.getBaseTable().getValueAt(i, 0).toString() + ","; } } if (columns.length() > 0) { columns = columns.substring(0, columns.length() - 1); } MulitCellEditor cell = (MulitCellEditor) baseTable.getCellEditor(0, 1); cell.getCellEditor().setData(columns.split(",")); } catch (Exception ex) { System.out.println(ex.getMessage() + "此异常不处理"); } } /** * 取消表格编辑状态 */ public void cancleEdit() { int row = baseTable.getSelectedRow(); if (row != -1) { DefaultTableModel dtm = (DefaultTableModel) baseTable.getModel(); dtm.setValueAt(zs.getText(), row, 7); if (baseTable.isEditing()) { baseTable.getCellEditor().stopCellEditing(); } } } public void rowClicked() { tabp.getToolBar().getComponentAtIndex(0).setEnabled(tabp.controlButton = true); inputSetup(true); DefaultTableModel dtm = (DefaultTableModel) baseTable.getModel(); if (prerow != -1 && (prerow + 1) <= baseTable.getRowCount()) { dtm.setValueAt(zs.getText(), prerow, 7); } int row = baseTable.getSelectedRow(); if (row != -1) { String comment = (String) dtm.getValueAt(row, 7); zs.setText(comment); prerow = row; } } /** * 编辑外键 * * @throws Exception */ public void editForeign() throws Exception { int rowcount = baseTable.getRowCount(); for (int i = rowcount - 1; i >= 0; i--) { tablePanel.getTableDataModel().removeRow(i); } List<Map<String, Object>> lic = tabp.sqls.getListBySql(ITEM_TYPE.TABLE, "columnsinfo", new String[] { tabp.getTableoId() }); values = new String[lic.size()]; for (int i = 0; i < lic.size(); i++) { Map<String, Object> m = lic.get(i); values[i] = m.get("名称").toString(); } // 查询表的外键 List<Map<String, Object>> li = tabp.sqls.getListBySql(ITEM_TYPE.FOREIGN, "prop_coll", new String[] { tabp.getTableoId() }); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (int i = 0; i < li.size(); i++) { Map<String, Object> mp = new HashMap<String, Object>(); TableForeignBean bean = new TableForeignBean(); Map<String, Object> m = li.get(i); bean.setOid(m.get("oid").toString()); mp.put("oid", m.get("oid").toString()); bean.setForeignName(m.get("conname").toString()); mp.put("名", m.get("conname").toString()); String conkey = m.get("conkey").toString().replace("{", "").replace("}", "").replace("\"", ""); // 获取外键表字段 List<Map<String, Object>> ll = tabp.sqls.getListBySql(ITEM_TYPE.TABLE, "attname", new String[] { tabp.getTableoId(), conkey }); String foricol = ""; for (int j = 0; j < ll.size(); j++) { foricol += ll.get(j).get("attname").toString() + ","; } if (foricol.length() > 0) { foricol = foricol.substring(0, foricol.length() - 1); } bean.setRelcolumn(foricol); mp.put("栏位", foricol); bean.setForeign_table(m.get("foreign_table").toString()); mp.put("外键表", m.get("foreign_table").toString()); String columns = ""; Map<String, List<String>> ml = tabp.sqls.grouping(tabp.sqls.getConstraint(tabp.getTableName(),"FOREIGN KEY")); if(ml.size()>0){ for (String s : ml.get(m.get("foreign_table").toString())) { columns += s + ","; } } if (columns.length() > 0) { columns = columns.substring(0, columns.length() - 1); } bean.setForeign_column(columns); mp.put("外键表栏位", columns); bean.setDeltype(mtype.get(m.get("confdeltype").toString())); mp.put("删除时", mtype.get(m.get("confdeltype").toString())); bean.setUpdatetype(mtype.get(m.get("confupdtype").toString())); mp.put("更新时", mtype.get(m.get("confupdtype").toString())); if (m.get("comment") != null) { mp.put("comment", m.get("comment")); bean.setComment(m.get("comment").toString()); } else { mp.put("comment", m.get("comment")); bean.setComment(""); } map.put(bean.getOid(), bean); list.add(mp); } tablePanel.setData(lists, list); initCellEditor(); } /** * 组装编辑sql * * @return */ public String editForeignSql() { int rows = baseTable.getRowCount(); StringBuffer sqlBuffer = new StringBuffer(); StringBuffer comment = new StringBuffer(); if (dels.size() > 0) { for (String str : dels) { sqlBuffer.append(NEW_LINE).append(ALTER+" TABLE " ).append("\""+tabp.getSchemaName()+"\".\""+tabp.getTableName()+"\"").append(" DROP CONSTRAINT ").append(str.trim()); sqlBuffer.append(SEMI_COLON); } } for (int i = 0; i < rows; i++) { StringBuffer ldef = new StringBuffer(); if (baseTable.getValueAt(i, 6) != null) { //修改 TableForeignBean bean = map.get(baseTable.getValueAt(i, 6).toString()); if (!bean.getForeignName().equals(baseTable.getValueAt(i, 0)) || !bean.getRelcolumn().equals(baseTable.getValueAt(i, 1)) || !bean.getForeign_table().equals(baseTable.getValueAt(i, 2)) || !bean.getForeign_column().equals(baseTable.getValueAt(i, 3)) || !bean.getDeltype().equals(baseTable.getValueAt(i, 4)) || !bean.getUpdatetype().equals(baseTable.getValueAt(i, 5)) ) { sqlBuffer.append(NEW_LINE).append(ALTER_TABLE).append("\""+tabp.getSchemaName()+"\".\""+tabp.getTableName()+"\""); sqlBuffer.append(NEW_LINE).append(" DROP CONSTRAINT ").append(bean.getForeignName()).append(COMMA); sqlBuffer.append(NEW_LINE).append(ADD_CONSTRAINT).append(baseTable.getValueAt(i, 0)).append(" FOREIGN KEY "); sqlBuffer.append(B_OPEN).append(baseTable.getValueAt(i, 1)).append(B_CLOSE).append(REFERENCES); sqlBuffer.append("\""+tabp.getSchemaName()+"\"").append(DOT).append("\""+baseTable.getValueAt(i, 2)+"\"").append(B_OPEN).append(baseTable.getValueAt(i, 3)).append(B_CLOSE); if (baseTable.getValueAt(i, 4) != null && !"".equals(baseTable.getValueAt(i, 4))) { sqlBuffer.append(ON).append("DELETE ").append(baseTable.getValueAt(i, 4)); } if (baseTable.getValueAt(i, 5) != null && !"".equals(baseTable.getValueAt(i, 5))) { sqlBuffer.append(ON).append("UPDATE ").append(baseTable.getValueAt(i, 5)); } sqlBuffer.append(SEMI_COLON); ldef.append(NEW_LINE).append(" COMMENT ON CONSTRAINT ").append(baseTable.getValueAt(i, 0)); ldef.append(ON).append("\""+tabp.getSchemaName()+"\".\""+tabp.getTableName()+"\"").append(" IS ").append("'" + baseTable.getValueAt(i, 7) + "'").append(SEMI_COLON); } if (!bean.getComment().equals(CommonsHelper.nullOfStr(baseTable.getValueAt(i, 7))) && ldef.length() == 0) { ldef.append(NEW_LINE).append(" COMMENT ON CONSTRAINT ").append(baseTable.getValueAt(i, 0)); ldef.append(ON).append("\""+tabp.getSchemaName()+"\".\""+tabp.getTableName()+"\"").append(" IS ").append("'" + baseTable.getValueAt(i, 7) + "'").append(SEMI_COLON); } comment.append(ldef); } else { //添加 if (baseTable.getValueAt(i, 0) != null || "".equals(baseTable.getValueAt(i, 0))) { sqlBuffer.append(NEW_LINE).append(ALTER_TABLE).append("\""+tabp.getSchemaName()+"\".\""+tabp.getTableName()+"\""); sqlBuffer.append(NEW_LINE).append(ADD_CONSTRAINT).append(baseTable.getValueAt(i, 0)).append(" FOREIGN KEY "); sqlBuffer.append(B_OPEN).append(baseTable.getValueAt(i, 1)).append(B_CLOSE).append(REFERENCES); sqlBuffer.append("\""+tabp.getSchemaName()+"\"").append(DOT).append("\""+baseTable.getValueAt(i, 2)+"\"").append(B_OPEN).append(baseTable.getValueAt(i, 3)).append(B_CLOSE); if (baseTable.getValueAt(i, 4) != null && !"".equals(baseTable.getValueAt(i, 4))) { sqlBuffer.append(ON).append("DELETE ").append(baseTable.getValueAt(i, 4)); } if (baseTable.getValueAt(i, 5) != null && !"".equals(baseTable.getValueAt(i, 5))) { sqlBuffer.append(ON).append("UPDATE ").append(baseTable.getValueAt(i, 5)); } sqlBuffer.append(SEMI_COLON); if (!"".equals(CommonsHelper.nullOfStr(baseTable.getValueAt(i, 7)))) { comment.append(NEW_LINE).append(" COMMENT ON CONSTRAINT ").append(baseTable.getValueAt(i, 0)); comment.append(ON).append("\""+tabp.getSchemaName()+"\".\""+tabp.getTableName()+"\"").append(" IS ").append("'" + baseTable.getValueAt(i, 7) + "'").append(SEMI_COLON); } } } } sqlBuffer.append(comment); if(sqlBuffer.length()>0){ return sqlBuffer.append(NEW_LINE).toString(); }else{ sqlBuffer.setLength(0); return sqlBuffer.toString(); } } /** * 输入框设置 * @param bool */ public void inputSetup(Boolean bool){ if(bool){ zs.setBackground(new Color(220, 255, 220)); zs.setEditable(true); }else{ zs.setEditable(false); } } public BaseTable getBaseTable() { return baseTable; } public JTextField getZs() { return zs; } public void setZs(JTextField zs) { this.zs = zs; } public void setBaseTable(BaseTable baseTable) { this.baseTable = baseTable; } }
/* * @(#) MspoolService.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ims.mspool.service.impl; import java.util.List; import com.esum.appframework.exception.ApplicationException; import com.esum.appframework.service.impl.BaseService; import com.esum.wp.ims.mspool.Mspool; import com.esum.wp.ims.mspool.dao.IMspoolDAO; import com.esum.wp.ims.mspool.service.IMspoolService; /** * * @author heowon@esumtech.com * @version $Revision: 1.1 $ $Date: 2009/01/20 01:30:59 $ */ public class MspoolService extends BaseService implements IMspoolService { /** * Default constructor. Can be used in place of getInstance() */ public MspoolService () {} public Object removeMspoolList(Object object) { List list = (List) object; for (int i = 0; i < list.size(); i++) { Mspool mspool = (Mspool) (list.get(i)); super.delete(mspool); } return list; } public Object detail(Object object) { try { IMspoolDAO iMspoolDAO = (IMspoolDAO)iBaseDAO; return iMspoolDAO.detail(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object checkdetial(Object object) { try { IMspoolDAO iMspoolDAO = (IMspoolDAO)iBaseDAO; return iMspoolDAO.checkdetial(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } public Object selectPageList(Object object) { try { IMspoolDAO iMspoolDAO = (IMspoolDAO)iBaseDAO; return iMspoolDAO.selectPageList(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } }
package com.example.htw.currencyconverter.network; import com.example.htw.currencyconverter.model.Currency; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.Url; public interface FixerService { String API_FIXER_IO_URL = "http://data.fixer.io/api/"; @GET("latest?access_key=9a56b78f60c20614986266c8bce163f7") Call<Currency> getProjectList(); @GET("{data}?access_key=9a56b78f60c20614986266c8bce163f7") Call<Currency> getOldProjectList(@Path(value = "data", encoded = true) String data); }
package wawi.fachlogik.sachbearbeitersteuerung.impl; import wawi.fachlogik.componentcontroller.service.CompType; import wawi.fachlogik.componentcontroller.service.IActivateComponent; public class IActivateComponentImpl implements IActivateComponent { private boolean activated; @Override public CompType getComponentType() { return CompType.SACHBEARBEITER; } @Override public boolean activateComponent(int userid) { if(!isActivated()&&(userid==20)){ activated = true; return activated; } return false; } @Override public boolean deactivateComponent() { if(!isActivated()){ return false; } else{ activated = false; return true; } } @Override public boolean isActivated() { return activated; } }
package be.darkshark.parkshark.domain.entity.parkinglot; import be.darkshark.parkshark.domain.entity.Division; import be.darkshark.parkshark.domain.entity.person.Employee; import be.darkshark.parkshark.domain.entity.util.Address; import javax.persistence.*; @Entity @Table(name = "parkinglot") public class ParkingLot { @Id @SequenceGenerator(name = "parkinglot_seq", sequenceName = "parkinglot_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "parkinglot_seq") private long id; @Column(name = "name") private String name; @Enumerated @Column(name = "category") private ParkingCategory parkingCategory; @Column(name = "capacity") private int capacity; @ManyToOne(optional = false) @JoinColumn(name = "contact_person") private Employee contactPerson; @Embedded @Column(name = "address") private Address address; @Column(name = "price_per_hour") private double pricePerHour; @ManyToOne(optional = false) @JoinColumn(name = "division") private Division division; public ParkingLot(String name, ParkingCategory parkingCategory, int capacity, Employee contactPerson, Address address, double pricePerHour, Division division) { this.name = name; this.parkingCategory = parkingCategory; this.capacity = capacity; this.contactPerson = contactPerson; this.address = address; this.pricePerHour = pricePerHour; this.division = division; } public ParkingLot(long id, String name, ParkingCategory parkingCategory, int capacity, Employee contactPerson, Address address, double pricePerHour, Division division) { this.id = id; this.name = name; this.parkingCategory = parkingCategory; this.capacity = capacity; this.contactPerson = contactPerson; this.address = address; this.pricePerHour = pricePerHour; this.division = division; } public ParkingLot() { } public long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ParkingCategory getParkingCategory() { return parkingCategory; } public void setParkingCategory(ParkingCategory parkingCategory) { this.parkingCategory = parkingCategory; } public int getCapacity() { return capacity; } public void setCapacity(int capacity) { this.capacity = capacity; } public Employee getContactPerson() { return contactPerson; } public void setContactPerson(Employee contactPerson) { this.contactPerson = contactPerson; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public double getPricePerHour() { return pricePerHour; } public void setPricePerHour(double pricePerHour) { this.pricePerHour = pricePerHour; } public Division getDivision() { return division; } public void setDivision(Division division) { this.division = division; } }
package ioconvert.products; import java.io.BufferedOutputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.List; public class ProductWriter { public void saveProduct(OutputStream fileStream, List<Product> products) { if (fileStream == null) { throw new IllegalArgumentException("File stream can't be null"); } if (products == null) { throw new IllegalArgumentException("Products can't be null"); } try (PrintStream stream = new PrintStream(new BufferedOutputStream(fileStream))) { for (Product item : products) { stream.println(item); } } } }
package com.cognixia.jump.djk.firstjavaproject.menus; import com.cognixia.jump.djk.firstjavaproject.data.Company; import com.cognixia.jump.djk.firstjavaproject.data.Department; import com.cognixia.jump.djk.firstjavaproject.data.RecordWithId; import com.cognixia.jump.djk.firstjavaproject.display.RecordReporter; import com.cognixia.jump.djk.firstjavaproject.inputs.AnythingInput; import com.cognixia.jump.djk.firstjavaproject.inputs.DepartmentAdder; import com.cognixia.jump.djk.firstjavaproject.inputs.RecordSelector; abstract class DepartmentsMenu { static MenuOption[] options = { new MenuOption("Add New Department", () -> { new DepartmentAdder().run(); }), new MenuOption("List All Departments", () -> { RecordReporter.departments.printEntities(Company.getDepartments()); new AnythingInput(DepartmentsMenu::run).run(); }), new MenuOption("View/Edit Single Department", () -> { new RecordSelector( "department", DepartmentsMenu::run, (RecordWithId selectedEntity) -> { Department selectedDepartment = (Department) selectedEntity; SingleDepartmentMenu.run(selectedDepartment); }, "Select a Department", "Enter the id of a department to select it." ).selectFrom(Company.getDepartments()); }), new MenuOption("Main Menu", Menus::main) }; static void run() { new Menu(options, "Departments Menu").run(); } }
package org.tudresden.ecatering.model.kitchen; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToOne; import org.javamoney.moneta.Money; import org.salespointframework.catalog.Product; import org.salespointframework.quantity.Metric; @Entity public class MenuItem extends Product { private static final long serialVersionUID = -3839280035059479617L; @OneToOne(fetch=FetchType.EAGER,cascade=CascadeType.DETACH) private Meal meal; private Helping helping; private Day day; @SuppressWarnings({ "unused", "deprecation" }) private MenuItem() {} protected MenuItem(Meal meal, Money price, Helping helping,Day day) { super(meal.getName(),price,Metric.UNIT); this.meal = meal; this.helping = helping; this.day = day; } /** * returns the Meal * @return Meal */ public Meal getMeal() { return meal; } /** * returns the Day * @return Day */ public Day getDay() { return day; } /** * returns the Helping * @return Helping */ public Helping getHelping() { return helping; } }
package com.adwork.microservices.users; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) //@DataJpaTest public class UserServiceTest { //@Autowired //private IUserService service; @Test public void add_user_test() { } /* @Test public void it_can_find_the_contact_after_save_it() { Contact contact = new Contact("Mary", "Zheng", "test@test.com", PhoneType.HOME, "6365272943"); Contact_Note note = new Contact_Note(); note.setMessage("She is a java geek"); contact.addNote(note); contactRepo.save(contact); List contacts = contactRepo.findAll(); assertEquals(1, contacts.size()); assertEquals("Mary", contacts.get(0).getFirstName()); assertEquals("Zheng", contacts.get(0).getLastName()); assertEquals("test@test.com", contacts.get(0).getEmail()); assertEquals(PhoneType.HOME, contacts.get(0).getPhoneType()); assertEquals("6365272943", contacts.get(0).getPhoneNumber()); assertEquals(1, contacts.get(0).getNotes().size()); assertEquals("She is a java geek", contacts.get(0).getNotes().get(0).getMessage()); } @Test public void it_can_delete_the_contact_after_save_it() { Contact contact = new Contact("Mary", "Zheng", "test@test.com", PhoneType.HOME, "6365272943"); Contact_Note note = new Contact_Note(); note.setMessage("She is a java geek"); contact.addNote(note); contactRepo.save(contact); List foundContacts = contactRepo.findAll(); contactRepo.delete(foundContacts.get(0)); List contacts = contactRepo.findAll(); assertEquals(0, contacts.size()); } @Test public void it_can_update_the_contact_after_save_it() { Contact contact = new Contact("Mary", "Zheng", "test@test.com", PhoneType.HOME, "6365272943"); contactRepo.save(contact); contact.setEmail("mary.zheng@test.com"); contactRepo.save(contact); List contacts = contactRepo.findAll(); assertEquals(1, contacts.size()); assertEquals("mary.zheng@test.com", contacts.get(0).getEmail()); } @Test public void it_can_find_contacts_by_name_and_type() { contactRepo.save(new Contact("Mary", "Zheng", "mary.zheng@jcg.org", PhoneType.HOME, "6368168164")); contactRepo.save(new Contact("Tom", "Smith", "tom.smith@jcg.org", PhoneType.MOBILE, "(636) 527-2943")); contactRepo.save(new Contact("John", "Joe", "john.joe@jcg.org", PhoneType.OFFICE, "(314) 527 2943")); contactRepo.save(new Contact("Cindy", "Chang", "cindy.change@jcg.org", PhoneType.OTHER, "404-789-1456")); List contactsWithZheng = contactRepo.findByLastNameAndPhoneType(PhoneType.HOME, "Zheng"); assertEquals(1, contactsWithZheng.size()); Contact foundContact = contactsWithZheng.get(0); assertEquals("Mary", foundContact.getFirstName()); assertEquals("Zheng", foundContact.getLastName()); assertEquals("mary.zheng@jcg.org", foundContact.getEmail()); assertEquals(PhoneType.HOME, foundContact.getPhoneType()); assertEquals("6368168164", foundContact.getPhoneNumber()); assertEquals(0, foundContact.getNotes().size()); } @Test public void it_return_null_when_not_found(){ Contact found = contactRepo.findOne(2L); assertNull(found); } */ }
package com.pansoft.xbrl.cloud; /** * @program: xbrl-cloud-config * @description: apollo的客户端sample * @author: <a href="mailto:xuran@pansoft.com">tEngSHe789</a> * @create: 2019-01-15 14:39 **/ public class ApolloSBootstrap { }
/* * 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 Vista; /** * * @author Percy */ public class FrmVerPerfil extends javax.swing.JFrame { /** * Creates new form FrmAgregarPerfil */ public FrmVerPerfil() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767)); bgGenero = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); txtapellidos = new javax.swing.JTextField(); txtnombre = new javax.swing.JTextField(); txtfechanac = new javax.swing.JTextField(); txtdni = new javax.swing.JTextField(); txttelefono = new javax.swing.JTextField(); txtdireccion = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); rbMasculino = new javax.swing.JRadioButton(); rbFemenino = new javax.swing.JRadioButton(); btnAgregar = new javax.swing.JButton(); btnActualizar = new javax.swing.JButton(); btnCancelar = new javax.swing.JButton(); jLabel10 = new javax.swing.JLabel(); txtcodigo = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); imgPerfil = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(17, 106, 59)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Informacion de Perfil"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Nombre"); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel4.setText("Apellidos"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel5.setText("DNI"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel6.setText("Telefono"); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 255, 255)); jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel7.setText("Direccion"); jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel8.setForeground(new java.awt.Color(255, 255, 255)); jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel8.setText("Fecha Nac"); txtapellidos.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtapellidosActionPerformed(evt); } }); txtnombre.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtnombreActionPerformed(evt); } }); txtfechanac.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtfechanacActionPerformed(evt); } }); txtdni.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtdniActionPerformed(evt); } }); txttelefono.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txttelefonoActionPerformed(evt); } }); txtdireccion.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtdireccionActionPerformed(evt); } }); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel9.setForeground(new java.awt.Color(255, 255, 255)); jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel9.setText("Genero"); bgGenero.add(rbMasculino); rbMasculino.setSelected(true); rbMasculino.setText("Masculino"); rbMasculino.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rbMasculinoActionPerformed(evt); } }); bgGenero.add(rbFemenino); rbFemenino.setText("Femenino"); rbFemenino.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rbFemeninoActionPerformed(evt); } }); btnAgregar.setText("Agregar"); btnAgregar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAgregarActionPerformed(evt); } }); btnActualizar.setText("Actualizar"); btnActualizar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnActualizarActionPerformed(evt); } }); btnCancelar.setText("Cancelar"); btnCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelarActionPerformed(evt); } }); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel10.setForeground(new java.awt.Color(255, 255, 255)); jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel10.setText("Codigo"); txtcodigo.setEditable(false); txtcodigo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtcodigoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(0, 39, Short.MAX_VALUE) .addComponent(imgPerfil, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(imgPerfil, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(rbMasculino) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(rbFemenino)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txttelefono, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtdireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtapellidos, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtfechanac, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtdni, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtnombre, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(113, 113, 113) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(60, 60, 60)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(110, 110, 110) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 539, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(82, 82, 82) .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(60, 60, 60) .addComponent(btnActualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(60, 60, 60) .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(60, 60, 60)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(7, 7, 7) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 5, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(20, 20, 20) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtnombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(33, 33, 33) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtapellidos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtdni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtfechanac, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtdireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txttelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(rbMasculino) .addComponent(rbFemenino))) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(57, 57, 57) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnActualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(60, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtapellidosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtapellidosActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtapellidosActionPerformed private void txtnombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtnombreActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtnombreActionPerformed private void txtfechanacActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtfechanacActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtfechanacActionPerformed private void txtdniActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtdniActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtdniActionPerformed private void txttelefonoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txttelefonoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txttelefonoActionPerformed private void txtdireccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtdireccionActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtdireccionActionPerformed private void rbFemeninoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbFemeninoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_rbFemeninoActionPerformed private void btnActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btnActualizarActionPerformed private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btnCancelarActionPerformed private void txtcodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtcodigoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtcodigoActionPerformed private void rbMasculinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbMasculinoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_rbMasculinoActionPerformed private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btnAgregarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FrmVerPerfil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FrmVerPerfil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FrmVerPerfil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FrmVerPerfil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FrmVerPerfil().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables public javax.swing.ButtonGroup bgGenero; public javax.swing.JButton btnActualizar; public javax.swing.JButton btnAgregar; public javax.swing.JButton btnCancelar; private javax.swing.Box.Filler filler1; public javax.swing.JLabel imgPerfil; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; public javax.swing.JRadioButton rbFemenino; public javax.swing.JRadioButton rbMasculino; public javax.swing.JTextField txtapellidos; public javax.swing.JTextField txtcodigo; public javax.swing.JTextField txtdireccion; public javax.swing.JTextField txtdni; public javax.swing.JTextField txtfechanac; public javax.swing.JTextField txtnombre; public javax.swing.JTextField txttelefono; // End of variables declaration//GEN-END:variables }
package com.kedeng.yangmuyi.dao; import java.util.List; import com.kedeng.yangmuyi.exception.SystemException; /** * * @ClassName: BaseDAO * @Description: Base DAO include all operation in Database. * @author rqian * @date Aug 8, 2013 2:38:00 PM * */ public interface BaseDAO { public Object loadById(Class<?> clazz, String id) throws SystemException; public Object loadObject(String hql); public boolean delById(Class<?> clazz, String id) throws SystemException; public boolean save(Object obj) throws SystemException; public List<?> listAll(String clazz) throws SystemException; public List<?> listAll(String clazz, int pageNo, int pageSize) throws SystemException; public int countAll(String clazz); public List<?> query(String hql); public List<?> query(String hql, int pageNo, int pageSize); public int countQuery(String hql); public int update(String hql); public boolean update(Object obj) throws SystemException; public int getNewestVersion(Class<?> clazz, String id) throws SystemException; }
package Movement; import Utilities.*; public interface Movement { public Coordinates move(double xLoc, double yLoc, double Vel); }
package bankaccount; /** * * @author desir */ public class CheckingAccountDemo { public static void main(String[] args) { CheckingAccount ktd = new CheckingAccount("20120", "Kamo Tsepo Desire"); ktd.deposit(500); ktd.withdraw(200); ktd.deposit(700); ktd.deductFees(); System.out.println("transactions <= 3: " + ktd.getBalance()); ktd.deposit(200); ktd.deductFees(); System.out.println("transactions > 3: " + ktd.getBalance()); } }
package mc.kurunegala.bop.model; import java.util.Date; public class BOP { private Integer idbop; private Integer customerIdcustomer; private Date bopApplayDate; private String bopPlanNo; private String bopUrveyorsName; private String bopNo; private String bopIsMarkonground; private String bopOwnership; private Double bopTotalPrice; private Integer bopCompleteStatus; public Integer getIdbop() { return idbop; } public void setIdbop(Integer idbop) { this.idbop = idbop; } public Integer getCustomerIdcustomer() { return customerIdcustomer; } public void setCustomerIdcustomer(Integer customerIdcustomer) { this.customerIdcustomer = customerIdcustomer; } public Date getBopApplayDate() { return bopApplayDate; } public void setBopApplayDate(Date bopApplayDate) { this.bopApplayDate = bopApplayDate; } public String getBopPlanNo() { return bopPlanNo; } public void setBopPlanNo(String bopPlanNo) { this.bopPlanNo = bopPlanNo == null ? null : bopPlanNo.trim(); } public String getBopUrveyorsName() { return bopUrveyorsName; } public void setBopUrveyorsName(String bopUrveyorsName) { this.bopUrveyorsName = bopUrveyorsName == null ? null : bopUrveyorsName.trim(); } public String getBopNo() { return bopNo; } public void setBopNo(String bopNo) { this.bopNo = bopNo == null ? null : bopNo.trim(); } public String getBopIsMarkonground() { return bopIsMarkonground; } public void setBopIsMarkonground(String bopIsMarkonground) { this.bopIsMarkonground = bopIsMarkonground == null ? null : bopIsMarkonground.trim(); } public String getBopOwnership() { return bopOwnership; } public void setBopOwnership(String bopOwnership) { this.bopOwnership = bopOwnership == null ? null : bopOwnership.trim(); } public Double getBopTotalPrice() { return bopTotalPrice; } public void setBopTotalPrice(Double bopTotalPrice) { this.bopTotalPrice = bopTotalPrice; } public Integer getBopCompleteStatus() { return bopCompleteStatus; } public void setBopCompleteStatus(Integer bopCompleteStatus) { this.bopCompleteStatus = bopCompleteStatus; } }
package com.mabang.sys.entity.vo; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.mabang.sys.entity.base.ApiVOBase; import com.mabang.sys.entity.po.Billboard; import com.mabang.sys.entity.po.Billboard.BillboardStatus; /** * 广告位信息 * * @author xiong * */ @SuppressWarnings("serial") public class BillboardInfo extends ApiVOBase { private Integer id; private String uniqueCode; // 唯一码 private String manageCode; // 管理码 private String shortName; // 名称 private String longAddress; // 地址全称 private String shedMaterial; // 雨棚材质 private String statusText; // 状态 private String statusDesc; // 状态描述 private String spec; // 规格 private String otherDescribe; // 其它描述 private Integer provinceId; // 省份ID private Integer cityId; // 城市ID private Integer areaId; // 区域ID private Integer streetId; // 街道ID private String address; // 详细地址 private Double locationLng; // 经度 private Double locationLat; // 纬度 private List<BillboardImageInfo> advertisingImageList; // 广告位图 private List<BillboardImageInfo> acceptanceImageList; // 验收图 private boolean available; // 是否可用、可被预约 private AliyunInfo aliyunInfo; // 阿里云配置文件 private int advanceType; // 预约类型, 1:可预约的 2:我预约的 private int status; // 状态:1为启用、非1为禁用 public BillboardInfo() { return; } public BillboardInfo(Billboard billboard) { this.id = billboard.getId(); this.uniqueCode = billboard.getUniqueCode() != null ? billboard.getUniqueCode() : ""; this.manageCode = billboard.getManageCode() != null ? billboard.getManageCode() : ""; this.shortName = billboard.getShortName() != null ? billboard.getShortName() : ""; if (StringUtils.isEmpty(this.shortName) && !StringUtils.isEmpty(billboard.getStreetName())) { this.shortName = billboard.getStreetName(); } this.longAddress = billboard.getLongAddress() != null ? billboard.getLongAddress() : ""; this.shedMaterial = billboard.getShedMaterial() != null ? billboard.getShedMaterial() : ""; this.statusText = billboard.getBillboardStatus() != null ? billboard.getBillboardStatus().getText() : ""; this.statusDesc = billboard.getStatusDesc() != null ? billboard.getStatusDesc() : ""; this.spec = billboard.getSpec() != null ? billboard.getSpec() : ""; this.otherDescribe = billboard.getOtherDescribe() != null ? billboard.getOtherDescribe() : ""; this.areaId = billboard.getZoneId(); this.locationLng = billboard.getLocationLng(); this.locationLat = billboard.getLocationLat(); if (billboard.getBillboardStatus() == null || BillboardStatus.IDLE.equals(billboard.getBillboardStatus())) this.available = true; return; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; return; } public String getUniqueCode() { return this.uniqueCode; } public void setUniqueCode(String uniqueCode) { this.uniqueCode = uniqueCode; return; } public String getManageCode() { return this.manageCode; } public void setManageCode(String manageCode) { this.manageCode = manageCode; return; } public String getShortName() { return this.shortName; } public void setShortName(String shortName) { this.shortName = shortName; return; } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; return; } public String getLongAddress() { return this.longAddress; } public void setLongAddress(String longAddress) { this.longAddress = longAddress; return; } public String getShedMaterial() { return this.shedMaterial; } public void setShedMaterial(String shedMaterial) { this.shedMaterial = shedMaterial; return; } public String getStatusText() { return this.statusText; } public void setStatusText(String statusText) { this.statusText = statusText; return; } public String getStatusDesc() { return this.statusDesc; } public void setStatusDesc(String statusDesc) { this.statusDesc = statusDesc; return; } public String getSpec() { return this.spec; } public void setSpec(String spec) { this.spec = spec; return; } public String getOtherDescribe() { return this.otherDescribe; } public void setOtherDescribe(String otherDescribe) { this.otherDescribe = otherDescribe; return; } public Integer getProvinceId() { return this.provinceId; } public void setProvinceId(Integer provinceId) { this.provinceId = provinceId; return; } public Integer getCityId() { return this.cityId; } public void setCityId(Integer cityId) { this.cityId = cityId; return; } public Integer getStreetId() { return this.streetId; } public void setStreetId(Integer streetId) { this.streetId = streetId; return; } public Integer getAreaId() { return this.areaId; } public void setAreaId(Integer areaId) { this.areaId = areaId; return; } public Double getLocationLng() { return this.locationLng; } public void setLocationLng(Double locationLng) { this.locationLng = locationLng; return; } public Double getLocationLat() { return this.locationLat; } public void setLocationLat(Double locationLat) { this.locationLat = locationLat; return; } public List<BillboardImageInfo> getAdvertisingImageList() { return this.advertisingImageList; } public void setAdvertisingImageList(List<BillboardImageInfo> advertisingImageList) { this.advertisingImageList = advertisingImageList; return; } public List<BillboardImageInfo> getAcceptanceImageList() { return this.acceptanceImageList; } public void setAcceptanceImageList(List<BillboardImageInfo> acceptanceImageList) { this.acceptanceImageList = acceptanceImageList; return; } public boolean isAvailable() { return this.available; } public void setAvailable(boolean available) { this.available = available; return; } public AliyunInfo getAliyunInfo() { return this.aliyunInfo; } public void setAliyunInfo(AliyunInfo aliyunInfo) { this.aliyunInfo = aliyunInfo; return; } public int getAdvanceType() { return this.advanceType; } public void setAdvanceType(int advanceType) { this.advanceType = advanceType; return; } public int getStatus() { return this.status; } public void setStatus(int status) { this.status = status; return; } }
package Section_3_Functions_and_1D_Array; import java.util.Scanner; public class Two { public static void main(String[] args) { Scanner scn = new Scanner(System.in); System.out.print("Enter the decimal number: "); int n = scn.nextInt(); System.out.print("Enter the destination base: "); int b = scn.nextInt(); System.out.print("Decimal Number: "+decimalToAnyBase(n,b)); } private static int decimalToAnyBase(int n,int b){ int rem=0; int num=0,i=0; while(n%b!=0){ rem=n%b; n/=b; num+=rem*Math.pow(10,i); i++; } return num; } }
package com.redsun.platf.util.convertor; /** * <p>Title : com.webapp </p> * <p>Description : </p> * <p>Copyright : Copyright (c) 2010</p> * <p>Company : FreedomSoft </p> * */ /** * @author Dick Pan * @version 1.0 * @since 1.0 * <p><H3>Change history</H3></p> * <p>2010/10/28 : Created </p> * */ /** * 字符串格式接口,用于将某个数据类型转化为指定的字符串格式用以显示和输出。 * @author CHEN Qiang * * @param <T> 要处理的数据类型 */ public interface Stringfier<S> extends Convertor<S, String>{ /** * 根据指定数据类型的实例得到表示字符串 * @param t 实例 * @return 字符串 */ public String convert(S s); }
package us.gibb.dev.gwt.demo.client.command; import us.gibb.dev.gwt.command.Command; import us.gibb.dev.gwt.command.results.StringResult; public class SayHelloCommand implements Command<StringResult> { private static final long serialVersionUID = 6440864902721536666L; private String name; SayHelloCommand() { } public SayHelloCommand(String name) { this.name = name; } public String getName() { return name; } }
package tutorial.basics.selenium.webdriver.test; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class MyFirstTest { @Test public void startWebDriver(){ WebDriver driver = null; //driver = new FirefoxDriver(); System.setProperty("webdriver.chrome.driver", "D:\\devtools\\chromedriver\\chromedriver.exe"); driver = new ChromeDriver(); driver.get("http://www.google.com"); driver.navigate().to("https://plus.google.com/"); Assert.assertTrue("Site title should start with Google+",driver.getTitle().startsWith("Google+")); driver.close(); driver.quit(); } }
package com.shady.nanogerdree.inventoryappstage1.database; import android.database.sqlite.SQLiteDatabase; /** * Created by Shady on 3/26/2018. */ public class InventoryTable { public static final String TABLE_INVENTORY = "inventory"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_PRODUCT_NAME = "productName"; public static final String COLUMN_PRICE = "price"; public static final String COLUMN_QUANTITY = "quantity"; public static final String COLUMN_SUPPLIER_NAME = "supplierName"; public static final String COLUMN_SUPPLIER_PHONE_NUMBER = "supplierPhoneNumber"; private static final String DATABASE_CREATE = "create table " + TABLE_INVENTORY + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_PRODUCT_NAME + " text not null, " + COLUMN_PRICE + " integer not null," + COLUMN_QUANTITY + " integer not null," + COLUMN_SUPPLIER_NAME + " text not null," + COLUMN_SUPPLIER_PHONE_NUMBER + " text not null" + ");"; public static void onCreate(SQLiteDatabase database) { database.execSQL(DATABASE_CREATE); } public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { database.execSQL("DROP TABLE IF EXISTS " + TABLE_INVENTORY); onCreate(database); } }
package com.vignettTaskExeptions; public class InvalidTankstationException extends Exception { @Override public String getMessage() { String text = "Invalid data for tank station!"; return text; } }
package facade; import dataMapper.OrderMapper; import domain.Order; import domain.OrderAssembler; import domain.OrderDTO; /** * a class for remote invoke */ public class OrderServiceBean { public OrderDTO getOrder(long id) { Order br = new Order(); br.setOrderId(id);; return new OrderAssembler().writeDTO( new OrderMapper().findOrderByOrderId(br).get(0)); } public String getBookedRoomString(int id) { return getOrder(id).toString(); } }
import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; public class Veterinarians_List { WebDriver driver; public Veterinarians_List(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); // This initElements method will create all WebElements } @FindBy(css ="body > div > div > h2") WebElement Vet_label ; @FindBy(id="vets") WebElement Vet_tbl ; public int verify_vet_info(String name,String specialities) { Assert.assertEquals("Name Specialties",Vet_tbl.findElement(By.xpath("//*[@id=\"vets\"]/thead")).getText()); List<WebElement> rows = Vet_tbl.findElements(By.xpath("//*[@id=\"vets\"]/tbody/tr")); for(int i=1;i<=rows.size();i++) { if(name.equals(Vet_tbl.findElement(By.xpath("//*[@id=\"vets\"]/tbody/tr["+i+"]/td[1]")).getText()) && specialities.equals(Vet_tbl.findElement(By.xpath("//*[@id=\"vets\"]/tbody/tr["+i+"]/td[2]")).getText())) { return 1; } } return 0; } }
/* $Id$ */ package djudge.dservice.interfaces; public interface DServiceCommonJudgeInterface { public boolean setTaskResult(int taskID, String judgement, String xmlData); }
package com.nisira.core.dao; import com.nisira.core.entity.*; import java.util.List; import android.database.sqlite.SQLiteDatabase; import com.nisira.core.database.DataBaseClass; import android.content.ContentValues; import android.database.Cursor; import com.nisira.core.util.ClaveMovil; import java.util.ArrayList; import java.util.LinkedList; import java.text.SimpleDateFormat; import java.util.Date; public class ContactosclieprovDao extends BaseDao<Contactosclieprov> { public ContactosclieprovDao() { super(Contactosclieprov.class); } public ContactosclieprovDao(boolean usaCnBase) throws Exception { super(Contactosclieprov.class, usaCnBase); } public Boolean insert(Contactosclieprov contactosclieprov) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ContentValues initialValues = new ContentValues(); initialValues.put("IDEMPRESA",contactosclieprov.getIdempresa()); initialValues.put("IDCLIEPROV",contactosclieprov.getIdclieprov()); initialValues.put("ITEM",contactosclieprov.getItem()); initialValues.put("NOMBRE",contactosclieprov.getNombre()); initialValues.put("DIRECCION",contactosclieprov.getDireccion()); initialValues.put("TELEFONO1",contactosclieprov.getTelefono1()); initialValues.put("TELEFONO2",contactosclieprov.getTelefono2()); initialValues.put("TELEFONO3",contactosclieprov.getTelefono3()); initialValues.put("EMAIL",contactosclieprov.getEmail()); initialValues.put("PREDETERMINADO",contactosclieprov.getPredeterminado()); initialValues.put("ESTADO",contactosclieprov.getEstado()); initialValues.put("SINCRONIZA",contactosclieprov.getSincroniza()); initialValues.put("FECHACREACION",dateFormat.format(contactosclieprov.getFechacreacion() ) ); initialValues.put("IDCARGO",contactosclieprov.getIdcargo()); initialValues.put("DNI",contactosclieprov.getDni()); initialValues.put("APELLIDOPATERNO",contactosclieprov.getApellidopaterno()); initialValues.put("APELLIDOMATERNO",contactosclieprov.getApellidomaterno()); initialValues.put("SEXO",contactosclieprov.getSexo()); initialValues.put("FECHA_NACIMIENTO",dateFormat.format(contactosclieprov.getFecha_nacimiento() ) ); initialValues.put("DIRECCION_NUMERO",contactosclieprov.getDireccion_numero()); initialValues.put("IDUBIGEO",contactosclieprov.getIdubigeo()); initialValues.put("IDESTADOCIVIL",contactosclieprov.getIdestadocivil()); initialValues.put("TELEFONO4",contactosclieprov.getTelefono4()); initialValues.put("TELEFONO5",contactosclieprov.getTelefono5()); initialValues.put("HORAPREF",contactosclieprov.getHorapref()); initialValues.put("MODOCONTACTO",contactosclieprov.getModocontacto()); initialValues.put("CARGO",contactosclieprov.getCargo()); initialValues.put("ESPROPIETARIO",contactosclieprov.getEspropietario()); initialValues.put("HORAPREFH",contactosclieprov.getHoraprefh()); resultado = mDb.insert("CONTACTOSCLIEPROV",null,initialValues)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } public Boolean update(Contactosclieprov contactosclieprov,String where) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ContentValues initialValues = new ContentValues(); initialValues.put("IDEMPRESA",contactosclieprov.getIdempresa()) ; initialValues.put("IDCLIEPROV",contactosclieprov.getIdclieprov()) ; initialValues.put("ITEM",contactosclieprov.getItem()) ; initialValues.put("NOMBRE",contactosclieprov.getNombre()) ; initialValues.put("DIRECCION",contactosclieprov.getDireccion()) ; initialValues.put("TELEFONO1",contactosclieprov.getTelefono1()) ; initialValues.put("TELEFONO2",contactosclieprov.getTelefono2()) ; initialValues.put("TELEFONO3",contactosclieprov.getTelefono3()) ; initialValues.put("EMAIL",contactosclieprov.getEmail()) ; initialValues.put("PREDETERMINADO",contactosclieprov.getPredeterminado()) ; initialValues.put("ESTADO",contactosclieprov.getEstado()) ; initialValues.put("SINCRONIZA",contactosclieprov.getSincroniza()) ; initialValues.put("FECHACREACION",dateFormat.format(contactosclieprov.getFechacreacion() ) ) ; initialValues.put("IDCARGO",contactosclieprov.getIdcargo()) ; initialValues.put("DNI",contactosclieprov.getDni()) ; initialValues.put("APELLIDOPATERNO",contactosclieprov.getApellidopaterno()) ; initialValues.put("APELLIDOMATERNO",contactosclieprov.getApellidomaterno()) ; initialValues.put("SEXO",contactosclieprov.getSexo()) ; initialValues.put("FECHA_NACIMIENTO",dateFormat.format(contactosclieprov.getFecha_nacimiento() ) ) ; initialValues.put("DIRECCION_NUMERO",contactosclieprov.getDireccion_numero()) ; initialValues.put("IDUBIGEO",contactosclieprov.getIdubigeo()) ; initialValues.put("IDESTADOCIVIL",contactosclieprov.getIdestadocivil()) ; initialValues.put("TELEFONO4",contactosclieprov.getTelefono4()) ; initialValues.put("TELEFONO5",contactosclieprov.getTelefono5()) ; initialValues.put("HORAPREF",contactosclieprov.getHorapref()) ; initialValues.put("MODOCONTACTO",contactosclieprov.getModocontacto()) ; initialValues.put("CARGO",contactosclieprov.getCargo()) ; initialValues.put("ESPROPIETARIO",contactosclieprov.getEspropietario()) ; initialValues.put("HORAPREFH",contactosclieprov.getHoraprefh()) ; resultado = mDb.update("CONTACTOSCLIEPROV",initialValues,where,null)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public Boolean delete(String where) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ resultado = mDb.delete("CONTACTOSCLIEPROV",where,null)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } public ArrayList<Contactosclieprov> listar(String where,String order,Integer limit) { if(limit == null){ limit =0; } ArrayList<Contactosclieprov> lista = new ArrayList<Contactosclieprov>(); SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ Cursor cur = mDb.query("CONTACTOSCLIEPROV", new String[] { "IDEMPRESA" , "IDCLIEPROV" , "ITEM" , "NOMBRE" , "DIRECCION" , "TELEFONO1" , "TELEFONO2" , "TELEFONO3" , "EMAIL" , "PREDETERMINADO" , "ESTADO" , "SINCRONIZA" , "FECHACREACION" , "IDCARGO" , "DNI" , "APELLIDOPATERNO" , "APELLIDOMATERNO" , "SEXO" , "FECHA_NACIMIENTO" , "DIRECCION_NUMERO" , "IDUBIGEO" , "IDESTADOCIVIL" , "TELEFONO4" , "TELEFONO5" , "HORAPREF" , "MODOCONTACTO" , "CARGO" , "ESPROPIETARIO" , "HORAPREFH" }, where, null, null, null, order); if (cur!=null){ cur.moveToFirst(); int i=0; while (cur.isAfterLast() == false) { int j=0; Contactosclieprov contactosclieprov = new Contactosclieprov() ; contactosclieprov.setIdempresa(cur.getString(j++)); contactosclieprov.setIdclieprov(cur.getString(j++)); contactosclieprov.setItem(cur.getString(j++)); contactosclieprov.setNombre(cur.getString(j++)); contactosclieprov.setDireccion(cur.getString(j++)); contactosclieprov.setTelefono1(cur.getString(j++)); contactosclieprov.setTelefono2(cur.getString(j++)); contactosclieprov.setTelefono3(cur.getString(j++)); contactosclieprov.setEmail(cur.getString(j++)); contactosclieprov.setPredeterminado(cur.getDouble(j++)); contactosclieprov.setEstado(cur.getDouble(j++)); contactosclieprov.setSincroniza(cur.getString(j++)); contactosclieprov.setFechacreacion(dateFormat.parse(cur.getString(j++)) ); contactosclieprov.setIdcargo(cur.getString(j++)); contactosclieprov.setDni(cur.getString(j++)); contactosclieprov.setApellidopaterno(cur.getString(j++)); contactosclieprov.setApellidomaterno(cur.getString(j++)); contactosclieprov.setSexo(cur.getString(j++)); contactosclieprov.setFecha_nacimiento(dateFormat.parse(cur.getString(j++)) ); contactosclieprov.setDireccion_numero(cur.getDouble(j++)); contactosclieprov.setIdubigeo(cur.getString(j++)); contactosclieprov.setIdestadocivil(cur.getString(j++)); contactosclieprov.setTelefono4(cur.getString(j++)); contactosclieprov.setTelefono5(cur.getString(j++)); contactosclieprov.setHorapref(cur.getString(j++)); contactosclieprov.setModocontacto(cur.getString(j++)); contactosclieprov.setCargo(cur.getString(j++)); contactosclieprov.setEspropietario(cur.getDouble(j++)); contactosclieprov.setHoraprefh(cur.getString(j++)); lista.add(contactosclieprov); i++; if(i == limit){ break; } cur.moveToNext(); } cur.close(); } } catch (Exception e) { }finally { mDb.close(); } return lista; } }
package Beans; import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; @Entity() public class Alien { @Id @GeneratedValue(strategy =GenerationType.AUTO) private int aid; private Aliean_Name aliname; private String color; private Date Bday; public int getAid() { return aid; } public void setAid(int aid) { this.aid = aid; } public Aliean_Name getAliname() { return aliname; } public void setAliname(Aliean_Name aliname) { this.aliname = aliname; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Date getBday() { return Bday; } public void setBday(Date bday) { Bday = bday; } @Override public String toString() { return "Alien [aid=" + aid + ", aliname=" + aliname + ", color=" + color + ", Bday=" + Bday + "]"; } }
package com.amundi.tech.onsite.model.usage; import java.time.LocalDate; public interface RestaurantUsage { LocalDate getDate(); int getH1130(); // max capacity int getH1200(); int getH1230(); int getH1300(); int getH1330(); int getH1130_u(); // _u => used int getH1200_u(); int getH1230_u(); int getH1300_u(); int getH1330_u(); }
/* * * * * * * @version 1.0.0 * * * * Copyright (C) 2012-2016 REDNOVO Corporation. * */ package com.rednovo.ace.common; import com.rednovo.libs.common.StringUtils; import org.json.JSONObject; import java.io.InputStream; /** * @author Zhen.Li * @fileNmae JsonUtils * @since 2016-03-05 */ public class JsonUtils { // private static Gson mGson = new GsonBuilder().create(); // // /** // * 获取GSON // * // * @return GSON实例 // */ // public static Gson gsonInstance() { // return mGson; // } // // /** // * 从json字符串构造 clazz 的实例 // * // * @param jsonString json字符串 // * @param clazz 目标转换对象的class类型 // * @param <T> 转换完成的类型实例 // * @return <p>json字符串解析成功,返回SplashScreenItemsResult</p> // * <p>json字符串解析失败时,返回null</p> // */ // public static <T> T fromJsonString(String jsonString, Class<T> clazz) { // try { // return gsonInstance().fromJson(jsonString, clazz); // } catch (com.google.gson.JsonSyntaxException e) { // e.printStackTrace(); // } // return null; // } // // // /** // * 从对象转换为json字符串 // * // * @param object 对象实例 // * @return json字符串 // */ // public static String toJsonString(Object object) { // try { // return gsonInstance().toJson(object); // } catch (ArrayIndexOutOfBoundsException e) { // e.printStackTrace(); // } // return ""; // } /** * InputSteam 转换到 JSONObject * * @param inputStream 输入流 * @return JSONObject */ public static JSONObject jsonObjectFromInputStream(InputStream inputStream) { try { return new JSONObject(StringUtils.stringFromInputStream(inputStream)); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 从对象转换为json数组字符串 * * @param object 对象实例 * @return json数组字符串 */ public static String toJsonArrayString(Object object) { String joinString = StringUtils.join(",", object); StringBuilder stringBuilder = new StringBuilder(joinString.length() + 2); return stringBuilder.append('[').append(joinString).append(']').toString(); } }
/** * Copyright (c) 2004-2021 All Rights Reserved. */ package com.adomy.mirpc.core.remoting.invoker.enums; /** * 调用模式枚举 * * @author adomyzhao * @version $Id: InvokeType.java, v 0.1 2021年03月23日 8:44 PM adomyzhao Exp $ */ public enum InvokeTypeEnum { SYNC, CALLBACK, ONEWAY; }
class F1 { public final void prt() //override 할 수 없다 final을 씀으로 { System.out.println("prt F1"); } } class F2 extends F1 { /*@Override public void prt()//Multiple markers at this line- overrides F1.prt- Cannot override the final method from F1 { System.out.println("F2 prt"); }*/ } public class A4FinalMethodTest { public static void main(String[] args) { // } }
// ********************************************************** // 1. 제 목: Correction ADMIN BEAN // 2. 프로그램명: TutorLoginBean.java // 3. 개 요: 첨삭관리 관리자 bean // 4. 환 경: JDK 1.3 // 5. 버 젼: 1.0 // 6. 작 성: // 7. 수 정: // ********************************************************** package com.ziaan.homepage; import java.sql.PreparedStatement; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.ErrorManager; import com.ziaan.library.ListSet; import com.ziaan.library.RequestBox; import com.ziaan.library.StringManager; public class TutorLoginBean { public TutorLoginBean() { } /********************************************************************** * 어드민 창 띄우기 로그 : 튜터로그인 * @param box receive from the form object and session * @return is_Ok 1 : success 2 : fail **********************************************************************/ public int tutorLogin(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; String sql1 = ""; String sql2 = ""; ListSet ls1 = null; int is_Ok = 0; int v_serno = 0; String v_userid = box.getSession("userid"); // String v_userip = box.getString("p_userip"); String v_userip = box.getSession("userip"); try { connMgr = new DBConnectionManager(); sql1 = "select nvl(max(serno),0) as serno from tz_tutorlog where tuserid=" + StringManager.makeSQL(v_userid); ls1 = connMgr.executeQuery(sql1); if ( ls1.next() ) { v_serno = ls1.getInt(1) + 1; } else { v_serno = 1; } sql2 = "insert into tz_tutorlog(tuserid, serno, login,loginip) "; sql2 += " values (?, ?, to_char(sysdate,'YYYYMMDDHH24MISS'), ?) "; pstmt = connMgr.prepareStatement(sql2); pstmt.setString(1, v_userid); pstmt.setInt(2, v_serno); pstmt.setString(3, v_userip); is_Ok = pstmt.executeUpdate(); // LogDB.insertLog(box, "update", "tz_tutorlog", v_userid + "," +v_serno + "," +v_userip , "튜터로그인"); } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, null, sql2); throw new Exception("sql2 = " + sql2 + "\r\n" + ex.getMessage() ); } finally { if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { }} if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return v_serno; } /********************************************************************** * 어드민 창 띄우기 로그 : 튜터로그아웃 * @param box receive from the form object and session * @return is_Ok 1 : success 2 : fail **********************************************************************/ public int tutorLogout(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; String sql1 = ""; String sql2 = ""; ListSet ls1 = null; ListSet ls2 = null; int is_Ok = 0; String v_userid = box.getSession("userid"); // String v_userip = box.getString("p_userip"); String v_userip = box.getSession("userip"); int v_serno = Integer.parseInt(box.getSession("serno") ); try { connMgr = new DBConnectionManager(); sql1 = " update tz_tutorlog "; sql1 += " set logout=to_char(sysdate, 'YYYYMMDDHH24MISS') "; sql1 += " , dtime = to_char(sysdate, 'YYYYMMDDHH24MISS')-login "; sql1 += " where tuserid = " + StringManager.makeSQL(v_userid); sql1 += " and serno = " + v_serno; connMgr.executeUpdate(sql1); // LogDB.insertLog(box, "update", "tz_tutorlog", v_userid + "," +v_serno , "튜터로그아웃"); } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, null, sql1); throw new Exception("sql1 = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return v_serno; } }
import java.util.*; class factorial { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); if(n<=100000){ int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=scan.nextInt(); } // Arrays.sort(arr); for(int j=0;j<n-1;j++) { System.out.printf("%d ",Math.max(arr[j],arr[j+1])); } } } }
package com.iotalking.lovertracker; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.MotionEvent; import com.baidu.location.BDLocation; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.map.OverlayOptions; import com.baidu.mapapi.map.Polyline; import com.baidu.mapapi.map.PolylineOptions; import com.baidu.mapapi.map.TextureMapView; import com.baidu.mapapi.model.LatLng; import com.iotalking.lovertracker.service.WakeupService; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private TextureMapView mMapView; private BaiduMap mBaiduMap; private MyReceiver mReceiver; private boolean mCanSetMyLocation = true; public Runnable mCanSetMyLocationRunner = new Runnable() { @Override public void run() { mCanSetMyLocation = true; } }; Handler mUIHandler = null; private BaiduMap.OnMapTouchListener mMapTouchListener = new BaiduMap.OnMapTouchListener() { @Override public void onTouch(MotionEvent motionEvent) { if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){ mCanSetMyLocation = false; if(mUIHandler != null){ mUIHandler.removeCallbacks(mCanSetMyLocationRunner); mUIHandler.postDelayed(mCanSetMyLocationRunner,5*1000); } } } }; private Polyline mPolyline; @RequiresApi(api = Build.VERSION_CODES.M) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_main); mUIHandler = new Handler(); mMapView = (TextureMapView) findViewById(R.id.bmapView); mBaiduMap = mMapView.getMap(); mBaiduMap.setMyLocationEnabled(true); mBaiduMap.setOnMapTouchListener(mMapTouchListener); requestGPSPerssion(); registerReceiver(); startService(); requestGPSPerssion(); } final int GPS_REQUEST_CODE = 6666; @RequiresApi(api = Build.VERSION_CODES.M) void requestGPSPerssion(){ if(checkSelfPermission(Manifest.permission_group.LOCATION) != PackageManager.PERMISSION_GRANTED){ if(shouldShowRequestPermissionRationale(Manifest.permission_group.LOCATION)){ }else{ this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},GPS_REQUEST_CODE); } }else{ setMyLocation(WakeupService.getLastLocation()); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){ if(requestCode == GPS_REQUEST_CODE){ boolean gpsGranted = false; for(int i = 0;i<permissions.length;i++){ String permission = permissions[i]; if(permission.equals(Manifest.permission.ACCESS_FINE_LOCATION) || permission.equals(Manifest.permission.ACCESS_COARSE_LOCATION)){ if(grantResults[i] == PackageManager.PERMISSION_GRANTED){ gpsGranted = true; break; } } } if(gpsGranted){ setMyLocation(WakeupService.getLastLocation()); } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(false); return true; } return super.onKeyDown(keyCode, event); } void registerReceiver(){ mReceiver = new MyReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(WakeupService.LOCATION_ACTION); filter.addAction(WakeupService.MOVE_TO_FRONT_ACTION); registerReceiver(mReceiver,filter); } void unregisterReceiver(){ if(mReceiver != null){ this.unregisterReceiver(mReceiver); mReceiver = null; } } void startService(){ Intent i = new Intent(); i.setClass(this,WakeupService.class); startService(i); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(); //在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理 mBaiduMap = null; if(mUIHandler != null){ mUIHandler.removeCallbacks(mCanSetMyLocationRunner); mUIHandler = null; } mMapView.onDestroy(); } @Override protected void onResume() { super.onResume(); //在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理 mMapView.onResume(); } @Override protected void onPause() { super.onPause(); //在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理 mMapView.onPause(); } void setMyLocation(BDLocation location){ if(mCanSetMyLocation == false){ return ; } if(location == null){ Intent i = new Intent(); i.setClass(this,WakeupService.class); i.setAction(WakeupService.RESTART_GPS_ACTION); startService(i); return; } // 构造定位数据 MyLocationData locData = new MyLocationData.Builder() .accuracy(location.getRadius()) // 此处设置开发者获取到的方向信息,顺时针0-360 .latitude(location.getLatitude()) .longitude(location.getLongitude()).build(); // 设置定位数据 mBaiduMap.setMyLocationData(locData); LatLng ll = new LatLng(location.getLatitude(), location.getLongitude()); MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 20.0f); mBaiduMap.animateMapStatus(u); if(mPolyline != null){ mPolyline.remove(); mPolyline = null; } if(mMyPoints.size() > 1){ OverlayOptions ooPolyline = new PolylineOptions().width(10) .color(0xAAFF0000).points(mMyPoints); mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline); } } List<LatLng> mMyPoints= new ArrayList<LatLng>(); class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals(WakeupService.LOCATION_ACTION)){ BDLocation location = intent.getParcelableExtra("location"); mMyPoints.add(new LatLng(location.getLatitude(),location.getLongitude())); setMyLocation(location); } } } }
package org.vincent.annon; import org.vincent.annon.example.DogImp; import org.vincent.annon.service.AnimalInterface; /** * @author PengRong IOC 依赖注入注解定义的属性 * @package org.vincent.proxy * @date 2018/12/15 - 14:46 * @ProjectName JavaAopLearning * @Description: TODO */ public class InjectionTest { /*** * 创建一个实例然后,通过注入逻辑自动将注解的内容赋值给实例属性 */ public static void main(String[] args) throws InterruptedException { AnimalInterface dogImp = new DogImp(); dogImp = (DogImp) SevenAnnoInjectionHandle.getBean(dogImp); Thread.sleep(100); System.out.println(dogImp.getName()); dogImp.getProperty(); } }
public class Person { //변수의 값을 외부에서 접근해서 바굴수 없게 private으로 선언한다 private String name; private int age; //외부에서 변수명은 모르게 하고 변수의 값만 바꿀수 있게 하기위해 세터 메소드를 선언한다 public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } //외부에서 변수에 저장되어있는 값이 무엇인지 알고싶을때 게터 메소드를 선언한다 public String getName() { return name; } public int getAge() { return age; } //퍼슨 클래스에 선언해놓은 변수의 접근자가 private이여도 퍼슨 클래스에서는 변수에 저장되어있는 값을 사용할수 있다 public void intro(){ System.out.println("나이: " + age + " 이름: " + name); } }
package com.haku.project.service; import com.haku.project.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; public interface UserService { public User queryUserById(Long id); public List<User> queryAllUsers(); }
package com.timewarp.games.onedroidcode.objects.tiles; import com.timewarp.games.onedroidcode.AssetManager; import com.timewarp.games.onedroidcode.level.TObject; public class TWall extends TObject { public TWall() { this.texture = AssetManager.wallStoneTexture; this.solid = true; } }
package kr.or.ddit.basic; public class T01_ArgsTest { /* * 가변형 인수 : 메소드의 매개변수 개수가 실행 시마다 다를 경우 사용 -> 데이터가 몇개 넘어올 지 모를 때 사용 * 가변형 인수는 메소드 안에서 배열로 처리 * 가변형 인수는 한가지 자료형만 사용 가능 * 타입명...변수이름 => ex) int...data */ // 배열을 이용한 메소드 // 매개변수로 받은 정수들의 합계를 구하는 메소드(이 정수들의 개수는 상황에 따라 달라짐) public int sumArr(int[] data) { int sum=0; for(int i=0;i<data.length;i++) { sum += data[i]; } return sum; } // 가변형 인수를 이용한 메소드 public int sumArg(int...data) { int sum=0; for(int i=0;i < data.length;i++) { sum += data[i]; } return sum; } // 가변형 인수와 일반적인 인수를 같이 사용할 경우 -> 가변형 인수를 제일 뒤쪽에 배치해야함 public String sumArg2(String name, int...data) { // int...data => 배열처럼 초기화됨 int sum=0; for(int i=0;i < data.length;i++) { sum += data[i]; } return name + "씨 점수:" + sum; } public static void main(String[] args) { T01_ArgsTest at = new T01_ArgsTest(); int[] nums = {100,200,300,}; System.out.println(at.sumArg(nums)); System.out.println(at.sumArr(new int[] {1,2,3,4,5})); System.out.println(at.sumArg(100,200,300)); System.out.println(at.sumArg(1,2,3,4,5)); System.out.println(); System.out.println(at.sumArg2("홍길동", 1,2,3,4,5,6,7,8,9,10)); } }
package you.in.spark.energy.cividroid.sync; import android.accounts.Account; import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SyncResult; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat.Builder; import android.support.v4.app.TaskStackBuilder; import android.support.v4.util.Pair; import com.google.gson.JsonObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Vector; import retrofit.RestAdapter; import retrofit.RestAdapter.LogLevel; import retrofit.RetrofitError; import you.in.spark.energy.cividroid.ActivityAlarm; import you.in.spark.energy.cividroid.CiviContract; import you.in.spark.energy.cividroid.R.drawable; import you.in.spark.energy.cividroid.R.string; import you.in.spark.energy.cividroid.api.ICiviApi; import you.in.spark.energy.cividroid.authentication.AuthenticatorActivity; import you.in.spark.energy.cividroid.entities.CiviActivity; import you.in.spark.energy.cividroid.entities.WriteNotesResult; public class SyncAdapter extends AbstractThreadedSyncAdapter { private final ContentResolver contentResolver; private static final String TAG = "SyncAdapter"; public SyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); this.contentResolver = context.getContentResolver(); } @TargetApi(VERSION_CODES.HONEYCOMB) public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) { super(context, autoInitialize, allowParallelSyncs); this.contentResolver = context.getContentResolver(); } public static boolean isConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); return isConnected; } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { if (isConnected(getContext())) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this.getContext()); String apiKey, siteKey, websiteUrl, lastScheduledID, sourceContactID; apiKey = sp.getString(CiviContract.API_KEY, null); siteKey = sp.getString(CiviContract.SITE_KEY, null); websiteUrl = sp.getString(CiviContract.WEBSITE_URL, null); sourceContactID = sp.getString(CiviContract.SOURCE_CONTACT_ID, null); String activityOffset = sp.getString(CiviContract.LAST_ACTIVITY_SYNC_ID, "0"); String notesOffset = sp.getString(CiviContract.LAST_NOTES_SYNC_ID, "0"); RestAdapter adapter = new RestAdapter.Builder().setLogLevel(LogLevel.FULL). setEndpoint(websiteUrl).build(); ICiviApi iCiviApi = adapter.create(ICiviApi.class); Map<String, String> fields = new HashMap<>(); fields.put("key", siteKey); fields.put("api_key", apiKey); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("sequential", 1); jsonObject.addProperty("status_id", "Scheduled"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date currentDate = new Date(System.currentTimeMillis()); fields.put("json", "{\"sequential\":1,\"id\":{\">\":" + activityOffset + "},\"status_id\":\"Scheduled\",\"activity_date_time\":{\">\":\"" + simpleDateFormat.format(currentDate) + "\"}}"); //Sync Activities CiviActivity activity = null; try { activity = iCiviApi.getActivity(fields); } catch (RetrofitError re) { } if (activity != null) { if (activity.getIsError() != 1) { int valSize = activity.getValues().size(); if (valSize > 0) { ContentValues values[] = new ContentValues[valSize]; String scheduleDate = null; Vector<Pair<String, String>> actIds = new Vector<>(); for (int i = 0; i < valSize; i++) { values[i] = activity.getValues().get(i).getAllValues(); actIds.add(new Pair<String, String>(activity.getValues().get(i).getId(), activity.getValues().get(i).getActivityDateTime())); } sp.edit().putString(CiviContract.LAST_ACTIVITY_SYNC_ID, actIds.get(actIds.size() - 1).first).apply(); int added = this.contentResolver.bulkInsert(Uri.parse(CiviContract.CONTENT_URI + "/" + CiviContract.ACTIVITY_TABLE), values); if (added > 0) { for (Pair<String, String> act : actIds) { Intent i = new Intent(this.getContext(), ActivityAlarm.class); i.putExtra(CiviContract.ACTIVITY_TABLE_COLUMNS[1], act.first); PendingIntent pi = PendingIntent.getBroadcast(this.getContext(), Integer.valueOf(act.first), i, PendingIntent.FLAG_ONE_SHOT); Date date = null; try { date = simpleDateFormat.parse(act.second); } catch (ParseException e) { } AlarmManager alarmManager = (AlarmManager) this.getContext().getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pi); } } } } else { this.invalidate(); } } //Sync Notes on Calls if (sourceContactID != null) { fields.clear(); fields.put("key", siteKey); fields.put("api_key", apiKey); String jsonValue = "{\"sequential\":1,\"activity_type_id\":\"Phone Call\",\"id\":{\">\":" + notesOffset + "},\"phone_number\":{\"IS NOT NULL\":1}}"; fields.put("json", jsonValue); try { activity = iCiviApi.getActivity(fields); } catch (RetrofitError re) { } if (activity != null) { if (activity.getIsError() != 1) { int size = activity.getValues().size(); if (size > 0) { ContentValues values[] = new ContentValues[size]; for (int i = 0; i < size; i++) { values[i] = activity.getValues().get(i).getAllNotesValue(); } sp.edit().putString(CiviContract.LAST_NOTES_SYNC_ID, activity.getValues().get(activity.getValues().size() - 1).getId()).apply(); this.contentResolver.bulkInsert(Uri.parse(CiviContract.CONTENT_URI + "/" + CiviContract.ACTIVITY_TABLE), values); } } else { this.invalidate(); } } //upload unsynced notes to web Vector<String> synced = new Vector<>(); Cursor notes = this.contentResolver.query(Uri.parse(CiviContract.CONTENT_URI + "/" + CiviContract.ACTIVITY_TABLE), new String[]{CiviContract.ACTIVITY_TABLE_COLUMNS[3], CiviContract.ACTIVITY_TABLE_COLUMNS[4], CiviContract.ACTIVITY_TABLE_COLUMNS[6], CiviContract.ACTIVITY_TABLE_COLUMNS[10]}, CiviContract.ACTIVITY_TABLE_COLUMNS[11] + "=?", new String[]{"1"}, null); while (notes.moveToNext()) { fields.clear(); fields.put("key", siteKey); fields.put("api_key", apiKey); String json = "{\"sequential\":1,\"source_contact_id\":" + sourceContactID + ",\"activity_type_id\":\"Phone Call\",\"details\":\"" + notes.getString(2) + "\",\"activity_date_time\":\"" + notes.getString(0) + "\",\"duration\":" + notes.getString(1) + ",\"phone_number\":" + notes.getString(3) + "}"; fields.put("json", json); WriteNotesResult result = null; try { result = iCiviApi.writeNotes(fields); } catch (RetrofitError rfe) { } if (result != null) { if (result.getIsError() == 0) { synced.add(notes.getString(3)); } } } notes.close(); //update sync detail in local db if (synced.size() > 0) { for (String id : synced) { ContentValues val = new ContentValues(); val.putNull(CiviContract.ACTIVITY_TABLE_COLUMNS[11]); this.contentResolver.update(Uri.parse(CiviContract.CONTENT_URI + "/" + CiviContract.ACTIVITY_TABLE), val, CiviContract.ACTIVITY_TABLE_COLUMNS[10] + "=?", new String[]{id}); } } } } } private void invalidate() { Builder mBuilder = new Builder(this.getContext()) .setSmallIcon(drawable.cividroid_logo) .setContentTitle(this.getContext().getString(string.connection_error)) .setContentText(this.getContext().getString(string.connection_error_desc)); Intent resultIntent = new Intent(this.getContext(), AuthenticatorActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getContext()); stackBuilder.addParentStack(AuthenticatorActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) this.getContext().getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(0, mBuilder.build()); } }
package yef.gwalior.aks.com.yef; import android.app.Activity; import android.app.DatePickerDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.UUID; import com.firebase.ui.auth.AuthUI; import com.firebase.ui.auth.data.model.User; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment; import com.google.android.gms.location.places.ui.PlaceSelectionListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.squareup.picasso.Picasso; import java.io.Serializable; import org.w3c.dom.Text; public class UserProfile extends AppCompatActivity implements AdapterView.OnItemSelectedListener { public String uid, name=null, email=null, photoUrl=null; public String uname=null, ugender=null, uemail=null, uphotourl=null, uphoneno=null, ubday=null, uplace=null, ustate=null, ucity=null, uaboutme=null, ugraduationlevel=null, ugraduationfield=null, utypeofyouth=null; public int uage=0; DatabaseReference myDatabase; public boolean language; EditText selectDate; private Button btnCover, btnProfile; private ImageView profilepic, coverpic; FirebaseStorage storage; StorageReference storageReference; private Uri filePath1,filePath2; public int n = 1; private final int PICK_IMAGE_REQUEST = 71; private int mYear, mMonth, mDay, currentYear; ArrayAdapter<String> dataAdapter, dataAdapter2, dataAdapter3, dataAdapter4, dataAdapter5; List<String> categories3; private FirebaseAuth mAuth; FirebaseUser mfirebaseUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_profile); Bundle extras = getIntent().getExtras(); if (extras != null) { language = extras.getBoolean("langkey"); uid = extras.getString("userid"); name = extras.getString("name"); email = extras.getString("email"); photoUrl = extras.getString("photourl"); } if (language == false) { btnCover = findViewById(R.id.coverpicupdate); btnProfile = findViewById(R.id.profilepicupdate); profilepic = findViewById(R.id.profile_image); coverpic = findViewById(R.id.cover_image); TextView name1 = findViewById(R.id.name); EditText entername = findViewById(R.id.entername); EditText aboutme = findViewById(R.id.aboutme); EditText email1 = findViewById(R.id.email); RadioGroup gender = findViewById(R.id.gender); EditText address = findViewById(R.id.Address); EditText phone = findViewById(R.id.phone); int gen = gender.getCheckedRadioButtonId(); RadioButton genradio = findViewById(gen); RadioButton m=findViewById(R.id.male); RadioButton f=findViewById(R.id.female); RadioButton o=findViewById(R.id.other); EditText date=findViewById(R.id.date); TextView t1=findViewById(R.id.edulevel); TextView t2=findViewById(R.id.edufield); TextView t3=findViewById(R.id.youthtype); Button b=findViewById(R.id.update); TextView belve=findViewById(R.id.beileveus); btnCover.setText("अपलोड"); btnProfile.setText("अपलोड"); entername.setHint("नाम"); aboutme.setHint("स्वयं का विवरण दें"); email1.setHint("ईमेल"); m.setText("पुरुष"); f.setText("महिला"); o.setText("अन्य"); date.setHint("जन्म तिथि"); address.setHint("पता"); phone.setHint("फोन"); t1.setText("शिक्षा स्तर"); t2.setText("शिक्षा क्षेत्र"); t3.setText("युवा प्रकार"); b.setText("सेव"); b.setTextSize(25); belve.setText("हम पर विश्वास कीजिये, यह जानकारी हमें युवाओं को बेहतर तरीके से आकार देने में मदद करती है। \n © YEF 2018 गोपनीयता नीति"); } if(language==false) Toast.makeText(this, "कृपया सुनिश्चित करें कि सभी फ़ील्ड चुने गए हैं!", Toast.LENGTH_LONG).show(); else Toast.makeText(this, "Please ensure all fields are selected!", Toast.LENGTH_LONG).show(); btnCover = findViewById(R.id.coverpicupdate); btnProfile = findViewById(R.id.profilepicupdate); profilepic = findViewById(R.id.profile_image); coverpic = findViewById(R.id.cover_image); TextView name1 = findViewById(R.id.name); EditText entername = findViewById(R.id.entername); EditText aboutme = findViewById(R.id.aboutme); EditText email1 = findViewById(R.id.email); RadioGroup gender = findViewById(R.id.gender); EditText address = findViewById(R.id.Address); EditText phone = findViewById(R.id.phone); int gen = gender.getCheckedRadioButtonId(); RadioButton genradio = findViewById(gen); if (name != null) { name1.setText("" + name); uname = name; } if (email != null) { email1.setText("" + email); uemail = email; } if (photoUrl != null) { Picasso.with(this).load(photoUrl).into(profilepic); uphotourl = photoUrl; } btnCover.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { n = 1; chooseImage1(); } }); btnProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { n = 2; chooseImage1(); } }); selectDate = (EditText) findViewById(R.id.date); // Spinner element Spinner spinner = (Spinner) findViewById(R.id.spinner); Spinner spinner2 = findViewById(R.id.spinner2); Spinner spinner3 = findViewById(R.id.spinner3); Spinner spinner4 = findViewById(R.id.spinner4); Spinner spinner5 = findViewById(R.id.spinner5); List<String> categories = new ArrayList<String>(); categories.add("Select"); categories.add("Below Metric"); categories.add("Metric"); categories.add("High School"); categories.add("Diploma"); categories.add("Graduate"); categories.add("Post Graduate"); categories.add("Doctorate"); categories.add("Other"); dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(dataAdapter); spinner.setOnItemSelectedListener(this); //second List<String> categories2 = new ArrayList<String>(); categories2.add("Select State"); categories2.add("Andaman and Nicobar Islands"); categories2.add("Andhra Pradesh"); categories2.add("Arunachal Pradesh"); categories2.add("Assam"); categories2.add("Bihar"); categories2.add("Chandigarh"); categories2.add("Chhattisgarh"); categories2.add("Dadra and Nagar Haveli"); categories2.add("Daman and Diu"); categories2.add("Delhi"); categories2.add("Goa"); categories2.add("Gujarat"); categories2.add("Haryana"); categories2.add("Himachal Pradesh"); categories2.add("Jammu and Kashmir"); categories2.add("Jharkhand"); categories2.add("Karnataka"); categories2.add("Kerala"); categories2.add("Lakshadweep"); categories2.add("Madhya Pradesh"); categories2.add("Maharashtra"); categories2.add("Manipur"); categories2.add("Meghalaya"); categories2.add("Mizoram"); categories2.add("Nagaland"); categories2.add("Orissa"); categories2.add("Puducherry"); categories2.add("Punjab"); categories2.add("Rajasthan"); categories2.add("Sikkim"); categories2.add("Tamil Nadu"); categories2.add("Telangana"); categories2.add("Tripura"); categories2.add("Uttarakhand"); categories2.add("Uttar Pradesh"); categories2.add("West Bengal"); dataAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories2) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner2.setAdapter(dataAdapter2); spinner2.setOnItemSelectedListener(this); //fourth List<String> categories4 = new ArrayList<String>(); categories4.add("Select"); categories4.add("Accountancy"); categories4.add("Aeronautics"); categories4.add("Agriculture"); categories4.add("Architecture"); categories4.add("Arts"); categories4.add("Astrology"); categories4.add("Astronomy"); categories4.add("Biology"); categories4.add("Biotechnology"); categories4.add("Chemistry"); categories4.add("Chemical Engineering"); categories4.add("Computer Science"); categories4.add("Commerce"); categories4.add("Civil Engineering"); categories4.add("Economics"); categories4.add("Electrical Engineering"); categories4.add("Electronics Engineering"); categories4.add("Engineering"); categories4.add("Finance"); categories4.add("Food Technology"); categories4.add("Geology"); categories4.add("Geography"); categories4.add("History"); categories4.add("Home Science"); categories4.add("Hotel Management"); categories4.add("Humanities"); categories4.add("Information Technology"); categories4.add("Law"); categories4.add("Management"); categories4.add("Marine Engineering"); categories4.add("Marketing"); categories4.add("MBBS"); categories4.add("Mechanical Engineering"); categories4.add("Material Science"); categories4.add("Political Science"); categories4.add("Physics"); categories4.add("Statistics"); categories4.add("Sales"); categories4.add("Technology"); categories4.add("Other"); dataAdapter4 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories4) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner4.setAdapter(dataAdapter4); spinner4.setOnItemSelectedListener(this); //fifth List<String> categories5 = new ArrayList<String>(); categories5.add("Select"); categories5.add("Creative"); categories5.add("Passionate"); categories5.add("Rough"); categories5.add("Smart"); categories5.add("Cheerful"); categories5.add("Happy"); categories5.add("Serious"); categories5.add("Dreamer"); categories5.add("Practical"); categories5.add("Intelligent"); categories5.add("Funny"); dataAdapter5 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories5) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter5.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner5.setAdapter(dataAdapter5); spinner5.setOnItemSelectedListener(this); storage = FirebaseStorage.getInstance(); storageReference = storage.getReference(); selectDate.setInputType(0); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // On selecting a spinner item switch (parent.getId()) { case R.id.spinner: String item1 = parent.getItemAtPosition(position).toString(); ugraduationlevel = item1; case R.id.spinner2: Spinner spinner3 = findViewById(R.id.spinner3); String item2 = parent.getItemAtPosition(position).toString(); ustate = item2; // Spinner Drop down elements switch (item2) { case "Andaman and Nicobar Islands": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Bamboo Flat"); categories3.add("Garacherama"); categories3.add("Port Blair"); categories3.add("Prothrapur"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Andhra Pradesh": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Adoni"); categories3.add("Amaravati"); categories3.add("Anantapur"); categories3.add("Chandragiri"); categories3.add("Chittoor"); categories3.add("Dowlaiswaram"); categories3.add("Eluru"); categories3.add("Guntur"); categories3.add("Kadapa"); categories3.add("Kakinada"); categories3.add("Kurnool"); categories3.add("Machilipatnam"); categories3.add("Nagarjunakonda"); categories3.add("Rajahmundry"); categories3.add("Srikakulam"); categories3.add("Tirupati"); categories3.add("Vijayawada"); categories3.add("Visakhapatnam"); categories3.add("Vizianagaram"); categories3.add("Yemmiganur"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Arunachal Pradesh": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Aalo"); categories3.add("Itanagar"); categories3.add("Naharlagun"); categories3.add("Pasighat"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Assam": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Dhuburi"); categories3.add("Dibrugarh"); categories3.add("Dispur"); categories3.add("Guwahati"); categories3.add("Jorhat"); categories3.add("Nagaon"); categories3.add("Sibsagar"); categories3.add("Silchar"); categories3.add("Tezpur"); categories3.add("Tinsukia"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Bihar": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Ara"); categories3.add("Baruni"); categories3.add("Begusarai"); categories3.add("Bettiah"); categories3.add("Bhagalpur"); categories3.add("Bihar Sharif"); categories3.add("Bodh Gaya"); categories3.add("Buxar"); categories3.add("Chapra"); categories3.add("Darbhanga"); categories3.add("Dehri"); categories3.add("Dinapur Nizamat"); categories3.add("Gaya"); categories3.add("Hajipur"); categories3.add("Jamalpur"); categories3.add("Katihar"); categories3.add("Madhubani"); categories3.add("Motihari"); categories3.add("Munger"); categories3.add("Muzzafarpur"); categories3.add("Patna"); categories3.add("Purnia"); categories3.add("Pusa"); categories3.add("Saharsa"); categories3.add("Samastipur"); categories3.add("Sasaram"); categories3.add("Sitamarhi"); categories3.add("Siwan"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Chandigarh": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Chandigarh"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Chhattisgarh": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Ambikapur"); categories3.add("Bhilai"); categories3.add("Bilaspur"); categories3.add("Dhamtari"); categories3.add("Durg"); categories3.add("Jagdalpur"); categories3.add("Raipur"); categories3.add("Rajnandgaon"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Dadra and Nagar Haveli": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Dadra"); categories3.add("Masat"); categories3.add("Naroli"); categories3.add("Samarvarni"); categories3.add("Silvassa"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Daman and Diu": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Dadhel"); categories3.add("Daman"); categories3.add("Diu"); categories3.add("Kachigam"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Delhi": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("New Delhi"); categories3.add("North Delhi"); categories3.add("North West Delhi"); categories3.add("West Delhi"); categories3.add("South West Delhi"); categories3.add("South Delhi"); categories3.add("South East Delhi"); categories3.add("Cental Delhi"); categories3.add("North East Delhi"); categories3.add("Shahdara"); categories3.add("East Delhi"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Goa": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Mapusa"); categories3.add("Madgaon"); categories3.add("Mormugao"); categories3.add("Panaji"); categories3.add("Ponda"); categories3.add("Sancoale"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Gujarat": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Ahmadabad"); categories3.add("Amreli"); categories3.add("Bharuch"); categories3.add("Bhavnagar"); categories3.add("Bhuj"); categories3.add("Dwarka"); categories3.add("Gandhinagar"); categories3.add("Godhra"); categories3.add("Jamnagar"); categories3.add("Junagadh"); categories3.add("Kandla"); categories3.add("Khambhat"); categories3.add("Kheda"); categories3.add("Mahesana"); categories3.add("Morvi"); categories3.add("Nadiad"); categories3.add("Navsari"); categories3.add("Okha"); categories3.add("Palanpur"); categories3.add("Patan"); categories3.add("Porbandar"); categories3.add("Rajkot"); categories3.add("Surat"); categories3.add("Surendranagar"); categories3.add("Valsad"); categories3.add("Veraval"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Haryana": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Ambala"); categories3.add("Bhiwani"); categories3.add("Chandigarh"); categories3.add("Faridabad"); categories3.add("Firozpur Jhirka"); categories3.add("Gurgaon"); categories3.add("Hansi"); categories3.add("Hisar"); categories3.add("Jind"); categories3.add("Kaithal"); categories3.add("Karnal"); categories3.add("Kurukshetra"); categories3.add("Panipat"); categories3.add("Pehowa"); categories3.add("Rewari"); categories3.add("Rohtak"); categories3.add("Sirsa"); categories3.add("Sonepat"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Himachal Pradesh": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Bilaspur"); categories3.add("Chamba"); categories3.add("Dalhousie"); categories3.add("Dharmshala"); categories3.add("Hamirpur"); categories3.add("Kangra"); categories3.add("Kullu"); categories3.add("Mandi"); categories3.add("Nahan"); categories3.add("Shimla"); categories3.add("Una"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Jammu and Kashmir": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Anantnag"); categories3.add("Baramula"); categories3.add("Doda"); categories3.add("Gulmarg"); categories3.add("Jammu"); categories3.add("Kathua"); categories3.add("Leh"); categories3.add("Poonch"); categories3.add("Rajauri"); categories3.add("Srinagar"); categories3.add("Udhampur"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Jharkhand": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Bokaro"); categories3.add("Chaibasa"); categories3.add("Deoghar"); categories3.add("Dhanbad"); categories3.add("Dumka"); categories3.add("Giridih"); categories3.add("Hazaribag"); categories3.add("Jamshedpur"); categories3.add("Jharia"); categories3.add("Rajmahal"); categories3.add("Ranchi"); categories3.add("Saraikela"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Karnataka": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Badami"); categories3.add("Ballari"); categories3.add("Bangalore"); categories3.add("Belgavi"); categories3.add("Bhadravati"); categories3.add("Bidar"); categories3.add("Chikkamangaluru"); categories3.add("Chitradurga"); categories3.add("Davangere"); categories3.add("Halebid"); categories3.add("Hassan"); categories3.add("Hubballi Dharwad"); categories3.add("Kalaburagi"); categories3.add("Kolar"); categories3.add("Madikeri"); categories3.add("Mandya"); categories3.add("Mangaluru"); categories3.add("Mysuru"); categories3.add("Raichur"); categories3.add("Shivamogga"); categories3.add("Sharavanabelagola"); categories3.add("Shrirangapattana"); categories3.add("Tumkuru"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Kerala": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Alappuzha"); categories3.add("Badagara"); categories3.add("Idukki"); categories3.add("Kannur"); categories3.add("Kochi"); categories3.add("Kollam"); categories3.add("Kottayam"); categories3.add("Kozhikode"); categories3.add("Mattancheri"); categories3.add("Palakkad"); categories3.add("Thalassery"); categories3.add("Thiruvananthapuram"); categories3.add("Thrissur"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Lakshadweep": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Amini"); categories3.add("Andrott"); categories3.add("Kavaratti"); categories3.add("Minicoy"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Madhya Pradesh": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Balaghat"); categories3.add("Barwani"); categories3.add("Betul"); categories3.add("Bharhut"); categories3.add("Bhind"); categories3.add("Bhojpur"); categories3.add("Bhopal"); categories3.add("Burhanpur"); categories3.add("Chhatarpur"); categories3.add("Chhindwara"); categories3.add("Damoh"); categories3.add("Datia"); categories3.add("Dewas"); categories3.add("Dhar"); categories3.add("Guna"); categories3.add("Gwalior"); categories3.add("Hoshangabad"); categories3.add("Indore"); categories3.add("Itarsi"); categories3.add("Jabalpur"); categories3.add("Jhabua"); categories3.add("Khajuraho"); categories3.add("Khandwa"); categories3.add("Khargaon"); categories3.add("Maheshwar"); categories3.add("Mandla"); categories3.add("Mandsaur"); categories3.add("Mhow"); categories3.add("Morena"); categories3.add("Murwara"); categories3.add("Narsimhapur"); categories3.add("NArsinghgarh"); categories3.add("Neemuch"); categories3.add("Orchha"); categories3.add("Panna"); categories3.add("Raisen"); categories3.add("Rajgarh"); categories3.add("Ratlam"); categories3.add("Rewa"); categories3.add("Sagar"); categories3.add("Sarangpur"); categories3.add("Satna"); categories3.add("Sehore"); categories3.add("Seoni"); categories3.add("Shahdol"); categories3.add("Shajapur"); categories3.add("Sheopur"); categories3.add("Shivpuri"); categories3.add("Ujjain"); categories3.add("Vidisha"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Maharashtra": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Ahmadnagar"); categories3.add("Akola"); categories3.add("Amravati"); categories3.add("Aurangabad"); categories3.add("Bhandara"); categories3.add("Bhusawal"); categories3.add("Bid"); categories3.add("Buldana"); categories3.add("Chandrapur"); categories3.add("Daulatabad"); categories3.add("Dhule"); categories3.add("Jalgaon"); categories3.add("Kalyan"); categories3.add("Karli"); categories3.add("Kolhapur"); categories3.add("Mahabaleshwar"); categories3.add("Malegaon"); categories3.add("Matheran"); categories3.add("Mumbai"); categories3.add("Nagpur"); categories3.add("Nanded"); categories3.add("Nashik"); categories3.add("Osmanabad"); categories3.add("Pandharpur"); categories3.add("Parbhani"); categories3.add("Pune"); categories3.add("Ratnagiri"); categories3.add("Sangli"); categories3.add("Satara"); categories3.add("Sevagram"); categories3.add("Solapur"); categories3.add("Thane"); categories3.add("Ulhasnagar"); categories3.add("Vasai-Virar"); categories3.add("Wardha"); categories3.add("Yavatmal"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Manipur": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Imphal"); categories3.add("Kakching"); categories3.add("Mayang Imphal"); categories3.add("Thoubal"); categories3.add("Ukhrul"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3); dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Meghalaya": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Jowai"); categories3.add("Nongstoin"); categories3.add("Shillong"); categories3.add("Tura"); categories3.add("Williamnagar"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Mizoram": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Aizawl"); categories3.add("Champhai"); categories3.add("Kolasib"); categories3.add("Lawngtlai"); categories3.add("Lunglei"); categories3.add("Saiha"); categories3.add("Serchipp"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Nagaland": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Dimapur"); categories3.add("Kohima"); categories3.add("Mokokchung"); categories3.add("Mon"); categories3.add("Tuensang"); categories3.add("Wokha"); categories3.add("Zunheboto"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Orissa": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Balangir"); categories3.add("Baleshwar"); categories3.add("Baripada"); categories3.add("Bhubaneshwar"); categories3.add("Brahmapur"); categories3.add("Cuttack"); categories3.add("Dhenkanal"); categories3.add("Keonjhar"); categories3.add("Konark"); categories3.add("Koraput"); categories3.add("Paradip"); categories3.add("Phulabani"); categories3.add("Puri"); categories3.add("Sambalpur"); categories3.add("Udaygiri"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Puducherry": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Karaikal"); categories3.add("Mahe"); categories3.add("Puducherry"); categories3.add("Yanam"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Punjab": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Amritsar"); categories3.add("Batala"); categories3.add("Chandigarh"); categories3.add("Faridkot"); categories3.add("Firozpur"); categories3.add("Gurdaspur"); categories3.add("Hoshiarpur"); categories3.add("Jalandhar"); categories3.add("Kapurthala"); categories3.add("Ludhiana"); categories3.add("Nabha"); categories3.add("Patiala"); categories3.add("Rupnagar"); categories3.add("Sangrur"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Rajasthan": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Abu"); categories3.add("Ajmer"); categories3.add("Alwar"); categories3.add("Amer"); categories3.add("Barmer"); categories3.add("Beawar"); categories3.add("Bharatpur"); categories3.add("Bhilwara"); categories3.add("Bikaner"); categories3.add("Bundi"); categories3.add("Chittorgarh"); categories3.add("Churu"); categories3.add("Dhaulpur"); categories3.add("Dungarpur"); categories3.add("Ganganagar"); categories3.add("Hanumangarh"); categories3.add("Jaipur"); categories3.add("Jaisalmer"); categories3.add("Jalor"); categories3.add("Jhalawar"); categories3.add("Jhunjhunu"); categories3.add("Jodhpur"); categories3.add("Kishangarh"); categories3.add("Kota"); categories3.add("Merta"); categories3.add("Nagaur"); categories3.add("Nathdwara"); categories3.add("Pali"); categories3.add("Phalodi"); categories3.add("Pushkar"); categories3.add("Sawai Madhopur"); categories3.add("Shahpura"); categories3.add("Sikar"); categories3.add("Sirohi"); categories3.add("Tonk"); categories3.add("Udaipur"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Sikkim": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Gangtok"); categories3.add("Gyalsing"); categories3.add("Lachung"); categories3.add("Mangan"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Tamil Nadu": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Arcot"); categories3.add("Chengalpattu"); categories3.add("Chennai"); categories3.add("Chidambaram"); categories3.add("Coimbatore"); categories3.add("Cuddalore"); categories3.add("Dharmapuri"); categories3.add("Dindigul"); categories3.add("Erode"); categories3.add("Kanchipuram"); categories3.add("Kanyakumari"); categories3.add("Kodaikanal"); categories3.add("Kumbakonam"); categories3.add("Madurai"); categories3.add("Mamallapuram"); categories3.add("Nagappattinam"); categories3.add("Nagercoil"); categories3.add("Palayankottai"); categories3.add("Pudukottai"); categories3.add("Rajapaliyam"); categories3.add("Ramnathapuram"); categories3.add("Salem"); categories3.add("Thanjavur"); categories3.add("Tiruchchirappalli"); categories3.add("Tirunelveli"); categories3.add("Tiruppur"); categories3.add("Tuticorin"); categories3.add("Udhagamandalam"); categories3.add("Vellore"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Telangana": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Hyderabad"); categories3.add("Karimnagar"); categories3.add("Khammam"); categories3.add("Mahbubnagar"); categories3.add("Nizamabad"); categories3.add("Sangareddi"); categories3.add("Warangal"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Tripura": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Agartala"); categories3.add("Belonia"); categories3.add("Bishalgarh"); categories3.add("Dharmanagar"); categories3.add("Kailashahar"); categories3.add("Teliamura"); categories3.add("Udaipur"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Uttarakhand": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Almora"); categories3.add("Dehradun"); categories3.add("Haridwar"); categories3.add("Kathgodam"); categories3.add("Mussorie"); categories3.add("Nainital"); categories3.add("Pithoragarh"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "Uttar Pradesh": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Agra"); categories3.add("Aligarh"); categories3.add("Allahabad"); categories3.add("Amroha"); categories3.add("Ayodhya"); categories3.add("Azamgarh"); categories3.add("Bahraich"); categories3.add("Balia"); categories3.add("Banda"); categories3.add("Barabanki"); categories3.add("Bareilly"); categories3.add("Basti"); categories3.add("Bijnor"); categories3.add("Bithur"); categories3.add("Budaun"); categories3.add("Bulandshahar"); categories3.add("Deoria"); categories3.add("Etah"); categories3.add("Etawah"); categories3.add("Faizabad"); categories3.add("Farrukhabad"); categories3.add("Fatehpur"); categories3.add("Fatehpur Sikri"); categories3.add("Ghaziabad"); categories3.add("Ghazipur"); categories3.add("Gonda"); categories3.add("Gorakhpur"); categories3.add("Hamirpur"); categories3.add("Hardoi"); categories3.add("Hathras"); categories3.add("Jalaun"); categories3.add("Jaunpur"); categories3.add("Jhansi"); categories3.add("Kannauj"); categories3.add("Kanpur"); categories3.add("Lakhimpur"); categories3.add("Lalitpur"); categories3.add("Lucknow"); categories3.add("Mainpuri"); categories3.add("Mathura"); categories3.add("Meerut"); categories3.add("Mirzapur"); categories3.add("Moradabad"); categories3.add("Muzzafarnagar"); categories3.add("Partapgarh"); categories3.add("Rae Bareli"); categories3.add("Rampur"); categories3.add("Saharanpur"); categories3.add("Sambhal"); categories3.add("Shahjahanpur"); categories3.add("Sitapur"); categories3.add("Sultanpur"); categories3.add("Tehri"); categories3.add("Varanasi"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; case "West Bengal": categories3 = new ArrayList<String>(); categories3.add("Select City"); categories3.add("Alipore"); categories3.add("Alipur Duar"); categories3.add("Asansol"); categories3.add("Baharampur"); categories3.add("Bally"); categories3.add("Balurghat"); categories3.add("Bankura"); categories3.add("Baranagar"); categories3.add("Barasat"); categories3.add("Barrackpore"); categories3.add("Basirhat"); categories3.add("Bhatpara"); categories3.add("Bishnupur"); categories3.add("Budge Budge"); categories3.add("Burdwan"); categories3.add("Chandernagore"); categories3.add("Darjiling"); categories3.add("Diamond Harbour"); categories3.add("Dum Dum"); categories3.add("Durgapur"); categories3.add("Halisahar"); categories3.add("Haora"); categories3.add("Hugli"); categories3.add("Ingraj Bazar"); categories3.add("Jalpaiguri"); categories3.add("Kalimpong"); categories3.add("Kamarhati"); categories3.add("Kanchrapara"); categories3.add("Kharagpur"); categories3.add("Koch Bihar"); categories3.add("Kolkata"); categories3.add("Krishnanagar"); categories3.add("Malda"); categories3.add("Midnapore"); categories3.add("Murshidabad"); categories3.add("Navadwip"); categories3.add("Palashi"); categories3.add("Panihati"); categories3.add("Purulia"); categories3.add("Raiganj"); categories3.add("Santipur"); categories3.add("Shantiniketan"); categories3.add("Shrirampur"); categories3.add("Siliguri"); categories3.add("Siuri"); categories3.add("Tamluk"); categories3.add("Titagarh"); dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories3) { @Override public boolean isEnabled(int position) { if (position == 0) { // Disable the first item from Spinner // First item will be use for hint return false; } else { return true; } } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { // Set the hint text color gray tv.setTextColor(Color.GRAY); } else { tv.setTextColor(Color.BLACK); } return view; } }; dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner3.setAdapter(dataAdapter3); spinner3.setOnItemSelectedListener(this); break; } case R.id.spinner3: String item3 = parent.getItemAtPosition(position).toString(); ucity = item3; break; case R.id.spinner4: String item4 = parent.getItemAtPosition(position).toString(); ugraduationfield = item4; case R.id.spinner5: String item5 = parent.getItemAtPosition(position).toString(); utypeofyouth = item5; } } public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } public void privacyLink(View view) { String privacy = "privacyyef"; Intent intent = new Intent(UserProfile.this, WebViewSampleActivity.class); intent.putExtra("privacyyef", privacy); startActivity(intent); } public void datepick(View view) { if (view == selectDate) { final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { selectDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year); } }, mYear, mMonth, mDay); datePickerDialog.show(); } ubday = "" + mDay + "-" + mMonth + "-" + mYear; uage = currentYear - mYear; } public void chooseImage1() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { try { if (n == 1) { filePath1 = data.getData(); Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath1); coverpic.setImageBitmap(bitmap); } if (n == 2) { filePath2=data.getData(); Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath2); profilepic.setImageBitmap(bitmap); } } catch (IOException e) { e.printStackTrace(); } } } public void updateProfile(View view) { btnCover = findViewById(R.id.coverpicupdate); btnProfile = findViewById(R.id.profilepicupdate); profilepic = findViewById(R.id.profile_image); coverpic = findViewById(R.id.cover_image); TextView name1 = findViewById(R.id.name); EditText entername = (EditText)findViewById(R.id.entername); EditText Aboutme = (EditText)findViewById(R.id.aboutme); EditText email1 = (EditText)findViewById(R.id.email); RadioGroup gender = (RadioGroup)findViewById(R.id.gender); EditText address = (EditText)findViewById(R.id.Address); EditText phone = (EditText)findViewById(R.id.phone); EditText bday=(EditText)findViewById(R.id.date); int gen =0; RadioButton male=findViewById(R.id.male); gen=gender.getCheckedRadioButtonId(); RadioButton genradio = null; genradio= findViewById(gen); if(gen!=-1) ugender = genradio.getText().toString(); Spinner spinner = (Spinner) findViewById(R.id.spinner); Spinner spinner2 = (Spinner)findViewById(R.id.spinner2); Spinner spinner3 = (Spinner)findViewById(R.id.spinner3); Spinner spinner4 = (Spinner)findViewById(R.id.spinner4); Spinner spinner5 = (Spinner)findViewById(R.id.spinner5); uphoneno = phone.getText().toString(); uplace = address.getText().toString(); uaboutme = Aboutme.getText().toString(); currentYear = Calendar.getInstance().get(Calendar.YEAR); uname = entername.getText().toString(); ustate=spinner2.getSelectedItem().toString(); try{ ucity=spinner3.getSelectedItem().toString();} catch(Exception e){ } ugraduationlevel=spinner.getSelectedItem().toString(); ugraduationfield=spinner4.getSelectedItem().toString(); utypeofyouth=spinner5.getSelectedItem().toString(); if(filePath2==null) { TextView profileimg=findViewById(R.id.profileerr); profileimg.requestFocus(); profileimg.setError("Please change Profile Picture"); return; } if(filePath1==null) { TextView coverimg=findViewById(R.id.covererr); coverimg.requestFocus(); coverimg.setError("Please change Cover Picture"); return; } if(entername.getText().length()==0) { entername.requestFocus(); entername.setError("Please fill your name"); return; } if(email!=null) { uemail = email; } if(email1.getText().length()!=0){ uemail=email1.getText().toString(); } if(email1.getText().length()==0) { email1.requestFocus(); email1.setError("Please provide email"); return; } if(Aboutme.getText().length()==0) { Aboutme.requestFocus(); Aboutme.setError("Please Describe yourself"); return; } if (gender.getCheckedRadioButtonId() == -1) { male.requestFocus(); male.setError("Please select Gender"); return; } if(bday.getText().length()==0) { bday.requestFocus(); bday.setError("Provide your Birth date"); return; } if(address.getText().length()==0) { address.requestFocus(); address.setError("Provide your Address"); return; } if(spinner2.getSelectedItem()=="Select State") { TextView errorText = (TextView)spinner2.getSelectedView(); errorText.setError(""); errorText.setTextColor(Color.RED); errorText.setText("Select State"); return; } if(spinner3.getSelectedItem()==null||spinner3.getSelectedItem()=="Select City") { TextView errorText = (TextView)spinner3.getSelectedView(); errorText.setError(""); errorText.setTextColor(Color.RED); errorText.setText("Select City"); return; } if(phone.getText().length()==0) { phone.requestFocus(); phone.setError("Enter Mobile Number"); return; } if(spinner.getSelectedItem()=="Select") { TextView errorText = (TextView) spinner.getSelectedView(); errorText.setError(""); errorText.setTextColor(Color.RED);//just to highlight that this is an error errorText.setText("Select Graduation Level"); return; } if(spinner4.getSelectedItem()=="Select") { TextView errorText = (TextView) spinner4.getSelectedView(); errorText.setError(""); errorText.setTextColor(Color.RED);//just to highlight that this is an error errorText.setText("Select Graduation Field"); return; } if(spinner5.getSelectedItem()=="Select") { TextView errorText = (TextView) spinner5.getSelectedView(); errorText.setError(""); errorText.setTextColor(Color.RED);//just to highlight that this is an error errorText.setText("Select Type of Youth"); return; } if(filePath1 != null) { final ProgressDialog progressDialog = new ProgressDialog(this); // progressDialog.setTitle("Uploading..."); // progressDialog.show(); final StorageReference ref = storageReference.child("Cover_images").child(uid); ref.putFile(filePath1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { final Uri downloadUrl = uri; } }); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.dismiss(); Toast.makeText(UserProfile.this, "Failed to upload Cover Photo" + e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } if(filePath2 != null) { final ProgressDialog progressDialog = new ProgressDialog(this); // progressDialog.setTitle("Uploading..."); // progressDialog.show(); final StorageReference ref = storageReference.child("Profile_images").child(uid); ref.putFile(filePath2).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { final Uri downloadUrl = uri; } }); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.dismiss(); Toast.makeText(UserProfile.this, "Failed to upload Profile Photo"+e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } final MainActivity.User user = new MainActivity.User(uname,ugender ,uemail,uphotourl,uphoneno,ubday,uplace,ustate,ucity,uaboutme,ugraduationlevel,ugraduationfield,utypeofyouth,uage); myDatabase = FirebaseDatabase.getInstance().getReference(); final ProgressDialog progress=new ProgressDialog(this); progress.setTitle("Updating Profile.."); progress.show(); myDatabase.child("users").child(uid).setValue(user) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progress.dismiss(); Toast.makeText(UserProfile.this,"Failed to Update Profile",Toast.LENGTH_LONG).show(); } }) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { progress.dismiss(); AuthUI.getInstance().signOut(UserProfile.this); Intent i=new Intent(UserProfile.this,VideoActivity.class); startActivity(i); } }); } private void requestFocus(View view){ if(view.requestFocus()){ getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } }
package my.myapps.model.dao.hibernate; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import my.myapps.model.dao.BranchDao; import my.myapps.model.entity.Branch; import my.myapps.model.entity.Topic; @ContextConfiguration(locations = {"classpath:applicationContext-dao.xml"}) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true) @Transactional public class BranchHibernateDaoTest extends AbstractTransactionalTestNGSpringContextTests { @Autowired private BranchDao branchDao; @Autowired private SessionFactory sessionFactory; private Session session; @BeforeMethod public void setUp() throws Exception { session = sessionFactory.getCurrentSession(); } @Test public void testUpdate() { Branch branch = new Branch("Title1"); session.save(branch); branch.setTitle("Title2"); branchDao.saveOrUpdate(branch); branch = (Branch) session.get(Branch.class, branch.getId()); assertEquals(branch.getTitle(), "Title2"); } @Test public void testGetTopLevelBranches() { Branch branch1 = new Branch("Title1"); Branch branch2 = new Branch("Title2"); session.save(branch1); branch2.setParentId(branch1.getId()); session.save(branch2); List<Branch> resultBranches=branchDao.getTopLevelBranches(); assertTrue(resultBranches.contains(branch1),"Returned list doesn't contain a needed element"); assertFalse(resultBranches.contains(branch2),"Returned list contains wrong element"); } @Test public void testGetBranchTopics() { Branch branch = new Branch("BranchTitle"); Topic topic = new Topic("TopicTitle",new DateTime()); session.save(branch); topic.setBranch(branch); session.save(topic); List<Topic> resultTopics=branchDao.getBranchTopics(branch.getId()); assertTrue(resultTopics.contains(topic),"Returned list doesn't contain a needed element"); } }
import java.util.Iterator; public class TorteriaCal implements Menu{ private Ingrediente [] items; int posicion=0; public TorteriaCal(){ items = new Ingrediente [13]; for(int i=0;i<items.length;i++){ items[i]=new Ingrediente(i); } } public Iterator iterator(){ return new IteradorTorta(items); } public void imprime(){ Iterator t = this.iterator(); while(t.hasNext()){ Ingrediente menu = (Ingrediente)t.next(); System.out.println(menu); } } private class IteradorTorta implements Iterator{ private Ingrediente[] items; private int indice; public IteradorTorta(Ingrediente []a){ items = a; indice=0; } public Object next(){ Object temp = items[indice]; indice += 1; return temp; } public boolean hasNext(){ return !(indice>=items.length); } } }
package fm.ua.bacs.testtaskrestservice.controller; import fm.ua.bacs.testtaskrestservice.helpers.FTP; import fm.ua.bacs.testtaskrestservice.helpers.Helper; import fm.ua.bacs.testtaskrestservice.helpers.Props; import org.apache.commons.net.ftp.FTPFile; import org.springframework.web.bind.annotation.*; import javax.ws.rs.core.Response; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @RestController public class FileCheckController { @GetMapping("/filescan") public Response fileScanner(@RequestParam(name = "filename") String filename) throws IOException { return searchFile(filename, "199350"); } private Response searchFile(String filename, String search) throws IOException { Helper helper = new Helper(); FTP ftp = new FTP(); String message = "File not found"; int status = 404; /*----------------------- Code for working with local folders ----------------------------------*/ Props props = new Props(); Collection<File> all = new ArrayList<>(); helper.addTree(new File(props.getProperties().getProperty("local.in")), all); for (File file : all) { if (file.getName().equals(filename)) { if (searchInFile(file, search)) { if (ftp.uploadToFTP(file)) { message = "File has been found, checked and uploaded to server"; status = 200; } } else { message = "File has been found but string " + search + " was not found"; status = 404; } } } fm.ua.bacs.testtaskrestservice.helpers.Response response = new fm.ua.bacs.testtaskrestservice.helpers.Response(); return response.makeResponse(filename, message, status); } private boolean searchInFile(File filename, String search) { BufferedReader br = null; FileReader fr = null; try { fr = new FileReader(filename); br = new BufferedReader(fr); String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { if (sCurrentLine.equals(search)) { System.out.println(sCurrentLine); return true; } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); if (fr != null) fr.close(); } catch (IOException ex) { ex.printStackTrace(); } } return false; } }
package net.cglab.hotelpraktikum.dao; import java.util.List; import net.cglab.hotelpraktikum.hibernate.ActivityFields; import net.cglab.hotelpraktikum.hibernate.JobImages; import net.cglab.hotelpraktikum.hibernate.Jobs; public interface JobDao{ public Jobs getJob(Integer Id); public List<Jobs> getJobList(); public Integer saveJob(Jobs jobs); public Integer saveJobImage(JobImages jobImages); public Integer saveActivityField(ActivityFields field); }
package com.BookShare.web; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * 数据库操作类 * @author mq * */ public class BaseDao { //数据库地址“jdbc:mysql://服务器域名:端口号/数据库名称” private String url = "jdbc:mysql://120.24.222.231:3306/BookShare1?useUnicode=true&characterEncoding=utf-8"; //用户名 private String user = "root"; //用户密码 private String pwd = "qqqqqqqq"; //数据库链接对象 private java.sql.Connection conn; //数据库命令执行对象 private Statement pstmt; //数据库返回结果 private java.sql.ResultSet rs; //静态代码块 static{ //1、加载驱动 try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //2、创建连接 private void getConnection(){ if(conn == null){ try { conn = DriverManager.getConnection(url, user, pwd); } catch (SQLException e) { e.printStackTrace(); } } } //执行读操作方法 public java.sql.ResultSet executeQuery(String query){ getConnection(); //System.out.println(query); try { //3、创建命令执行对象 pstmt = conn.createStatement(); //4、执行 /*if(params!=null && params.size()>0){ for(int i=0;i<params.size();i++){ pstmt.setObject(i+1, params.get(i)); } }*/ rs = pstmt.executeQuery(query); } catch (SQLException e) { e.printStackTrace(); } return rs; } //执行写操作方法 public int executeUpdate(String query){ int result = 0; getConnection(); System.out.println(query); try { //3、创建命令执行对象 pstmt = conn.createStatement(); // //4、执行 // if(params!=null && params.size()>0){ // for(int i=0;i<params.size();i++){ // pstmt.setObject(i+1, params.get(i)); // } // } //5、处理结果 result = pstmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); }finally{ //6、释放资源 this.close(); } return result; } //关闭资源 // public void close(){ try { if(rs!=null){ rs.close(); rs = null; } if(pstmt!=null){ pstmt.close(); pstmt = null; } if(conn!=null){ conn.close(); conn = null; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.mabang.android.entity.vo; /** * 区域信息 * * @author xiong * */ @SuppressWarnings("serial") public class AreaInfo extends VoBase { private Integer areaId; private String areaName; private boolean check; public Integer getAreaId() { return this.areaId; } public void setAreaId(Integer areaId) { this.areaId = areaId; return; } public String getAreaName() { return this.areaName; } public void setAreaName(String areaName) { this.areaName = areaName; return; } public boolean isCheck() { return check; } public void setCheck(boolean check) { this.check = check; } }
package DemoRest.WebApp.model; import org.hibernate.annotations.GenericGenerator; import org.springframework.stereotype.Component; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List; @Component @Entity @Table(name = "bill") public class Bill { public enum paymentStatus { paid, due, past_due, no_payment_required; } @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") @Column(name = "id") private String id; @Column(name = "created_ts") private Date created_ts; @Column(name = "updated_ts") private Date updated_ts; @NotNull(message = "Owner Id is compulsory") @Column(name = "owner_id") private String ownerId; @NotNull(message = "vendor is compulsory") @Column(name = "vendor") private String vendor; @NotNull(message = "Bill date Id is compulsory") @Column(name = "bill_date") private Date bill_date; @NotNull(message = "Due Date is compulsory") @Column(name = "due_date") private Date due_date; @NotNull(message = "Amount due is compulsory") @Column(name = "amount_due") private Double amount_due; @NotNull(message = "categories is compulsory") @Column(name = "categories") private String categories; @NotNull(message = "paymentStatus is compulsory") @Enumerated(EnumType.STRING) @Column(name = "paymentStatus") private paymentStatus paymentStatus; public String getAttachment() { return attachment; } public void setAttachment(String attachment) { this.attachment = attachment; } @Column(name = "attachment") private String attachment; public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getCreated_ts() { return created_ts; } public void setCreated_ts(Date created_ts) { this.created_ts = created_ts; } public Date getUpdated_ts() { return updated_ts; } public void setUpdated_ts(Date updated_ts) { this.updated_ts = updated_ts; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor; } public Date getBill_date() { return bill_date; } public void setBill_date(Date bill_date) { this.bill_date = bill_date; } public Date getDue_date() { return due_date; } public void setDue_date(Date due_date) { this.due_date = due_date; } public Double getAmount_due() { return amount_due; } public void setAmount_due(Double amount_due) { this.amount_due = amount_due; } public String getCategories() { return categories; } public void setCategories(String categories) { this.categories = categories; } public paymentStatus getPaymentStatus() { return paymentStatus; } public void setPaymentStatus(paymentStatus paymentStatus) { this.paymentStatus = paymentStatus; } }
/** * Copyright (c) 2000-2016 Liferay, Inc. 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. * 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.liferay.store.monolith.purchase.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import javax.annotation.PostConstruct; import javax.faces.bean.ApplicationScoped; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import com.liferay.store.monolith.customer.model.Customer; import com.liferay.store.monolith.customer.service.CustomerService; import com.liferay.store.monolith.product.model.Product; import com.liferay.store.monolith.product.service.ProductService; import com.liferay.store.monolith.purchase.model.Purchase; import com.liferay.store.monolith.purchase.model.PurchaseImpl; /** * @author Neil Griffin */ @ManagedBean(eager = true, name = "purchaseService") @ApplicationScoped public class PurchaseServiceImpl implements PurchaseService { @ManagedProperty(value = "#{customerService}") private CustomerService customerService; @ManagedProperty(value = "#{productService}") private ProductService productService; private Map<Long, List<Purchase>> purchases; @Override public List<Purchase> getPurchases(long customerId) { return purchases.get(customerId); } @PostConstruct public void postConstruct() { purchases = new HashMap<Long, List<Purchase>>(); Random random = new Random(); for (Customer customer : customerService.getCustomers()) { List<Purchase> customerPurchases = new ArrayList<Purchase>(); List<Product> products = productService.getProducts(); int startPurchaseIndex = random.nextInt(5); int finishPurchaseIndex = random.nextInt(7) + startPurchaseIndex + 1; long purchaseId = 1L; for (int i = startPurchaseIndex; i < finishPurchaseIndex; i++) { int quantity = random.nextInt(5) + 1; PurchaseImpl purchase = new PurchaseImpl(purchaseId++, products.get(i), quantity); customerPurchases.add(purchase); } purchases.put(customer.getCustomerId(), customerPurchases); } } public void setCustomerService(CustomerService customerService) { // Injected via @ManagedProperty this.customerService = customerService; } public void setProductService(ProductService productService) { // Injected via @ManagedProperty this.productService = productService; } }
package org.osource.scd.parse.consumer; import org.osource.scd.parse.model.LargeData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.function.Consumer; /** * @author James */ public class SaveService implements Consumer<List<LargeData>> { private static final Logger LOGGER = LoggerFactory.getLogger(SaveService.class); private int sum = 0; @Override public void accept(List<LargeData> largeDataList) { sum = sum + largeDataList.size(); LOGGER.info("saved data size {}", largeDataList.size()); System.out.println(largeDataList); } @Override public Consumer<List<LargeData>> andThen(Consumer<? super List<LargeData>> after) { return null; } public int getSum() { return sum; } }
import java.io.*; public class ResponseReader { public static String getBody(BufferedReader buf) throws IOException { String line = null; StringBuilder builder = new StringBuilder(); while((line = buf.readLine()) != null) { builder.append(line); } return builder.toString(); } }
package com.sirma.itt.javacourse.inputOutput.test.task4.transferingObject; import static org.junit.Assert.*; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import org.junit.Before; import org.junit.Test; import com.sirma.itt.javacourse.inputoutput.task4.transferingObjects.TransferObject; /** * Class for testing the transferring data between files. * * @author simeon */ public class TestTransferObject { private TransferObject transporter; private TransferObject transporter2; private InputStream input; private OutputStream output; /** * Set up method. * * @throws java.lang.Exception * something went wrong */ @Before public void setUp() throws Exception { input = new FileInputStream(getClass().getResource("/Origin.txt").getFile()); output = new FileOutputStream(getClass().getResource("/Destination.txt").getFile()); transporter = new TransferObject(input, output); transporter2 = new TransferObject(input, null); } /** * Test method for * {@link com.sirma.itt.javacourse.inputoutput.task4.transferingObjects.TransferObject#transfer(int, int)} * . */ @Test public void testTransfer() { assertEquals(15, transporter.transfer(15, 0)); } /** * Test method for * {@link com.sirma.itt.javacourse.inputoutput.task4.transferingObjects.TransferObject#transfer(int, int)} * . Test when we use an overflowing offset. */ @Test public void testTransferOutOfrange() { assertEquals(-1, transporter.transfer(15, 10000)); } /** * Test method for * {@link com.sirma.itt.javacourse.inputoutput.task4.transferingObjects.TransferObject#transfer(int, int)} * . */ @Test public void testTransferToMuchBytes() { assertEquals(36, transporter.transfer(150000, 0)); } /** * Test method for * {@link com.sirma.itt.javacourse.inputoutput.task4.transferingObjects.TransferObject#transfer(int, int)} * . */ @Test(expected = NullPointerException.class) public void testTransferNullBuffer() { transporter2.transfer(15, 0); } }
/* * 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 com.ag.bean; import com.ag.beanI.EventBeanI; import com.ag.dao.EventDao; import com.ag.factory.DaoFactory; import com.ag.factory.DaoType; import com.ag.model.Event; import com.xag.util.NoMatchFoundException; import java.util.List; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.Persistence; import javax.persistence.PersistenceContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; /** * * @author agunga */ //@Service @Stateless public class EventBean implements EventBeanI { Logger log = LoggerFactory.getLogger(EventBean.class); @PersistenceContext(unitName = "eventaPU") EntityManager em; //EntityManager em = Persistence.createEntityManagerFactory("eventaPU").createEntityManager(); public EventDao getDao() { return (EventDao) new DaoFactory(DaoType.EVENT).getDao(em); } @Override public Event add(Event o) { try { return getDao().save(o); } catch (Exception e) { log.error(e.getMessage()); return null; } } @Override public Event update(Event o) { try { return getDao().merge(o); } catch (Exception e) { log.error(e.getMessage()); return null; } } @Override public List<Event> findAll() { return getDao().findAll(); } @Override public Event findById(long id) { try { return getDao().findById(id); } catch (NoMatchFoundException ex) { return null; } } @Override public boolean delete(Event o) { return getDao().remove(o); } @Override public int delete(long id) { return getDao().removeById(id); } }
package org.ohdsi.webapi.feanalysis; import org.ohdsi.analysis.cohortcharacterization.design.FeatureAnalysis; import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisDomain; import org.ohdsi.webapi.Pagination; import org.ohdsi.webapi.common.OptionDTO; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisEntity; import org.ohdsi.webapi.feanalysis.dto.FeAnalysisDTO; import org.ohdsi.webapi.feanalysis.dto.FeAnalysisShortDTO; import org.springframework.core.convert.ConversionService; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.List; @Path("/feature-analysis") @Controller public class FeAnalysisController { private FeAnalysisService service; private ConversionService conversionService; FeAnalysisController( final FeAnalysisService service, final ConversionService conversionService) { this.service = service; this.conversionService = conversionService; } @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Page<FeAnalysisShortDTO> list(@Pagination Pageable pageable) { return service.getPage(pageable).map(this::convertFeAnaysisToShortDto); } @GET @Path("/{id}/exists") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public int getCountFeWithSameName(@PathParam("id") @DefaultValue("0") final int id, @QueryParam("name") String name) { return service.getCountFeWithSameName(id, name); } @GET @Path("/domains") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public List<OptionDTO> listDomains() { List<OptionDTO> options = new ArrayList<>(); for(StandardFeatureAnalysisDomain enumEntry: StandardFeatureAnalysisDomain.values()) { options.add(new OptionDTO(enumEntry.name(), enumEntry.getName())); } return options; } @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public FeAnalysisDTO createAnalysis(final FeAnalysisDTO dto) { final FeAnalysisEntity createdEntity = service.createAnalysis(conversionService.convert(dto, FeAnalysisEntity.class)); return convertFeAnalysisToDto(createdEntity); } @PUT @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public FeAnalysisDTO updateAnalysis(@PathParam("id") final Integer feAnalysisId, final FeAnalysisDTO dto) { final FeAnalysisEntity updatedEntity = service.updateAnalysis(feAnalysisId, conversionService.convert(dto, FeAnalysisEntity.class)); return convertFeAnalysisToDto(updatedEntity); } @DELETE @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public void deleteAnalysis(@PathParam("id") final Integer feAnalysisId) { final FeAnalysisEntity entity = service.findById(feAnalysisId).orElseThrow(NotFoundException::new); service.deleteAnalysis(entity); } @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public FeAnalysisDTO getFeAnalysis(@PathParam("id") final Integer feAnalysisId) { final FeAnalysisEntity feAnalysis = service.findById(feAnalysisId) .orElseThrow(NotFoundException::new); return convertFeAnalysisToDto(feAnalysis); } private FeAnalysisShortDTO convertFeAnaysisToShortDto(final FeatureAnalysis entity) { return conversionService.convert(entity, FeAnalysisShortDTO.class); } private FeAnalysisDTO convertFeAnalysisToDto(final FeatureAnalysis entity) { return conversionService.convert(entity, FeAnalysisDTO.class); } }
package com.example.tateti; public enum State { NOT_STARTED, MI_TURNO, WAITING_FOR_AWAY_PLAYER; }
package io.youngwon.app.utils; public class ApiResponse<T> { private final boolean success; private final T data; // private final ApiError error; public ApiResponse(boolean success, T data){ this.success = success; this.data = data; } // public class ApiError { // // } }
package com.asgab.web.business.opportunity; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.alibaba.fastjson.JSONObject; import com.asgab.core.pagination.Page; import com.asgab.entity.BusinessOpportunity; import com.asgab.service.business.opportunity.BusinessOpportunityService; import com.asgab.util.CommonUtil; import com.asgab.util.Servlets; @Controller @RequestMapping(value = "/businessOpportunity") public class BusinessOpportunityController { private static final String PAGE_SIZE = "10"; @Autowired private BusinessOpportunityService businessOpportunityService; @RequestMapping(method = RequestMethod.GET) public String list(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber, @RequestParam(value = "pageSize", defaultValue = PAGE_SIZE) int pageSize, @RequestParam(value = "sort", defaultValue = "id desc") String sort, ServletRequest request, Model model) { Map<String, Object> params = new HashMap<String, Object>(); String number = request.getParameter("number"); if (StringUtils.isNotBlank(number)) { params.put("number", number); params.put("fmt_number", number.replace("SO", "").replaceFirst("^0*", "")); } if (StringUtils.isNotBlank(request.getParameter("advertiser"))) { params.put("advertiser", request.getParameter("advertiser")); } if (StringUtils.isNotBlank(request.getParameter("name"))) { params.put("name", request.getParameter("name")); } if (StringUtils.isNotBlank(request.getParameter("status"))) { params.put("status", request.getParameter("status")); } model.addAttribute("search", Servlets.encodeParameterString(params)); params.put("sort", sort); Page<BusinessOpportunity> page = new Page<BusinessOpportunity>(pageNumber, pageSize, sort, params); Page<BusinessOpportunity> pages = businessOpportunityService.search(page); model.addAttribute("pages", pages); model.addAttribute("statusesMap", BusinessOpportunityService.statusMap); model.addAttribute("statusesZH", BusinessOpportunityService.statusZH); model.addAttribute("statusesEN", BusinessOpportunityService.statusEN); return "businessOpportunity/businessOpportunityList"; } @RequestMapping(value = "create", method = RequestMethod.GET) public String toCreate(Model model, HttpServletRequest request) { BusinessOpportunity businessOpportunity = new BusinessOpportunity(); businessOpportunity.setProgress(10); businessOpportunity.setExist_msa(1); businessOpportunity.setExist_service(1); model.addAttribute("businessOpportunity", businessOpportunity); model.addAttribute("action", "create"); return "businessOpportunity/businessOpportunityForm"; } @RequestMapping(value = "create", method = RequestMethod.POST) public String create(BusinessOpportunity businessOpportunity, HttpServletRequest request, RedirectAttributes redirectAttributes) { businessOpportunity.setDeliver_start_date(businessOpportunity.getDeliver_date().substring(0, 10)); businessOpportunity.setDeliver_end_date(businessOpportunity.getDeliver_date().substring(13, 23)); businessOpportunityService.save(businessOpportunity); redirectAttributes.addFlashAttribute("message", CommonUtil.getProperty(request, "message.create.success")); return "redirect:/businessOpportunity"; } @RequestMapping(value = "update", method = RequestMethod.POST) public String update(@ModelAttribute("businessOpportunity") BusinessOpportunity businessOpportunity, HttpServletRequest request, RedirectAttributes redirectAttributes) { String result = businessOpportunityService.update(businessOpportunity); if (result != null) { String orderMessage = ""; JSONObject jsonObject = JSONObject.parseObject(result); if (jsonObject.containsKey("success")) { if (jsonObject.getBoolean("success")) { orderMessage = CommonUtil.getProperty(request, "message.create.order.success") + ", "; orderMessage += CommonUtil.getProperty(request, "message.create.order.id") + ": " + jsonObject.getInteger("order_id"); } else { orderMessage = CommonUtil.getProperty(request, "message.create.order.error"); } } else { // token access denied orderMessage = CommonUtil.getProperty(request, "message.token.denied"); } redirectAttributes.addFlashAttribute("orderMessage", orderMessage); } redirectAttributes.addFlashAttribute("message", CommonUtil.getProperty(request, "message.update.success")); return "redirect:/businessOpportunity"; } @RequestMapping(value = "delete/{id}", method = RequestMethod.GET) public String delete(@PathVariable("id") Long id, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) { businessOpportunityService.delete(id); redirectAttributes.addFlashAttribute("message", CommonUtil.getProperty(request, "message.delete.success")); return "redirect:/businessOpportunity"; } @RequestMapping(value = "addProduct", method = RequestMethod.POST) public String addProduct(HttpServletRequest request, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("index", request.getParameter("index")); return "businessOpportunity/product"; } @ModelAttribute public void getCustMaster(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) { if (id != -1) { model.addAttribute("businessOpportunity", businessOpportunityService.get(id)); } } }
package com.androidbook.SuperPetTracker; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteQueryBuilder; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import com.androidbook.SuperPetTracker.SuperPetTrackerDatabase.PetType; import com.androidbook.SuperPetTracker.SuperPetTrackerDatabase.Pets; public class SuperPetTrackEntry extends SuperPetTracker { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.petentry); // Fill AutoComplete word list from database fillAutoCompleteFromDatabase(); // Handle Save Button final Button savePet = (Button) findViewById(R.id.ButtonSave); savePet.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final EditText petName = (EditText) findViewById(R.id.EditTextName); final EditText petType = (EditText) findViewById(R.id.EditTextSpecies); // Save new records mDB.beginTransaction(); try { // check if species type exists already long rowId = 0; String strPetType = petType.getText().toString() .toLowerCase(); // SQL Query SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); queryBuilder.setTables(PetType.PETTYPE_TABLE_NAME); queryBuilder.appendWhere(PetType.PET_TYPE_NAME + "='" + strPetType + "'"); // run the query since it's all ready to go Cursor c = queryBuilder.query(mDB, null, null, null, null, null, null); if (c.getCount() == 0) { // add the new type to our list ContentValues typeRecordToAdd = new ContentValues(); typeRecordToAdd.put(PetType.PET_TYPE_NAME, strPetType); rowId = mDB.insert(PetType.PETTYPE_TABLE_NAME, PetType.PET_TYPE_NAME, typeRecordToAdd); // Update autocomplete with new record fillAutoCompleteFromDatabase(); } else { c.moveToFirst(); rowId = c.getLong(c.getColumnIndex(PetType._ID)); } c.close(); // Always insert new pet records, even if the names clash ContentValues petRecordToAdd = new ContentValues(); petRecordToAdd.put(Pets.PET_NAME, petName.getText() .toString()); petRecordToAdd.put(Pets.PET_TYPE_ID, rowId); mDB.insert(Pets.PETS_TABLE_NAME, Pets.PET_NAME, petRecordToAdd); mDB.setTransactionSuccessful(); } finally { mDB.endTransaction(); } // reset form petName.setText(null); petType.setText(null); } }); // Handle Go to List button final Button gotoList = (Button) findViewById(R.id.ButtonShowPets); gotoList.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Go to other activity that displays pet list Intent intent = new Intent(SuperPetTrackEntry.this, SuperPetList.class); startActivity(intent); } }); } // This method is similar to the one in PetTracker, only we let the Activity manage the Cursor for us, and keep it around // This is still not the ideal method of binding SQLite data to an AutoCompleteTextView. See MediaPetTracker for a more appropriate method void fillAutoCompleteFromDatabase() { mCursor = mDB.query(PetType.PETTYPE_TABLE_NAME, new String[] {PetType.PET_TYPE_NAME, PetType._ID}, null, null, null, null, PetType.DEFAULT_SORT_ORDER); // Have the Activity manage the cursor for us cause we're lazy and don't want to override onPause and such. startManagingCursor(mCursor); // Quick and dirty, this method is not using database data-binding, instead, we spin through the Cursor and make an Array Adapter int iNumberOfSpeciesTypes = mCursor.getCount(); String astrAutoTextOptions[] = new String[iNumberOfSpeciesTypes]; if((iNumberOfSpeciesTypes > 0) && (mCursor.moveToFirst())) { for(int i = 0; i < iNumberOfSpeciesTypes; i++) { astrAutoTextOptions[i] = mCursor.getString(mCursor.getColumnIndex(PetType.PET_TYPE_NAME)); mCursor.moveToNext(); } ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_dropdown_item_1line, astrAutoTextOptions); AutoCompleteTextView text = (AutoCompleteTextView) findViewById(R.id.EditTextSpecies); text.setAdapter(adapter); } } }
/* * 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 poo.consultorio; import java.util.Date; /** * * @author Candelaria */ public class Consulta { private Date horaFin; private Date horaInicio; private String descripcion; /** * Constructor por Defecto. */ public Consulta() { } /** * Constructor con parámetros, sin incluir atributos referenciales. * @param horaFin * @param horaInicio * @param descripcion */ public Consulta(Date horaFin, Date horaInicio, String descripcion) { this.horaFin = horaFin; this.horaInicio = horaInicio; this.descripcion = descripcion; } public Date getHoraFin() { return horaFin; } public void setHoraFin(Date horaFin) { this.horaFin = horaFin; } public Date getHoraInicio() { return horaInicio; } public void setHoraInicio(Date horaInicio) { this.horaInicio = horaInicio; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } }
package org.dbdoclet.test.option; import junit.framework.Test; import junit.framework.TestSuite; import org.dbdoclet.log.Logger; import org.dbdoclet.service.ExecResult; import org.dbdoclet.service.ExecServices; import org.dbdoclet.service.FileServices; import org.dbdoclet.service.XmlServices; import org.dbdoclet.service.XmlValidationResult; public class BookTypeTests extends OptionTestCase { private static Log logger = LogFactory.getLog(BookTypeTests.class.getName()); public BookTypeTests(String name) { super(name); } public static Test suite() { return new TestSuite(BookTypeTests.class); } public void testBookTypeBook() { try { String sourceFileName = FileServices.appendFileName(sourcePath, "TestOption.java"); String destPath = FileServices.appendPath(tmpPath, getName()); String[] cmd = { "dbdoclet", "-d" , destPath, "--book-type", "book", "--style-type", "listing", sourceFileName }; ExecResult result = ExecServices.exec(cmd); if (result.getExitCode() != 0) { logger.fatal(result.getOutput()); fail("Execution of dbdoclet failed!"); } logger.info(result.getOutput()); String fileName = FileServices.appendFileName(destPath, "Reference.xml"); XmlValidationResult vres = XmlServices.validate(fileName); if (vres.failed() == true) { fail("Validation of " + fileName + " failed! " + vres.createTextReport()); } String buffer = FileServices.readToString(fileName); if (buffer.indexOf("<refnamediv>") != -1) { fail("A book document should be created!"); } } catch (Exception oops) { fail("Exception: " + oops.getClass().getName()); } } public void testBookTypeReference() { try { String sourceFileName = FileServices.appendFileName(sourcePath, "TestOption.java"); String destPath = FileServices.appendPath(tmpPath, getName()); String[] cmd = { "dbdoclet", "-d" , destPath, "--book-type", "reference", "--style-type", "strict", sourceFileName }; ExecResult result = ExecServices.exec(cmd); if (result.getExitCode() != 0) { logger.fatal(result.getOutput()); fail("Execution of dbdoclet failed!"); } logger.info(result.getOutput()); String fileName = FileServices.appendFileName(destPath, "Reference.xml"); XmlValidationResult vres = XmlServices.validate(fileName); if (vres.failed() == true) { fail("Validation of " + fileName + " failed! " + vres.createTextReport()); } String buffer = FileServices.readToString(fileName); if (buffer.indexOf("<refnamediv>") == -1) { fail("A reference book should be created!"); } } catch (Exception oops) { fail("Exception: " + oops.getClass().getName()); } } }
package king_tokyo_power_up.game.card; /** * Target enum is used to decide which monsters to target. * This can be used with terminal/ attacking/ card effects etc. */ public enum Target { /** * Effects your self. */ SELF, /** * Effects only other monsters. */ OTHERS, /** * Effects everyone. */ ALL, /** * Effects monsters in Tokyo */ IN_TOKYO, /** * Effects monsters outside Tokyo. */ OUTSIDE_TOKYO, }
package com.beike.util; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.StringReader; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.xml.sax.InputSource; /** * @title: XmlUtils.java * @package com.beike.util * @description: xml工具类 * @author wangweijie * @date 2012-6-26 下午05:19:19 * @version v1.0 */ public class XmlUtils { private static String delimiter = ";"; /** * xml转化成map * @param xml * @return */ public static Map<String,String> xml2Map(String xml) throws JDOMException,IOException{ if(null==xml || "".equals(xml.trim())) return null; // 创建一个新的字符串 StringReader xmlString = new StringReader(xml); // 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入 InputSource source = new InputSource(xmlString); SAXBuilder saxBuilder = new SAXBuilder(false); //使用默认解析器 Map<String,String> xmlMap = null; try { // 通过输入源构造一个Document Document doc = saxBuilder.build(source); // 取的根元素 Element root = doc.getRootElement(); //获得所有叶子节点 List<Element> elementList = getLeafElement(root); xmlMap = new HashMap<String,String>(elementList.size()); for(Element element : elementList){ String key = element.getName(); String value = element.getValue(); //不添加空 元素 if(null == key || "".equals(key.trim()) || null == value || "".equals(value.trim())){ continue; } if(xmlMap.containsKey(key)){ value = xmlMap.get(key) + delimiter + value; //存在多个元素key一样,value值以;分割 }else{ xmlMap.put(key, value); } } } catch (JDOMException e) { e.printStackTrace(); throw e; } catch (IOException e) { e.printStackTrace(); throw e; } return xmlMap; } /** * 获得所有叶子节点 * @param element * @return */ @SuppressWarnings("unchecked") private static List<Element> getLeafElement(Element element){ List<Element> elementList = new ArrayList<Element>(); List<Element> childrenList = element.getChildren(); if(null !=childrenList && childrenList.size()>0){ for(Element childElement : childrenList){ elementList.addAll(getLeafElement(childElement)); } }else{ elementList.add(element); } return elementList; } public static String object2xml(String xmlHead,String rootElement,Object objectXml){ if(null == xmlHead || "".equals(xmlHead.trim())){ xmlHead = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; } StringBuffer xml = new StringBuffer(xmlHead); xml.append(elmentObject2xml(rootElement,objectXml)); return xml.toString(); } @SuppressWarnings("unchecked") private static String elmentObject2xml(String elementName ,Object objectXml){ StringBuffer xml = new StringBuffer(""); if(null == objectXml){ xml.append(""); }else{ //List if(objectXml instanceof List){ List listXml = (List)objectXml; for(Object subObjectXml : listXml){ xml.append(elmentObject2xml(elementName,subObjectXml)); } } //Set else if (objectXml instanceof Set){ Set setXml = (Set)objectXml; for(Object subObjectXml : setXml){ xml.append(elmentObject2xml(elementName,subObjectXml)); } } //数组 else if(objectXml instanceof Object[]){ Object[] arrayXml = (Object[])objectXml; for(Object subObjectXml : arrayXml){ xml.append(elmentObject2xml(elementName,subObjectXml)); } } //map else if(objectXml instanceof Map){ Map mapXml = (Map)objectXml; xml.append("<" + elementName + ">"); for(Object key : mapXml.keySet()){ xml.append(elmentObject2xml(key.toString(),mapXml.get(key))); } xml.append("<" + elementName + ">"); } //其他基本类型 else if(objectXml instanceof String || objectXml instanceof Integer || objectXml instanceof Float || objectXml instanceof Boolean || objectXml instanceof Short || objectXml instanceof Double || objectXml instanceof Long || objectXml instanceof BigDecimal || objectXml instanceof BigInteger || objectXml instanceof Byte || objectXml instanceof Date){ xml.append("<" + elementName + ">"); xml.append(objectXml); xml.append("<" + elementName + ">"); } //bean else{ PropertyDescriptor[] props = null; try { props = Introspector.getBeanInfo(objectXml.getClass(), Object.class).getPropertyDescriptors(); } catch (IntrospectionException e) {} if (props != null) { xml.append("<" + elementName + ">"); for (int i = 0; i < props.length; i++) { try { xml.append(elmentObject2xml(props[i].getName(),props[i].getReadMethod().invoke(objectXml))); } catch (Exception e) {} } xml.append("<" + elementName + ">"); } else { xml.append("<" + elementName + "><" + elementName + ">"); } } } return xml.toString(); } // public static void main(String[] args) throws Exception { // String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" // +"<alipay xmlns=\"http://tuan.360buy.com/SendOrderRequest\">" // +"<is_success>T</is_success>" // +"<request>" // +"<param name=\"_input_charset\">UTF-8</param>" // +"<param name=\"service\">single_trade_query</param>" // +"<param name=\"partner\">2088601322494371</param>" // +"<param name=\"out_trade_no\">QAPay00967461R</param>" // +"</request>" // +"<response>" // +"<trade>" // +"<body>0.15-11111111020-12497-1020-880397</body>" // +"<buyer_email>huangyuan@vip.qq.com</buyer_email>" // +"<buyer_id>2088002014080601</buyer_id>" // +"<coupon_used_fee>0.00</coupon_used_fee>" // +"<discount>0.00</discount>" // +"<flag_trade_locked>0</flag_trade_locked>" // +"<gmt_create>2012-06-25 16:56:50</gmt_create>" // +"<gmt_last_modified_time>2012-06-25 16:56:51</gmt_last_modified_time>" // +"<gmt_payment>2012-06-25 16:56:51</gmt_payment>" // +"<is_total_fee_adjust>F</is_total_fee_adjust>" // +"<operator_role>B</operator_role>" // +"<out_trade_no>QAPay00967461R</out_trade_no>" // +"<payment_type>1</payment_type>" // +"<price>0.01</price>" // +"<quantity>1</quantity>" // +"<seller_email>alipay@qianpin.com</seller_email>" // +"<seller_id>2088601322494371</seller_id>" // +"<subject>这个是测试......</subject>" // +"<to_buyer_fee>0.00</to_buyer_fee>" // +"<to_seller_fee>0.01</to_seller_fee>" // +"<total_fee>0.01</total_fee>" // +"<trade_no>2012062547948360</trade_no>" // +"<trade_status>TRADE_FINISHED</trade_status>" // +"<use_coupon>F</use_coupon>" // +"</trade>" // +"</response>" // +"<sign>59019996449ac9f31b99349df28c56c6</sign>" // +"<sign_type>MD5</sign_type>" // +"</alipay>"; // // System.out.println(XmlUtils.xml2Map(xml)); // // // Map<String,Object> map = new HashMap<String, Object>(); // Map<String,Object> subMap = new HashMap<String, Object>(); // subMap.put("totalCount", "1"); // subMap.put("errorCount", "2"); // // Map<String,Object> thirdMap = new HashMap<String, Object>(); // List<Map<String,String>> list = new ArrayList<Map<String,String>>(); // for(int i=0;i<3;i++){ // Map<String,String> _3map = new HashMap<String, String>(); // _3map.put("voucherCode", "voucherCode_"+i); // _3map.put("issueTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); // _3map.put("consumptionTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); // _3map.put("voucherCount", "voucherCount_"+i); // list.add(_3map); // } // thirdMap.put("VoucherInfo", list); // // subMap.put("voucherInfoList",thirdMap); // String[] s = new String[]{"1","2","3","4"}; // subMap.put("testList", s); // System.out.println(XmlUtils.object2xml("", "response", subMap)); // } }
package com.capella.mvc.example.controllers; import java.net.InetAddress; import java.time.LocalDateTime; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import redis.clients.jedis.Jedis; @Controller public class HelloController { private static final Logger LOGGER = LoggerFactory .getLogger(HelloController.class); @Autowired private Jedis jedis; public HelloController() { } @RequestMapping(value = { "/" }) public ModelAndView handleRequest(HttpServletRequest request) throws Exception { if (!jedis.exists("COUNT")) { jedis.set("COUNT", "0"); } ModelAndView model = new ModelAndView("index"); model.addObject("dateTime", LocalDateTime.now()); model.addObject("hostName", InetAddress.getLocalHost()); model.addObject("sessionId", request.getSession().getId()); model.addObject("count", jedis.incr("COUNT")); return model; } }
package com.nibu.atm; import java.util.ArrayList; import java.util.List; public class TransactionsProcessor { //These should be processed automatically. private List<AutoTransaction> autoTransactions; private BankAccountAccess accountAccess; public TransactionsProcessor(ArrayList<AutoTransaction> autoTransactions, BankAccountAccess accountAccess) { this.autoTransactions = autoTransactions; this.accountAccess = accountAccess; for (int i = 0; i < autoTransactions.size(); i++) { Account from = accountAccess.get(autoTransactions.get(i).getCardFromNumber()); from.autoTransactions.add(autoTransactions.get(i)); } } public boolean add(Transaction transaction) { if (transaction instanceof AutoTransaction) { AutoTransaction t = (AutoTransaction) transaction; autoTransactions.add(t); Account from = accountAccess.get(t.from); from.autoTransactions.add(t); } else { Account from = accountAccess.get(transaction.from); Account to = accountAccess.get(transaction.to); if (transaction.process(from, to)) {//Transaction was successful if (to.protectingAccount != null) { if (to.balance > to.protectMoneyAmount) { add(new Transaction(to.getCardNumber(), to.getProtectingAccount(), to.balance - to.protectMoneyAmount)); } } } else return false; } return true; } public ArrayList<Transaction> getAutoTransactions() { return new ArrayList<Transaction>(autoTransactions); } }
//PRIORITY QUEUE import java.util.*; class Books implements Comparable<Books>{ int id; String name,author; Books(int id, String name, String author){ this.id=id; this.name=name; this.author=author; } public int compareTo(Books b){ if(id>b.id){return 1;} else if(id==b.id){return 0;} else {return -1;} } } class LinkedListExample{ public static void main(String []z){ Books b1=new Books(1,"krishan","bla1 bla1"); Books b2=new Books(2,"Gulati","bla2 bla2"); Books b3=new Books(3,"Bhawesh","bla3 bla3"); LinkedList <Books> lk=new LinkedList<>(); lk.add(b1); lk.add(b2); lk.add(b3); for(Books b:lk){ System.out.println(""+b.id+" "+b.name+" "+b.author); } lk.remove(); System.out.println("\nAfter removing from the queue\n"); for(Books b:lk){ System.out.println(""+b.id+" "+b.name+" "+b.author); } } }
package com.hlx.service; import com.hlx.config.PrizeEnum; import com.hlx.config.RuleConfig; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.regex.Pattern; /** * A recognize service that format and recognize the game result * @author hlx * @version 1.0 2018-3-16 */ @Service public class RecognitionServiceImpl implements RecognitionService{ private static final Logger logger = Logger.getLogger(RecognitionServiceImpl.class); public PrizeEnum recognize(String result) { String formatResult = formatResult(result); logger.info(formatResult); if (Pattern.matches(RuleConfig.FLOWERPATTERN, formatResult)) { return PrizeEnum.FLOWER; } else if (Pattern.matches(RuleConfig.SIXPATTERN, formatResult)) { return PrizeEnum.SIX; } else if (Pattern.matches(RuleConfig.FIVEPATTERN, formatResult)) { return PrizeEnum.FIVE; }else if (Pattern.matches(RuleConfig.CHIEFPATTERN, formatResult)) { return PrizeEnum.CHIEF; } else if (Pattern.matches(RuleConfig.PAIRPATTERN, formatResult)) { return PrizeEnum.PAIR; } else if (Pattern.matches(RuleConfig.REDPATTERN, formatResult)) { return PrizeEnum.RED; } else if (Pattern.matches(RuleConfig.ENTERPATTERN, formatResult)) { return PrizeEnum.ENTER; } else if (Pattern.matches(RuleConfig.LIFTPATTERN, formatResult)) { return PrizeEnum.LIFT; } else if (Pattern.matches(RuleConfig.SHOWPATTERN, formatResult)) { return PrizeEnum.SHOW; }else{ return PrizeEnum.BLANK; } } private String formatResult(String result) { int[] resultNum = new int[result.length()]; for(int i=0;i<result.length();i++) { resultNum[i] = Character.getNumericValue(result.charAt(i)); } Arrays.sort(resultNum); return Arrays.toString(resultNum) .replaceAll("(\\[|]|, )",""); } }
package com.croquis.crary.sample; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.croquis.crary.app.CraryActionBarActivity; import java.util.ArrayList; import rx.functions.Action1; import rx.subjects.PublishSubject; public class MainActivity extends CraryActionBarActivity { PublishSubject<Void> mReactiveError = PublishSubject.create(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); subscribe(mReactiveError, new Action1<Void>() { @Override public void call(Void aVoid) { throw new RuntimeException("Error while handling event"); } }); ArrayList<String> titleList = new ArrayList<String>(); titleList.add("Dialog"); titleList.add("Open Browser"); titleList.add("Reactive Error"); ListView listView = findViewById(R.id.listView); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, titleList); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (i == 0) { Intent intent = new Intent(MainActivity.this, DialogActivity.class); startActivity(intent); } else if (i == 1) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")); startActivity(intent); } else if (i == 2) { mReactiveError.onNext(null); } } }); } }
package com.example.core.handle; public interface GetHandler<T> { T doGet(String module); }
package net.myinfosys.desembertraining.swing.button; import javax.swing.ImageIcon; import javax.swing.JFrame; public class ButtonTest { public static void main(String[] args) { // TODO Auto-generated method stub JFrame frame = new JFrame("JButton"); frame.setSize(700, 600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); //get image icon ImageIcon image = new ImageIcon("logo.jpg"); frame.setIconImage(image.getImage()); Panel panel = new Panel(); frame.setJMenuBar(panel.menuBar); frame.add(panel); frame.setVisible(true); } }
package com.cbsystematics.edu.internet_shop.controller; import com.cbsystematics.edu.internet_shop.service.DiscountService; import com.cbsystematics.edu.internet_shop.service.ProductService; import com.cbsystematics.edu.internet_shop.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping(value = "/admin") public class AdminController { private final UserService userService; private final ProductService productService; private final DiscountService discountService; @Autowired public AdminController(UserService userService, ProductService productService, DiscountService discountService) { this.userService = userService; this.productService = productService; this.discountService = discountService; } @RequestMapping(method = RequestMethod.GET) public ModelAndView home(ModelAndView modelAndView) { modelAndView.addObject("users", userService.getAll()); modelAndView.addObject("products", productService.getAll()); modelAndView.addObject("discounts", discountService.getAll()); modelAndView.setViewName("admin"); return modelAndView; } }
package com.example.vplayer.dialog; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import com.example.vplayer.R; import com.example.vplayer.fragment.adapter.PlayListAdapter; import com.example.vplayer.fragment.event.RenameEvent; import com.example.vplayer.fragment.event.UpdateAdapterEvent; import com.example.vplayer.fragment.utils.PreferencesUtility; import com.example.vplayer.fragment.utils.RxBus; import com.example.vplayer.fragment.utils.VideoPlayerUtils; import com.example.vplayer.model.Video; import com.example.vplayer.ui.fragment.PlaylistFragment; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import static com.example.vplayer.ui.fragment.PlaylistFragment.allPlaylist; public class DeletePlaylistDialog extends DialogFragment { Context context; String title; long id; public static PreferencesUtility preferencesUtility; TextView btnCancel, btnDelete; public static DeletePlaylistDialog getInstance(Activity context, String title) { DeletePlaylistDialog dialog = new DeletePlaylistDialog(); dialog.context = context; dialog.title = title; dialog.setStyle(DialogFragment.STYLE_NO_TITLE, R.style.WideDialog); return dialog; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.dialog_delete, container, false); btnDelete = v.findViewById(R.id.btnDelete); btnCancel = v.findViewById(R.id.btnCancel); return v; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); preferencesUtility = PreferencesUtility.getInstance(context); //btnRename.setTextColor(ATEUtil.getThemeAccentColor(context)); /* renameText.setText(title);*/ //renameText.setSelection(title.length()); btnCancel.setOnClickListener(view1 -> { getDialog().dismiss(); }); btnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* if (!renameText.getText().toString().isEmpty()) { if (!renameText.getText().toString().equalsIgnoreCase(title)) {*/ // set rename LinkedHashMap<String, String> playlists = preferencesUtility.getPlaylists(); if (playlists.containsKey(title)) { getDialog().dismiss(); playlists.remove(title); } preferencesUtility.setPlaylists(playlists); /*PlaylistFragment.playListAdapter = new PlayListAdapter(getContext(), preferencesUtility.getPlaylists()); PlaylistFragment.videoLList.setAdapter(PlaylistFragment.playListAdapter);*/ //PlaylistFragment.playListAdapter.notifyDataSetChanged(); RxBus.getInstance().post(new UpdateAdapterEvent()); /* } else { // set rename getDialog().dismiss(); Toast.makeText(context, "Same playlist name cannot be updated", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), "New name can't be empty.", Toast.LENGTH_SHORT).show(); }*/ } }); } /* private void showRenameValidationDialog() { Dialog validationDialog = new Dialog(getContext(), R.style.WideDialog); validationDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); validationDialog.setCancelable(true); validationDialog.setContentView(R.layout.dialog_rename_same_name_validation); validationDialog.setCanceledOnTouchOutside(true); validationDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); validationDialog.getWindow().setGravity(Gravity.CENTER); LinearLayout btn_ok; btn_ok = validationDialog.findViewById(R.id.btn_ok); btn_ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { validationDialog.dismiss(); } }); validationDialog.show(); } */ /* private void reNameFile(File file, String newName) { File file2 = new File(file.getParent() + "/" + newName); Log.e("1", "file name: " + file.getPath()); Log.e("2", "file2 name: " + file2.getPath()); if (file2.exists()) { Log.e("rename", "File already exists!"); showRenameValidationDialog(); } else { boolean renamed = false; if (sdCardPath != null && !sdCardPath.equalsIgnoreCase("") && file.getPath().contains(sdCardPath)) { renamed = VideoPlayerUtils.renameFile(file, newName, getContext()); } else { renamed = file.renameTo(file2); } if (renamed) { Log.e("LOG", "File renamed..."); MediaScannerConnection.scanFile(getContext(), new String[]{file2.getPath()}, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { // Log.i("ExternalStorage", "Scanned " + path + ":" + uri); } }); Toast.makeText(getContext(), "Rename file successfully", Toast.LENGTH_SHORT).show(); RxBus.getInstance().post(new RenameEvent(file, file2)); } else { Log.e("LOG", "File not renamed..."); } // storageList.clear(); // getFilesList(arrayListFilePaths.get(arrayListFilePaths.size() - 1)); } }*/ }