text
stringlengths
10
2.72M
package com.swjt.xingzishop.enums; import lombok.Getter; @Getter public enum RandCode { EMAIL("email-code"), PHONE("phone-code"), PHONE_NUMBER("phone-number"), EMAIL_NUMBER("email-address"), CAPTCHA("captcha"); private String type; RandCode(String type) { this.type = type; } }
public class SoundTest { public static void main(String[] args) { int[] values = {0,0,25,300,-400,26,0,-555,16,333,0,0,0}; Sound sound1 = new Sound(values); System.out.println(sound1); int changes = sound1.limitAmplitude(200); System.out.println("Number of changes made: " + changes); System.out.println(sound1); sound1.trimSilenceFromBeginning(); System.out.println(sound1); sound1.trimSilenceFromEnd(); System.out.println(sound1); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); TerminalImpl terminal = new TerminalImpl(); int pin = 0; while (true) { System.out.print("Введите pin: "); pin = scanner.nextInt(); terminal.getMenu(pin); } } }
package factories; import domain.Lecturer; import java.util.Map; /** * Created by rodrique on 8/11/2017. */ public class LecturerFactory { public static Lecturer getStudent(Map<String,String> values, int empNo) {Lecturer lecturer = new Lecturer.Builder() .empNo(empNo) .lectName(values.get("Lecturer Name:")) .build(); return lecturer; } }
package com.wkrzywiec.spring.library.validation; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.springframework.stereotype.Component; @Component public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber, String>{ @Override public boolean isValid(String value, ConstraintValidatorContext context) { return value != null && value.matches("[0-9]{9}"); } }
/** * Created by Adolph on 2017/8/11. */ public class chapter4_11_1 { public static void main(String[] args){ System.out.println("fd"); int a = 1; if (a==1){ System.out.println("正确!"); }else{ System.out.println("错误!"); } } }
/* * 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.test.context.support; import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.SpringProperties; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.lang.Nullable; import org.springframework.test.context.TestConstructor; import org.springframework.test.context.TestConstructor.AutowireMode; import org.springframework.test.context.TestContextAnnotationUtils; /** * Utility methods for working with {@link TestConstructor @TestConstructor}. * * <p>Primarily intended for use within the framework. * * @author Sam Brannen * @since 5.2 * @see TestConstructor */ public abstract class TestConstructorUtils { private TestConstructorUtils() { } /** * Determine if the supplied executable for the given test class is an * autowirable constructor. * <p>This method delegates to {@link #isAutowirableConstructor(Executable, Class, PropertyProvider)} * will a value of {@code null} for the fallback {@link PropertyProvider}. * @param executable an executable for the test class * @param testClass the test class * @return {@code true} if the executable is an autowirable constructor * @see #isAutowirableConstructor(Executable, Class, PropertyProvider) */ public static boolean isAutowirableConstructor(Executable executable, Class<?> testClass) { return isAutowirableConstructor(executable, testClass, null); } /** * Determine if the supplied constructor for the given test class is * autowirable. * <p>This method delegates to {@link #isAutowirableConstructor(Constructor, Class, PropertyProvider)} * will a value of {@code null} for the fallback {@link PropertyProvider}. * @param constructor a constructor for the test class * @param testClass the test class * @return {@code true} if the constructor is autowirable * @see #isAutowirableConstructor(Constructor, Class, PropertyProvider) */ public static boolean isAutowirableConstructor(Constructor<?> constructor, Class<?> testClass) { return isAutowirableConstructor(constructor, testClass, null); } /** * Determine if the supplied executable for the given test class is an * autowirable constructor. * <p>This method delegates to {@link #isAutowirableConstructor(Constructor, Class, PropertyProvider)} * if the supplied executable is a constructor and otherwise returns {@code false}. * @param executable an executable for the test class * @param testClass the test class * @param fallbackPropertyProvider fallback property provider used to look up * the value for {@link TestConstructor#TEST_CONSTRUCTOR_AUTOWIRE_MODE_PROPERTY_NAME} * if no such value is found in {@link SpringProperties} * @return {@code true} if the executable is an autowirable constructor * @since 5.3 * @see #isAutowirableConstructor(Constructor, Class, PropertyProvider) */ public static boolean isAutowirableConstructor(Executable executable, Class<?> testClass, @Nullable PropertyProvider fallbackPropertyProvider) { return (executable instanceof Constructor<?> constructor && isAutowirableConstructor(constructor, testClass, fallbackPropertyProvider)); } /** * Determine if the supplied constructor for the given test class is * autowirable. * * <p>A constructor is considered to be autowirable if one of the following * conditions is {@code true}. * * <ol> * <li>The constructor is annotated with {@link Autowired @Autowired}.</li> * <li>{@link TestConstructor @TestConstructor} is <em>present</em> or * <em>meta-present</em> on the test class with * {@link TestConstructor#autowireMode() autowireMode} set to * {@link AutowireMode#ALL ALL}.</li> * <li>The default <em>test constructor autowire mode</em> has been set to * {@code ALL} in {@link SpringProperties} or in the supplied fallback * {@link PropertyProvider} (see * {@link TestConstructor#TEST_CONSTRUCTOR_AUTOWIRE_MODE_PROPERTY_NAME}).</li> * </ol> * @param constructor a constructor for the test class * @param testClass the test class * @param fallbackPropertyProvider fallback property provider used to look up * the value for the default <em>test constructor autowire mode</em> if no * such value is found in {@link SpringProperties} * @return {@code true} if the constructor is autowirable * @since 5.3 */ public static boolean isAutowirableConstructor(Constructor<?> constructor, Class<?> testClass, @Nullable PropertyProvider fallbackPropertyProvider) { // Is the constructor annotated with @Autowired? if (AnnotatedElementUtils.hasAnnotation(constructor, Autowired.class)) { return true; } AutowireMode autowireMode = null; // Is the test class annotated with @TestConstructor? TestConstructor testConstructor = TestContextAnnotationUtils.findMergedAnnotation(testClass, TestConstructor.class); if (testConstructor != null) { autowireMode = testConstructor.autowireMode(); } else { // Custom global default from SpringProperties? String value = SpringProperties.getProperty(TestConstructor.TEST_CONSTRUCTOR_AUTOWIRE_MODE_PROPERTY_NAME); autowireMode = AutowireMode.from(value); // Use fallback provider? if (autowireMode == null && fallbackPropertyProvider != null) { value = fallbackPropertyProvider.get(TestConstructor.TEST_CONSTRUCTOR_AUTOWIRE_MODE_PROPERTY_NAME); autowireMode = AutowireMode.from(value); } } return (autowireMode == AutowireMode.ALL); } }
package com.trump.auction.web.vo; import java.util.Date; import java.util.List; import org.springframework.web.util.HtmlUtils; import com.cf.common.utils.DateUtil; import com.trump.auction.web.util.Base64Utils; import lombok.Getter; import lombok.Setter; import lombok.ToString; @ToString public class AppraisesVo { @Setter private Integer id; @Setter Integer appraisesId; public Integer getAppraisesId() { return id; } @Setter private String buyNickName; @Getter @Setter private String headImg; @Setter private Date createTime; @Setter private String appraisesPic; @Setter private String content; @Setter private String updateTimeStr ; @Getter @Setter private List<String> imgs ; public String getUpdateTimeStr(){ return DateUtil.getDateFormat(createTime, "yyyy-MM-dd HH:mm:ss"); } public String getBuyNickName() { return Base64Utils.decodeStr(buyNickName); } public String getContent() { return HtmlUtils.htmlUnescape(Base64Utils.decodeStr(content)); } }
package main; import modelo.Casa; import modelo.ConstrutorCasa; import modelo.ConstrutorPredio; import modelo.Diretor; import modelo.Predio; public class Cliente { public static void main(String[] args){ //Não Obrigatório ConstrutorPredio cP = new ConstrutorPredio(); ConstrutorCasa cC = new ConstrutorCasa(); Diretor d = new Diretor(cP); //Predio d.construir(); System.out.println(cP.obterProduto()); //unico tipo de acesso p Construtor //Casa Diretor d2 = new Diretor(cC); d2.construir(); System.out.println(cC.obterProduto()); } }
package be.openclinic.finance; import be.openclinic.common.OC_Object; import be.openclinic.common.ObjectReference; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.Debug; import be.mxs.common.util.system.ScreenHelper; import java.sql.Connection; import java.sql.Timestamp; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Vector; public class WicketDebet extends OC_Object{ private Wicket wicket; private String wicketUID; private Timestamp operationDate; private double amount; private int userUID; private String operationType; private StringBuffer comment; private ObjectReference referenceObject; public Wicket getWicket(){ if(wicket==null && wicketUID!=null && wicketUID.length()>0){ wicket = Wicket.get(wicketUID); } return wicket; } public void setWicket(Wicket wicket){ this.wicket = wicket; } public String getWicketUID(){ return wicketUID; } public void setWicketUID(String wicketUID){ this.wicketUID = wicketUID; } public Timestamp getOperationDate(){ return operationDate; } public void setOperationDate(Timestamp operationDate){ this.operationDate = operationDate; } public double getAmount(){ return amount; } public void setAmount(double amount){ this.amount = amount; } public int getUserUID(){ return userUID; } public void setUserUID(int userUID){ this.userUID = userUID; } public String getOperationType(){ return operationType; } public void setOperationType(String operationType){ this.operationType = operationType; } public StringBuffer getComment(){ return comment; } public void setComment(StringBuffer comment){ this.comment = comment; } public ObjectReference getReferenceObject(){ return referenceObject; } public void setReferenceObject(ObjectReference referenceObject){ this.referenceObject = referenceObject; } //--- GET ------------------------------------------------------------------------------------- public static WicketDebet get(String uid){ PreparedStatement ps = null; ResultSet rs = null; WicketDebet wicketOps = new WicketDebet(); if(uid != null && uid.length() > 0){ String sUids[] = uid.split("\\."); if(sUids.length==2){ Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); try{ String sSelect = "SELECT * FROM OC_WICKET_DEBETS"+ " WHERE OC_WICKET_DEBET_SERVERID = ?"+ " AND OC_WICKET_DEBET_OBJECTID = ?"; ps = oc_conn.prepareStatement(sSelect); ps.setInt(1,Integer.parseInt(sUids[0])); ps.setInt(2,Integer.parseInt(sUids[1])); rs = ps.executeQuery(); if(rs.next()){ wicketOps.setUid(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_SERVERID"))+"."+ ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_OBJECTID"))); wicketOps.setWicketUID(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_WICKETUID"))); wicketOps.setCreateDateTime(rs.getTimestamp("OC_WICKET_DEBET_CREATETIME")); wicketOps.setUpdateDateTime(rs.getTimestamp("OC_WICKET_DEBET_UPDATETIME")); wicketOps.setUpdateUser(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_UPDATEUID"))); wicketOps.setAmount(rs.getDouble("OC_WICKET_DEBET_AMOUNT")); wicketOps.setOperationType(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_TYPE"))); wicketOps.setComment(new StringBuffer(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_COMMENT")))); wicketOps.setOperationDate(rs.getTimestamp("OC_WICKET_DEBET_OPERATIONDATE")); //wicket.setAuthorizedUsersId(ScreenHelper.checkString(rs.getString("OC_WICKET_AUTHORIZEDUSERS"))); ObjectReference or = new ObjectReference(); or.setObjectType(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_REFERENCETYPE"))); or.setObjectUid(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_REFERENCEUID"))); wicketOps.setReferenceObject(or); wicketOps.setVersion(rs.getInt("OC_WICKET_DEBET_VERSION")); } } catch(Exception e){ Debug.println("OpenClinic => WicketOperation.java => get => "+e.getMessage()); e.printStackTrace(); } finally{ try{ if(rs!= null) rs.close(); if(ps!= null) ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } } return wicketOps; } //--- STORE ----------------------------------------------------------------------------------- public void store(){ PreparedStatement ps = null; ResultSet rs = null; String sSelect,sInsert,sDelete; int iVersion = 1; String ids[]; Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ if(this.getUid()!=null && this.getUid().length() >0){ ids = this.getUid().split("\\."); if(ids.length == 2){ sSelect = " SELECT * FROM OC_WICKET_DEBETS "+ " WHERE OC_WICKET_DEBET_SERVERID = ? "+ " AND OC_WICKET_DEBET_OBJECTID = ?"; ps = oc_conn.prepareStatement(sSelect); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); rs = ps.executeQuery(); if(rs.next()){ iVersion = rs.getInt("OC_WICKET_DEBET_VERSION")+1; } rs.close(); ps.close(); sInsert = "INSERT INTO OC_WICKET_DEBETS_HISTORY "+ " SELECT OC_WICKET_DEBET_SERVERID,"+ " OC_WICKET_DEBET_OBJECTID,"+ " OC_WICKET_DEBET_WICKETUID,"+ " OC_WICKET_DEBET_OPERATIONDATE,"+ " OC_WICKET_DEBET_AMOUNT,"+ " OC_WICKET_DEBET_USERUID,"+ " OC_WICKET_DEBET_TYPE,"+ " OC_WICKET_DEBET_COMMENT,"+ " OC_WICKET_DEBET_REFERENCETYPE,"+ " OC_WICKET_DEBET_REFERENCEUID,"+ " OC_WICKET_DEBET_CREATETIME,"+ " OC_WICKET_DEBET_UPDATETIME,"+ " OC_WICKET_DEBET_UPDATEUID," + " OC_WICKET_DEBET_VERSION"+ " FROM OC_WICKET_DEBETS "+ " WHERE OC_WICKET_DEBET_SERVERID = ? AND OC_WICKET_DEBET_OBJECTID = ?"; ps = oc_conn.prepareStatement(sInsert); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); ps.executeUpdate(); ps.close(); sDelete = " DELETE FROM OC_WICKET_DEBETS WHERE OC_WICKET_DEBET_SERVERID = ? AND OC_WICKET_DEBET_OBJECTID = ? "; ps = oc_conn.prepareStatement(sDelete); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); ps.executeUpdate(); ps.close(); } } else{ ids = new String[] {MedwanQuery.getInstance().getConfigString("serverId"),MedwanQuery.getInstance().getOpenclinicCounter("OC_WICKET_DEBETS")+""}; } if(ids.length == 2){ sInsert = " INSERT INTO OC_WICKET_DEBETS"+ "("+ " OC_WICKET_DEBET_SERVERID,"+ " OC_WICKET_DEBET_OBJECTID,"+ " OC_WICKET_DEBET_WICKETUID,"+ " OC_WICKET_DEBET_OPERATIONDATE,"+ " OC_WICKET_DEBET_AMOUNT,"+ " OC_WICKET_DEBET_USERUID,"+ " OC_WICKET_DEBET_TYPE,"+ " OC_WICKET_DEBET_COMMENT,"+ " OC_WICKET_DEBET_REFERENCETYPE,"+ " OC_WICKET_DEBET_REFERENCEUID,"+ " OC_WICKET_DEBET_CREATETIME,"+ " OC_WICKET_DEBET_UPDATETIME,"+ " OC_WICKET_DEBET_UPDATEUID," + " OC_WICKET_DEBET_VERSION"+ ") "+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; ps = oc_conn.prepareStatement(sInsert); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); ps.setString(3,this.getWicketUID()); ps.setTimestamp(4,this.getOperationDate()); ps.setDouble(5,this.getAmount()); ps.setInt(6,this.getUserUID()); ps.setString(7,this.getOperationType()); ps.setString(8,this.getComment().toString()); if (this.getReferenceObject()!=null){ ps.setString(9,this.getReferenceObject().getObjectType()); ps.setString(10,this.getReferenceObject().getObjectUid()); } else{ ps.setString(9,""); ps.setString(10,""); } ps.setTimestamp(11,new Timestamp(this.getCreateDateTime().getTime())); ps.setTimestamp(12,new Timestamp(this.getUpdateDateTime().getTime())); ps.setString(13,this.getUpdateUser()); ps.setInt(14,iVersion); ps.executeUpdate(); ps.close(); this.setUid(ids[0]+"."+ ids[1]); } } catch(Exception e){ Debug.println("OpenClinic => WicketOperations.java => store => "+e.getMessage()); e.printStackTrace(); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } //--- SELECT WICKET OPERATIONS ---------------------------------------------------------------- public static Vector selectWicketOperations(String sBegindate, String sEnddate, String sReferenceUID, String sReferenceType, String sType, String sWicketUID, String findSortColumn){ PreparedStatement ps = null; ResultSet rs = null; Vector vWicketOps = new Vector(); WicketDebet wicketOps; String sCondition = ""; String sSelect = " SELECT * FROM OC_WICKET_DEBETS"; if(sBegindate.length() > 0) sCondition+= " OC_WICKET_DEBET_OPERATIONDATE >= ? AND"; if(sEnddate.length() > 0) sCondition+= " OC_WICKET_DEBET_OPERATIONDATE < ? AND"; if(sType.length() > 0) sCondition+= " OC_WICKET_DEBET_TYPE = ? AND"; if(sReferenceUID.length() > 0) sCondition+= " OC_WICKET_DEBET_REFERENCEUID = ? AND"; if(sReferenceType.length() > 0) sCondition+= " OC_WICKET_DEBET_REFERENCETYPE = ? AND"; if(sWicketUID.length() > 0) sCondition+= " OC_WICKET_DEBET_WICKETUID = ? AND"; if(sCondition.length() > 0){ sSelect += " WHERE "+ sCondition; sSelect = sSelect.substring(0,sSelect.length() - 3); } if(findSortColumn.length() == 0){ findSortColumn = "OC_WICKET_DEBET_OPERATIONDATE DESC"; } sSelect += " ORDER BY "+ findSortColumn; Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ int i = 1; ps = oc_conn.prepareStatement(sSelect); if(sBegindate.length() > 0) ps.setDate(i++,ScreenHelper.getSQLDate(sBegindate)); if(sEnddate.length() > 0) ps.setDate(i++,ScreenHelper.getSQLDate(sEnddate)); if(sType.length() > 0) ps.setString(i++,sType); if(sReferenceUID.length() > 0) ps.setString(i++,sReferenceUID); if(sReferenceType.length() > 0) ps.setString(i++,sReferenceType); if(sWicketUID.length() > 0) ps.setString(i++,sWicketUID); rs = ps.executeQuery(); while(rs.next()){ wicketOps = new WicketDebet(); wicketOps.setUid(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_SERVERID"))+"."+ ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_OBJECTID"))); wicketOps.setWicketUID(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_WICKETUID"))); wicketOps.setCreateDateTime(rs.getTimestamp("OC_WICKET_DEBET_CREATETIME")); wicketOps.setUpdateDateTime(rs.getTimestamp("OC_WICKET_DEBET_UPDATETIME")); wicketOps.setUpdateUser(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_UPDATEUID"))); wicketOps.setAmount(rs.getDouble("OC_WICKET_DEBET_AMOUNT")); wicketOps.setOperationDate(rs.getTimestamp("OC_WICKET_DEBET_OPERATIONDATE")); wicketOps.setUserUID(rs.getInt("OC_WICKET_DEBET_USERUID")); wicketOps.setOperationType(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_TYPE"))); wicketOps.setComment(new StringBuffer(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_COMMENT")))); //wicket.setAuthorizedUsersId(ScreenHelper.checkString(rs.getString("OC_WICKET_AUTHORIZEDUSERS"))); ObjectReference or = new ObjectReference(); or.setObjectType(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_REFERENCETYPE"))); or.setObjectUid(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_REFERENCEUID"))); wicketOps.setReferenceObject(or); wicketOps.setVersion(rs.getInt("OC_WICKET_DEBET_VERSION")); vWicketOps.addElement(wicketOps); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return vWicketOps; } //--- SELECT WICKET OPERATIONS BY WICKET ------------------------------------------------------ public static Vector selectWicketOperationsByWicket(String sWicketUID){ PreparedStatement ps = null; ResultSet rs = null; String sSelect = "SELECT * FROM OC_WICKET_DEBETS"+ " WHERE OC_WICKET_DEBET_WICKETUID = ?"+ " ORDER BY OC_WICKET_DEBET_OPERATIONDATE DESC"; Vector vWicketOps = new Vector(); WicketDebet wicketOp; Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ ps = oc_conn.prepareStatement(sSelect); ps.setString(1,sWicketUID); rs = ps.executeQuery(); while(rs.next()){ wicketOp = new WicketDebet(); wicketOp.setUid(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_SERVERID"))+"."+ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_OBJECTID"))); wicketOp.setWicketUID(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_WICKETUID"))); wicketOp.setCreateDateTime(rs.getTimestamp("OC_WICKET_DEBET_CREATETIME")); wicketOp.setUpdateDateTime(rs.getTimestamp("OC_WICKET_DEBET_UPDATETIME")); wicketOp.setUpdateUser(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_UPDATEUID"))); wicketOp.setAmount(rs.getDouble("OC_WICKET_DEBET_AMOUNT")); wicketOp.setOperationDate(rs.getTimestamp("OC_WICKET_DEBET_OPERATIONDATE")); wicketOp.setUserUID(rs.getInt("OC_WICKET_DEBET_USERUID")); wicketOp.setOperationType(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_TYPE"))); wicketOp.setComment(new StringBuffer(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_COMMENT")))); //wicket.setAuthorizedUsersId(ScreenHelper.checkString(rs.getString("OC_WICKET_AUTHORIZEDUSERS"))); ObjectReference or = new ObjectReference(); or.setObjectType(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_REFERENCETYPE"))); or.setObjectUid(ScreenHelper.checkString(rs.getString("OC_WICKET_DEBET_REFERENCEUID"))); wicketOp.setReferenceObject(or); wicketOp.setVersion(rs.getInt("OC_WICKET_DEBET_VERSION")); vWicketOps.addElement(wicketOp); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return vWicketOps; } //--- DELETE ---------------------------------------------------------------------------------- public void delete(){ PreparedStatement ps = null; String sInsert, sDelete; String ids[]; Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); try{ if(this.getUid()!=null && this.getUid().length() > 0){ ids = this.getUid().split("\\."); if(ids.length==2){ //*** insert *** sInsert = "INSERT INTO OC_WICKET_DEBETS_HISTORY "+ " SELECT OC_WICKET_DEBET_SERVERID,"+ " OC_WICKET_DEBET_OBJECTID,"+ " OC_WICKET_DEBET_WICKETUID,"+ " OC_WICKET_DEBET_OPERATIONDATE,"+ " OC_WICKET_DEBET_AMOUNT,"+ " OC_WICKET_DEBET_USERUID,"+ " OC_WICKET_DEBET_TYPE,"+ " OC_WICKET_DEBET_COMMENT,"+ " OC_WICKET_DEBET_REFERENCETYPE,"+ " OC_WICKET_DEBET_REFERENCEUID,"+ " OC_WICKET_DEBET_CREATETIME,"+ " OC_WICKET_DEBET_UPDATETIME,"+ " OC_WICKET_DEBET_UPDATEUID,"+ " OC_WICKET_DEBET_VERSION"+ " FROM OC_WICKET_DEBETS"+ " WHERE OC_WICKET_DEBET_SERVERID = ?"+ " AND OC_WICKET_DEBET_OBJECTID = ?"; ps = oc_conn.prepareStatement(sInsert); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); ps.executeUpdate(); ps.close(); //*** delete *** sDelete = "DELETE FROM OC_WICKET_DEBETS"+ " WHERE OC_WICKET_DEBET_SERVERID = ?"+ " AND OC_WICKET_DEBET_OBJECTID = ?"; ps = oc_conn.prepareStatement(sDelete); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); ps.executeUpdate(); ps.close(); } } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } }
package com.example.demo.metier; import org.springframework.data.rest.core.config.Projection; @Projection(name="P1", types=Produit.class) public interface ProduitProjection { public String getDesignation(); public double getPrix(); public Long getId(); }
package com.alex.eat; import java.util.*; public class CabbageBasketCollection implements Weigh { private Set<Cabbage> cabbages; private int size; public CabbageBasketCollection(int size) { this.cabbages = new HashSet<>(size); this.size = size; } public void addCabbage(Cabbage cabbage) { if (cabbages.size() < size){ cabbages.add(cabbage); }else{ System.out.println("Sorry basket is full"); } } public Cabbage getCabbage() { Iterator<Cabbage> iterator = cabbages.iterator(); if (iterator.hasNext()) { Cabbage nextCabbage = iterator.next(); cabbages.remove(nextCabbage); return nextCabbage; } else { throw new IllegalStateException("Sorry, no cabbages in basket!"); } } public Set<Cabbage> getCabbages() { return Collections.unmodifiableSet(cabbages); } public int getCurrentSize() { return cabbages.size(); } @Override public int getWeight() { //int sum = 0; //3 variant /*for (Cabbage cabbage : cabbages) { if (cabbage != null) { sum = sum + cabbage.getWeight(); } }*/ //4 variant return cabbages.stream().mapToInt(cabbage -> cabbage.getWeight()).sum(); } }
package nightgames.status; import nightgames.characters.Character; public interface Resistance { String resisted(Character character, Status s); }
package com.esum.comp.sftp.server.session; import java.io.File; import java.util.Calendar; import com.esum.framework.FrameworkSystemVariables; import com.esum.framework.common.util.SysUtil; public class UpdateServerLock { private Object lock = new Object(); /** server.lock파일을 업데이트 한다. 서버 lock 파일이 업데이트 되지 않으면, server가 hang걸린것으로 간주하고 restart한다. */ public void updateLock() { synchronized(lock) { String nodeId = System.getProperty(FrameworkSystemVariables.NODE_ID); File lockDir = new File(SysUtil.replacePropertyToValue("${xtrus.home}/repository/sshd/"+nodeId)); if(!lockDir.exists()) return; File lockFile = new File(lockDir, "server.lock"); if(lockFile.exists()) lockFile.setLastModified(Calendar.getInstance().getTimeInMillis()); } } }
package com.zantong.mobilecttx.interf; import com.zantong.mobilecttx.base.interf.IBaseView; /** * Created by zhengyingbing on 16/6/1. */ public interface UserInfoUpdateView extends IBaseView{ String getOrderType(); void showProgress(); void updateView(Object object, int index); void hideProgress(); }
package oop.practice; /** * Created by Roman on 16.08.2016. */ public class HospitalManagement { // this class will call upon employees to do expected duties. // upper management should be able to order all kinds of employees to perform expected duties. public void callUpon(Employee employee){ if(employee instanceof Nurse){ checkVitalSigns(); drawBlood(); cleanPatientArea(); } if(employee instanceof Doctor){ prescribeMedicine(); diagnosePatiets(); } } //Notice how violating single responsibility principle is making this class unreadable to look at? !!!!!!!!!!!!! // what kinds of behavior this class expect of conducting? //Nurses private void checkVitalSigns(){ System.out.println("Checking Vital Signs ... "); } private void drawBlood(){ System.out.println("Drawing Blood ... "); } private void cleanPatientArea(){ System.out.println("Checking Vital Signs ... "); } //======================================================================================== // Doctors private void prescribeMedicine(){ System.out.println(" Prescribe Medicine ... "); } private void diagnosePatiets(){ System.out.println(" Prescribe Medicine ... "); } }
package com.cqut.dto; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotEmpty; import com.cqut.model.OperatorExtra; import com.cqut.util.BeanUtil; public class OperatorDTO { @Size(max=30) private String Id; @Size(max=30) private String userId;//运营中心对应的用户Id @Size(max=100) private String userNickName;//对应的用户昵称 @NotEmpty(message="{general.NotEmpty}") @Size(max=100) private String name;//运营中心的名字 @Size(max=30) private String area;//地区编码 @Size(max=100) private String areaName;//地区名字 private double income = 0;//当前收入 private double totalIncome = 0;//累计收益 private double royaltyRate = 0;//返佣比例 public double getTotalIncome() { return totalIncome; } public void setTotalIncome(double totalIncome) { this.totalIncome = totalIncome; } public double getRoyaltyRate() { return royaltyRate; } public void setRoyaltyRate(double royaltyRate) { this.royaltyRate = royaltyRate; } public String getId() { return Id; } public String getUserId() { return userId; } public String getUserNickName() { return userNickName; } public String getName() { return name; } public String getArea() { return area; } public String getAreaName() { return areaName; } public double getIncome() { return income; } public void setId(String id) { Id = id; } public void setUserId(String userId) { this.userId = userId; } public void setUserNickName(String userNickName) { this.userNickName = userNickName; } public void setName(String name) { this.name = name; } public void setArea(String area) { this.area = area; } public void setAreaName(String areaName) { this.areaName = areaName; } public void setIncome(double income) { this.income = income; } /** * 转化成实体类 * 参数为对象的ID * @param createTimestamp * @return */ public OperatorExtra toModel(String createTimestamp) { OperatorExtra model = new OperatorExtra(createTimestamp); BeanUtil.convert(this, model); return model; } /** * 转化成实体类 * @return */ public OperatorExtra toModel() { OperatorExtra model = new OperatorExtra(); BeanUtil.convert(this, model); return model; } }
// Generated from C:/Users/georg/Documents/GitHub/endless-ql/ForcePush/src/main/java/org/uva/forcepushql/parser\GrammarLexer.g4 by ANTLR 4.7 package org.uva.forcepushql.parser.antlr; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class GrammarLexer extends Lexer { static { RuntimeMetaData.checkVersion("4.7", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int WHITESPACE=1, COMMENT=2, LINE_COMMENT=3, FORM=4, BOOL=5, STR=6, INT=7, DATE=8, DECIMAL=9, MULTIPLEANSWER=10, MONEY=11, ASSIGN=12, IF=13, ELSE=14, IFELSE=15, LPAREN=16, RPAREN=17, LBRACE=18, RBRACE=19, SEMI=20, COMMA=21, DOT=22, PLUS=23, MINUS=24, MULTIPLY=25, DIVIDE=26, EQUAL=27, LESS=28, GREATER=29, EQUALGREATER=30, EQUALLESS=31, NOTEQUAL=32, ISEQUAL=33, AND=34, OR=35, NOT=36, NUM=37, VAR=38, LABEL=39, DEC=40; public static String[] channelNames = { "DEFAULT_TOKEN_CHANNEL", "HIDDEN" }; public static String[] modeNames = { "DEFAULT_MODE" }; public static final String[] ruleNames = { "WHITESPACE", "COMMENT", "LINE_COMMENT", "FORM", "BOOLEAN", "STRING", "INTEGER", "DATE", "DECIMAL", "MULTIPLEANSWER", "MONEY", "ASSIGN", "IF", "ELSE", "IFELSE", "LPAREN", "RPAREN", "LBRACE", "RBRACE", "SEMI", "COMMA", "DOT", "PLUS", "MINUS", "MULTIPLY", "DIVIDE", "EQUAL", "LESS", "GREATER", "EQUALGREATER", "EQUALLESS", "NOTEQUAL", "ISEQUAL", "AND", "OR", "NOT", "NUM", "VAR", "LABEL", "DEC" }; private static final String[] _LITERAL_NAMES = { null, null, null, null, "'form'", "'boolean'", "'string'", "'integer'", "'date'", "'decimal'", "'multipleAnswer'", null, "':'", "'if'", "'else'", "'ifelse'", "'('", "')'", "'{'", "'}'", "';'", "','", "'.'", "'+'", "'-'", "'*'", "'/'", "'='", "'<'", "'>'", "'>='", "'<='", "'!='", "'=='", "'&&'", "'||'", "'!'" }; private static final String[] _SYMBOLIC_NAMES = { null, "WHITESPACE", "COMMENT", "LINE_COMMENT", "FORM", "BOOLEAN", "STRING", "INTEGER", "DATE", "DECIMAL", "MULTIPLEANSWER", "MONEY", "ASSIGN", "IF", "ELSE", "IFELSE", "LPAREN", "RPAREN", "LBRACE", "RBRACE", "SEMI", "COMMA", "DOT", "PLUS", "MINUS", "MULTIPLY", "DIVIDE", "EQUAL", "LESS", "GREATER", "EQUALGREATER", "EQUALLESS", "NOTEQUAL", "ISEQUAL", "AND", "OR", "NOT", "NUM", "VAR", "LABEL", "DEC" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public GrammarLexer(CharStream input) { super(input); _interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } @Override public String getGrammarFileName() { return "GrammarLexer.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getChannelNames() { return channelNames; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2*\u011a\b\1\4\2\t"+ "\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13"+ "\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22"+ "\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31\t\31"+ "\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\4 \t \4!"+ "\t!\4\"\t\"\4#\t#\4$\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\3\2\6\2U\n\2\r"+ "\2\16\2V\3\2\3\2\3\3\3\3\3\3\3\3\7\3_\n\3\f\3\16\3b\13\3\3\3\3\3\3\3\3"+ "\3\3\3\3\4\3\4\3\4\3\4\7\4m\n\4\f\4\16\4p\13\4\3\4\3\4\3\5\3\5\3\5\3\5"+ "\3\5\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\b\3"+ "\b\3\b\3\b\3\b\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3\n"+ "\3\n\3\n\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3"+ "\13\3\13\3\13\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\5\f"+ "\u00b9\n\f\3\r\3\r\3\16\3\16\3\16\3\17\3\17\3\17\3\17\3\17\3\20\3\20\3"+ "\20\3\20\3\20\3\20\3\20\3\21\3\21\3\22\3\22\3\23\3\23\3\24\3\24\3\25\3"+ "\25\3\26\3\26\3\27\3\27\3\30\3\30\3\31\3\31\3\32\3\32\3\33\3\33\3\34\3"+ "\34\3\35\3\35\3\36\3\36\3\37\3\37\3\37\3 \3 \3 \3!\3!\3!\3\"\3\"\3\"\3"+ "#\3#\3#\3$\3$\3$\3%\3%\3&\6&\u00fd\n&\r&\16&\u00fe\3\'\3\'\7\'\u0103\n"+ "\'\f\'\16\'\u0106\13\'\3(\3(\6(\u010a\n(\r(\16(\u010b\3(\3(\3)\6)\u0111"+ "\n)\r)\16)\u0112\3)\3)\6)\u0117\n)\r)\16)\u0118\3`\2*\3\3\5\4\7\5\t\6"+ "\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\17\35\20\37\21!\22#\23%\24"+ "\'\25)\26+\27-\30/\31\61\32\63\33\65\34\67\359\36;\37= ?!A\"C#E$G%I&K"+ "\'M(O)Q*\3\2\b\5\2\13\f\17\17\"\"\4\2\f\f\17\17\3\2\62;\4\2C\\c|\5\2\62"+ ";C\\c|\t\2\"#))..\60<AAC\\c|\2\u0122\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2"+ "\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23"+ "\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2"+ "\2\2\2\37\3\2\2\2\2!\3\2\2\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2"+ "\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2\65\3"+ "\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2\2\2\2?\3\2\2\2\2A\3\2"+ "\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3\2\2\2\2I\3\2\2\2\2K\3\2\2\2\2M\3\2\2\2"+ "\2O\3\2\2\2\2Q\3\2\2\2\3T\3\2\2\2\5Z\3\2\2\2\7h\3\2\2\2\ts\3\2\2\2\13"+ "x\3\2\2\2\r\u0080\3\2\2\2\17\u0087\3\2\2\2\21\u008f\3\2\2\2\23\u0094\3"+ "\2\2\2\25\u009c\3\2\2\2\27\u00b8\3\2\2\2\31\u00ba\3\2\2\2\33\u00bc\3\2"+ "\2\2\35\u00bf\3\2\2\2\37\u00c4\3\2\2\2!\u00cb\3\2\2\2#\u00cd\3\2\2\2%"+ "\u00cf\3\2\2\2\'\u00d1\3\2\2\2)\u00d3\3\2\2\2+\u00d5\3\2\2\2-\u00d7\3"+ "\2\2\2/\u00d9\3\2\2\2\61\u00db\3\2\2\2\63\u00dd\3\2\2\2\65\u00df\3\2\2"+ "\2\67\u00e1\3\2\2\29\u00e3\3\2\2\2;\u00e5\3\2\2\2=\u00e7\3\2\2\2?\u00ea"+ "\3\2\2\2A\u00ed\3\2\2\2C\u00f0\3\2\2\2E\u00f3\3\2\2\2G\u00f6\3\2\2\2I"+ "\u00f9\3\2\2\2K\u00fc\3\2\2\2M\u0100\3\2\2\2O\u0107\3\2\2\2Q\u0110\3\2"+ "\2\2SU\t\2\2\2TS\3\2\2\2UV\3\2\2\2VT\3\2\2\2VW\3\2\2\2WX\3\2\2\2XY\b\2"+ "\2\2Y\4\3\2\2\2Z[\7\61\2\2[\\\7,\2\2\\`\3\2\2\2]_\13\2\2\2^]\3\2\2\2_"+ "b\3\2\2\2`a\3\2\2\2`^\3\2\2\2ac\3\2\2\2b`\3\2\2\2cd\7,\2\2de\7\61\2\2"+ "ef\3\2\2\2fg\b\3\2\2g\6\3\2\2\2hi\7\61\2\2ij\7\61\2\2jn\3\2\2\2km\n\3"+ "\2\2lk\3\2\2\2mp\3\2\2\2nl\3\2\2\2no\3\2\2\2oq\3\2\2\2pn\3\2\2\2qr\b\4"+ "\2\2r\b\3\2\2\2st\7h\2\2tu\7q\2\2uv\7t\2\2vw\7o\2\2w\n\3\2\2\2xy\7d\2"+ "\2yz\7q\2\2z{\7q\2\2{|\7n\2\2|}\7g\2\2}~\7c\2\2~\177\7p\2\2\177\f\3\2"+ "\2\2\u0080\u0081\7u\2\2\u0081\u0082\7v\2\2\u0082\u0083\7t\2\2\u0083\u0084"+ "\7k\2\2\u0084\u0085\7p\2\2\u0085\u0086\7i\2\2\u0086\16\3\2\2\2\u0087\u0088"+ "\7k\2\2\u0088\u0089\7p\2\2\u0089\u008a\7v\2\2\u008a\u008b\7g\2\2\u008b"+ "\u008c\7i\2\2\u008c\u008d\7g\2\2\u008d\u008e\7t\2\2\u008e\20\3\2\2\2\u008f"+ "\u0090\7f\2\2\u0090\u0091\7c\2\2\u0091\u0092\7v\2\2\u0092\u0093\7g\2\2"+ "\u0093\22\3\2\2\2\u0094\u0095\7f\2\2\u0095\u0096\7g\2\2\u0096\u0097\7"+ "e\2\2\u0097\u0098\7k\2\2\u0098\u0099\7o\2\2\u0099\u009a\7c\2\2\u009a\u009b"+ "\7n\2\2\u009b\24\3\2\2\2\u009c\u009d\7o\2\2\u009d\u009e\7w\2\2\u009e\u009f"+ "\7n\2\2\u009f\u00a0\7v\2\2\u00a0\u00a1\7k\2\2\u00a1\u00a2\7r\2\2\u00a2"+ "\u00a3\7n\2\2\u00a3\u00a4\7g\2\2\u00a4\u00a5\7C\2\2\u00a5\u00a6\7p\2\2"+ "\u00a6\u00a7\7u\2\2\u00a7\u00a8\7y\2\2\u00a8\u00a9\7g\2\2\u00a9\u00aa"+ "\7t\2\2\u00aa\26\3\2\2\2\u00ab\u00ac\7o\2\2\u00ac\u00ad\7q\2\2\u00ad\u00ae"+ "\7p\2\2\u00ae\u00af\7g\2\2\u00af\u00b9\7{\2\2\u00b0\u00b1\7e\2\2\u00b1"+ "\u00b2\7w\2\2\u00b2\u00b3\7t\2\2\u00b3\u00b4\7t\2\2\u00b4\u00b5\7g\2\2"+ "\u00b5\u00b6\7p\2\2\u00b6\u00b7\7e\2\2\u00b7\u00b9\7{\2\2\u00b8\u00ab"+ "\3\2\2\2\u00b8\u00b0\3\2\2\2\u00b9\30\3\2\2\2\u00ba\u00bb\7<\2\2\u00bb"+ "\32\3\2\2\2\u00bc\u00bd\7k\2\2\u00bd\u00be\7h\2\2\u00be\34\3\2\2\2\u00bf"+ "\u00c0\7g\2\2\u00c0\u00c1\7n\2\2\u00c1\u00c2\7u\2\2\u00c2\u00c3\7g\2\2"+ "\u00c3\36\3\2\2\2\u00c4\u00c5\7k\2\2\u00c5\u00c6\7h\2\2\u00c6\u00c7\7"+ "g\2\2\u00c7\u00c8\7n\2\2\u00c8\u00c9\7u\2\2\u00c9\u00ca\7g\2\2\u00ca "+ "\3\2\2\2\u00cb\u00cc\7*\2\2\u00cc\"\3\2\2\2\u00cd\u00ce\7+\2\2\u00ce$"+ "\3\2\2\2\u00cf\u00d0\7}\2\2\u00d0&\3\2\2\2\u00d1\u00d2\7\177\2\2\u00d2"+ "(\3\2\2\2\u00d3\u00d4\7=\2\2\u00d4*\3\2\2\2\u00d5\u00d6\7.\2\2\u00d6,"+ "\3\2\2\2\u00d7\u00d8\7\60\2\2\u00d8.\3\2\2\2\u00d9\u00da\7-\2\2\u00da"+ "\60\3\2\2\2\u00db\u00dc\7/\2\2\u00dc\62\3\2\2\2\u00dd\u00de\7,\2\2\u00de"+ "\64\3\2\2\2\u00df\u00e0\7\61\2\2\u00e0\66\3\2\2\2\u00e1\u00e2\7?\2\2\u00e2"+ "8\3\2\2\2\u00e3\u00e4\7>\2\2\u00e4:\3\2\2\2\u00e5\u00e6\7@\2\2\u00e6<"+ "\3\2\2\2\u00e7\u00e8\7@\2\2\u00e8\u00e9\7?\2\2\u00e9>\3\2\2\2\u00ea\u00eb"+ "\7>\2\2\u00eb\u00ec\7?\2\2\u00ec@\3\2\2\2\u00ed\u00ee\7#\2\2\u00ee\u00ef"+ "\7?\2\2\u00efB\3\2\2\2\u00f0\u00f1\7?\2\2\u00f1\u00f2\7?\2\2\u00f2D\3"+ "\2\2\2\u00f3\u00f4\7(\2\2\u00f4\u00f5\7(\2\2\u00f5F\3\2\2\2\u00f6\u00f7"+ "\7~\2\2\u00f7\u00f8\7~\2\2\u00f8H\3\2\2\2\u00f9\u00fa\7#\2\2\u00faJ\3"+ "\2\2\2\u00fb\u00fd\t\4\2\2\u00fc\u00fb\3\2\2\2\u00fd\u00fe\3\2\2\2\u00fe"+ "\u00fc\3\2\2\2\u00fe\u00ff\3\2\2\2\u00ffL\3\2\2\2\u0100\u0104\t\5\2\2"+ "\u0101\u0103\t\6\2\2\u0102\u0101\3\2\2\2\u0103\u0106\3\2\2\2\u0104\u0102"+ "\3\2\2\2\u0104\u0105\3\2\2\2\u0105N\3\2\2\2\u0106\u0104\3\2\2\2\u0107"+ "\u0109\7$\2\2\u0108\u010a\t\7\2\2\u0109\u0108\3\2\2\2\u010a\u010b\3\2"+ "\2\2\u010b\u0109\3\2\2\2\u010b\u010c\3\2\2\2\u010c\u010d\3\2\2\2\u010d"+ "\u010e\7$\2\2\u010eP\3\2\2\2\u010f\u0111\t\4\2\2\u0110\u010f\3\2\2\2\u0111"+ "\u0112\3\2\2\2\u0112\u0110\3\2\2\2\u0112\u0113\3\2\2\2\u0113\u0114\3\2"+ "\2\2\u0114\u0116\7\60\2\2\u0115\u0117\t\4\2\2\u0116\u0115\3\2\2\2\u0117"+ "\u0118\3\2\2\2\u0118\u0116\3\2\2\2\u0118\u0119\3\2\2\2\u0119R\3\2\2\2"+ "\f\2V`n\u00b8\u00fe\u0104\u010b\u0112\u0118\3\b\2\2"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
/* * Copyright 2014 Brian Roach <roach at basho dot com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.basho.riak.client.api.commands.itest; import com.basho.riak.client.api.annotations.RiakBucketName; import com.basho.riak.client.api.annotations.RiakBucketType; import com.basho.riak.client.api.annotations.RiakContentType; import com.basho.riak.client.api.annotations.RiakIndex; import com.basho.riak.client.api.annotations.RiakKey; import com.basho.riak.client.api.annotations.RiakLastModified; import com.basho.riak.client.api.annotations.RiakTombstone; import com.basho.riak.client.api.annotations.RiakVClock; import com.basho.riak.client.api.annotations.RiakVTag; import com.basho.riak.client.api.cap.VClock; import java.util.Set; /** * * @author Brian Roach <roach at basho dot com> */ public class RiakAnnotatedPojo { @RiakKey public String key; @RiakBucketName public String bucketName; @RiakBucketType public String bucketType; @RiakVClock public VClock vclock; @RiakContentType public String contentType; @RiakLastModified public Long lastModified; @RiakVTag public String vtag; @RiakTombstone public boolean deleted; @RiakIndex(name="email") public Set<String> emailIndx; @RiakIndex(name="user_id") public Long userId; public String value; }
package cc.ipotato.socket; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; /** * Created by haohao on 2018/5/10. */ public class UdpReceive { public static void main(String[] args) throws IOException { DatagramSocket socket = new DatagramSocket(8888); DatagramPacket packet = new DatagramPacket(new byte[1024],1024); while(true) { socket.receive(packet); byte[] arr = packet.getData(); String ip = packet.getAddress().getHostAddress(); int port = packet.getPort(); System.out.println(ip + ":" + port + ": " + new String(arr, 0, packet.getLength())); } } }
package com.lirong.nacosprovider.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RefreshScope public class HelloController { @Value("${myName}") private String myName; @Value("${redisUrl}") private String redisUrl; @Value("${jdbcUrl}") private String jdbcUrl; @RequestMapping("hello") public String hello() { return "hello " + myName+"----"+redisUrl+"----"+jdbcUrl; } }
package com.example.workstudy.service.impl; import com.example.workstudy.service.Life; public class LifeImpl implements Life { @Override public void bath() { System.out.println("bath"); } @Override public void washHands() { System.out.println("washHands"); } @Override public void eat() { System.out.println("eat"); } }
package com.example.procrastinator.tools.tools; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; import android.view.View; import android.view.Window; import android.widget.ProgressBar; import android.widget.RelativeLayout; import androidx.recyclerview.widget.RecyclerView; import com.example.procrastinator.R; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; /** * Classe technique de connexion distante HTTP */ public class AccesHTTP extends AsyncTask<String, Integer, Long> { // propriétés public String ret=""; // information retournée par le serveur public AsyncResponse delegate=null; // gestion du retour asynchrone private String parametres = ""; // paramètres à envoyer en POST au serveur ProgressBar progress; Context context; Handler handler; Dialog dialog; int myProgress; /** * Constructeur : ne fait rien */ public AccesHTTP(Context contexte) { super(); this.context = contexte; } /** * Construction de la chaîne de paramètres à envoyer en POST au serveur * @param nom * @param valeur */ public void addParam(String nom, String valeur) { try { if (parametres.equals("")) { // premier paramètre parametres = URLEncoder.encode(nom, "UTF-8") + "=" + URLEncoder.encode(valeur, "UTF-8"); }else{ // paramètres suivants (séparés par &) parametres += "&" + URLEncoder.encode(nom, "UTF-8") + "=" + URLEncoder.encode(valeur, "UTF-8"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override protected void onPreExecute() { super.onPreExecute(); // create dialog dialog=new Dialog(context); dialog.setCancelable(true); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.progressdialog); /* RelativeLayout layout = dialog.findViewById(R.layout.progressdialog); progress = new ProgressBar(context, null, android.R.attr.progressBarStyleLarge); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100); params.addRule(RelativeLayout.CENTER_IN_PARENT); layout.addView(progress, params);*/ progress=(ProgressBar)dialog.findViewById(R.id.progressBar); progress.setVisibility(View.VISIBLE); dialog.show(); } /** * Méthode appelée par la méthode execute * permet d'envoyer au serveur une liste de paramètres en GET * @param urls contient l'adresse du serveur dans la case 0 de urls * @return null */ @Override protected Long doInBackground(String... urls) { // pour éliminer certaines erreurs System.setProperty("http.keepAlive", "false"); // objets pour gérer la connexion, la lecture et l'écriture PrintWriter writer = null; BufferedReader reader = null; HttpURLConnection connexion = null; try { // création de l'url à partir de l'adresse reçu en paramètre, dans urls[0] URL url = new URL(urls[0]); // ouverture de la connexion connexion = (HttpURLConnection) url.openConnection(); connexion.setDoOutput(true); // choix de la méthode POST pour l'envoi des paramètres connexion.setRequestMethod("POST"); connexion.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connexion.setFixedLengthStreamingMode(parametres.getBytes().length); // création de la requete d'envoi sur la connexion, avec les paramètres writer = new PrintWriter(connexion.getOutputStream()); System.out.println(writer.checkError()); writer.print(parametres); // Une fois l'envoi réalisé, vide le canal d'envoi writer.flush(); // Récupération du retour du serveur reader = new BufferedReader(new InputStreamReader(connexion.getInputStream())); ret = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } finally { // fermeture des canaux d'envoi et de réception try{ writer.close(); }catch(Exception e){} try{ reader.close(); }catch(Exception e){} } return null; } /** * Sur le retour du serveur, envoi l'information retournée à processFinish * @param result */ @Override protected void onPostExecute(Long result) { // ret contient l'information récupérée delegate.processFinish(this.ret.toString()); if (dialog.isShowing()){ dialog.dismiss(); dialog.cancel();} } }
package it.ialweb.poi.it.ialweb.poi.fragments; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import it.ialweb.poi.R; import it.ialweb.poi.it.ialweb.poi.models.Post; import it.ialweb.poi.it.ialweb.poi.models.User; /** * Created by TSAIM044 on 08/07/2015. */ public class UsersListFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RecyclerView recyclerView = new RecyclerView(getActivity()); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setAdapter(new UserAdapter(getActivity(), (UserHandler)getActivity())); return recyclerView; } private class UserAdapter extends RecyclerView.Adapter { private Context mContext; private List<User> users; private UserHandler userHandler; public UserAdapter(Context context, UserHandler handler) { mContext = context; userHandler = handler; users = userHandler.getUserDataSet(this); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { UserViewHolder viewHolder = (UserViewHolder)holder; final User user = users.get(position); if (user != null) { viewHolder.userName.setText(user.getName()); viewHolder.followButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { userHandler.followUser(user.getId()); } }); } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) { View view = LayoutInflater.from(mContext).inflate(R.layout.element_user, parent, false); return new UserViewHolder(view); } @Override public int getItemCount() { return users.size(); } } private class UserViewHolder extends RecyclerView.ViewHolder { Button followButton; TextView userName; ImageView userPicture; public UserViewHolder(View view) { super(view); userName = (TextView) view.findViewById(R.id.textView_username); followButton = (Button)view.findViewById(R.id.button_follow); userPicture = (ImageView) view.findViewById(R.id.imageView_userPicture); } } public interface UserHandler { void followUser(String userId); List<User> getUserDataSet(RecyclerView.Adapter adapter); } }
package com.getroadmap.r2rlib.parser; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import java.lang.reflect.Type; import com.getroadmap.r2rlib.models.DayFlags; /** * Created by jan on 28/08/2017. */ public class DayFlagsParser implements JsonDeserializer<DayFlags> { @Override public DayFlags deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { //Expected input should be a int in the [0-127] range (7 bytes) int intFlag = json.getAsInt(); if (intFlag < 0 || intFlag > 127) { return new DayFlags(0); } return new DayFlags(intFlag); } }
import java.io.*; import java.util.ArrayList; import java.util.List; // +------------------------------------------------------------+ // | | // | Replaces flags in a XML document using a .txt file, | // | located in the root directory, containing the key | // | using the following format: | // | | // | oldTag1 newTag1 | // | ... | // | oldTagN newTagN | // | | // +------------------------------------------------------------+ public class XML_Tag_Replacer { private static String rutaClave = "C:\\Users\\05719450\\Desktop\\keys.txt" ; private static String rutaViejoXML = "C:\\Users\\05719450\\Desktop\\Prueba.xml" ; private static String rutaNuevoXML = "C:\\Users\\05719450\\Desktop\\Final.xml" ; private static List<String> etiquetasViejas = new ArrayList<String>(); private static List<String> etiquetasNuevas = new ArrayList<String>(); public static void main (String args[]) throws FileNotFoundException { cargarEtiquetas(rutaClave); //System.out.println("Etiqueta Vieja--"+etiquetasViejas.get(0)); //System.out.println("Etiqueta Nueva--"+etiquetasNuevas.get(0)); FileReader fr = null; BufferedReader br = null; PrintWriter writer = null; String linea; //Open the file for reading try { writer = new PrintWriter(rutaNuevoXML, "UTF-8"); fr=new FileReader(rutaViejoXML); //BufferedReader br = new BufferedReader(new FileReader(rutaViejoXML)); br = new BufferedReader(fr); while ((linea = br.readLine()) != null) { // while loop begins here System.out.println("linea1"+linea); linea = ReemplazarEtiquetas(linea); System.out.println("linea2"+linea); writer.println(linea); } // end while writer.close(); } // end try catch (IOException e) { System.err.println("Error: " + e); }finally{ // En el finally cerramos el fichero, para asegurarnos // que se cierra tanto si todo va bien como si salta // una excepcion. try{ if( null != fr ){ fr.close(); writer.close(); } }catch (Exception e2){ e2.printStackTrace(); } } // } // end for } // end main private static void cargarEtiquetas(String ruta) throws FileNotFoundException { String linea; BufferedReader br = new BufferedReader(new FileReader(ruta)); //Open the file for reading try { while ((linea = br.readLine()) != null) { // while loop begins here String[] parts = linea.split(" "); etiquetasViejas.add(parts[0]); etiquetasNuevas.add(parts[1]); //System.out.println(linea); } // end while } // end try catch (IOException e) { System.err.println("Error: " + e); } finally{ // En el finally cerramos el fichero, para asegurarnos // que se cierra tanto si todo va bien como si salta // una excepcion. try{ if( null != br ){ br.close(); } }catch (Exception e2){ e2.printStackTrace(); } } } public static String ReemplazarEtiquetas(String linea) { String nuevaLinea = linea; String lineaAux; int indice1; int indice2; for(int i = 0; i<etiquetasViejas.size(); i++) { /* if(linea.contains(etiquetasViejas.get(i))) { //String[] parts = linea.split(etiquetasViejas.get(i)); if(!etiquetasViejas.get(i).contains("/")) { lineaAux = linea.substring(0, etiquetasViejas.get(i).length() - 1); nuevaLinea = etiquetasNuevas.get(i) + lineaAux; }else { lineaAux = linea.substring(linea.length() - etiquetasViejas.get(i).length(), linea.length() - 1); nuevaLinea = lineaAux + etiquetasNuevas.get(i); } } }*/ if(linea.contains(etiquetasViejas.get(i))) { //String[] parts = linea.split(etiquetasViejas.get(i)); if(!etiquetasViejas.get(i).contains("/")) { indice1 = linea.indexOf("<"); indice2 = linea.indexOf(":"); }else { indice1 = linea.indexOf("/"); indice2 = linea.indexOf(":"); } lineaAux = linea.substring(indice1+1, indice2); } } return nuevaLinea; } //linea.replaceAll(etiquetasViejas.get(i), etiquetasNuevas.get(i)); /*for(int i = 0; i<etiquetasViejas.size(); i++) { System.out.println("ReemplazarEtiquetaAntes"); //linea.replaceAll(etiquetasViejas.get(i), etiquetasNuevas.get(i)); linea=linea.replaceAll(etiquetasViejas.get(i), etiquetasNuevas.get(i)); System.out.println("ReemplazarEtiquetasDespues"+linea); } for(int i = 0; i<etiquetasViejas.size(); i++) { System.out.println("ReemplazarEtiquetaAntes"); //linea.replaceAll(etiquetasViejas.get(i), etiquetasNuevas.get(i)); linea=linea.replace("<.*:", "<"); System.out.println("ReemplazarEtiquetasDespues"+linea); } return linea; }*/ }
package cn.kgc.domain; public class Vehicle { private Integer id; private String brand; private String type; private String driveType; private Integer seat; private Integer rentMoney; private String quality; private String license; private String img; private String owner; private String safetyPeril; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDriveType() { return driveType; } public void setDriveType(String driveType) { this.driveType = driveType; } public Integer getSeat() { return seat; } public void setSeat(Integer seat) { this.seat = seat; } public Integer getRentMoney() { return rentMoney; } public void setRentMoney(Integer rentMoney) { this.rentMoney = rentMoney; } public String getQuality() { return quality; } public void setQuality(String quality) { this.quality = quality; } public String getLicense() { return license; } public void setLicense(String license) { this.license = license; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getSafetyPeril() { return safetyPeril; } public void setSafetyPeril(String safetyPeril) { this.safetyPeril = safetyPeril; } }
package de.uulm.in.vs.grn.c1; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class NumberGuessingGameThreadedServer { public static int clientCount = 0; public static void main(String [] args){ ExecutorService executor = Executors.newFixedThreadPool(4); ServerSocket serverSocket; { try { serverSocket = new ServerSocket(5555); System.out.println("Server gestartet!"); while (true) { try { Socket clientSocket = serverSocket.accept(); executor.execute(new NumberGuessingGameRequestHandler(clientSocket)); clientCount++; System.out.println("Client connected (" + clientCount + "/4)"); } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } } }
package com.mycompany.myapp.web.rest; import com.mycompany.myapp.domain.Proba; import com.mycompany.myapp.repository.ProbaRepository; import com.mycompany.myapp.web.rest.errors.BadRequestAlertException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Objects; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import tech.jhipster.web.util.HeaderUtil; import tech.jhipster.web.util.ResponseUtil; /** * REST controller for managing {@link com.mycompany.myapp.domain.Proba}. */ @RestController @RequestMapping("/api") @Transactional public class ProbaResource { private final Logger log = LoggerFactory.getLogger(ProbaResource.class); private static final String ENTITY_NAME = "servisProba"; @Value("${jhipster.clientApp.name}") private String applicationName; private final ProbaRepository probaRepository; public ProbaResource(ProbaRepository probaRepository) { this.probaRepository = probaRepository; } /** * {@code POST /probas} : Create a new proba. * * @param proba the proba to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new proba, or with status {@code 400 (Bad Request)} if the proba has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("/probas") public ResponseEntity<Proba> createProba(@RequestBody Proba proba) throws URISyntaxException { log.debug("REST request to save Proba : {}", proba); if (proba.getId() != null) { throw new BadRequestAlertException("A new proba cannot already have an ID", ENTITY_NAME, "idexists"); } Proba result = probaRepository.save(proba); return ResponseEntity .created(new URI("/api/probas/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) .body(result); } /** * {@code PUT /probas/:id} : Updates an existing proba. * * @param id the id of the proba to save. * @param proba the proba to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated proba, * or with status {@code 400 (Bad Request)} if the proba is not valid, * or with status {@code 500 (Internal Server Error)} if the proba couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PutMapping("/probas/{id}") public ResponseEntity<Proba> updateProba(@PathVariable(value = "id", required = false) final Long id, @RequestBody Proba proba) throws URISyntaxException { log.debug("REST request to update Proba : {}, {}", id, proba); if (proba.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, proba.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!probaRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } Proba result = probaRepository.save(proba); return ResponseEntity .ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, proba.getId().toString())) .body(result); } /** * {@code PATCH /probas/:id} : Partial updates given fields of an existing proba, field will ignore if it is null * * @param id the id of the proba to save. * @param proba the proba to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated proba, * or with status {@code 400 (Bad Request)} if the proba is not valid, * or with status {@code 404 (Not Found)} if the proba is not found, * or with status {@code 500 (Internal Server Error)} if the proba couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PatchMapping(value = "/probas/{id}", consumes = { "application/json", "application/merge-patch+json" }) public ResponseEntity<Proba> partialUpdateProba(@PathVariable(value = "id", required = false) final Long id, @RequestBody Proba proba) throws URISyntaxException { log.debug("REST request to partial update Proba partially : {}, {}", id, proba); if (proba.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } if (!Objects.equals(id, proba.getId())) { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } if (!probaRepository.existsById(id)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } Optional<Proba> result = probaRepository .findById(proba.getId()) .map(existingProba -> { if (proba.getIme() != null) { existingProba.setIme(proba.getIme()); } return existingProba; }) .map(probaRepository::save); return ResponseUtil.wrapOrNotFound( result, HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, proba.getId().toString()) ); } /** * {@code GET /probas} : get all the probas. * * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of probas in body. */ @GetMapping("/probas") public List<Proba> getAllProbas() { log.debug("REST request to get all Probas"); return probaRepository.findAll(); } /** * {@code GET /probas/:id} : get the "id" proba. * * @param id the id of the proba to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the proba, or with status {@code 404 (Not Found)}. */ @GetMapping("/probas/{id}") public ResponseEntity<Proba> getProba(@PathVariable Long id) { log.debug("REST request to get Proba : {}", id); Optional<Proba> proba = probaRepository.findById(id); return ResponseUtil.wrapOrNotFound(proba); } /** * {@code DELETE /probas/:id} : delete the "id" proba. * * @param id the id of the proba to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/probas/{id}") public ResponseEntity<Void> deleteProba(@PathVariable Long id) { log.debug("REST request to delete Proba : {}", id); probaRepository.deleteById(id); return ResponseEntity .noContent() .headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())) .build(); } }
package com.kic.map; import java.util.Map; import com.kic.set.MemberDTO; public class Map2 { public Map<String,MemberDTO> m2; public Map<String, MemberDTO> getM2() { return m2; } public void setM2(Map<String, MemberDTO> m2) { this.m2 = m2; } }
/** * Cette classe représente un point 3D */ public class Point extends Tuple { /** * constructeur * @param x * @param y * @param z */ public Point(float x, float y, float z) { super(x, y, z); } /** * constructeur par défaut */ public Point() { super(); } /** * retourne une chaîne décrivant le point */ public String toString() { return "Point("+x+","+y+","+z+")"; } /** * retourne un point correspondant à this + v * @param u * @param v * @return */ public static Point add(Point u, Vecteur v) { return new Point(u.x + v.x, u.y + v.y, u.z + v.z); } /** * retourne this + v * @param v * @return */ public Point add(Vecteur v) { return new Point(this.x + v.x, this.y + v.y, this.z + v.z); } }
package com.training.utils; import java.sql.SQLException; public interface DAO<T> { public boolean validate(String userId, String passWord) throws SQLException; public int register(String userId,String passWord) throws SQLException; }
package fr.univsavoie.istoage.clienttri; /** * Please modify this class to meet your needs * This class is not complete */ import java.io.File; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * This class was generated by Apache CXF 2.7.3 * 2013-03-18T16:54:33.096+01:00 * Generated source version: 2.7.3 * */ public final class StageSort_StageSortImplPort_Client { private static final QName SERVICE_NAME = new QName("http://soaptri.istoage.univsavoie.fr/", "StageSortImplService"); public StageSort_StageSortImplPort_Client( String stages ) { URL wsdlURL = StageSortImplService.WSDL_LOCATION; StageSortImplService ss = new StageSortImplService(wsdlURL, SERVICE_NAME); StageSort port = ss.getStageSortImplPort(); System.out.println("Invoking stageSort..."); String resultat = port.stageSort(stages); System.out.println("stageSort.result=" + resultat); } }
/* * Copyright (C) 2008-2010 Martin Riesz <riesz.martin at gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.petrinator.editor.canvas; import java.awt.Graphics; import java.awt.event.MouseEvent; import javax.swing.JPopupMenu; import org.petrinator.editor.PNEditor; import org.petrinator.petrinet.ArcEdge; import org.petrinator.petrinet.PlaceNode; import org.petrinator.petrinet.Subnet; import org.petrinator.petrinet.Transition; import org.petrinator.editor.Root; /** * * @author Martin Riesz <riesz.martin at gmail.com> */ public class PopupMenuFeature implements Feature { private Canvas canvas; public PopupMenuFeature(Canvas canvas) { this.canvas = canvas; } public void mousePressed(MouseEvent event) { int x = event.getX(); int y = event.getY(); int mouseButton = event.getButton(); int realX = x + canvas.getTranslationX(); int realY = y + canvas.getTranslationY(); if (mouseButton == MouseEvent.BUTTON3) { if (PNEditor.getRoot().getClickedElement() != null && (PNEditor.getRoot().isSelectedTool_Select() || PNEditor.getRoot().isSelectedTool_Place() || PNEditor.getRoot().isSelectedTool_Transition() || PNEditor.getRoot().isSelectedTool_Arc() || PNEditor.getRoot().isSelectedTool_Token() && !(PNEditor.getRoot().getClickedElement() instanceof PlaceNode))) { if (PNEditor.getRoot().getClickedElement() instanceof PlaceNode) { showPopup(PNEditor.getRoot().getPlacePopup(), realX, realY); if (!PNEditor.getRoot().getSelection().contains(PNEditor.getRoot().getClickedElement())) { PNEditor.getRoot().getSelection().clear(); } } else if (PNEditor.getRoot().getClickedElement() instanceof Subnet) { showPopup(PNEditor.getRoot().getSubnetPopup(), realX, realY); if (!PNEditor.getRoot().getSelection().contains(PNEditor.getRoot().getClickedElement())) { PNEditor.getRoot().getSelection().clear(); } } else if (PNEditor.getRoot().getClickedElement() instanceof Transition) { showPopup(PNEditor.getRoot().getTransitionPopup(), realX, realY); if (!PNEditor.getRoot().getSelection().contains(PNEditor.getRoot().getClickedElement())) { PNEditor.getRoot().getSelection().clear(); } } else if (PNEditor.getRoot().getClickedElement() instanceof ArcEdge) { showPopup(PNEditor.getRoot().getArcEdgePopup(), realX, realY); if (!PNEditor.getRoot().getSelection().contains(PNEditor.getRoot().getClickedElement())) { PNEditor.getRoot().getSelection().clear(); } } } if (PNEditor.getRoot().getClickedElement() == null && PNEditor.getRoot().isSelectedTool_Select()) { showPopup(PNEditor.getRoot().getCanvasPopup(), realX, realY); } } } private void showPopup(JPopupMenu popupMenu, int clickedX, int clickedY) { popupMenu.show(canvas, clickedX - 10, clickedY - 2); } public void drawForeground(Graphics g) { } public void drawBackground(Graphics g) { } public void mouseDragged(int x, int y) { } public void mouseReleased(int x, int y) { } public void setHoverEffects(int x, int y) { } public void setCursor(int x, int y) { } public void drawMainLayer(Graphics g) { } public void mouseMoved(int x, int y) { } }
package org.example; import java.util.ArrayList; import java.util.List; import com.aliyun.opensearch.*; import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Lists; import com.aliyun.opensearch.sdk.generated.OpenSearch; import com.aliyun.opensearch.sdk.generated.search.*; import com.aliyun.opensearch.sdk.generated.search.general.SearchResult; import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException; import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException; import com.aliyun.opensearch.search.SearchParamsBuilder; import org.junit.Assert; import org.junit.Test; public class SearchTest { private static String appName = "datax_test_v3"; private static String tableName = "datax_main_table"; private static String accesskey = "abc_key"; private static String secret = "abc_secret"; private static String host = "http://opensearch-cn-hangzhou.aliyuncs.com"; @Test public void testSearch() { //创建并构造OpenSearch对象 OpenSearch openSearch = new OpenSearch(accesskey, secret, host); //创建OpenSearchClient对象,并以OpenSearch对象作为构造参数 // OpenSearchClient serviceClient = new OpenSearchClient(openSearch, new EagleEyeHttpClientCollector()); OpenSearchClient serviceClient = new OpenSearchClient(openSearch); // serviceClient.setExpired(true); //创建SearcherClient对象,并以OpenSearchClient对象作为构造参数 SearcherClient searcherClient = new SearcherClient(serviceClient); //定义Config对象,用于设定config子句参数,指定应用名,分页,数据返回格式等等 Config config = new Config(Lists.newArrayList(appName)); config.setStart(0); config.setHits(10); List<String> fetchFields = new ArrayList<>(); fetchFields.add("data_id"); fetchFields.add("type_text"); fetchFields.add("type_double"); fetchFields.add("type_int"); fetchFields.add("type_int_array"); fetchFields.add("type_float_array"); fetchFields.add("type_literal"); fetchFields.add("type_short_test"); fetchFields.add("type_float"); fetchFields.add("type_double_array"); fetchFields.add("type_literal_array"); config.setFetchFields(fetchFields); // config.setCustomConfig() // config.addToCustomConfig("rerank_size:200"); // config.addToCustomConfig("total_rank_size:200000"); //设置返回格式为fulljson格式 config.setSearchFormat(SearchFormat.JSON); // 创建参数对象 SearchParams searchParams = new SearchParams(config); // 指定搜索的关键词,这里要指定在哪个索引上搜索,如果不指定的话默认在使用“default”索引(索引字段名称是您在您的数据结构中的“索引字段列表”中对应字段。),若需多个索引组合查询,需要在setQuery处合并,否则若设置多个setQuery子句,则后面的子句会替换前面子句 searchParams.setQuery("data_id:'data_id_lsh-15-03'"); // searchParams.setUserId("12314"); ////设置查询过滤条件 // searchParams.setFilter("id>0"); ////创建sort对象,并设置二维排序 // Sort sort = new Sort(); // searchParams.setSort(new Sort(Lists.newArrayList(new SortField("n", Order.DECREASE)))); // searchParams.setFilter(""); //////设置id字段降序 // sort.addToSortFields(new SortField("id", Order.DECREASE)); ////若id相同则以RANK相关性算分升序 // sort.addToSortFields(new SortField("RANK", Order.INCREASE)); ////添加Sort对象参数 // searchParams.setSort(sort); //执行查询语句返回数据对象 // Rank rank = new Rank(); // rank.setSecondRankName("asdaf"); // rank.setSecondRankType(RankType.CAVA_SCRIPT); // searchParams.setRank(rank); // searchParams.setRawQuery("abcdef"); try{ SearchParamsBuilder paramsBuilder = SearchParamsBuilder.create(searchParams); // paramsBuilder.addDistinct("", 0, 0, false, "", false, 0); // paramsBuilder.addFilter(""); SearchResult searchResult = searcherClient.execute(searchParams); //以字符串返回查询数据 String result = searchResult.getResult(); System.out.println(result); Thread.sleep(1000); } catch (OpenSearchException exception){ exception.printStackTrace(); } catch (OpenSearchClientException exception){ exception.printStackTrace(); }catch (InterruptedException e) { }finally { System.out.println(1); } Assert.assertTrue(true); } }
/* * 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 bts2java; /** * * @author rlaroussi */ public class Agrege extends Titulaire { public Agrege(String nom) { super(); } public void setDefaultCouleur(String couleur) { this.couleur = "Green"; }; public String toString() { return this.getNom(); } }
package com.liuyufei.bmc_android; import android.Manifest; import android.content.AsyncQueryHandler; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.view.GestureDetectorCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.util.Log; import com.liuyufei.bmc_android.admin.AdminActivity; import com.liuyufei.bmc_android.data.BMCContract; import com.liuyufei.bmc_android.login.LoginActivity; import com.liuyufei.bmc_android.model.Staff; import com.liuyufei.bmc_android.model.Visitor; import com.liuyufei.bmc_android.utility.Constants; import static com.liuyufei.bmc_android.R.id.checkbtn; import static com.liuyufei.bmc_android.data.BMCContract.CHECKIN; public class VisitorWelcomeActivity extends AppCompatActivity implements GestureDetector.OnDoubleTapListener, GestureDetector.OnGestureListener{ static String TAG = "VisitorWelcomeActivity"; Button btnRing; private GestureDetectorCompat myDector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Actionbar ActionBar actionBar = getSupportActionBar(); actionBar.hide(); setContentView(R.layout.activity_visitor_welcome); btnRing = (Button) findViewById(R.id.ring_button_visit); //ring reception // Set click Ring btnRing.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG,"User Click Ring"); if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { requestCameraPermission(); return ; } Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "0277777006")); startActivity(intent); } }); findViewById(checkbtn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { TextView mobileTV = (TextView) findViewById(R.id.inputMobile); final String inputMobile = mobileTV.getText().toString(); if(inputMobile==null||inputMobile.length()==0){ //alert input mobile is null new AlertDialog.Builder(VisitorWelcomeActivity.this) .setTitle("ERROR") .setMessage("Please input the Mobile") .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, null) .show(); return; } AsyncQueryHandler queryHandler = new AsyncQueryHandler(getContentResolver()) { @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { try { if ((cursor != null) && cursor.moveToFirst()) { // String displayName = cursor.getString(0); // go to appointment staffList page\ //find all appointments relevant to the visitor. //Intent intentToAppointmentForm = new Intent(VisitorWelcomeActivity.this,AdminActivity.class); Constants.STR_ACIVITY_NAME = "VisitorWelcomeActivity"; String visitorName = cursor.getString(cursor.getColumnIndex(BMCContract.VisitorEntry.COLUMN_NAME)); String visitorCompanyName = cursor.getString(cursor.getColumnIndex(BMCContract.VisitorEntry.COLUMN_BUSINESS_NAME)); String visitorMobile = cursor.getString(cursor.getColumnIndex(BMCContract.VisitorEntry.COLUMN_MOBILE)); Visitor visitor = new Visitor(-1,visitorName,visitorCompanyName,visitorMobile); Intent intentToAppointmentForm = new Intent(VisitorWelcomeActivity.this,VisitorCheckIn.class); intentToAppointmentForm.putExtra("visitor",visitor); intentToAppointmentForm.putExtra("check_status",CHECKIN); startActivity(intentToAppointmentForm); }else{ //check if the visitor is new //if new go to the appointment creation page Intent intentToAppointmentForm = new Intent(VisitorWelcomeActivity.this,VisitorCheckIn.class); intentToAppointmentForm.putExtra("mobile",inputMobile); intentToAppointmentForm.putExtra("check_status",CHECKIN); startActivity(intentToAppointmentForm); } } finally { cursor.close(); } } }; String selection = BMCContract.VisitorEntry.COLUMN_MOBILE+"=?"; String[] selectionArgs = {inputMobile}; queryHandler.startQuery(0, null, BMCContract.VisitorEntry.CONTENT_URI, new String[] {BMCContract.VisitorEntry.COLUMN_NAME, BMCContract.VisitorEntry.COLUMN_BUSINESS_NAME, BMCContract.VisitorEntry.COLUMN_MOBILE}, selection, selectionArgs, null); } }); myDector = new GestureDetectorCompat(this,this); myDector.setOnDoubleTapListener(this); } private static final int REQUEST_CALL_PHONE = 0; public void requestCameraPermission(){ Log.i(TAG,"requestCameraPermission -- start --"); if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CALL_PHONE)){ ActivityCompat.requestPermissions(VisitorWelcomeActivity.this, new String[]{Manifest.permission.CALL_PHONE},REQUEST_CALL_PHONE); }else{ ActivityCompat.requestPermissions(VisitorWelcomeActivity.this, new String[]{Manifest.permission.CALL_PHONE},REQUEST_CALL_PHONE); } } /** * Handle the permission check result of contacts * @param requestCode * @param permissions * @param grantResults */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if(requestCode==RESULT_OK){ Log.i(TAG,"print onRequestPermission return yes"); Log.i(TAG,"print permission granted:" + PackageManager.PERMISSION_GRANTED); //check if only permission has been granted if(grantResults.length==1 && grantResults[0]==PackageManager.PERMISSION_GRANTED){ Log.i(TAG,"Contacts Permission Granted"); } } } @Override public boolean onTouchEvent(MotionEvent event) { this.myDector.onTouchEvent(event); return super.onTouchEvent(event); } // Visitor Welcome public void backToAdminActivity(){ Intent i = new Intent(getApplicationContext(), AdminActivity.class); startActivity(i); finish(); } @Override public boolean onSingleTapConfirmed(MotionEvent e) { return false; } @Override public boolean onDoubleTap(MotionEvent e) { backToAdminActivity(); return true; } @Override public boolean onDoubleTapEvent(MotionEvent e) { return false; } @Override public boolean onDown(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } }
package com.davivienda.utilidades.ws.cliente.solicitudNotaCreditoCtaCorriente; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for generarNotaCreditoCtaCorrienteResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="generarNotaCreditoCtaCorrienteResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="result" type="{http://servicios.davivienda.com/solicitudNotaCreditoCtaCorrienteServiceTypes}RespuestaNotaCreditoCtaCorrienteDto"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "generarNotaCreditoCtaCorrienteResponse_", propOrder = { "result" }) public class GenerarNotaCreditoCtaCorrienteResponse { @XmlElement(required = true, nillable = true) protected RespuestaNotaCreditoCtaCorrienteDto result; /** * Gets the value of the result property. * * @return * possible object is * {@link RespuestaNotaCreditoCtaCorrienteDto } * */ public RespuestaNotaCreditoCtaCorrienteDto getResult() { return result; } /** * Sets the value of the result property. * * @param value * allowed object is * {@link RespuestaNotaCreditoCtaCorrienteDto } * */ public void setResult(RespuestaNotaCreditoCtaCorrienteDto value) { this.result = value; } }
package com.legaoyi; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration("appConfiguration") @ImportResource(locations = {"classpath*:applicationContext*.xml"}) public class AppConfiguration { }
import edu.duke.*; import java.io.*; public class Image_Inversion { public ImageResource makeInversion(ImageResource inImage) { ImageResource outImage = new ImageResource(inImage.getWidth(),inImage.getHeight()); for(Pixel pixel: outImage.pixels()){ Pixel inPixel = inImage.getPixel(pixel.getX(),pixel.getY()); int negRed = 255 - inPixel.getRed(); int negGreen = 255 - inPixel.getGreen(); int negBlue = 255 - inPixel.getBlue(); pixel.setRed(negRed); pixel.setGreen(negGreen); pixel.setBlue(negBlue); } return outImage; } public void SaveCopyImage(ImageResource inImage,String name,String accion){ String newName = "Copy-"+accion+name; inImage.setFileName(newName); inImage.save(); } public void selecAndConvert(){ DirectoryResource dr = new DirectoryResource(); for(File f : dr.selectedFiles()){ ImageResource currentImg = new ImageResource(f); String name = currentImg.getFileName(); ImageResource negative = makeInversion(currentImg); SaveCopyImage(negative,name,"Negative"); negative.draw(); } } }
package com.soldevelo.vmi.testclient.client; import com.soldevelo.vmi.enumerations.DiagnosticState; import com.soldevelo.vmi.enumerations.TestProtocol; import com.soldevelo.vmi.packets.ResultPacket; import com.soldevelo.vmi.packets.TestIncrement; import com.soldevelo.vmi.packets.TestLocation; import com.soldevelo.vmi.packets.TestRequest; import com.soldevelo.vmi.packets.TestRequestPhase2; import com.soldevelo.vmi.packets.TestResult; import com.soldevelo.vmi.packets.TestResultDns; import com.soldevelo.vmi.testclient.conf.ClientConfig; import com.soldevelo.vmi.testclient.facade.DnsTestFacade; import com.soldevelo.vmi.testclient.facade.FtpTestFacade; import com.soldevelo.vmi.testclient.facade.HttpTestFacade; import com.soldevelo.vmi.testclient.facade.ServerFacade; import com.soldevelo.vmi.time.VerizonTimestamp; import com.soldevelo.vmi.utils.MacHelper; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.RandomUtils; import org.apache.commons.lang.time.StopWatch; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @Component public class TestClient { private static final Logger LOG = LoggerFactory.getLogger(TestClient.class); private static final int INCREMENT_COUNT = 2; @Autowired private ServerFacade serverFacade; @Autowired private HttpTestFacade httpTestFacade; @Autowired private DnsTestFacade dnsTestFacade; @Autowired private FtpTestFacade ftpTestFacade; private StopWatch clock = new StopWatch(); private ClientConfig clientConfig; public ExecutionResult go(ClientConfig clientConfig) { this.clientConfig = clientConfig; TestRequest testRequestResponse; if (clientConfig.sendRequest()) { try { testRequestResponse = sendTestRequest(); } catch (IOException e) { LOG.error("Error while handling TestRequests", e); return new ExecutionResult(false); } } else { testRequestResponse = fakeRequestResponse(); } if (testRequestResponse instanceof TestRequestPhase2) { TestRequestPhase2 phase2response = (TestRequestPhase2) testRequestResponse; logResponse(phase2response); if (phase2response.getNRT()) { LOG.info("Rescheduled for a different date: " + phase2response.getNextRequestTime()); ExecutionResult executionResult = new ExecutionResult(false); executionResult.setNextRequestTime(phase2response.getNextRequestTime()); return executionResult; } } LOG.info("Beginning tests"); waitBeforeExecution(); TestLocation testLocation = null; List<TestResult> testResults = executeTests(testRequestResponse); List<TestIncrement> increments = new ArrayList<TestIncrement>(); if (clientConfig.sendIncrements()) { increments.addAll(fakeTestIncrements(clientConfig.getDownloadUrl(), INCREMENT_COUNT, clientConfig.getDownloadSize())); increments.addAll(fakeTestIncrements(clientConfig.getUploadUrl(), INCREMENT_COUNT, clientConfig.getUploadSize())); } if (testResults.isEmpty()) { LOG.info("No results to send"); } else if (clientConfig.sendResults()) { LOG.info("Sending results"); try { testLocation = (clientConfig.getRequestVersion() > 0) ? buildTestLocation() : null; sendPackets(testResults, testLocation, increments); } catch (IOException e) { LOG.error("Error while sending test results to server", e); return new ExecutionResult(false); } } return new ExecutionResult(true, testLocation, testResults, increments); } private void logResponse(TestRequestPhase2 phase2response) { LOG.info("Protocol in Test Response: " + phase2response.getTestProtocol()); LOG.info("Phase 2 bits in the received Test Response:"); LOG.info("WFI: " + phase2response.getWFI()); LOG.info("NRT: " + phase2response.getNRT()); String nrt = phase2response.getNextRequestTime(); if (StringUtils.isNotBlank(nrt)) { LOG.info("Next request time: " + nrt); } } private void waitBeforeExecution() { int waitPeriod = clientConfig.getWaitPeriod(); if (waitPeriod > 0) { try { Thread.sleep(waitPeriod * 1000); } catch (InterruptedException e) { LOG.error("Interrupted", e); } } } private List<TestResult> executeTests(TestRequest testRequestResponse) { List<TestResult> testResults = new ArrayList<TestResult>(); String downloadUrl = (testRequestResponse instanceof TestRequestPhase2) ? ((TestRequestPhase2) testRequestResponse) .getDownloadUrl() : clientConfig.getDownloadUrl(); String uploadUrl = (testRequestResponse instanceof TestRequestPhase2) ? ((TestRequestPhase2) testRequestResponse) .getUploadUrl() : clientConfig.getUploadUrl(); if (testRequestResponse.isHTTPRequest()) { testResults.addAll(executeHttpTests(testRequestResponse, downloadUrl, uploadUrl)); } else if (testRequestResponse.getTestProtocol() == TestProtocol.WPR && testRequestResponse.getDTE()) { testResults.add(executeWebPageTest(testRequestResponse, downloadUrl)); } else if (testRequestResponse.getTestProtocol() == TestProtocol.NDT) { testResults.addAll(executeNdtTests(testRequestResponse, downloadUrl)); } else if (testRequestResponse.getTestProtocol() == TestProtocol.DNS && testRequestResponse instanceof TestRequestPhase2) { testResults.addAll(executeDnsTest((TestRequestPhase2) testRequestResponse)); } else if (testRequestResponse.getTestProtocol() == TestProtocol.FTP) { testResults.addAll(executeFtpTests(testRequestResponse, downloadUrl, uploadUrl)); } return testResults; } private List<TestResult> executeHttpTests(TestRequest testRequestResponse, String downloadUrl, String uploadUrl) { LOG.info("Starting HTTP tests"); List<TestResult> testResults = new ArrayList<TestResult>(); if (testRequestResponse.getDTE()) { TestResult downloadResult = (clientConfig.doTransfer()) ? httpTestFacade .executeDownloadTest(downloadUrl, clientConfig.getDownloadSize(), clientConfig.getThreadNumber()) : randomTestResult(downloadUrl, clientConfig.getDownloadSize()); testResults.add(downloadResult); } if (testRequestResponse.getUTE()) { TestResult uploadResult = (clientConfig.doTransfer()) ? httpTestFacade .executeUploadTest(uploadUrl, clientConfig.getUploadSize(), clientConfig.getThreadNumber()) : randomTestResult(uploadUrl, clientConfig.getUploadSize()); testResults.add(uploadResult); } return testResults; } private List<TestResult> executeFtpTests(TestRequest testRequestResponse, String downloadUrl, String uploadUrl) { LOG.info("Starting FTP tests"); List<TestResult> testResults = new ArrayList<TestResult>(); if (testRequestResponse.getDTE()) { TestResult downloadResult = (clientConfig.doTransfer()) ? ftpTestFacade .executeDownloadTest(downloadUrl, clientConfig.getDownloadSize()) : randomTestResult(downloadUrl, clientConfig.getDownloadSize()); testResults.add(downloadResult); } if (testRequestResponse.getUTE()) { TestResult uploadResult = (clientConfig.doTransfer()) ? ftpTestFacade .executeUploadTest(uploadUrl, clientConfig.getUploadSize()) : randomTestResult( uploadUrl, clientConfig.getUploadSize()); testResults.add(uploadResult); } return testResults; } private List<TestResult> executeNdtTests(TestRequest testRequestResponse, String ndtUrl) { List<TestResult> testResults = new ArrayList<TestResult>(); if (testRequestResponse.getDTE()) { TestResult downloadResult = randomTestResult(ndtUrl, clientConfig.getDownloadSize()); testResults.add(downloadResult); } if (testRequestResponse.getUTE()) { TestResult uploadResult = randomTestResult(ndtUrl, clientConfig.getUploadSize()); testResults.add(uploadResult); } return testResults; } private TestResult executeWebPageTest(TestRequest testRequest, String downloadUrl) { TestResult downloadResult = null; if (testRequest.getDTE()) { downloadResult = (clientConfig.doTransfer()) ? httpTestFacade.executeDownloadTest( downloadUrl, 0, clientConfig.getThreadNumber()) : randomTestResult(downloadUrl, clientConfig.getDownloadSize()); String diagnosticState = downloadResult.getDiagnosticState(); diagnosticState = "WebPage_" + diagnosticState + " " + (RandomUtils.nextInt(8000) + 1000); downloadResult.setDiagnosticState(diagnosticState); } return downloadResult; } private List<TestResultDns> executeDnsTest(TestRequestPhase2 testRequestPhase2) { List<TestResultDns> testResults = new ArrayList<TestResultDns>(); if (testRequestPhase2.getDTE()) { int numberOfRepetitions = Integer.parseInt(testRequestPhase2.getUploadUrl()); String hostname = testRequestPhase2.getDownloadUrl(); testResults.addAll(dnsTestFacade.dnsResponseTimeTest(hostname, clientConfig.getDnsServer(), numberOfRepetitions)); } return testResults; } private void sendPackets(List<TestResult> testResults, TestLocation testLocation, List<TestIncrement> increments) { LOG.info("Sending results"); try { List<ResultPacket> packetsToSend = new ArrayList<ResultPacket>(); packetsToSend.addAll(testResults); if (testLocation != null) { packetsToSend.add(testLocation); } packetsToSend.addAll(increments); serverFacade.sendResults(packetsToSend, clientConfig.getServer(), clientConfig.getResultsPort()); } catch (Exception e) { LOG.error("Error while sending test results to server, please check the resultPort"); } } private TestRequest sendTestRequest() throws IOException { TestRequest testRequest = buildTestRequest(); LOG.info(String.format("Sending TestRequest to %s:%d", clientConfig.getServer(), clientConfig.getRequestPort())); clock.start(); TestRequest response = serverFacade.sendRequest(testRequest, clientConfig.getServer(), clientConfig.getRequestPort()); clock.stop(); LOG.info("Received response after " + clock.getTime() + " ms\n"); clock.reset(); return response; } private TestRequest buildTestRequest() { TestRequest testRequest = (clientConfig.getRequestVersion() == 1) ? new TestRequestPhase2() : new TestRequest(); testRequest.setMacAddress(MacHelper.toBytes(clientConfig.getMacAddress())); testRequest.setUTR(clientConfig.scheduleUpload()); testRequest.setDTR(clientConfig.scheduleDownload()); TestProtocol protocol = TestProtocol.valueOf(clientConfig.getTestProtocol()); testRequest.setTestProtocol(protocol); if (testRequest instanceof TestRequestPhase2) { TestRequestPhase2 testRequestPhase2 = (TestRequestPhase2) testRequest; testRequestPhase2.setThreadNumber(clientConfig.getThreadNumber()); testRequestPhase2.setUploadUrl(clientConfig.getUploadUrl()); testRequestPhase2.setDownloadUrl(clientConfig.getDownloadUrl()); } return testRequest; } private TestRequest fakeRequestResponse() { TestRequest testRequest = buildTestRequest(); testRequest.setUTR(clientConfig.scheduleUpload()); testRequest.setUTE(clientConfig.scheduleUpload()); testRequest.setDTR(clientConfig.scheduleDownload()); testRequest.setDTE(clientConfig.scheduleDownload()); return testRequest; } private TestLocation buildTestLocation() throws UnknownHostException { TestLocation testLocation = new TestLocation(); testLocation.setBhrIPAddress(InetAddress.getByName("localhost").getHostAddress()); testLocation.setBhrMACAddress(clientConfig.getMacAddress().replace(":", "")); testLocation.setDeviceSerialNumber(clientConfig.getSerialNumber()); testLocation.setDownstreamSpeedTier("Downstream"); testLocation.setUpstreamSpeedTier("Upstream"); testLocation.setGwrId(clientConfig.getGwrId()); testLocation.setOltId(clientConfig.getOltId()); testLocation.setOntModel(clientConfig.getOntId()); testLocation.setLataId(clientConfig.getLataId()); testLocation.setLowAcitivityWaitExpirationCount(ByteBuffer.allocate(4) .putInt(clientConfig.getLowActivityCount()).array()); return testLocation; } private List<TestIncrement> fakeTestIncrements(String url, int incrementCount, long totalBytes) { List<TestIncrement> increments = new ArrayList<TestIncrement>(); for (int i = 1; i <= incrementCount; i++) { TestIncrement increment = new TestIncrement(); increment.setDiagnosticState("TestIncrement " + i); increment.setDownloadUploadUrl(url); increment.setIncTotalBytesReceivedSent(totalBytes / incrementCount * i + 10); increment.setIncTestBytesReceivedSent(totalBytes / incrementCount * i); VerizonTimestamp incBomTime = new VerizonTimestamp(); increment.setIncBomTime(incBomTime.toString()); incBomTime.setTime(incBomTime.getTime() + 5000); increment.setIncEomTime(incBomTime.toString()); increments.add(increment); } return increments; } private TestResult randomTestResult(String url, long size) { TestResult testResult = new TestResult(); testResult.setDiagnosticState(DiagnosticState.COMPLETED); long bomTime = DateTime.now().getMillis(); long romTime = bomTime + RandomUtils.nextInt(60) * 1000; long eomTime = bomTime + 3000 + RandomUtils.nextInt(60) * 1000; testResult.setRomTime(new VerizonTimestamp(romTime).toString()); testResult.setBomTime(new VerizonTimestamp(bomTime).toString()); testResult.setEomTime(new VerizonTimestamp(eomTime).toString()); testResult.setTcpOpenResponseTime(new VerizonTimestamp(bomTime).toString()); testResult.setTcpOpenResponseTime(new VerizonTimestamp(eomTime).toString()); testResult.setDownloadOrUploadUrl(url); testResult.setTestBytesReceivedOrFileLength(size); testResult.setTotalBytesReceivedOrSent(size); return testResult; } }
package com.codingchili.instance.model.spells; import com.codingchili.instance.model.entity.Vector; /** * @author Robin Duda * <p> * A spell target is required to cast spells. * A target can be either a vector or a single creature, depending on the spell. */ public class SpellTarget { private Vector vector; private String targetId; public Vector getVector() { return vector; } public SpellTarget setVector(Vector vector) { this.vector = vector; return this; } public String getTargetId() { return targetId; } public SpellTarget setTargetId(String targetId) { this.targetId = targetId; return this; } }
package gov.nih.mipav.model.structures; import java.util.*; // VOI event change /** * <code>UpdateVOISelectionListener</code> permits objects to listen for updates to a <code>VOI</code>. This may permit * an object to update its view when the <code>VOI</code> changes. * * @see UpdateVOIEvent $Logfile: /mipav/src/gov/nih/mipav/model/structures/UpdateVOISelectionListener.java $ $Revision: * 1 $ $Date: 8/08/02 10:06a $ */ public interface UpdateVOISelectionListener extends EventListener { //~ Methods -------------------------------------------------------------------------------------------------------- /** * handles an UpdateVOIEvent as a selection change. * * @param newVOIselection DOCUMENT ME! */ void selectionChanged(UpdateVOIEvent newVOIselection); }
package week1homework; import java.util.*; public class SumOfNumber { public static void main(String[] args) { // TODO Auto-generated method stub int number; int sum=0; Scanner n=new Scanner(System.in); System.out.println("Enter the number:"); number=n.nextInt(); for(int i=number; i!=0;--i ) { sum=sum+number; System.out.println(sum); n.close(); /*3!=0 --2 s=0+3=3 2!=0 --1 s=3+3=6 1!=0 --0 s=6+3*/ } } }
import java.sql.Connection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class Pagamento { private int id; private String data; private double valor; private int idCompra; private MysqlConnect db; private Connection conn; public Pagamento(int id, String data, double valor, int idCompra) { this.id = id; this.data = data; this.valor = valor; this.idCompra = idCompra; connect(); } private void connect(){ db = new MysqlConnect(); conn = db.getConnection(); } public int getIdCompra() { return idCompra; } public void setIdCompra(int idCompra) { this.idCompra = idCompra; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } public double getValor() { return valor; } public void setValor(double valor) { this.valor = valor; } public void incluir() { String sql = "INSERT INTO pagamento (data,valor,idcompra) VALUES (?,?,?)"; PreparedStatement st; try { st = conn.prepareStatement(sql); st.setString(1, getData()); st.setDouble(2, getValor()); st.setInt(3, getIdCompra()); st.executeUpdate(); st.close(); } catch (SQLException e) { e.printStackTrace(); } db.closeConnection(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * ConsultiPanel.java * * Created on Nov 12, 2010, 6:35:07 PM */ package josteo.views; import josteo.views.UI.ConsultoAdvancedTableFormat; import josteo.infrastructure.UI.PanelListBase; import josteo.application.IPazienteSelectedListner; import java.util.*; import javax.swing.event.*; import ca.odell.glazedlists.swing.*; import ca.odell.glazedlists.*; import ca.odell.glazedlists.gui.*; import java.beans.PropertyChangeEvent; import josteo.viewmodels.*; import josteo.model.paziente.*; import josteo.application.*; import josteo.infrastructure.helpers.*; import josteo.infrastructure.DomainBase.*; import josteo.infrastructure.UI.*; import josteo.views.UI.*; import javax.swing.text.*; import javax.swing.*; import java.awt.event.*; /** * * @author cristiano */ public class ConsultiPanel extends PanelListBase<Consulto> implements IPazienteSelectedListner { //private josteo.viewmodels.ConsultiPresenter _presenter; /** Creates new form ConsultiPanel */ public ConsultiPanel() { super(); initComponents(); //josteo.application.ApplicationState.getInstance().addPazienteChangedListner("ConsultiView"); this._presenter = new josteo.viewmodels.ConsultiPresenter(); ApplicationState.getInstance().addPazienteSelectedListener(this); this.jTable1.setRowHeight(32); this.taDescrizione.getDocument().addDocumentListener(new UpdateListener()); this.dcData.addPropertyChangeListener(new MyPropertyChangeListener()); EsamiPanel esamiPanel = new EsamiPanel(); AnamnesiProssimePanel anamnesiProssimePanel = new AnamnesiProssimePanel(); ValutazioniPanel valutazioniPanel = new ValutazioniPanel(); TrattamentiPanel trattamentiPanel = new TrattamentiPanel(); this.jTabbedPane1.addTab("Esami", esamiPanel); this.jTabbedPane1.addTab("Anamnesi Prossime", anamnesiProssimePanel); this.jTabbedPane1.addTab("Trattamenti", trattamentiPanel); this.jTabbedPane1.addTab("Valutazioni", valutazioniPanel); // Disable the tab //jTabbedPane1.setEnabledAt(0, false); } /** 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() { jSplitPane1 = new javax.swing.JSplitPane(); spConsulti = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); pnConsulto = new javax.swing.JPanel(); pnConsultoData = new javax.swing.JPanel(); lblData = new javax.swing.JLabel(); dcData = new com.toedter.calendar.JDateChooser(); pnSubmit = new javax.swing.JPanel(); btnReset = new javax.swing.JButton(); btnStore = new javax.swing.JButton(); pnDescrizione = new javax.swing.JPanel(); lblDescr = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); taDescrizione = new javax.swing.JTextArea(); jTabbedPane1 = new javax.swing.JTabbedPane(); jSplitPane1.setDividerLocation(400); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Data", "Descrizione" } ) { boolean[] canEdit = new boolean [] { false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); spConsulti.setViewportView(jTable1); jSplitPane1.setLeftComponent(spConsulti); pnConsulto.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Consulto", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Lucida Grande", 2, 13))); // NOI18N pnConsulto.setPreferredSize(new java.awt.Dimension(840, 310)); lblData.setText("Data"); org.jdesktop.layout.GroupLayout pnConsultoDataLayout = new org.jdesktop.layout.GroupLayout(pnConsultoData); pnConsultoData.setLayout(pnConsultoDataLayout); pnConsultoDataLayout.setHorizontalGroup( pnConsultoDataLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(lblData) .add(dcData, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 203, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) ); pnConsultoDataLayout.setVerticalGroup( pnConsultoDataLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(pnConsultoDataLayout.createSequentialGroup() .add(lblData) .add(0, 0, 0) .add(dcData, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) ); btnReset.setText("Reset"); btnReset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnResetActionPerformed(evt); } }); btnStore.setText("Store"); btnStore.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnStoreActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout pnSubmitLayout = new org.jdesktop.layout.GroupLayout(pnSubmit); pnSubmit.setLayout(pnSubmitLayout); pnSubmitLayout.setHorizontalGroup( pnSubmitLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(pnSubmitLayout.createSequentialGroup() .addContainerGap() .add(btnReset) .add(32, 32, 32) .add(btnStore) .addContainerGap(20, Short.MAX_VALUE)) ); pnSubmitLayout.setVerticalGroup( pnSubmitLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(pnSubmitLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(btnStore) .add(btnReset)) ); lblDescr.setText("Descrizione"); taDescrizione.setColumns(2); taDescrizione.setRows(2); taDescrizione.setWrapStyleWord(true); jScrollPane1.setViewportView(taDescrizione); org.jdesktop.layout.GroupLayout pnDescrizioneLayout = new org.jdesktop.layout.GroupLayout(pnDescrizione); pnDescrizione.setLayout(pnDescrizioneLayout); pnDescrizioneLayout.setHorizontalGroup( pnDescrizioneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(lblDescr) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 471, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) ); pnDescrizioneLayout.setVerticalGroup( pnDescrizioneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(pnDescrizioneLayout.createSequentialGroup() .add(lblDescr) .add(0, 0, 0) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)) ); org.jdesktop.layout.GroupLayout pnConsultoLayout = new org.jdesktop.layout.GroupLayout(pnConsulto); pnConsulto.setLayout(pnConsultoLayout); pnConsultoLayout.setHorizontalGroup( pnConsultoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(pnConsultoLayout.createSequentialGroup() .add(pnConsultoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(pnConsultoLayout.createSequentialGroup() .add(5, 5, 5) .add(pnConsultoData, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(pnConsultoLayout.createSequentialGroup() .add(110, 110, 110) .add(pnSubmit, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(pnDescrizione, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 443, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pnConsultoLayout.setVerticalGroup( pnConsultoLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(pnConsultoLayout.createSequentialGroup() .add(pnConsultoData, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(pnDescrizione, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(18, 18, 18) .add(pnSubmit, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(126, 126, 126)) ); jSplitPane1.setRightComponent(pnConsulto); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 869, Short.MAX_VALUE) .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 869, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jSplitPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 336, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed // TODO add your handling code here: reset(); }//GEN-LAST:event_btnResetActionPerformed private void btnStoreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStoreActionPerformed // TODO add your handling code here: store(); }//GEN-LAST:event_btnStoreActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnReset; private javax.swing.JButton btnStore; private com.toedter.calendar.JDateChooser dcData; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTable jTable1; private javax.swing.JLabel lblData; private javax.swing.JLabel lblDescr; private javax.swing.JPanel pnConsulto; private javax.swing.JPanel pnConsultoData; private javax.swing.JPanel pnDescrizione; private javax.swing.JPanel pnSubmit; private javax.swing.JScrollPane spConsulti; private javax.swing.JTextArea taDescrizione; // End of variables declaration//GEN-END:variables public void PazienteSelected( Paziente paziente ){ System.out.println("ConsultiPanel->PazienteSelected" + (paziente==null? "null" : paziente.getCognome().toString())); this.Init(); } public void Init(){ this._items = new SortedList( this._presenter.getItems(), new DateComparator()); gridConfig(new ConsultoAdvancedTableFormat()); this._presenter.Load(); reset(); jTabbedPane1.setVisible(false); this.addTabLisntener(); } @Override protected void jTable1_SelectionChanged(ListSelectionEvent evt){ super.jTable1_SelectionChanged(evt); //System.out.println("ConsultiPanel.jTable1_SelectionChanged -> selItem:"+this._presenter.getSelected().get_Key().toString()); boolean bConsultoSelected = ConsultiPanel.this._presenter.getSelected()!=null; jTabbedPane1.setVisible(bConsultoSelected); } @Override protected JTable getTable(){ return this.jTable1; } @Override protected void bindUI(){ Consulto item = (Consulto)this._presenter.getSelected(); if(item==null) item = (Consulto)this._presenter.getNewItem(); ApplicationState.getInstance().setSelectedConsulto(item); jSplitPane1.setDividerLocation(0.5); System.out.println("bindUI -> selItem:"+item.get_Key().toString()); if(item==null) return; boolean bBind = true; if(this._isDirty){ int i = JOptionPane.showConfirmDialog(null,"Vuoi sovrascrivere i dati nel form con la nuova selezione?","Dati non salvati", JOptionPane.YES_NO_OPTION); bBind = (i==0); } if(bBind){ this.taDescrizione.setText((this._presenter.getSelected()!=null)? item.get_ProblemaIniziale() : ""); this.dcData.setDate((this._presenter.getSelected()!=null)? item.get_Data() : new Date()); this._isDirty = false; System.out.println("bindUI done"); } } @Override protected boolean bindToPresenter(){ Consulto itemTmp = new Consulto(0, this.dcData.getDate(), this.taDescrizione.getText()); List<BrokenRule> brokenRules = itemTmp.GetBrokenRules(); if(brokenRules.size()>0){ List<String> errors = new ArrayList<String>(); for(BrokenRule br : brokenRules) errors.add(br.get_Message()); JOptionPane.showMessageDialog(this, josteo.infrastructure.helpers.StringHelper.join(errors,"\n")); return false; } Consulto item = this._presenter.getSelected()==null? (Consulto)this._presenter.getNewItem() : (Consulto)this._presenter.getSelected(); System.out.println("bindToPresenter:" + item.get_Key()); item.set_Data(itemTmp.get_Data()); item.set_ProblemaIniziale(itemTmp.get_ProblemaIniziale()); return true; } class DateComparator implements Comparator{ public int compare(Object obj1, Object obj2){ //parameter are of type Object, so we have to downcast it to Employee objects Date dt1 = ( (Consulto) obj1 ).get_Data(); Date dt2 = ( (Consulto) obj2 ).get_Data(); //uses compareTo method of String class to compare names of the employee return dt1.compareTo(dt2); } } }
package br.com.maricamed.entities; import java.time.Instant; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; @SuppressWarnings("serial") @Entity @Table(name = "usuarios", indexes = {@Index(name = "idx_usuario_email", columnList = "email")}) public class Usuario extends AbstractEntity { @Column(name = "nome", nullable = false, length = 200) private String nome; @Column(name = "telefone1", length = 20) private String telefone1; @Column(name = "telefone2", length = 20) private String telefone2; @Column(name = "celular", length = 20) private String celular; @Column(name = "data_cadastro", nullable = false, length = 10) private Instant dtCadastro; @Column(name = "email", unique = true, nullable = false) private String email; @JsonIgnore @Column(name = "senha") private String senha; @ManyToMany @JoinTable( name = "usuarios_tem_perfis", joinColumns = { @JoinColumn(name = "usuario_id", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "perfil_id", referencedColumnName = "id") } ) private List<Perfil> perfis; @Column(name = "ativo", nullable = false, columnDefinition = "TINYINT(1)") private boolean ativo; @Column(name = "codigo_verificador", length = 6) private String codigoVerificador; public Usuario() { super(); } public Usuario(Long id) { super.setId(id); } // adiciona perfis a lista public void addPerfil(PerfilTipo tipo) { if (this.perfis == null) { this.perfis = new ArrayList<>(); } this.perfis.add(new Perfil(tipo.getCod())); } public Usuario(String email) { this.email = email; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getTelefone1() { return telefone1; } public void setTelefone1(String telefone1) { this.telefone1 = telefone1; } public String getTelefone2() { return telefone2; } public void setTelefone2(String telefone2) { this.telefone2 = telefone2; } public String getCelular() { return celular; } public void setCelular(String celular) { this.celular = celular; } public Instant getDtCadastro() { return dtCadastro; } public void setDtCadastro(Instant dtCadastro) { this.dtCadastro = dtCadastro; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public List<Perfil> getPerfis() { return perfis; } public void setPerfis(List<Perfil> perfis) { this.perfis = perfis; } public boolean isAtivo() { return ativo; } public void setAtivo(boolean ativo) { this.ativo = ativo; } public String getCodigoVerificador() { return codigoVerificador; } public void setCodigoVerificador(String codigoVerificador) { this.codigoVerificador = codigoVerificador; } }
package com.zxt.framework.dictionary.service; import java.util.List; import com.zxt.framework.dictionary.entity.DataDictionary; import com.zxt.framework.dictionary.entity.DictionaryGroup; public interface IDataDictionaryService { /** * 根据Id查找对象 * @param id * @return */ public DataDictionary findById(String id); /** * 根据名称查找对象 * @param name * @return */ public DictionaryGroup findGroupByName(String name); /** * 判断对象是否存在 * @param id * @param name * @return */ public boolean isExist(String id,String name); /** * 判断对象是否存在 * @param id * @param name * @return */ public boolean isExistUpdate(String id,String name); /** * 判断数据字典分组是否存在 * @param id * @param name * @return */ public boolean isDicGroupExistUpdate(String id,String name); /** * 根据ID查找所有对象 * @param ids * @return */ public List findAllByIds(String ids); /** * 根据多个GroupID查找所有对象 * @param ids * @return */ public List findAllByGroupIds(String ids); /** * 查找所有对象 * @return */ public List findAll(); /** * 根据GroupID查找所有对象 * @param dictGroupId * @return */ public List findByDictGroupId(String dictGroupId); /** * 根据名称模糊查询对象 * @return */ public List findDictLikeName(String dictName); /** * 查找总记录数 * @return */ public int findTotalRows(); /** * 分页查找 * @param page 页码 * @param rows 每页记录数 * @return */ public List findAllByPage(int page,int rows); /** * 查找总记录数 * @return */ public int findTotalRowsByCondition(String dictName,String dictGroup); /** * 分页查找 * @param page 页码 * @param rows 每页记录数 * @return */ public List findAllByCondition(int page,int rows,String dictName,String dictGroup); /** * 插入对象 * @param DataDictionary */ public void insert(DataDictionary dataDictionary); public void insertAll(List dataDictionarys) ; /** * 修改对象 * @param DataDictionary */ public void update(DataDictionary dataDictionary); /** * 删除对象 * @param DataDictionary */ public void delete(DataDictionary dataDictionary); /** * 根据Id删除对象 * @param id */ public void deleteById(String id); /** * 删除对象 * @param paramCollection */ public void deleteAll(List paramCollection); //group /** * 根据Id查找对象 * @param id * @return */ public DictionaryGroup findDictGroupById(String id); /** * 根据ID查找所有DictionaryGroup对象 * @param ids * @return */ public List findAllDictGroupByIds(String ids); /** * 查找所有DictionaryGroup对象 * @return */ public List findAllDictGroup(); /** * 查找DictionaryGroup总记录数 * @return */ public int findDictGroupTotalRows(); /** * 分页查找DictionaryGroup * @param page 页码 * @param rows 每页记录数 * @return */ public List findAllDictGroupByPage(int page,int rows); /** * 插入DictionaryGroup对象 * @param DictionaryGroup */ public void insertDictGroup(DictionaryGroup dictionaryGroup); /** * 修改DictionaryGroup对象 * @param DictionaryGroup */ public void updateDictGroup(DictionaryGroup dictionaryGroup); /** * 删除DictionaryGroup对象 * @param DictionaryGroup */ public void deleteDictGroup(DictionaryGroup dictionaryGroup); /** * 根据Id删除DictionaryGroup对象 * @param id */ public void deleteDictGroupById(String id); /** * 删除对象 * @param paramCollection */ public void deleteAllDictGroup(List paramCollection); /** * 对象转成字典项 * @param id * @return */ public List findDictItemById(String id); /** * 快速批量生成动态字典 * @param dbSource * @param dicGroup * @param tableKey * @param primaryKey * @param nameKey * @return */ public List magicMake(String dbSource, String dicGroup, String tableKey, String primaryKey, String nameKey); /** * * @return */ public List findAllOrgGroup(); public void deleteAllByDataSourceId(String dataSourceId); public List findAllByDataSourceId(String dataSourceId); /** * 查询当前页数据 * GUOWEIXIN */ public List findAllByPageByGroupId(int page, int rows,String groupId); /** * 根据字典分组ID得到下方字典行。 * GUOWEIXIN */ public int findTotalRowsByGroupId(String groupId); /** * 插入全部数据 */ public boolean insertAllDataDictionary(List list); }
package com.cninnovatel.ev; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import com.cninnovatel.ev.utils.NetworkUtil; import com.cninnovatel.ev.utils.Utils; public class SplashActivity extends BaseActivity { private SharedPreferences sp; private Handler autoLoginHandler; private Activity context; private final int TIMEOUT = -100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = this; log.info("app splash onCreate"); sp = getSharedPreferences("login", Context.MODE_PRIVATE); autoLoginHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (context.isDestroyed()) return; if (msg.what == TIMEOUT) { log.info("splash timeout after 5 seconds"); Login.actionStart(context); RuntimeData.reset(); finish(); return; } if (msg.what == 0) { log.info("network connected, relogin for new token -- ok"); sp.edit().putBoolean("login", true).commit(); } else { log.info("network connected, relogin for new token -- failed"); } HexMeet.actionStart(context); finish(); } }; new Thread(new Runnable() { @Override public void run() { if(PermissionWrapper.getInstance().checkStoragePermission(SplashActivity.this)) { App.initLogs(); initView(); Message msg = Message.obtain(); msg.what = TIMEOUT; autoLoginHandler.sendMessageDelayed(msg, 5000); } } }).start(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permission, @NonNull int[] grantResults) { int result = PermissionWrapper.getInstance().processRequestPermissionsResult(requestCode, grantResults); if(result == PermissionWrapper.RESULT_PERMISSIONS_PASS) { App.initLogs(); initView(); } else if (result == PermissionWrapper.RESULT_PERMISSIONS_REJECT) { Utils.showToast(SplashActivity.this,R.string.permisssion); finish(); } } private void initView() { final String ucmServer = RuntimeData.getUcmServer(); String username = sp.getString("username", ""); String password = sp.getString("password", ""); boolean login = sp.getBoolean("login", false); App.setNetworkConnected(NetworkUtil.isNetConnected(context)); if (!login || ucmServer.equals("") || username.equals("") || password.equals("") || (RuntimeData.getLogUser() != null && RuntimeData.getLogUser().isPasswordModifiedByUser() == false)) { log.info("not logined before this launch, jump to login UI"); Login.actionStart(context); RuntimeData.reset(); finish(); } else { log.info("logined before this launch, jump to HexMeet main UI"); setTheme(android.R.style.Theme_NoDisplay); if (App.isNetworkConnected()) { log.info("network connected, relogin for new token"); LoginService.getInstance().autoLogin(autoLoginHandler); } } } }
package in.co.scsonline.rafaqatrasool.jkssbnotifier; import android.content.Context; import android.util.Log; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; /** * Created by Rafaqat Rasool on 10/29/2015. */ public class Parser { public Parser(){ } Context context; public Parser(Context context) { this.context = context; } /* * This function takes url as argument to connect to the web page and * fetches the web page as a Document type object which is returned by this * function. */ public Document getDoc(String url) throws IOException { Document doc = Jsoup.connect(url).get(); return doc; } /* * This functions fetches the <li> tags from the doc supplied by the * getDoc() method and the div tag and returns the notification text and * dwonload links in the form of an list containing HashMap of notification * text and download links. */ public ArrayList<HashMap<String, String>> fetchData(Document doc, String divId){ // List to store data from the website ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>(); try { Elements div = doc.select(divId); Elements li = div.select("li"); for (Element link : li) { Elements links = link.select("a[href]"); // Put the values in the HashMap HashMap<String, String> hm = new HashMap<String, String>(); hm.put("notification", links.text()); hm.put("link", links.attr("abs:href")); // Push the HashMap in to the ArrayList data.add(hm); } }catch(NullPointerException e){ e.printStackTrace(); } return data; } public ArrayList<HashMap<String, String>> fetchSyllabus(Document doc) { // List to store data from the website ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>(); //just selecting all the link tags cuz this page just contains links for syllabus Elements links = doc.select("a[href]"); for (Element link : links) { // Put the values in the HashMap HashMap<String, String> hm = new HashMap<String, String>(); hm.put("notification", link.text()); hm.put("link", link.attr("abs:href")); // Push the HashMap in to the ArrayList data.add(hm); } Log.d("CHECKING FETCH--", data.get(0).get("notification")); return data; } }
class Disparejos extends Figuras{ protected float lado2; public void setLado2(float lado2){ this.lado2=lado2; } public float getlado2(){ return lado2; } }
package com.softserve.task; import java.util.LinkedHashMap; public class ReplaceLeastUsedStrategyCache<K, V> extends Cache<K, V> { private final int MIN_CAPACITY = 0; private final long MIN_LIFE_TIME = 0; private final int DEFAULT_CAPACITY = 5; private final int DEFAULT_LIFE_TIME = 5000; private final int STEP = 1; public ReplaceLeastUsedStrategyCache(int capacity, long lifeTime) { if (capacity > MIN_CAPACITY && lifeTime > MIN_LIFE_TIME) { setCapacity(capacity); setLifeTime(lifeTime); } else { setCapacity(DEFAULT_CAPACITY); setLifeTime(DEFAULT_LIFE_TIME); } cacheMap = new LinkedHashMap<K, V>(getCapacity()); timeOfCreatingMap = new LinkedHashMap<K, Long>(getCapacity()); counterGetAccess = new LinkedHashMap<K, Integer>(getCapacity()); } @Override public V get(K key) { synchronized (cacheMap) { V cache = cacheMap.get(key); int value = counterGetAccess.get(key) + STEP; counterGetAccess.put(key, value); if (cache == null) { return null; } else { return cache; } } } @Override public void put(K key, V value) { synchronized (cacheMap) { if (isCapacityNormal(getCapacity())) { cacheMap.put(key, value); } else { K leastUsedEntryKey = null; leastUsedEntryKey = leastUsedEntry((LinkedHashMap<K, Integer>) counterGetAccess); cacheMap.remove(leastUsedEntryKey); cacheMap.put(key, value); counterGetAccess.remove(leastUsedEntryKey); timeOfCreatingMap.remove(leastUsedEntryKey); } timeOfCreatingMap.put(key, currentTime()); counterGetAccess.put(key, 0); } } /** * Method return key of the least used entry */ private K leastUsedEntry(LinkedHashMap<K, Integer> cacheMap) { K key = null; int leastUsedValue = 0; K leastUsedKey = null; for (K k : cacheMap.keySet()) { key = k; break; } leastUsedKey = key; leastUsedValue = cacheMap.get(key); for (K k : cacheMap.keySet()) { key = k; if (leastUsedValue > cacheMap.get(key)) { leastUsedValue = cacheMap.get(key); leastUsedKey = key; } } return leastUsedKey; } @Override public void remove(K key) { synchronized (cacheMap) { cacheMap.remove(key); counterGetAccess.remove(key); timeOfCreatingMap.remove(key); } } }
package com.cloudinte.modules.xingzhengguanli.web; import com.thinkgem.jeesite.common.config.Global; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; 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.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.web.BaseController; import com.thinkgem.jeesite.common.web.Servlets; import com.thinkgem.jeesite.common.utils.DateUtils; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.common.utils.excel.ExportExcel; import com.thinkgem.jeesite.common.utils.excel.ImportExcel; import com.cloudinte.modules.xingzhengguanli.entity.WorkRegularMeeting; import com.cloudinte.modules.xingzhengguanli.entity.WorkRegularMeetingContent; import com.cloudinte.modules.xingzhengguanli.service.WorkRegularMeetingContentService; import com.cloudinte.modules.xingzhengguanli.service.WorkRegularMeetingService; import com.cloudinte.modules.xingzhengguanli.utils.NumberUtils; import com.cloudinte.modules.xingzhengguanli.utils.WordUtils; /** * 工作例会征集Controller * @author dcl * @version 2019-12-11 */ @Controller @RequestMapping(value = "${adminPath}/xingzhengguanli/workRegularMeeting") public class WorkRegularMeetingController extends BaseController { private static final String FUNCTION_NAME_SIMPLE = "工作例会征集"; @Autowired private WorkRegularMeetingService workRegularMeetingService; @Autowired private WorkRegularMeetingContentService workRegularMeetingContentService; @ModelAttribute public WorkRegularMeeting get(@RequestParam(required=false) String id) { WorkRegularMeeting entity = null; if (StringUtils.isNotBlank(id)){ entity = workRegularMeetingService.get(id); } if (entity == null){ entity = new WorkRegularMeeting(); } return entity; } @RequiresPermissions("xingzhengguanli:workRegularMeeting:view") @RequestMapping(value = {"list", ""}) public String list(WorkRegularMeeting workRegularMeeting, HttpServletRequest request, HttpServletResponse response, Model model) { Page<WorkRegularMeeting> page = workRegularMeetingService.findPage(new Page<WorkRegularMeeting>(request, response), workRegularMeeting); model.addAttribute("page", page); model.addAttribute("ename", "workRegularMeeting"); setBase64EncodedQueryStringToEntity(request, workRegularMeeting); return "modules/xingzhengguanli/workRegularMeeting/workRegularMeetingList"; } @RequiresPermissions("xingzhengguanli:workRegularMeeting:view") @RequestMapping(value = "form") public String form(WorkRegularMeeting workRegularMeeting, Model model) { model.addAttribute("workRegularMeeting", workRegularMeeting); model.addAttribute("ename", "workRegularMeeting"); return "modules/xingzhengguanli/workRegularMeeting/workRegularMeetingForm"; } @RequiresPermissions("xingzhengguanli:workRegularMeeting:view") @RequestMapping(value = "showRegularMeetingContent") public String showRegularMeetingContent(WorkRegularMeeting workRegularMeeting, Model model) { WorkRegularMeetingContent workRegularMeetingContent = new WorkRegularMeetingContent(); workRegularMeetingContent.setRegularMeeting(workRegularMeeting); List<WorkRegularMeetingContent> contentList = workRegularMeetingContentService.findList(workRegularMeetingContent); model.addAttribute("contentList", contentList); model.addAttribute("workRegularMeeting", workRegularMeeting); model.addAttribute("ename", "workRegularMeeting"); return "modules/xingzhengguanli/workRegularMeeting/showRegularMeetingContent"; } @RequestMapping(value = "downloadWorkArrangement") public String downloadWorkArrangement(WorkRegularMeeting workRegularMeeting, Model model, HttpServletRequest request,HttpServletResponse response) { WorkRegularMeetingContent workRegularMeetingContent = new WorkRegularMeetingContent(); workRegularMeetingContent.setRegularMeeting(workRegularMeeting); List<WorkRegularMeetingContent> contentList = workRegularMeetingContentService.findList(workRegularMeetingContent); String content = ""; if(contentList != null && contentList.size() != 0){ for (int i = 0; i < contentList.size(); i++) { WorkRegularMeetingContent meetingContent = contentList.get(i); String con = meetingContent.getContent(); if(StringUtils.isNotBlank(con)){ con = con.replaceAll("\r\n", "<w:br/>"); con = con.replaceAll("&mdash;", "-"); con = con.replaceAll("&ldquo;", "“"); con = con.replaceAll("&rdquo;", "”"); content += "事项"+NumberUtils.foematInteger(i+1)+":"+"<w:br/>"+con+"<w:br/>"; } } } if(workRegularMeeting.getMeetingDate() != null){ workRegularMeeting.setMeetingTime(DateUtils.formatDate(workRegularMeeting.getMeetingDate(), "yyyy-MM-dd HH:mm:ss")); } Map<String, Object> map = Maps.newConcurrentMap(); map.put("workRegularMeeting", workRegularMeeting); map.put("content", content); String templateFile = "/WEB-INF/classes/templates/modules/word/"; String ftlPath = Servlets.getRealPath(request, templateFile); String ftlname = "regularmeeting.ftl"; String filename = StringEscapeUtils.unescapeHtml4(workRegularMeeting.getTitle()); try { WordUtils.exportMillCertificateWord(request, response, map, filename, ftlname,ftlPath); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequiresPermissions("xingzhengguanli:workRegularMeeting:edit") @RequestMapping(value = "save") public String save(WorkRegularMeeting workRegularMeeting, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, workRegularMeeting)){ return form(workRegularMeeting, model); } addMessage(redirectAttributes, StringUtils.isBlank(workRegularMeeting.getId()) ? "保存"+FUNCTION_NAME_SIMPLE+"成功" : "修改"+FUNCTION_NAME_SIMPLE+"成功"); workRegularMeetingService.save(workRegularMeeting); return "redirect:"+adminPath+"/xingzhengguanli/workRegularMeeting/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(workRegularMeeting)); } @RequiresPermissions("xingzhengguanli:workRegularMeeting:edit") @RequestMapping(value = "disable") public String disable(WorkRegularMeeting workRegularMeeting, RedirectAttributes redirectAttributes) { workRegularMeetingService.disable(workRegularMeeting); addMessage(redirectAttributes, "禁用"+FUNCTION_NAME_SIMPLE+"成功"); return "redirect:"+adminPath+"/xingzhengguanli/workRegularMeeting/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(workRegularMeeting)); } @RequiresPermissions("xingzhengguanli:workRegularMeeting:edit") @RequestMapping(value = "delete") public String delete(WorkRegularMeeting workRegularMeeting, RedirectAttributes redirectAttributes) { workRegularMeetingService.delete(workRegularMeeting); addMessage(redirectAttributes, "删除"+FUNCTION_NAME_SIMPLE+"成功"); return "redirect:"+adminPath+"/xingzhengguanli/workRegularMeeting/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(workRegularMeeting)); } @RequiresPermissions("xingzhengguanli:workRegularMeeting:edit") @RequestMapping(value = "deleteBatch") public String deleteBatch(WorkRegularMeeting workRegularMeeting, RedirectAttributes redirectAttributes) { workRegularMeetingService.deleteByIds(workRegularMeeting); addMessage(redirectAttributes, "批量删除"+FUNCTION_NAME_SIMPLE+"成功"); return "redirect:"+adminPath+"/xingzhengguanli/workRegularMeeting/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(workRegularMeeting)); } /** * 导出数据 */ @RequiresPermissions("xingzhengguanli:workRegularMeeting:edit") @RequestMapping(value = "export", method = RequestMethod.POST) public String exportFile(WorkRegularMeeting workRegularMeeting, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) { try { String fileName = FUNCTION_NAME_SIMPLE + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx"; workRegularMeeting.setPage(new Page<WorkRegularMeeting>(request, response, -1)); new ExportExcel(FUNCTION_NAME_SIMPLE, WorkRegularMeeting.class).setDataList(workRegularMeetingService.findList(workRegularMeeting)).write(response, fileName).dispose(); return null; } catch (Exception e) { addMessage(redirectAttributes, "导出" + FUNCTION_NAME_SIMPLE + "失败!失败信息:" + e.getMessage()); return "redirect:"+adminPath+"/xingzhengguanli/workRegularMeeting/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(workRegularMeeting)); } } /** * 下载导入数据模板 */ @RequiresPermissions("xingzhengguanli:workRegularMeeting:view") @RequestMapping(value = "import/template") public String importFileTemplate(WorkRegularMeeting workRegularMeeting, HttpServletResponse response, RedirectAttributes redirectAttributes) { try { String fileName = FUNCTION_NAME_SIMPLE + "导入模板.xlsx"; List<WorkRegularMeeting> list = workRegularMeetingService.findPage(new Page<WorkRegularMeeting>(1, 5), new WorkRegularMeeting()).getList(); if (list == null) { list = Lists.newArrayList(); } if (list.size() < 1) { list.add(new WorkRegularMeeting()); } new ExportExcel(FUNCTION_NAME_SIMPLE, WorkRegularMeeting.class).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { addMessage(redirectAttributes, "导入模板下载失败!失败信息:" + e.getMessage()); return "redirect:"+adminPath+"/xingzhengguanli/workRegularMeeting/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(workRegularMeeting)); } } /** * 导入数据<br> */ @RequiresPermissions("xingzhengguanli:workRegularMeeting:edit") @RequestMapping(value = "import", method = RequestMethod.POST) public String importFile(WorkRegularMeeting workRegularMeeting, MultipartFile file, RedirectAttributes redirectAttributes) { if(Global.isDemoMode()){ addMessage(redirectAttributes, "演示模式,不允许操作!"); return "redirect:"+adminPath+"/xingzhengguanli/workRegularMeeting/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(workRegularMeeting)); } try { long beginTime = System.currentTimeMillis();//1、开始时间 StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<WorkRegularMeeting> list = ei.getDataList(WorkRegularMeeting.class); List<WorkRegularMeeting> insertList=new ArrayList<WorkRegularMeeting>(); List<WorkRegularMeeting> subList=new ArrayList<WorkRegularMeeting>(); int batchinsertSize=500; int batchinsertCount=list.size()/batchinsertSize+(list.size()%batchinsertSize==0?0:1); int addNum=0; int updateNum=0; int toIndex=0; for(int i=0;i<batchinsertCount;i++) { insertList=new ArrayList<WorkRegularMeeting>(); toIndex=(i+1)*batchinsertSize; if(toIndex>list.size()) toIndex=list.size(); subList=list.subList(i*batchinsertSize, toIndex); for(WorkRegularMeeting zsJh : subList) { zsJh.preInsert(); insertList.add(zsJh); } if(insertList!=null&&insertList.size()>0) { System.out.println("insertList size is :"+insertList.size()); workRegularMeetingService.batchInsertUpdate(insertList); addNum+=insertList.size(); } } long endTime = System.currentTimeMillis(); //2、结束时间 addMessage(redirectAttributes, "执行时间"+DateUtils.formatDateTime(endTime - beginTime)+",导入 "+addNum+"条"+FUNCTION_NAME_SIMPLE+"信息,"+failureMsg); System.out.println("执行时间:"+DateUtils.formatDateTime(endTime - beginTime)); } catch (Exception e) { addMessage(redirectAttributes, "导入"+FUNCTION_NAME_SIMPLE+"信息失败!失败信息:"+e.getMessage()); } return "redirect:"+adminPath+"/xingzhengguanli/workRegularMeeting/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(workRegularMeeting)); } }
package com.quickblox.sample.chat.java.repository.helpers; import android.util.Log; import com.quickblox.chat.model.QBChatDialog; import com.quickblox.chat.model.QBChatMessage; import com.quickblox.chat.model.QBDialogType; import com.quickblox.sample.chat.java.App; import com.quickblox.sample.chat.java.repository.converters.DatabaseConvertor; import com.quickblox.sample.chat.java.repository.models.Dialog; import com.quickblox.users.model.QBUser; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.observers.DisposableMaybeObserver; import io.reactivex.observers.DisposableSingleObserver; import io.reactivex.schedulers.Schedulers; public class DialogRepositoryHelper { private static final String TAG = DialogRepositoryHelper.class.getSimpleName(); private static DialogRepositoryHelper instance; public static synchronized DialogRepositoryHelper getInstance() { if (instance == null) { instance = new DialogRepositoryHelper(); } return instance; } // public boolean hasDialogWithId(String dialogId) { // App.getInstance().getAppDatabase().dialogRepository().getChatDialogById(dialogId) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Consumer<List<Dialog>>() { // @Override // public void accept(@NotNull List<Dialog> dialogs) throws Exception { // // } // }); // Dialog dialog = App.getInstance().getAppDatabase().dialogRepository().getChatDialogById(dialogId); // return dialog != null; // } public CompletableFuture<Boolean> hasPrivateDialogWithUser(QBUser user) { return getPrivateDialogWithUser(user).thenApply(Objects::nonNull); } public CompletableFuture<Dialog> getPrivateDialogWithUser(QBUser user) { CompletableFuture<Dialog> future = new CompletableFuture<>(); App.getInstance().getAppDatabase().dialogRepository().getDialogs() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new DisposableMaybeObserver<List<Dialog>>() { @Override public void onSuccess(@NotNull List<Dialog> dialogs) { if (!dialogs.isEmpty()) { for (Dialog dialog : dialogs) { if (QBDialogType.PRIVATE.equals(QBDialogType.parseByCode(dialog.getType())) && dialog.getOccupantsIds().contains(user.getId())) { future.complete(dialog); } } } if (!future.isDone()) { future.complete(null); } } @Override public void onError(@NotNull Throwable e) { System.out.println(e.getMessage()); } @Override public void onComplete() { future.complete(null); } }); return future; } public void updateDialog(String dialogId, QBChatMessage qbChatMessage) { App.getInstance().getAppDatabase().dialogRepository().getChatDialogById(dialogId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new DisposableMaybeObserver<List<Dialog>>() { @Override public void onSuccess(@NotNull List<Dialog> dialogs) { if (!dialogs.isEmpty()) { QBChatDialog updatedDialog = DatabaseConvertor.convert(dialogs.get(0)); updatedDialog.setLastMessage(qbChatMessage.getBody()); updatedDialog.setLastMessageDateSent(qbChatMessage.getDateSent()); updatedDialog.setUnreadMessageCount(updatedDialog.getUnreadMessageCount() != null ? updatedDialog.getUnreadMessageCount() + 1 : 1); updatedDialog.setLastMessageUserId(qbChatMessage.getSenderId()); App.getInstance().getAppDatabase().dialogRepository().updateDialog(DatabaseConvertor.convert(updatedDialog)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new DisposableSingleObserver<Integer>() { @Override public void onSuccess(@NotNull Integer integer) { Log.i(TAG, "Dialog has been updated by id: " + integer); } @Override public void onError(@NotNull Throwable e) { Log.e(TAG, e.getMessage()); } }); } } @Override public void onError(@NotNull Throwable e) { Log.e(TAG, e.getMessage()); } @Override public void onComplete() { Log.i(TAG, "onComplete() method in updateDialog"); } }); } }
package be.mxs.common.util.pdf.general.oc.examinations; import java.util.Vector; import java.awt.*; import java.awt.image.BufferedImage; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.Font; import com.itextpdf.text.Paragraph; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Image; import be.mxs.common.util.pdf.general.PDFGeneralBasic; import be.mxs.common.util.system.Miscelaneous; public class PDFOpthalmology extends PDFGeneralBasic { // declarations protected Vector list; protected String item; //--- ADD CONTENT ------------------------------------------------------------------------------ protected void addContent(){ try{ if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_VISUS_AV_RAS").equalsIgnoreCase("medwan.common.false")){ printGezichtsscherpte(); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_VISUS_STEREO_RAS").equalsIgnoreCase("medwan.common.false")){ printStereoscopie(); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_VISUS_COLOR_RAS").equalsIgnoreCase("medwan.common.false")){ printKleurenzicht(); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_VISUS_PERI_RAS").equalsIgnoreCase("medwan.common.false")){ printGezichtsveld(); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_VISUS_MESO_RAS").equalsIgnoreCase("medwan.common.false")){ printMesoEnFoto(); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_VISUS_SCREEN_RAS").equalsIgnoreCase("medwan.common.false")){ printBeeldschermwerkers(); } } catch(Exception e){ e.printStackTrace(); } } //### PRIVATE METHODS ########################################################################## //////////////////////////////////////////////////////////////////////////////////////////////// // PRINT GEZICHTSSCHERPTE ////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// private void printGezichtsscherpte() throws Exception { contentTable = new PdfPTable(1); table = new PdfPTable(5); // title table.addCell(createTitleCell(getTran("medwan.healthrecord.ophtalmology.acuite-visuelle"),5)); //--- aanbevolen correctie ----------------------------------------------------------------- list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_NORMAL"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_GLASSES"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_CONTACT"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_LASIK"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_KERATOTOMY"); if(verifyList(list)){ String sOut = printList(list,false,", "); if(sOut.length() > 0){ table.addCell(createItemNameCell(getTran("healthrecord.ophtalmology.correction-prescribe"),2)); table.addCell(createValueCell(sOut.toLowerCase(),3)); } } //--- table -------------------------------------------------------------------------------- list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_OD_WITHOUT_GLASSES"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_OG_WITHOUT_GLASSES"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_BONI_P_WITHOUT_GLASSES"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_BONI_WITHOUT_GLASSES"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_OD_WITH_GLASSES"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_OG_WITH_GLASSES"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_BONI_P_WITH_GLASSES"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_BONI_WITH_GLASSES"); if(verifyList(list)){ // spacer row table.addCell(createBorderlessCell(5)); // borderless corner cell table.addCell(emptyCell(1)); // header table.addCell(createHeaderCell(getTran("medwan.common.right"),1)); table.addCell(createHeaderCell(getTran("medwan.common.left"),1)); table.addCell(createHeaderCell(getTran("medwan.common.binocular"),1)); table.addCell(createHeaderCell(getTran("medwan.healthrecord.ophtalmology.acuite-binoculaire-VP"),1)); // Zonder correctie if(verifyList(list,IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_OD_WITHOUT_GLASSES",IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_BONI_WITHOUT_GLASSES")){ table.addCell(createHeaderCell(getTran("medwan.healthrecord.ophtalmology.SANS-verres-2"),1)); table.addCell(createContentCell(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_OD_WITHOUT_GLASSES"))); table.addCell(createContentCell(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_OG_WITHOUT_GLASSES"))); table.addCell(createContentCell(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_BONI_WITHOUT_GLASSES"))); table.addCell(createContentCell(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_BONI_P_WITHOUT_GLASSES"))); } // Met correctie if(verifyList(list,IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_OD_WITH_GLASSES",IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_BONI_WITH_GLASSES")){ table.addCell(createHeaderCell(getTran("medwan.healthrecord.ophtalmology.AVEC-verres-2"),1)); table.addCell(createContentCell(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_OD_WITH_GLASSES"))); table.addCell(createContentCell(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_OG_WITH_GLASSES"))); table.addCell(createContentCell(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_BONI_WITH_GLASSES"))); table.addCell(createContentCell(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_BONI_P_WITH_GLASSES"))); } } //--- remark ------------------------------------------------------------------------------- itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_REMARK"); if(itemValue.length() > 0){ // spacer row table.addCell(createBorderlessCell(5)); addItemRow(table,getTran("medwan.common.remark"),itemValue); } // add content if(table.size() > 1){ contentTable.addCell(createCell(new PdfPCell(table),1,PdfPCell.ALIGN_CENTER,PdfPCell.NO_BORDER)); tranTable.addCell(createContentCell(contentTable)); } // add transaction to doc addTransactionToDoc(); } //////////////////////////////////////////////////////////////////////////////////////////////// // PRINT STEREOSCOPIE ////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// private void printStereoscopie() throws Exception { contentTable = new PdfPTable(1); table = new PdfPTable(5); // title table.addCell(createTitleCell(getTran("medwan.healthrecord.ophtalmology.stereoscopie"),5)); //--- tests table -------------------------------------------------------------------------- PdfPTable testsTable = new PdfPTable(5); // construct tests table for(int i=1; i<=5; i++){ itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_STEREOSCOPY_LINE_"+i); for(int j=1; j<=5; j++){ if(itemValue.equals(j+"")) testsTable.addCell(createGreenCell(j+"")); else testsTable.addCell(createContentCell(j+"")); } } // add tests table is any content if(testsTable.size() > 0){ // row title table.addCell(createItemNameCell(getTran("medwan.healthrecord.ophtalmology.stereoscopie"))); // [cell 1] close / far itemValue = "\n"+ getTran("medwan.healthrecord.ophtalmology.plus-pres")+ "\n\n\n\n\n"+ getTran("medwan.healthrecord.ophtalmology.plus-loin"); table.addCell(createValueCell(itemValue,1)); // [cell 2] 5*5 cells table.addCell(testsTable); // [cell 3] normal / abnormal itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_STEREOSCOPY_NORMAL"); table.addCell(createValueCell(getTran(itemValue),1)); } //------------------------------------------------------------------------------------------ // correction itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_STEREOSCOPY_CORRECTION"); if(itemValue.length() > 0){ addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_STEREOSCOPY_CORRECTION"),getTran(itemValue)); } // remark itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_STEREOSCOPY_REMARK"); if(itemValue.length() > 0){ addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_STEREOSCOPY_REMARK"),itemValue); } // add content if(table.size() > 1){ contentTable.addCell(createCell(new PdfPCell(table),1,PdfPCell.ALIGN_CENTER,PdfPCell.NO_BORDER)); tranTable.addCell(createContentCell(contentTable)); } // add transaction to doc addTransactionToDoc(); } //////////////////////////////////////////////////////////////////////////////////////////////// // PRINT KLEURENZICHT ////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// private void printKleurenzicht() throws Exception { list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_ESSILOR"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_FARNSWORTH"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_ISHIHARA"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_CARTECOULEUR"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_REMARK"); if(verifyList(list)){ contentTable = new PdfPTable(1); table = new PdfPTable(5); // title table.addCell(createTitleCell(getTran("medwan.healthrecord.ophtalmology.couleurs"),5)); //--- COLORS (on one row) -------------------------------------------------------------- // ESSILOR itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_ESSILOR"); if(itemValue.length() > 0) table.addCell(createValueCell("Essilor: "+getTran(itemValue),1)); else table.addCell(createValueCell("Essilor: /",1)); // FARNSWORTH itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_FARNSWORTH"); if(itemValue.length() > 0) table.addCell(createValueCell("Farnsworth: "+getTran(itemValue),1)); else table.addCell(createValueCell("Farnsworth: /",1)); // ISHIHARA itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_ISHIHARA"); if(itemValue.length() > 0) table.addCell(createValueCell("Ishihara: "+getTran(itemValue),1)); else table.addCell(createValueCell("Ishihara: /",1)); // CARTECOULEUR itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_CARTECOULEUR"); if(itemValue.length() > 0) table.addCell(createValueCell("Carte de couleur: "+getTran(itemValue),1)); else table.addCell(createValueCell("Carte de couleur: /",1)); // 5th empty cell table.addCell(emptyCell()); // correction itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_CORRECTION"); if(itemValue.length() > 0){ addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_CORRECTION"),getTran(itemValue)); } // remark itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_COLOR_REMARK"); if(itemValue.length() > 0){ addItemRow(table,getTran("medwan.common.remark"),itemValue); } // add content if(table.size() > 1){ contentTable.addCell(createCell(new PdfPCell(table),1,PdfPCell.ALIGN_CENTER,PdfPCell.NO_BORDER)); tranTable.addCell(createContentCell(contentTable)); } // add transaction to doc addTransactionToDoc(); } } //////////////////////////////////////////////////////////////////////////////////////////////// // PRINT GEZICHTSVELD ////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// private void printGezichtsveld() throws Exception { list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_22"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_2"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_1"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_6"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_5"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_11"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_8"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_7"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_3"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_4"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_22"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_22"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_3"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_4"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_8"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_7"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_6"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_5"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_11"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_2"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_1"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_REMARK"); if(verifyList(list)){ contentTable = new PdfPTable(1); table = new PdfPTable(5); // title table.addCell(createTitleCell(getTran("medwan.healthrecord.ophtalmology.vision-peripherique"),5)); // prepare images MediaTracker mediaTracker = new MediaTracker(new Container()); java.awt.Image OD = Miscelaneous.getImage("OD_pdf.gif"); mediaTracker.addImage(OD,0); mediaTracker.waitForID(0); java.awt.Image OG = Miscelaneous.getImage("OG_pdf.gif"); mediaTracker.addImage(OG,1); mediaTracker.waitForID(1); //*** Rechter oog ********************************************************************** BufferedImage rightImg = new BufferedImage(OD.getWidth(null),OD.getHeight(null),BufferedImage.TYPE_INT_RGB); Graphics2D graphics = rightImg.createGraphics(); graphics.drawImage(OD,0,0,Color.WHITE,null); // Hier de vakjes tekenen in functie van het feit of ze 'aan' of 'af' staan String sRechts = "", sKomma = ""; int counter = 0; if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_2").equals("")){ drawRectangle(graphics,0.15*rightImg.getWidth(),0.20*rightImg.getHeight(),Color.BLACK,10,"2"); sRechts = "2"; counter++; } else{ drawRectangle(graphics,0.15*rightImg.getWidth(),0.20*rightImg.getHeight(),Color.WHITE,10,"2"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_3").equals("")){ drawRectangle(graphics,0.90*rightImg.getWidth(),0.20*rightImg.getHeight(),Color.BLACK,10,"3"); if(counter > 0) sKomma = ", "; sRechts+= sKomma+"3"; counter++; } else{ drawRectangle(graphics,0.90*rightImg.getWidth(),0.20*rightImg.getHeight(),Color.WHITE,10,"3"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_22").equals("")){ drawRectangle(graphics,0.0001*rightImg.getWidth(),0.50*rightImg.getHeight(),Color.BLACK,10,"22"); if(counter > 0) sKomma = ", "; sRechts+= sKomma+"22"; counter++; } else{ drawRectangle(graphics,0.0001*rightImg.getWidth(),0.50*rightImg.getHeight(),Color.WHITE,10,"22"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_6").equals("")){ drawRectangle(graphics,0.45*rightImg.getWidth(),0.40*rightImg.getHeight(),Color.BLACK,10,"6"); if(counter > 0) sKomma = ", "; sRechts+= sKomma+"6"; counter++; } else{ drawRectangle(graphics,0.45*rightImg.getWidth(),0.40*rightImg.getHeight(),Color.WHITE,10,"6"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_8").equals("")){ drawRectangle(graphics,0.65*rightImg.getWidth(),0.40*rightImg.getHeight(),Color.BLACK,10,"8"); if(counter > 0) sKomma = ", "; sRechts+= sKomma+"8"; counter++; } else{ drawRectangle(graphics,0.65*rightImg.getWidth(),0.40*rightImg.getHeight(),Color.WHITE,10,"8"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_5").equals("")){ drawRectangle(graphics,0.45*rightImg.getWidth(),0.53*rightImg.getHeight(),Color.BLACK,10,"5"); if(counter > 0) sKomma = ", "; sRechts+= sKomma+"5"; counter++; } else{ drawRectangle(graphics,0.45*rightImg.getWidth(),0.53*rightImg.getHeight(),Color.WHITE,10,"5"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_7").equals("")){ drawRectangle(graphics,0.65*rightImg.getWidth(),0.53*rightImg.getHeight(),Color.BLACK,10,"7"); if(counter > 0) sKomma = ", "; sRechts+= sKomma+"7"; counter++; } else{ drawRectangle(graphics,0.65*rightImg.getWidth(),0.53*rightImg.getHeight(),Color.WHITE,10,"7"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_4").equals("")){ drawRectangle(graphics,0.90*rightImg.getWidth(),0.65*rightImg.getHeight(),Color.BLACK,10,"4"); if(counter > 0) sKomma = ", "; sRechts+= sKomma+"4"; counter++; } else{ drawRectangle(graphics,0.90*rightImg.getWidth(),0.65*rightImg.getHeight(),Color.WHITE,10,"4"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_1").equals("")){ drawRectangle(graphics,0.25*rightImg.getWidth(),0.75*rightImg.getHeight(),Color.BLACK,10,"1"); if(counter > 0) sKomma = ", "; sRechts+= sKomma+"1"; counter++; } else{ drawRectangle(graphics,0.25*rightImg.getWidth(),0.75*rightImg.getHeight(),Color.WHITE,10,"1"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OD_11").equals("")){ drawRectangle(graphics,0.47*rightImg.getWidth(),0.75*rightImg.getHeight(),Color.BLACK,10,"11"); if(counter > 0) sKomma = ", "; sRechts+= sKomma+"11"; } else{ drawRectangle(graphics,0.47*rightImg.getWidth(),0.75*rightImg.getHeight(),Color.WHITE,10,"11"); } //*** Linker oog *********************************************************************** BufferedImage leftImg = new BufferedImage(OG.getWidth(null),OG.getHeight(null), BufferedImage.TYPE_INT_RGB); graphics = leftImg.createGraphics(); graphics.drawImage(OG,0,0,Color.WHITE,null); // Hier de vakjes tekenen in functie van het feit of ze 'aan' of 'af' staan String sLinks = ""; sKomma = ""; counter = 0; if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_2").equals("")){ drawRectangle(graphics,(1-0.20)*leftImg.getWidth(),0.20*leftImg.getHeight(),Color.BLACK,10,"2"); sLinks= "2"; counter++; } else{ drawRectangle(graphics,(1-0.20)*leftImg.getWidth(),0.20*leftImg.getHeight(),Color.WHITE,10,"2"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_3").equals("")){ drawRectangle(graphics,(1-0.96)*leftImg.getWidth(),0.20*leftImg.getHeight(),Color.BLACK,10,"3"); if(counter > 0) sKomma = ", "; sLinks+= sKomma+"3"; counter++; } else{ drawRectangle(graphics,(1-0.96)*leftImg.getWidth(),0.20*leftImg.getHeight(),Color.WHITE,10,"3"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_22").equals("")){ drawRectangle(graphics,(1-0.07)*leftImg.getWidth(),0.50*leftImg.getHeight(),Color.BLACK,10,"22"); if(counter > 0) sKomma = ", "; sLinks+= sKomma+"22"; counter++; } else{ drawRectangle(graphics,(1-0.07)*leftImg.getWidth(),0.50*leftImg.getHeight(),Color.WHITE,10,"22"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_6").equals("")){ drawRectangle(graphics,(1-0.50)*leftImg.getWidth(),0.40*leftImg.getHeight(),Color.BLACK,10,"6"); if(counter > 0) sKomma = ", "; sLinks+= sKomma+"6"; counter++; } else{ drawRectangle(graphics,(1-0.50)*leftImg.getWidth(),0.40*leftImg.getHeight(),Color.WHITE,10,"6"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_8").equals("")){ drawRectangle(graphics,(1-0.70)*leftImg.getWidth(),0.40*leftImg.getHeight(),Color.BLACK,10,"8"); if(counter > 0) sKomma = ", "; sLinks+= sKomma+"8"; counter++; } else{ drawRectangle(graphics,(1-0.70)*leftImg.getWidth(),0.40*leftImg.getHeight(),Color.WHITE,10,"8"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_5").equals("")){ drawRectangle(graphics,(1-0.50)*leftImg.getWidth(),0.53*leftImg.getHeight(),Color.BLACK,10,"5"); if(counter > 0) sKomma = ", "; sLinks+= sKomma+"5"; counter++; } else{ drawRectangle(graphics,(1-0.50)*leftImg.getWidth(),0.53*leftImg.getHeight(),Color.WHITE,10,"5"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_7").equals("")){ drawRectangle(graphics,(1-0.70)*leftImg.getWidth(),0.53*leftImg.getHeight(),Color.BLACK,10,"7"); if(counter > 0) sKomma = ", "; sLinks+= sKomma +"7"; counter++; } else{ drawRectangle(graphics,(1-0.70)*leftImg.getWidth(),0.53*leftImg.getHeight(),Color.WHITE,10,"7"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_4").equals("")){ drawRectangle(graphics,(1-0.96)*leftImg.getWidth(),0.65*leftImg.getHeight(),Color.BLACK,10,"4"); if(counter > 0) sKomma = ", "; sLinks+= sKomma+"4"; counter++; } else{ drawRectangle(graphics,(1-0.96)*leftImg.getWidth(),0.65*leftImg.getHeight(),Color.WHITE,10,"4"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_1").equals("")){ drawRectangle(graphics,(1-0.30)*leftImg.getWidth(),0.75*leftImg.getHeight(),Color.BLACK,10,"1"); if(counter > 0) sKomma = ", "; sLinks+= sKomma+"1"; counter++; } else{ drawRectangle(graphics,(1-0.30)*leftImg.getWidth(),0.75*leftImg.getHeight(),Color.WHITE,10,"1"); } if(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_OG_11").equals("")){ drawRectangle(graphics,(1-0.55)*leftImg.getWidth(),0.75*leftImg.getHeight(),Color.BLACK,10,"11"); if(counter > 0) { sKomma = ", "; }else{ sKomma = "";} sLinks+= sKomma+"11"; } else{ drawRectangle(graphics,(1-0.55)*leftImg.getWidth(),0.75*leftImg.getHeight(),Color.WHITE,10,"11"); } //*** BUILD OUTPUT ********************************************************************* // row title table.addCell(createItemNameCell(getTran("medwan.healthrecord.vision.erreur-champs-vision"),2)); PdfPTable imgsTable = new PdfPTable(2); // [row 1] numbers cell = createHeaderCell(getTran("medwan.common.right")+": "+sRechts,1); cell.setBorder(PdfPCell.BOX); imgsTable.addCell(cell); cell = createHeaderCell(getTran("medwan.common.left")+": "+sLinks,1); cell.setBorder(PdfPCell.BOX); imgsTable.addCell(cell); // [row 2] add images cell = new PdfPCell(); cell.setImage(Image.getInstance(rightImg,null)); cell.setColspan(1); cell.setPaddingLeft(15); cell.setBorder(PdfPCell.NO_BORDER); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); imgsTable.addCell(cell); cell = new PdfPCell(); cell.setImage(Image.getInstance(leftImg,null)); cell.setColspan(1); cell.setPaddingRight(15); cell.setBorder(PdfPCell.NO_BORDER); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); imgsTable.addCell(cell); table.addCell(createCell(new PdfPCell(imgsTable),3,PdfPCell.ALIGN_MIDDLE,PdfPCell.BOX)); // 3=2+emptyCell // correction itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_CORRECTION"); if(itemValue.length() > 0){ addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_CORRECTION"),getTran(itemValue)); } // remark itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PERIPHERIC_REMARK"); if(itemValue.length() > 0){ addItemRow(table,getTran("medwan.common.remark"),itemValue); } // add content if(table.size() > 1){ contentTable.addCell(createCell(new PdfPCell(table),1,PdfPCell.ALIGN_CENTER,PdfPCell.NO_BORDER)); tranTable.addCell(createContentCell(contentTable)); } // add transaction to doc addTransactionToDoc(); } } //////////////////////////////////////////////////////////////////////////////////////////////// // PRINT MESO & FOTO /////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// private void printMesoEnFoto() throws Exception { // count saved meso items int mesosize = 0; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_MESOPIC_2").equals("")) mesosize++; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_MESOPIC_4").equals("")) mesosize++; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_MESOPIC_6").equals("")) mesosize++; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_MESOPIC_8").equals("")) mesosize++; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_MESOPIC_10").equals("")) mesosize++; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_MESOPIC_12").equals("")) mesosize++; // count saved foto items int fotosize = 0; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PHOTOPIC_2").equals("")) fotosize++; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PHOTOPIC_4").equals("")) fotosize++; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PHOTOPIC_6").equals("")) fotosize++; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PHOTOPIC_8").equals("")) fotosize++; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PHOTOPIC_10").equals("")) fotosize++; if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_PHOTOPIC_12").equals("")) fotosize++; contentTable = new PdfPTable(1); table = new PdfPTable(5); // title table.addCell(createTitleCell(getTran("medwan.healthrecord.ophtalmology.vision-mesopique"),5)); // Mesopische visus if(mesosize > 0){ String mesoValue = ""; if(mesosize == 1) mesoValue = "2"; else if(mesosize == 2) mesoValue = "4"; else if(mesosize == 3) mesoValue = "6"; else if(mesosize == 4) mesoValue = "8"; else if(mesosize == 5) mesoValue = "10"; else if(mesosize == 6) mesoValue = "12"; addItemRow(table,getTran("medwan.healthrecord.ophtalmology.acuite-mesopique"),mesoValue); } // Fotopische visus if(fotosize > 0){ String fotoValue = ""; if(fotosize == 1) fotoValue = "2"; else if(fotosize == 2) fotoValue = "4"; else if(fotosize == 3) fotoValue = "6"; else if(fotosize == 4) fotoValue = "8"; else if(fotosize == 5) fotoValue = "10"; else if(fotosize == 6) fotoValue = "12"; addItemRow(table,getTran("medwan.healthrecord.ophtalmology.acuite-photopique"),fotoValue); } // correction itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_MESOPIC_CORRECTION"); if(itemValue.length() > 0){ addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_MESOPIC_CORRECTION"),getTran(itemValue)); } // remark itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_VISION_MESOPIC_REMARK"); if(itemValue.length() > 0){ addItemRow(table,getTran("medwan.common.remark"),itemValue); } // add content if(table.size() > 1){ contentTable.addCell(createCell(new PdfPCell(table),1,PdfPCell.ALIGN_CENTER,PdfPCell.NO_BORDER)); tranTable.addCell(createContentCell(contentTable)); } // add transaction to doc addTransactionToDoc(); } //////////////////////////////////////////////////////////////////////////////////////////////// // PRINT BEELDSCHERMWERKERS //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// private void printBeeldschermwerkers() throws Exception { contentTable = new PdfPTable(1); table = new PdfPTable(5); String visusTran = getTran("medwan.common.vision"); // title table.addCell(createTitleCell(getTran("medwan.healthrecord.ophtalmology.workers-on-screen"),5)); // common used translations String odTran = getTran("medwan.healthrecord.ophtalmology.OD"); String ogTran = getTran("medwan.healthrecord.ophtalmology.OG"); //### VISUS Loin ########################################################################### //--- VISION VL OD ------------------------------------------------------------------------- list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OD_2"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OD_4"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OD_6"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OD_8"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OD_10"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OD_12"); String itemOD = getItemWithContent(list); //--- VISION VL OG ------------------------------------------------------------------------- list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OG_2"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OG_4"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OG_6"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OG_8"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OG_10"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_VL_OG_12"); String itemOG = getItemWithContent(list); if(itemOD.length() > 0 || itemOG.length() > 0){ // row title table.addCell(createItemNameCell(visusTran+" "+getTran("medwan.healthrecord.ophtalmology.far"))); // OD if(itemOD.length() > 0) table.addCell(createValueCell(odTran+": "+getItemValue(itemOD),1)); else table.addCell(emptyCell(1)); // OG if(itemOG.length() > 0) table.addCell(createValueCell(ogTran+": "+getItemValue(itemOG),2)); else table.addCell(emptyCell(2)); } //### bonnette + 1D ######################################################################## list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONNETTE_OD_EQUAL"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONNETTE_OD_LESS_GOOD"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONNETTE_OG_EQUAL"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONNETTE_OG_LESS_GOOD"); if(verifyList(list)){ // row title table.addCell(createItemNameCell(getTran("medwan.healthrecord.ophtalmology.workers-on-screen-bonnette"))); //--- OD ------------------------------------------------------------------------------- itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONNETTE_OD_EQUAL"); if(itemValue.length() > 0){ table.addCell(createValueCell(odTran+": "+getTran(itemValue),1)); } else{ itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONNETTE_OD_LESS_GOOD"); if(!itemValue.equals("")) table.addCell(createValueCell(odTran+": "+getTran(itemValue),1)); else table.addCell(emptyCell(1)); } //--- OG ------------------------------------------------------------------------------- itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONNETTE_OG_EQUAL"); if(itemValue.length() > 0){ table.addCell(createValueCell(ogTran+": "+getTran(itemValue),2)); } else{ itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONNETTE_OG_LESS_GOOD"); if(!itemValue.equals("")) table.addCell(createValueCell(ogTran+": "+getTran(itemValue),2)); else table.addCell(emptyCell(2)); } } //### rood + groen ######################################################################### list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OD_EQUAL"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OD_RED"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OD_GREEN"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OG_EQUAL"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OG_RED"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OG_GREEN"); if(verifyList(list)){ // row title table.addCell(createItemNameCell(getTran("medwan.healthrecord.ophtalmology.workers-on-screen-RED-GREEN"))); // OD if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OD_EQUAL").equals("")){ table.addCell(createValueCell(odTran+": "+getTran(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OD_EQUAL")),1)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OD_RED").equals("")){ table.addCell(createValueCell(odTran+": "+getTran(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OD_RED")),1)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OD_GREEN").equals("")){ table.addCell(createValueCell(odTran+": "+getTran(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OD_GREEN")),1)); } else{ table.addCell(emptyCell(1)); } // OG if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OG_EQUAL").equals("")){ table.addCell(createValueCell(ogTran+": "+getTran(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OG_EQUAL")),2)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OG_RED").equals("")){ table.addCell(createValueCell(ogTran+": "+getTran(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OG_RED")),2)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OG_GREEN").equals("")){ table.addCell(createValueCell(ogTran+": "+getTran(getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_RED_GREEN_OG_GREEN")),2)); } else{ table.addCell(emptyCell(2)); } } //### ASTIGMATISME ######################################################################### list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_1"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_2"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_3"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_4"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_5"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_6"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_7"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_EQUAL"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_BLACK"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_1"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_2"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_3"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_4"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_5"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_6"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_7"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_EQUAL"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_BLACK"); if(verifyList(list)){ // row title table.addCell(createItemNameCell(getTran("medwan.healthrecord.ophtalmology.workers-on-screen-astigmatisme"))); PdfPTable astigmaTable = new PdfPTable(2); // labels astigmaTable.addCell(createHeaderCell(getTran("medwan.common.right"),1)); astigmaTable.addCell(createHeaderCell(getTran("medwan.common.left"),1)); // prepare images MediaTracker mediaTracker = new MediaTracker(new Container()); java.awt.Image OD_lines = Miscelaneous.getImage("lines_pdf.gif"); mediaTracker.addImage(OD_lines, 0); mediaTracker.waitForID(0); java.awt.Image OG_lines = Miscelaneous.getImage("lines_pdf.gif"); mediaTracker.addImage(OG_lines, 1); mediaTracker.waitForID(1); // Rechter oog BufferedImage img = new BufferedImage(OD_lines.getWidth(null),OD_lines.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); graphics.drawImage(OD_lines,0,0,Color.WHITE,null); if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_1").equals("")){ drawRectangle(graphics,0.15*img.getWidth(),0.82*img.getHeight(),Color.BLACK,10,"1"); } else{ drawRectangle(graphics,0.15*img.getWidth(),0.82*img.getHeight(),Color.WHITE,10,"1"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_7").equals("")){ drawRectangle(graphics,0.82*img.getWidth(),0.82*img.getHeight(),Color.BLACK,10,"7"); } else{ drawRectangle(graphics,0.82*img.getWidth(),0.82*img.getHeight(),Color.WHITE,10,"7"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_2").equals("")){ drawRectangle(graphics,0.16*img.getWidth(),0.50*img.getHeight(),Color.BLACK,10,"2"); } else{ drawRectangle(graphics,0.16*img.getWidth(),0.50*img.getHeight(),Color.WHITE,10,"2"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_6").equals("")){ drawRectangle(graphics,0.80*img.getWidth(),0.50*img.getHeight(),Color.BLACK,10,"6"); } else{ drawRectangle(graphics,0.80*img.getWidth(),0.50*img.getHeight(),Color.WHITE,10,"6"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_3").equals("")){ drawRectangle(graphics,0.30*img.getWidth(),0.25*img.getHeight(),Color.BLACK,10,"3"); } else{ drawRectangle(graphics,0.30*img.getWidth(),0.25*img.getHeight(),Color.WHITE,10,"3"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_5").equals("")){ drawRectangle(graphics,0.68*img.getWidth(),0.25*img.getHeight(),Color.BLACK,10,"5"); } else{ drawRectangle(graphics,0.68*img.getWidth(),0.25*img.getHeight(),Color.WHITE,10,"5"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_4").equals("")){ drawRectangle(graphics,0.49*img.getWidth(),0.15*img.getHeight(),Color.BLACK,10,"4"); } else{ drawRectangle(graphics,0.49*img.getWidth(),0.15*img.getHeight(),Color.WHITE,10,"4"); } // right image cell = new PdfPCell(); cell.setImage(Image.getInstance(img,null)); cell.setColspan(1); cell.setPaddingTop(2); cell.setBorderColor(innerBorderColor); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); astigmaTable.addCell(cell); //--- Linker oog ----------------------------------------------------------------------- img = new BufferedImage(OG_lines.getWidth(null),OG_lines.getHeight(null), BufferedImage.TYPE_INT_RGB); graphics = img.createGraphics(); graphics.drawImage(OG_lines,0,0,Color.WHITE,null); if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_1").equals("")){ drawRectangle(graphics,(1-0.85)*img.getWidth(),0.82*img.getHeight(),Color.BLACK,10,"1"); } else{ drawRectangle(graphics,(1-0.85)*img.getWidth(),0.82*img.getHeight(),Color.WHITE,10,"1"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_7").equals("")){ drawRectangle(graphics,(1-0.18)*img.getWidth(),0.82*img.getHeight(),Color.BLACK,10,"7"); } else{ drawRectangle(graphics,(1-0.18)*img.getWidth(),0.82*img.getHeight(),Color.WHITE,10,"7"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_2").equals("")){ drawRectangle(graphics,(1-0.84)*img.getWidth(),0.50*img.getHeight(),Color.BLACK,10,"2"); } else{ drawRectangle(graphics,(1-0.84)*img.getWidth(),0.50*img.getHeight(),Color.WHITE,10,"2"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_6").equals("")){ drawRectangle(graphics,(1-0.21)*img.getWidth(),0.50*img.getHeight(),Color.BLACK,10,"6"); } else{ drawRectangle(graphics,(1-0.21)*img.getWidth(),0.50*img.getHeight(),Color.WHITE,10,"6"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_3").equals("")){ drawRectangle(graphics,(1-0.71)*img.getWidth(),0.25*img.getHeight(),Color.BLACK,10,"3"); } else{ drawRectangle(graphics,(1-0.71)*img.getWidth(),0.25*img.getHeight(),Color.WHITE,10,"3"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_5").equals("")){ drawRectangle(graphics,(1-0.33)*img.getWidth(),0.25*img.getHeight(),Color.BLACK,10,"5"); } else{ drawRectangle(graphics,(1-0.33)*img.getWidth(),0.25*img.getHeight(),Color.WHITE,10,"5"); } if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_4").equals("")){ drawRectangle(graphics,(1-0.52)*img.getWidth(),0.15*img.getHeight(),Color.BLACK,10,"4"); } else{ drawRectangle(graphics,(1-0.52)*img.getWidth(),0.15*img.getHeight(),Color.WHITE,10,"4"); } // left image cell = new PdfPCell(); cell.setImage(Image.getInstance(img,null)); cell.setColspan(1); cell.setPaddingTop(2); cell.setBorderColor(innerBorderColor); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); astigmaTable.addCell(cell); //--- equal or black R ----------------------------------------------------------------- String sEqual = "", sBlack = ""; itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_EQUAL"); if(itemValue.length() > 0){ sEqual = getTran(itemValue)+" "; } itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OD_BLACK"); if(itemValue.length() > 0){ sBlack = getTran(itemValue); } astigmaTable.addCell(createContentCell((sEqual+sBlack).toLowerCase())); //--- equal or black L ----------------------------------------------------------------- sEqual = ""; sBlack = ""; itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_EQUAL"); if(itemValue.length() > 0){ sEqual = getTran(itemValue)+" "; } itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_ASTIGMATISME_OG_BLACK"); if(itemValue.length() > 0){ sBlack = getTran(itemValue); } astigmaTable.addCell(createContentCell((sEqual+sBlack).toLowerCase())); // add astigmatisme table table.addCell(createCell(new PdfPCell(astigmaTable),3,PdfPCell.ALIGN_LEFT,PdfPCell.NO_BORDER)); } //### VISUS BINOCULAR ###################################################################### //--- Proche ------------------------------------------------------------------------------- list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VP_2"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VP_4"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VP_6"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VP_8"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VP_10"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VP_12"); item = getItemWithContent(list); if(item.length() > 0){ table.addCell(createItemNameCell(visusTran+" "+getTran("medwan.healthrecord.ophtalmology.close"))); table.addCell(createValueCell(getTran("medwan.common.binocular")+": "+getItemValue(item))); } //--- Intermediaire ------------------------------------------------------------------------ list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VI_2"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VI_4"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VI_6"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VI_8"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VI_10"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VI_12"); item = getItemWithContent(list); if(item.length() > 0){ table.addCell(createItemNameCell(visusTran+" "+getTran("medwan.healthrecord.ophtalmology.intermediate"))); table.addCell(createValueCell(getTran("medwan.common.binocular")+": "+getItemValue(item))); } //--- Loin --------------------------------------------------------------------------------- list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VL_2"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VL_4"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VL_6"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VL_8"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VL_10"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_BONI_VL_12"); item = getItemWithContent(list); if(item.length() > 0){ table.addCell(createItemNameCell(visusTran+" "+getTran("medwan.healthrecord.ophtalmology.far"))); table.addCell(createValueCell(getTran("medwan.common.binocular")+": "+getItemValue(item))); } //### VERMOEIDHEID ######################################################################### list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_TIME_SPAN"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_1"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_2"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_3"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_4"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_5"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_1"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_2"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_3"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_4"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_5"); if(verifyList(list)){ // row title table.addCell(createItemNameCell(getTran("medwan.healthrecord.ophtalmology.fatigue"))); //--- time span ------------------------------------------------------------------------ itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_TIME_SPAN"); if(itemValue.length() > 0){ table.addCell(createValueCell(getTran("medwan.healthrecord.ophtalmology.time-span")+": "+itemValue,1)); } else{ table.addCell(emptyCell(1)); } //--- fatigue LOIN --------------------------------------------------------------------- if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_1").equals("")){ table.addCell(createValueCell(getTran("medwan.healthrecord.ophtalmology.far")+": "+getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_1"),1)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_2").equals("")){ table.addCell(createValueCell(getTran("medwan.healthrecord.ophtalmology.far")+": "+getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_2"),1)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_3").equals("")){ table.addCell(createValueCell(getTran("medwan.healthrecord.ophtalmology.far")+": "+getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_3"),1)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_4").equals("")){ table.addCell(createValueCell(getTran("medwan.healthrecord.ophtalmology.far")+": "+getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_4"),1)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_5").equals("")){ table.addCell(createValueCell(getTran("medwan.healthrecord.ophtalmology.far")+": "+getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VL_5"),1)); } else{ table.addCell(emptyCell(1)); } //--- fatigue PROCHE ------------------------------------------------------------------- if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_1").equals("")){ table.addCell(createValueCell(getTran("medwan.healthrecord.ophtalmology.close")+": "+getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_1"),1)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_2").equals("")){ table.addCell(createValueCell(getTran("medwan.healthrecord.ophtalmology.close")+": "+getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_2"),1)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_3").equals("")){ table.addCell(createValueCell(getTran("medwan.healthrecord.ophtalmology.close")+": "+getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_3"),1)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_4").equals("")){ table.addCell(createValueCell(getTran("medwan.healthrecord.ophtalmology.close")+": "+getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_4"),1)); } else if(!getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_5").equals("")){ table.addCell(createValueCell(getTran("medwan.healthrecord.ophtalmology.close")+": "+getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_FATIGUE_VP_5"),1)); } else{ table.addCell(emptyCell(1)); } } //### CONTRASTEN ########################################################################### list = new Vector(); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_4_06"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_4_04"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_4_02"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_6_06"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_6_04"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_6_02"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_8_06"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_8_04"); list.add(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_8_02"); if(verifyList(list)){ // row title table.addCell(createItemNameCell(getTran("medwan.healthrecord.ophtalmology.workers-on-screen-vision-contrast"))); PdfPTable contrastTable = new PdfPTable(4); // borderless corner cell contrastTable.addCell(createBorderlessCell(1)); // header contrastTable.addCell(createHeaderCell("0,6",1)); contrastTable.addCell(createHeaderCell("0,4",1)); contrastTable.addCell(createHeaderCell("0,2",1)); //*** row 1 **************************************************************************** String cross = "x"; contrastTable.addCell(createHeaderCell("4",1)); itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_4_06"); if(itemValue.length() > 0) contrastTable.addCell(createContentCell(cross)); else contrastTable.addCell(createBorderlessCell(1)); itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_4_04"); if(itemValue.length() > 0) contrastTable.addCell(createContentCell(cross)); else contrastTable.addCell(createBorderlessCell(1)); itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_4_02"); if(itemValue.length() > 0) contrastTable.addCell(createContentCell(cross)); else contrastTable.addCell(createBorderlessCell(1)); //*** row 2 **************************************************************************** contrastTable.addCell(createHeaderCell("6",1)); itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_6_06"); if(itemValue.length() > 0) contrastTable.addCell(createContentCell(cross)); else contrastTable.addCell(createBorderlessCell(1)); itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_6_04"); if(itemValue.length() > 0) contrastTable.addCell(createContentCell(cross)); else contrastTable.addCell(createBorderlessCell(1)); itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_6_02"); if(itemValue.length() > 0) contrastTable.addCell(createContentCell(cross)); else contrastTable.addCell(createBorderlessCell(1)); //*** row 3 **************************************************************************** contrastTable.addCell(createHeaderCell("8",1)); itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_8_06"); if(itemValue.length() > 0) contrastTable.addCell(createContentCell(cross)); else contrastTable.addCell(createBorderlessCell(1)); itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_8_04"); if(itemValue.length() > 0) contrastTable.addCell(createContentCell(cross)); else contrastTable.addCell(createBorderlessCell(1)); itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_VISION_CONTRAST_8_02"); if(itemValue.length() > 0) contrastTable.addCell(createContentCell(cross)); else contrastTable.addCell(createBorderlessCell(1)); // add contrast table table.addCell(createCell(new PdfPCell(contrastTable),1,PdfPCell.ALIGN_CENTER,PdfPCell.NO_BORDER)); // spacer cell table.addCell(emptyCell(1)); // spacer cell cell.setBorder(PdfPCell.RIGHT); table.addCell(cell); } // correction itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_CORRECTION"); if(itemValue.length() > 0){ addItemRow(table,getTran(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_CORRECTION"),getTran(itemValue)); } // screenworkers remark itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPTHALMOLOGY_SCREEN_REMARK"); if(itemValue.length() > 0){ addItemRow(table,getTran("medwan.common.remark"),itemValue); } // add content if(table.size() > 1){ contentTable.addCell(createCell(new PdfPCell(table),1,PdfPCell.ALIGN_CENTER,PdfPCell.NO_BORDER)); tranTable.addCell(createContentCell(contentTable)); } // add transaction to doc addTransactionToDoc(); } //### VARIOUS METHODS ########################################################################## //--- GET ITEM WITH CONTENT -------------------------------------------------------------------- private String getItemWithContent(Vector list){ String item; for(int i=0; i<list.size(); i++){ item = (String)list.get(i); if(getItemValue(item).length() > 0){ return item; } } return ""; } //--- DRAW RECTANGLE --------------------------------------------------------------------------- protected void drawRectangle(Graphics2D graphics, double x, double y, Color color, int size, String label){ graphics.setColor(color); graphics.fillRect(new Double(x).intValue(),new Double(y).intValue(),size,size); graphics.setColor(Color.BLACK); graphics.drawRect(new Double(x).intValue(),new Double(y).intValue(),size,size); if(label!=null){ graphics.setFont(new java.awt.Font(FontFactory.HELVETICA,Font.ITALIC,10)); graphics.drawString(label,new Double(x).intValue(),new Double(y).intValue()-1); } } //--- DRAW TEXT -------------------------------------------------------------------------------- protected void drawText(Graphics2D graphics, double x, double y, Color color, String label){ graphics.setColor(color); graphics.setFont(new java.awt.Font(FontFactory.HELVETICA,Font.ITALIC,10)); graphics.drawString(label,(float)x,(float)y); } //--- CREATE CONTENT CELL ---------------------------------------------------------------------- protected PdfPCell createContentCell(String value, int colSpan){ cell = new PdfPCell(new Paragraph(value,FontFactory.getFont(FontFactory.HELVETICA,Math.round((double)7*fontSizePercentage/100.0),Font.NORMAL))); cell.setColspan(colSpan); cell.setBorder(PdfPCell.BOX); cell.setBorderColor(innerBorderColor); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // difference return cell; } protected PdfPCell createContentCell(String value){ return this.createContentCell(value,1); } }
package com.framgia.fsalon.screen.customerinfo; import android.databinding.BaseObservable; import android.databinding.Bindable; import android.support.annotation.StringDef; import android.support.v7.app.AppCompatActivity; import com.framgia.fsalon.BR; import com.framgia.fsalon.R; import com.framgia.fsalon.data.model.User; import com.framgia.fsalon.screen.billcustomer.BillCustomerFragment; import com.framgia.fsalon.screen.customerinfo.user.UserFragment; import com.framgia.fsalon.screen.imagecustomer.ImageCustomerFragment; import static com.framgia.fsalon.screen.customerinfo.CustomerInfoViewModel.Tab.BILL; import static com.framgia.fsalon.screen.customerinfo.CustomerInfoViewModel.Tab.INFO; import static com.framgia.fsalon.screen.customerinfo.CustomerInfoViewModel.Tab.PICTURE; /** * Exposes the data to be used in the CustomerInfo screen. */ public class CustomerInfoViewModel extends BaseObservable implements CustomerInfoContract.ViewModel { private CustomerInfoContract.Presenter mPresenter; private CustomerInfoAdapter mPagerAdapter; int[] mImageResource = {R.drawable.ic_user_trans, R.drawable.ic_list, R.drawable.ic_picture}; public CustomerInfoViewModel(AppCompatActivity activity, User user) { mPagerAdapter = new CustomerInfoAdapter(activity.getSupportFragmentManager()); mPagerAdapter.addFragment(UserFragment.newInstance(user), INFO); mPagerAdapter.addFragment(BillCustomerFragment.newInstance(user.getId()), BILL); mPagerAdapter.addFragment(ImageCustomerFragment.newInstance(user.getId()), PICTURE); } @Override public void onStart() { mPresenter.onStart(); } @Override public void onStop() { mPresenter.onStop(); } @Override public void setPresenter(CustomerInfoContract.Presenter presenter) { mPresenter = presenter; } @Bindable public CustomerInfoAdapter getPagerAdapter() { return mPagerAdapter; } public void setPagerAdapter(CustomerInfoAdapter pagerAdapter) { mPagerAdapter = pagerAdapter; notifyPropertyChanged(BR.pagerAdapter); } /** * Title of pages */ @StringDef({INFO, BILL, PICTURE}) public @interface Tab { String INFO = "Info"; String BILL = "Bill"; String PICTURE = "Picture"; } public int[] getImageResource() { return mImageResource; } public void setImageResource(int[] imageResource) { mImageResource = imageResource; } }
package com.vpt.pw.demo.dtos; import com.vpt.pw.demo.model.FormCrf1.FormCrf1; import java.util.List; public class TeamDTO { private Integer id; private String sraName; private String userName; private String password; private TeamTitleDTO teamTitle; private SiteDTO site; private List<FormCrf1> formCrf1; private Integer status; private String date; private String time; public TeamDTO() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public TeamTitleDTO getTeamTitle() { return teamTitle; } public void setTeamTitle(TeamTitleDTO teamTitle) { this.teamTitle = teamTitle; } public SiteDTO getSite() { return site; } public void setSite(SiteDTO site) { this.site = site; } public List<FormCrf1> getFormCrf1() { return formCrf1; } public void setFormCrf1(List<FormCrf1> formCrf1) { this.formCrf1 = formCrf1; } public String getSraName() { return sraName; } public void setSraName(String sraName) { this.sraName = sraName; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } }
package at.ac.tuwien.sepm.groupphase.backend.endpoint.dto; import javax.validation.Valid; import javax.validation.constraints.NotNull; public class OrderDto { private Long id; @Valid @NotNull(message = "Kunde darf nicht null sein") private CustomerDto customer; @Valid @NotNull(message = "Rechnung darf nicht null sein") private DetailedInvoiceDto invoice; private PromotionDto promotion; public OrderDto(Long id, CustomerDto customer, DetailedInvoiceDto invoice) { this.id = id; this.invoice = invoice; this.customer = customer; } public OrderDto(Long id, CustomerDto customer, DetailedInvoiceDto invoice, PromotionDto promotion) { this.id = id; this.invoice = invoice; this.customer = customer; this.promotion = promotion; } public OrderDto() { } public OrderDto(CustomerDto customer, DetailedInvoiceDto invoice) { this.invoice = invoice; this.customer = customer; } public PromotionDto getPromotion() { return promotion; } public void setPromotion(PromotionDto promotion) { this.promotion = promotion; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public DetailedInvoiceDto getInvoice() { return invoice; } public void setInvoice(DetailedInvoiceDto invoice) { this.invoice = invoice; } public CustomerDto getCustomer() { return customer; } public void setCustomer(CustomerDto customerId) { this.customer = customerId; } }
package edu.utn.utnphones.exception; public class IllegalDurationException extends IllegalArgumentException{ public IllegalDurationException(String message){ super(message); } }
/* * 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 model.bean.tag; import com.fasterxml.jackson.annotation.JsonBackReference; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import model.bean.manual.Manual; import org.hibernate.annotations.GenericGenerator; import util.BeanValidator; import util.exceptions.BeanException; /** * * @author Andriy */ @Entity @Table(name = "tag", catalog = "testfield") public class Tag implements Serializable { @Id @GenericGenerator(name = "generator", strategy = "uuid2") @GeneratedValue(generator = "generator") @Column(name = "ID", unique = true, nullable = false, length = 60) private String id; @Column(name = "DESCRIPTION", nullable = false, length = 255) private String description; @ManyToMany(fetch = FetchType.LAZY, mappedBy = "tags") @JsonBackReference private List<Manual> manuals; public List<Manual> getManuals() { return manuals; } public void setManuals(List<Manual> manuals) { this.manuals = manuals; } public String getId() { return id; } public void setId(String id) throws BeanException { BeanValidator.validateNull(id, "Id"); BeanValidator.validateLength(id, 60, "Id"); this.id = id; } public String getDescription() { return description; } public void setDescription(String description) throws BeanException { BeanValidator.validateEmpty(description, "Description"); BeanValidator.validateLength(description, 255, "Description"); this.description = description; } @Override public String toString() { return "" + "\nTAG (" + "\nID: " + id + "\nDESCRIPTION: " + description + "\n)" + ""; } }
package com.rudolfschmidt.amr.model; class ModelException extends RuntimeException { }
package com.itsoul.lab.ledgerbook.accounting.head; import com.itsoul.lab.generalledger.entities.*; import com.itsoul.lab.generalledger.exception.InfrastructureException; import com.itsoul.lab.generalledger.exception.LedgerAccountException; import com.itsoul.lab.ledgerbook.connector.SQLConnector; import com.itsoul.lab.ledgerbook.connector.SourceConnector; import java.util.List; import java.util.logging.Level; import java.util.stream.Collectors; /** * A general ledger contains all the accounts for recording transactions relating to assets, * liabilities, owners' equity, revenue, and expenses. * * @author towhidul islam * @since 16-Sept-19 */ public class Ledger extends AbstractAccountingConcept { private static final String FACTORY_CLASS_NAME = "com.itsoul.lab.ledgerbook.accounting.dependency.ContextResolverImpl"; private String name; private ChartOfAccounts chartOfAccounts; private boolean skipPrinting; private Ledger(LedgerBuilder builder) throws InfrastructureException { init(FACTORY_CLASS_NAME, builder.connector, builder.client); this.chartOfAccounts = builder.chartOfAccounts; this.name = builder.name; this.skipPrinting = builder.skipPrinting; } private Ledger init() { chartOfAccounts.get().forEach(account -> { if (!account.getBalance().isNullMoney()) { getAccountService().createAccount(account.getAccountRef(), account.getBalance()); } }); return this; } public void commit(TransferRequest transferRequest) { validateAccountRefs( transferRequest.getLegs() .stream() .map(TransactionLeg::getAccountRef) .toArray(String[]::new) ); getTransferService().transferFunds(transferRequest); } private void validateAccountRefs(String... accountRefs) { List<String> chartOfAccountsRefs = this.chartOfAccounts.get() .stream() .map(Account::getAccountRef) .collect(Collectors.toList()); for (String ref : accountRefs) { if (!chartOfAccountsRefs.contains(ref)) { throw new LedgerAccountException(ref); } } } public TransferRequest.ReferenceStep createTransferRequest() { return TransferRequest.builder(); } public List<Transaction> findTransactions(String accountRef) { validateAccountRefs(accountRef); return getTransferService().findTransactionsByAccountRef(accountRef); } public Transaction getTransactionByRef(String transactionRef) { return getTransferService().getTransactionByRef(transactionRef); } public Money getAccountBalance(String accountRef) { validateAccountRefs(accountRef); return getAccountService().getAccountBalance(accountRef); } @Override public String toString() { return this.name; } @Override public void close() { printHistoryLog(); super.close(); } public void printHistoryLog() { if (skipPrinting) return; try { String logInfo = formatAccounts() + "\n\n" + formatTransactionLog() + "\n\n"; LOG.log(Level.INFO, logInfo); } catch (Exception e) { LOG.log(Level.WARNING, e.getMessage(), e); } } private String formatAccounts() { StringBuilder sb = new StringBuilder(); sb.append("Ledger: " + name + "\n\n"); sb.append(String .format("%20s %20s %10s %15s %10s %10s", "Account", "|", "Amount", "|", "Currency", "|")); sb.append(String.format("%s", "\n------------------------------------------------------------------------------------------")); chartOfAccounts.get().forEach(account -> { Money money = getAccountService().getAccountBalance(account.getAccountRef()); sb.append("\n" + String .format("%20s %20s %10.2f %15s %10s %10s", account.getAccountRef(), "|", money.getAmount(), "|", money.getCurrency(), "|")); }); return sb.toString(); } private String formatTransactionLog() { StringBuilder sb = new StringBuilder(); sb.append(String .format("%20s %20s %15s %10s %10s %10s %10s", "Account", "|", "Transaction", "|", "Type", "|", "Date")); sb.append(String.format("%s", "\n-------------------------------------------------------------------------------------------------------------------------")); chartOfAccounts.get().forEach(account -> { List<Transaction> transactions = getTransferService() .findTransactionsByAccountRef(account.getAccountRef()); if (!transactions.isEmpty()) { transactions.forEach(transaction -> sb.append("\n" + String .format("%20s %20s %10s %15s %10s %10s %10s %1s", account.getAccountRef(), "|", transaction.getTransactionRef(), "|", transaction.getTransactionType(), "|", transaction.getTransactionDate(), "|"))); } else { sb.append("\n" + String .format("%20s %20s %10s %15s %10s %10s %10s %1s", account.getAccountRef(), "|", "N/A", "|", "N/A", "|", "N/A", "|")); } }); chartOfAccounts.get().forEach(account -> { List<Transaction> transactions = getTransferService() .findTransactionsByAccountRef(account.getAccountRef()); if (!transactions.isEmpty()) { sb.append( "\n\n" + String.format("%20s %20s %15s %11s %12s %8s %10s %10s %15s %5s %10s %10s" , "Account", "|", "Transaction Leg Ref", "|", "Entry", "|", "Amount", "|", "Currency", "|", "Balance", "|")); sb.append(String.format("%s", "\n------------------------------------------------------------------------------------------------------------------------------------------------------------------")); transactions.forEach(transaction -> transaction.getLegs().forEach(leg -> sb.append("\n" + String .format("%20s %20s %20s %10s %10s %10s %10s %10s %10s %10s %10s %10s", account.getAccountRef(), "|", leg.getAccountRef(), "|", leg.getEntry(), "|", leg.getAmount().getAmount(), "|", leg.getAmount().getCurrency(), "|", leg.getBalance(), "|")))); } }); return sb.toString(); } public static class LedgerBuilder { private String name = "General Ledger"; private ChartOfAccounts chartOfAccounts; private SourceConnector connector = SQLConnector.EMBEDDED_H2_CONNECTOR; private Client client = new Client("Client_" + System.currentTimeMillis() , "Tenant_" + System.currentTimeMillis()); private boolean skipPrinting = true; public LedgerBuilder(ChartOfAccounts chartOfAccounts) { this.chartOfAccounts = chartOfAccounts; } public LedgerBuilder name(String name) { this.name = name; return this; } public LedgerBuilder connector(SourceConnector connector) { this.connector = connector; return this; } public LedgerBuilder client(String ref, String tenantRef){ String secret = this.client.getSecret(); this.client = new Client(ref, tenantRef); return secret(secret); } public LedgerBuilder secret(String secret){ this.client.setSecret(secret); return this; } public LedgerBuilder skipLogPrinting(boolean skipPrinting){ this.skipPrinting = skipPrinting; return this; } public Ledger build() { return new Ledger(this).init(); } } }
package com.capstone.videoeffect; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import com.bumptech.glide.Glide; import java.io.File; import java.util.ArrayList; public class MyVideosAdapter extends BaseAdapter { int THUMBSIZE = 128; Context context; ArrayList<String> f; LayoutInflater inflater; class ViewHolder { ImageView imageview; ViewHolder() { } } public MyVideosAdapter(Context context, ArrayList<String> f) { this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.context = context; this.f = f; } public int getCount() { return f.size(); } public String getItem(int position) { return (String) f.get(position); } public long getItemId(int position) { return (long) position; } public View getView(int position, View convertView, ViewGroup parent) { View tmpView = convertView; if (tmpView == null) { ViewHolder holder = new ViewHolder(); tmpView = inflater.inflate(R.layout.custom_video_grid, null); holder.imageview = (ImageView) tmpView.findViewById(R.id.grid_item); tmpView.setTag(holder); } ViewHolder v1 = (ViewHolder) tmpView.getTag(); // v1.imageview.setImageBitmap(ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile((String) this.f.get(position)), 128, 128)); // Bitmap thumbImage = ThumbnailUtils.extractThumbnail( // BitmapFactory.decodeFile(f.get(position)), // THUMBSIZE, // THUMBSIZE); Glide.with(context) .load(new File(f.get(position))) .placeholder(R.drawable.videoeffectlogo) .centerCrop() .into(v1.imageview); return tmpView; } }
package com.iot.wookee.searchpicture; import android.content.Context; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.GridView; import android.widget.ImageView; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by iot22 on 2015-06-15. */ public class ImageAdapter extends BaseAdapter { private Context mContext; private int flag; // flag 1: 남자용 게임(여자 그림), 1 : 여자용 게임, 2 : 문제판(그리드뷰) private int[] cards1p = new int[5]; private int[] cards2p = new int[5]; private int type; // 남자, 여자 이미지 리소스 배열 private int[] cardBoys = { R.drawable.boycard00, R.drawable.boycard01, R.drawable.boycard02, R.drawable.boycard03, R.drawable.boycard04, R.drawable.boycard05, R.drawable.boycard06, R.drawable.boycard07, R.drawable.boycard08, R.drawable.boycard09, R.drawable.boycard10, R.drawable.boycard11, R.drawable.boycard12, R.drawable.boycard13, R.drawable.boycard14, R.drawable.boycard15 }; private int[] cardGirls = { R.drawable.girlcard00, R.drawable.girlcard01, R.drawable.girlcard02, R.drawable.girlcard03, R.drawable.girlcard04, R.drawable.girlcard05, R.drawable.girlcard06, R.drawable.girlcard07, R.drawable.girlcard08, R.drawable.girlcard09, R.drawable.girlcard10, R.drawable.girlcard11, R.drawable.girlcard12, R.drawable.girlcard13, R.drawable.girlcard14, R.drawable.girlcard15 }; // 실제 어뎁터에서 사용할 배열 private int[] cards = new int[16]; public ImageAdapter(Context mContext, int imagetype) { this.mContext = mContext; // 받아온 imagetype에 따라 // 남자 연예인 게임 / 여자 연예인 게임 type = imagetype; if (imagetype == 0) cards = cardGirls; else if (imagetype == 1) cards = cardBoys; shuffle(); } @Override public int getCount() { // 반환될 아이템 갯수. if (flag == 2) return cards.length; if (flag == 0 || flag == 1) return cards1p.length; return 0; } @Override public Object getItem(int i) { // 반환하는 값. 여기서는 이미지 if (flag == 2) return cards[i]; else if (flag == 0) return cards1p[i]; else if (flag == 1) return cards2p[i]; // 다 실패하면 return null; } @Override public long getItemId(int i) { return i; } int cnt = 1; // 이미지 뷰 만들어서, 리스트에 부려줌 @Override public View getView(int position, View convertView, ViewGroup parent) { Log.i("log", "1"); ImageView imageView; if (convertView == null) { // 이미지 뷰 생성 imageView = new ImageView(mContext); // 이미지 크기 조정 if (flag == 2) imageView.setLayoutParams(new GridView.LayoutParams(170, 170)); else if (flag == 0 || flag == 1) imageView.setLayoutParams(new Gallery.LayoutParams(300, 300)); Log.i("log", "imageView cnt : " + cnt++); // 이미지 크롭 imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); // 패딩 설정 imageView.setPadding(3, 3, 3, 3); } else { imageView = (ImageView) convertView; } if (flag == 2) { // flag 2 : 문제판(그리드뷰)에 뿌려질 이미지들. // 기본 이미지는 카드의 뒷면을 뿌려줌 if ( type == 0) imageView.setImageResource(R.drawable.girlcardback); else if (type == 1) imageView.setImageResource(R.drawable.boycardback); // flag 1 or 2 : 남여 사람 이미지 출력부분. // 플레이어 카드(갤러리)에 뿌려줄 이미지들 } else if (flag == 0) imageView.setImageResource(cards1p[position]); else if (flag == 1) imageView.setImageResource(cards2p[position]); return imageView; } // 배열을 섞자. private void shuffle() { // shuffle 쓸라문 list에 담아야 되노. List<Integer> tmpList = new ArrayList<>(); // 한개씩 담아라 for (int i = 0; i < 16; ++i) tmpList.add(cards[i]); // 섞고 Collections.shuffle(tmpList); for (int i = 0; i < 16; ++i) cards[i] = tmpList.get(i); // 1번 플레이어 문제 리스트1 Collections.shuffle(tmpList); for (int i = 0; i < 5; ++i) cards1p[i] = tmpList.get(i); // 2번 플레이어 문제 리스트2 Collections.shuffle(tmpList); for (int i = 0; i < 5; ++i) cards2p[i] = tmpList.get(i); } // flag 설정 public void setFlag(int i) { this.flag = i; } // play 중 카드 확인 위해 imageID 받기 public int getImageID(int flag, int index){ if (flag == 2) return cards[index]; else if (flag == 0) return cards1p[index]; else if (flag == 1) return cards2p[index]; return -1; } }
package com.cs240.famillymap.ui; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentManager; import com.cs240.famillymap.R; import com.cs240.famillymap.model.DataCache; import com.google.android.gms.maps.model.Marker; import android.content.Intent; import android.os.Bundle; import android.view.View; import java.util.ArrayList; import java.util.Map; import model.Event; //Handles when someone selects a person in the person activity public class EventActivity extends AppCompatActivity { private String eventID; private MapFragment mapFragment; private DataCache cache; /*** * Setup a new mapfragment, and set the focus to the event passed in. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event); //Setup Back button getSupportActionBar().setDisplayHomeAsUpEnabled(true); cache = DataCache.getInstance(); //Get caller arguments. Intent intent = getIntent(); eventID = intent.getStringExtra("EventID"); mapFragment = new MapFragment(); //Set Marker focus if the event exists. if(cache.getMapMarkers().get(eventID) != null){ mapFragment.setFocusMarker(cache.getMapMarkers().get(eventID)); } //Add the new Fragment. FragmentManager fm = this.getSupportFragmentManager(); fm.beginTransaction() .add(R.id.eventFragmentContainer,mapFragment) .commit(); } }
public class SplayRecordTree<K extends Comparable<K>, V> { private SplayRecord<K, V> root; private int size; public SplayRecordTree(){ this.clear(); } public void clear(){ this.root = null; size = 0; } public boolean isEmpty(){ return this.root == null; } public void insert(K key, V value){ SplayRecord<K, V> found = exists(key); if (found != null){ found.setValue(value); } else { SplayRecord<K, V> marker = root; SplayRecord<K, V> previous = null; while (marker != null){ previous = marker; if (key.compareTo(previous.getKey()) > 0) marker = marker.getRight(); else marker = marker.getLeft(); } marker = new SplayRecord<>(key, value); marker.setParent(previous); if (previous == null) this.root = marker; else if (key.compareTo(previous.getKey()) > 0) previous.setRight(marker); else previous.setLeft(marker); splay(marker); size++; } } public V remove(K key){ SplayRecord<K, V> marker = findNode(key); return remove(marker); } private V remove(SplayRecord<K, V> record){ if (record == null) return null; splay(record); V value; if (record.getLeft() != null && record.getRight() != null){ SplayRecord<K, V> minimum = record.getLeft(); while (minimum.getRight() != null) minimum = minimum.getRight(); minimum.setRight(record.getRight()); record.getRight().setParent(minimum); record.getLeft().setParent(null); this.root = record.getLeft(); value = record.getValue(); } else if (record.getRight() != null) { record.getRight().setParent(null); value = record.getValue(); root = record.getRight(); } else if (record.getLeft() != null){ record.getLeft().setParent(null); value = record.getValue(); root = record.getLeft(); } else { value = record.getValue(); root = null; } record.setParent(null); record.setLeft(null); record.setRight(null); record = null; size--; return value; } private SplayRecord<K, V> exists(K key){ SplayRecord<K, V> marker = root; while(marker != null){ if (key.compareTo(marker.getKey()) > 0) marker = marker.getRight(); else if (key.compareTo(marker.getKey()) < 0) marker = marker.getLeft(); else if (key.compareTo(marker.getKey()) == 0) return marker; } return null; } private SplayRecord<K, V> findNode(K key){ SplayRecord<K, V> previous = null; SplayRecord<K, V> marker = root; while (marker != null){ previous = marker; if (key.compareTo(marker.getKey()) > 0){ marker = marker.getRight(); } else if (key.compareTo(marker.getKey()) < 0){ marker = marker.getLeft(); } else if (key.compareTo(marker.getKey()) == 0){ splay(marker); return marker; } } if (previous != null){ splay(previous); return null; } return null; } private void splay(SplayRecord<K, V> record){ while (record.getParent() != null){ SplayRecord<K, V> parent = record.getParent(); SplayRecord<K, V> grandparent = parent.getParent(); if (grandparent == null){ if (record.equals(parent.getLeft())){ rotateLeftSide(record, parent); } else { rotateRightSide(record, parent); } } else { if (record.equals(parent.getLeft())){ if (parent.equals(grandparent.getLeft())){ rotateLeftSide(parent, grandparent); rotateLeftSide(record, parent); } else { rotateRightSide(parent, grandparent); rotateLeftSide(record, parent); } } else { if (parent.equals(grandparent.getLeft())){ rotateLeftSide(parent, grandparent); rotateRightSide(record, parent); } else { rotateRightSide(parent, grandparent); rotateRightSide(record, parent); } } } } this.root = record; } private void rotateLeftSide(SplayRecord<K, V> child, SplayRecord<K, V> parent){ if (parent.getParent() != null){ if (parent.equals(parent.getParent().getLeft())) parent.getParent().setLeft(child); else parent.getParent().setRight(child); } if (child.getRight() != null){ child.getRight().setParent(parent); } child.setParent(parent.getParent()); parent.setParent(child); parent.setLeft(child.getRight()); child.setRight(parent); } private void rotateRightSide(SplayRecord<K, V> child, SplayRecord<K, V> parent){ if (parent.getParent() != null){ if (parent.equals(parent.getParent().getLeft())) parent.getParent().setLeft(child); else parent.getParent().setRight(child); } if (child.getLeft() != null) child.getLeft().setParent(parent); child.setParent(parent.getParent()); parent.setParent(child); parent.setRight(child.getLeft()); child.setLeft(parent); } @Override public String toString(){ return (this.root == null? "Empty SplayRecord Tree" : this.root.toString()); } }
package week4.homework4; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class CollectionUtils { public static <T> void addAll(List<? extends T> source, List<? super T> destination) { destination.addAll(source); } public static <T> List<T> newArrayLit() { return new ArrayList<T>(); } public static <T> int indexOf(List<? extends T> source, T o) { return source.indexOf(o); } public static <T> List<? extends T> limit(List<? extends T> source, int size) { return source.subList(0, size); } public static <T> void add(List<? super T> destination, T o) { destination.add(o); } public static <T> void removeAll(List<? super T> removeFrom, List<T> c2) { removeFrom.removeAll(c2); } public static <T> boolean containsAll(List<T> c1, List<? extends T> c2) { for (T elem : c2) { if (!c1.contains(elem)) { return false; } } return true; } public static <T> boolean containsAny(List<T> c1, List<? extends T> c2) { for (T elem : c2) { if (c1.contains(elem)) { return true; } } return false; } public static <T extends Comparable<T>> List range(List<? extends T> list, T min, T max) { List<? super T> destination = new ArrayList<>(); for (T elem : list) { if (elem.compareTo(min) > 0 && elem.compareTo(max) < 0) { destination.add(elem); } } return destination; } public static <T> List<? super T> range(List<? extends T> list, T min, T max, Comparator<T> comparator) { List<? super T> destination = new ArrayList<>(); for (T elem : list) { if (comparator.compare(elem, min) > 0 && comparator.compare(elem, max) < 0) { destination.add(elem); } } return destination; } }
package agenda.vista; import java.awt.event.ActionListener; import javax.swing.*; import agenda.modelo.Agenda; public class AgendaFrame extends JFrame { public AgendaFrame() { super("MiniAgenda"); AgendaVista vista = new AgendaPanel(); Agenda agenda = new Agenda(); ActionListener ctrl = new AgendaCtrl(vista, agenda); vista.controlador(ctrl); setContentPane((JPanel) vista); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); } }
package com.project.dao; import java.util.ArrayList; import com.project.database.DatabaseAccess; import com.project.model.Party; public interface PartyDao { Party getPartyById(int id); Party createParty(Party party); ArrayList<Party> getAllParties(); }
package com.kopo.jaemin; public class Student { int idx; String name; double middleScore; double finalScore; String created; Student() { } Student(String name, double middleScore, double finalScore, String created) { this.name = name; this.middleScore = middleScore; this.finalScore = finalScore; this.created = created; } Student(int idx, String name, double middleScore, double finalScore, String created) { this.idx = idx; this.name = name; this.middleScore = middleScore; this.finalScore = finalScore; this.created = created; } }
package java.exceptions; /** * Created by user on 21.11.16. */ public class Main { public static void main(String[] args) { try { parseDoubleFromString("1.244"); countNumbersInString("fgh"); } catch (MyUncheckedException | MyCheckedException e) { e.printStackTrace(); } finally { System.out.println("Continue anyway"); } } public static void parseDoubleFromString(final String str) throws MyUncheckedException { if (str == null || str.isEmpty()) { throw new IllegalArgumentException("this is IllegalArgumentException"); } try { double d = Double.parseDouble(str); System.out.println(d); } catch (NumberFormatException e) { throw new MyUncheckedException("MyCustomException : Incoming string[" + str + "] is not a number.", e); } } public static void countNumbersInString (final String str) throws MyCheckedException{ if(str == null || str.isEmpty()) { throw new IllegalArgumentException("this is IllegalArgumentException"); } try { int i = 0; for (char ch: str.toCharArray()) { if (Character.isDigit(str.charAt(ch))) { i++;//???? } } if (i == 0) { throw new MyCheckedException("no numbers!"); } else { System.out.println(i); } } catch (IllegalArgumentException e){ System.out.println("wrong arguments"); } } }
package dwz.cache; import dwz.cache.memcache.MemcacheCacheManager; /** * <strong>CacheManagerFactory</strong><br> * * <strong>Create on : 2012-2-15<br></strong> * * <strong>Copyright (C) Ecointel Software Co.,Ltd.<br></strong> * * * @author peng.shi peng.shi@ecointel.com.cn<br> * @version <strong>ecointel-epp v1.0.0</strong><br> */ public class CacheManagerFactory { private static CacheManagerFactory cmf = null; private CacheManagerFactory() { } /** * 获取CacheManagerFactory实例 * * @return */ public static CacheManagerFactory getInstance() { if (cmf == null) { cmf = new CacheManagerFactory(); } return cmf; } /** * 获取MemcachedManager * * @return */ public CacheManager getMemCacheManager() { return new MemcacheCacheManager(); } }
/* * DiscoverySNPCallerPlugin */ package net.maizegenetics.analysis.gbs; import cern.colt.GenericSorting; import cern.colt.Swapper; import cern.colt.function.IntComparator; import net.maizegenetics.dna.map.TOPMInterface; import net.maizegenetics.dna.map.TagLocus; import net.maizegenetics.dna.map.TagsOnPhysicalMap; import net.maizegenetics.dna.snp.GenotypeTable; import net.maizegenetics.dna.snp.GenotypeTableUtils; import net.maizegenetics.dna.snp.NucleotideAlignmentConstants; import net.maizegenetics.dna.tag.TagsByTaxa; import net.maizegenetics.dna.tag.TagsByTaxaByteFileMap; import net.maizegenetics.dna.tag.TagsByTaxaByteHDF5TagGroups; import net.maizegenetics.dna.BaseEncoder; import net.maizegenetics.plugindef.AbstractPlugin; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.util.ArgsEngine; import net.maizegenetics.util.Utils; import org.apache.log4j.Logger; import org.biojava3.core.util.ConcurrencyTools; import javax.swing.*; import java.awt.*; import java.io.*; import java.util.Arrays; import java.util.HashMap; import static net.maizegenetics.dna.snp.NucleotideAlignmentConstants.*; /** * This class aligns tags at the same physical location against one another, * calls SNPs, and then outputs the SNPs to a HapMap file. * * It is multi-threaded, as there are substantial speed increases with it. * @author Jeff Glaubitz * @author Ed Buckler */ public class DiscoverySNPCallerPlugin extends AbstractPlugin { private double minF = -2.0, minMAF = 0.01; private int minMAC = 10; private boolean inclRare = false; // false = only call the two most common alleles at a site private boolean inclGaps = false; // false = ignore sites where the major or the 1st minor alleles are gaps private boolean callBiallelicSNPsWithGap = false; // true = call sites with a biallelic SNP plus a gap (e.g., A/C/-) private boolean useTBTByte = false; static double defaultMinPropTaxaWithLocus = 0.1; private static Logger myLogger = Logger.getLogger(DiscoverySNPCallerPlugin.class); TagsOnPhysicalMap theTOPM = null; TagsByTaxa theTBT = null; File inputTBTFile = null; private String inTOPMFile = null; private String outTOPMFile = null; private boolean usePedigree = false; HashMap<String, Double> taxaFs = null; boolean[] useTaxaForMinF = null; int nInbredTaxa = Integer.MIN_VALUE; String logFileName = "TagLocusLog.txt"; int startChr = Integer.MAX_VALUE; int endChr = Integer.MIN_VALUE; private static ArgsEngine myArgsEngine = null; int minTaxaWithLocus; private double errorRate = 0.01; private boolean includeReference = false; private String refGenomeFileStr = null; private long[] refGenomeChr = null; private boolean fuzzyStartPositions = false; int locusBorder = 0; final static int CHR = 0, STRAND = 1, START_POS = 2; // indices of these position attributes in array returned by theTOPM.getPositionArray(a) private boolean customSNPLogging = true; // a custom SNP log that collects useful info for filtering SNPs through machine learning criteria private CustomSNPLog myCustomSNPLog = null; private boolean customFiltering = false; public DiscoverySNPCallerPlugin() { super(null, false); } public DiscoverySNPCallerPlugin(Frame parentFrame) { super(parentFrame, false); } @Override public DataSet performFunction(DataSet input) { myLogger.info("Finding SNPs in " + inputTBTFile.getAbsolutePath() + "."); myLogger.info(String.format("StartChr:%d EndChr:%d %n", startChr, endChr)); theTOPM.sortTable(true); myLogger.info("\nAs a check, here are the first 5 tags in the TOPM (sorted by position):"); theTOPM.printRows(5, true, true); DataOutputStream locusLogDOS = openLocusLog(logFileName); if (customSNPLogging) myCustomSNPLog = new CustomSNPLog(logFileName); for (int chr = startChr; chr <= endChr; chr++) { myLogger.info("\n\nProcessing chromosome " + chr + "..."); if (includeReference) { refGenomeChr = readReferenceGenomeChr(refGenomeFileStr, chr); if (refGenomeChr == null) { myLogger.info(" WARNING: chromosome "+chr+" not found in the reference genome file. Skipping this chromosome."); continue; } } discoverSNPsOnChromosome(chr, locusLogDOS); myLogger.info("Finished processing chromosome " + chr + "\n\n"); } if (outTOPMFile.endsWith(".txt")) { theTOPM.writeTextFile(new File(outTOPMFile)); } else { theTOPM.writeBinaryFile(new File(outTOPMFile)); } try{ locusLogDOS.close(); } catch(Exception e) { catchLocusLogException(e); } if (customSNPLogging) myCustomSNPLog.close(); ConcurrencyTools.shutdown(); return null; } private void printUsage() { myLogger.info( "\n\n\nThe available options for the DiscoverySNPCallerPlugin are as follows:\n" + "-i Input TagsByTaxa file (if hdf5 format, use .hdf or .h5 extension)\n" + "-y Use byte format TagsByTaxa file (*.tbt.byte)\n" + "-m TagsOnPhysicalMap (TOPM) file containing genomic positions of tags\n" + "-o Output TagsOnPhysicalMap (TOPM) file with allele calls (variants) added (for use with ProductionSNPCallerPlugin)\n" + "-log TagLocus log file name (default: "+logFileName+")\n" + "-mnF Minimum F (inbreeding coefficient) (default: " + minF + " = no filter)\n" + "-p Pedigree file containing full sample names (or expected names after merging) & expected inbreeding\n" + " coefficient (F) for each. Only taxa with expected F >= mnF used to calculate F = 1-Ho/He.\n" + " (default: use ALL taxa to calculate F)\n" + "-mnMAF Minimum minor allele frequency (default: " + minMAF + ")\n" + "-mnMAC Minimum minor allele count (default: " + minMAC + ")\n" + "-mnLCov Minimum locus coverage (proportion of Taxa with a genotype) (default: " + defaultMinPropTaxaWithLocus + ")\n" + "-eR Average sequencing error rate per base (used to decide between heterozygous and homozygous calls) (default: "+errorRate+")\n" + "-ref Path to reference genome in fasta format. Ensures that a tag from the reference genome is always included\n" + " when the tags at a locus are aligned against each other to call SNPs. The reference allele for each site\n" + " is then provided in the output HapMap files, under the taxon name \"REFERENCE_GENOME\" (first taxon).\n" + " DEFAULT: Don't use reference genome.\n" // + "-LocusBorder All tags on either strand with start postions that differ by less than the specified\n" // + " integer (LocusBorder) are aligned to the reference genome to call SNPs at a locus.\n" // + " By default (without the -LocusBorder option), only tags with identical start postions and\n" // + " strand are grouped as a locus.\n" // + " Use of the -LocusBorder option requires that the -ref option is also invoked.\n" + "-inclRare Include the rare alleles at site (3 or 4th states) (default: " + inclRare + ")\n" + "-inclGaps Include sites where major or minor allele is a GAP (default: " + inclGaps + ")\n" + "-callBiSNPsWGap Include sites where the third allele is a GAP (default: " + callBiallelicSNPsWithGap + ") (mutually exclusive with inclGaps)\n" + "-sC Start chromosome\n" + "-eC End chromosome\n\n\n"); } @Override public void setParameters(String[] args) { // myLogger.addAppender(new ConsoleAppender(new SimpleLayout())); if (args.length == 0) { printUsage(); throw new IllegalArgumentException("\n\nPlease use the above arguments/options.\n\n"); } if (myArgsEngine == null) { myArgsEngine = new ArgsEngine(); myArgsEngine.add("-i", "--input-tbt-file", true); myArgsEngine.add("-y", "--useTBTByte", false); myArgsEngine.add("-m", "--physical-map", true); myArgsEngine.add("-o", "--physical-map-with-variants", true); myArgsEngine.add("-log", "--TagLocus-log-file", true); myArgsEngine.add("-mnF", "--minFInbreeding", true); myArgsEngine.add("-p", "--pedigree-file", true); myArgsEngine.add("-mnMAF", "--minMinorAlleleFreq", true); myArgsEngine.add("-mnMAC", "--minMinorAlleleCount", true); myArgsEngine.add("-mnLCov", "--minLocusCov", true); myArgsEngine.add("-eR", "-errRate", true); // shortened shortForm from -errRate to -eR & longForm from --seqErrRate to -errRate myArgsEngine.add("-ref", "--referenceGenome", true); // myArgsEngine.add("-LocusBorder", "--locus-border", true); myArgsEngine.add("-inclRare", "--includeRare", false); myArgsEngine.add("-inclGaps", "--includeGaps", false); myArgsEngine.add("-callBiSNPsWGap", "--callBiSNPsWGap", false); myArgsEngine.add("-cF", "--customSNPFiltering", false); myArgsEngine.add("-sC", "--start-chromosome", true); myArgsEngine.add("-eC", "--end-chromosome", true); } myArgsEngine.parse(args); if (myArgsEngine.getBoolean("-y")) { useTBTByte = true; } if (myArgsEngine.getBoolean("-i")) { String inputTBTFileName = myArgsEngine.getString("-i"); inputTBTFile = new File(inputTBTFileName); if (!inputTBTFile.exists() || !inputTBTFile.isFile()) { printUsage(); throw new IllegalArgumentException("Can't find the TagsByTaxa input file (-i option: " + myArgsEngine.getString("-i") + ")."); } if (inputTBTFileName.endsWith(".hdf") || inputTBTFileName.endsWith(".h5")) { theTBT = new TagsByTaxaByteHDF5TagGroups(inputTBTFileName); } else if (useTBTByte) { theTBT = new TagsByTaxaByteFileMap(inputTBTFileName); } } else { printUsage(); throw new IllegalArgumentException("Please specify a TagsByTaxa input file (-i option)."); } if (myArgsEngine.getBoolean("-m")) { inTOPMFile = myArgsEngine.getString("-m"); File inTOPMFileTest = new File(inTOPMFile); if (!inTOPMFileTest.exists() || !inTOPMFileTest.isFile()) { printUsage(); throw new IllegalArgumentException("Can't find the TOPM input file (-m option: " + inTOPMFile + ")."); } inTOPMFileTest = null; boolean loadBinary = (inTOPMFile.endsWith(".txt")) ? false : true; theTOPM = new TagsOnPhysicalMap(inTOPMFile, loadBinary); } else { printUsage(); throw new IllegalArgumentException("Please specify a physical map file."); } if (myArgsEngine.getBoolean("-o")) { outTOPMFile = myArgsEngine.getString("-o"); String outFolder = outTOPMFile.substring(0,outTOPMFile.lastIndexOf(File.separator)); File outDir = new File(outFolder); try { if (!outDir.getCanonicalFile().isDirectory()) { throw new Exception(); } } catch (Exception e) { printUsage(); throw new IllegalArgumentException("Path to the output TOPM file (with variants added) does not exist (-o option: " + outTOPMFile + ")"); } } else { printUsage(); throw new IllegalArgumentException("Please specify an output (variant-added) TOPM file."); } if (myArgsEngine.getBoolean("-log")) { logFileName = myArgsEngine.getString("-log"); String logFolder = logFileName.substring(0,logFileName.lastIndexOf(File.separator)); File logDir = new File(logFolder); try { if (!logDir.getCanonicalFile().isDirectory()) { throw new Exception(); } } catch (Exception e) { printUsage(); throw new IllegalArgumentException("Path to the TagLocus log file does not exist (-log option: " + logFileName + ")"); } } else { String outFolder = outTOPMFile.substring(0,outTOPMFile.lastIndexOf(File.separator)); logFileName = outFolder + File.separator + logFileName; } if (myArgsEngine.getBoolean("-mnF")) { minF = Double.parseDouble(myArgsEngine.getString("-mnF")); } if (myArgsEngine.getBoolean("-p")) { String pedigreeFileStr = myArgsEngine.getString("-p"); File pedigreeFile = new File(pedigreeFileStr); if (!pedigreeFile.exists() || !pedigreeFile.isFile()) { printUsage(); throw new IllegalArgumentException("Can't find the pedigree input file (-p option: " + pedigreeFileStr + ")."); } taxaFs = readTaxaFsFromFile(pedigreeFile); if (taxaFs == null) { throw new IllegalArgumentException("Problem reading the pedigree file. Progam aborted."); } if (!maskNonInbredTaxa()) { throw new IllegalArgumentException("Mismatch between taxa names in the pedigree file and TBT. Progam aborted."); } usePedigree = true; } if (myArgsEngine.getBoolean("-mnMAF")) { minMAF = Double.parseDouble(myArgsEngine.getString("-mnMAF")); } if (myArgsEngine.getBoolean("-mnMAC")) { minMAC = Integer.parseInt(myArgsEngine.getString("-mnMAC")); } minTaxaWithLocus = (int) Math.round(theTBT.getTaxaCount() * defaultMinPropTaxaWithLocus); if (myArgsEngine.getBoolean("-mnLCov")) { double minPropTaxaWithLocus = Double.parseDouble(myArgsEngine.getString("-mnLCov")); minTaxaWithLocus = (int) Math.round(theTBT.getTaxaCount() * minPropTaxaWithLocus); } if (myArgsEngine.getBoolean("-eR") || myArgsEngine.getBoolean("-errRate")) { errorRate = Double.parseDouble(myArgsEngine.getString("-eR")); // both shortForm and longForm are used as keys to the same Option } if (myArgsEngine.getBoolean("-ref")) { refGenomeFileStr = myArgsEngine.getString("-ref"); File refGenomeFile = new File(refGenomeFileStr); if (!refGenomeFile.exists() || !refGenomeFile.isFile()) { printUsage(); throw new IllegalArgumentException("Can't find the reference genome fasta file (-ref option: " + refGenomeFileStr + ")."); } includeReference = true; refGenomeFile = null; System.gc(); } if (myArgsEngine.getBoolean("-inclRare")) { inclRare = true; } if (myArgsEngine.getBoolean("-inclGaps")) { inclGaps = true; } if (myArgsEngine.getBoolean("-callBiSNPsWGap")) { if (inclGaps) { printUsage(); throw new IllegalArgumentException("The callBiSNPsWGap option is mutually exclusive with the inclGaps option."); } else { callBiallelicSNPsWithGap = true; } } if (myArgsEngine.getBoolean("-cF")) { customFiltering = true; } if (myArgsEngine.getBoolean("-sC")) { startChr = Integer.parseInt(myArgsEngine.getString("-sC")); } else { printUsage(); throw new IllegalArgumentException("Please specify start and end chromosome numbers."); } if (myArgsEngine.getBoolean("-eC")) { endChr = Integer.parseInt(myArgsEngine.getString("-eC")); } else { printUsage(); throw new IllegalArgumentException("Please specify start and end chromosome numbers."); } if (endChr - startChr < 0) { printUsage(); throw new IllegalArgumentException("Error: The start chromosome is larger than the end chromosome."); } myLogger.info(String.format("minTaxaWithLocus:%d MinF:%g MinMAF:%g MinMAC:%d %n", minTaxaWithLocus, minF, minMAF, minMAC)); myLogger.info(String.format("includeRare:%s includeGaps:%s %n", inclRare, inclGaps)); } @Override public ImageIcon getIcon() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getButtonName() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getToolTipText() { throw new UnsupportedOperationException("Not supported yet."); } public void discoverSNPsOnChromosome(int targetChromo, DataOutputStream locusLogDOS) { long time = System.currentTimeMillis(); TagLocus currTAL = new TagLocus(Integer.MIN_VALUE,Byte.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,includeReference,fuzzyStartPositions,errorRate); int[] currPos = null; int countLoci = 0; int siteCnt=0; for (int i = 0; i < theTOPM.getSize(); i++) { int ri = theTOPM.getReadIndexForPositionIndex(i); // process tags in order of physical position int[] newPos = theTOPM.getPositionArray(ri); if (newPos[CHR] != targetChromo) continue; //Skip tags from other chromosomes if ((fuzzyStartPositions && nearbyTag(newPos, currPos)) || Arrays.equals(newPos, currPos)) { currTAL.addTag(ri, theTOPM, theTBT, includeReference, fuzzyStartPositions); } else { int nTaxaCovered = currTAL.getNumberTaxaCovered(); if (currTAL.getSize()>1 && nTaxaCovered >= minTaxaWithLocus) { // finish the current TAL siteCnt+=findSNPsInTagLocus(currTAL, locusLogDOS); // note that with fuzzyStartPositions there may be no overlapping tags!! countLoci++; if (siteCnt % 100 == 0) { double rate = (double) siteCnt / (double) (System.currentTimeMillis() - time); myLogger.info(String.format( "Chr:%d Pos:%d Loci=%d SNPs=%d rate=%g SNP/millisec", currPos[CHR], currPos[START_POS], countLoci, siteCnt, rate)); } } else if (currPos!=null) { logRejectedTagLocus(currTAL,locusLogDOS); } currPos = newPos; // start a new TAL with the current tag if ((currPos[STRAND] != TagsOnPhysicalMap.BYTE_MISSING) && (currPos[START_POS] != TOPMInterface.INT_MISSING)) { // we already know that currPos[CHR]==targetChromo currTAL = new TagLocus(currPos[CHR],(byte) currPos[STRAND],currPos[START_POS],theTOPM.getTagLength(ri),includeReference,fuzzyStartPositions,errorRate); currTAL.addTag(ri, theTOPM, theTBT, includeReference, fuzzyStartPositions); } else { currPos = null; // invalid position } } } if ((currTAL.getSize() > 1) && (currTAL.getNumberTaxaCovered() >= minTaxaWithLocus)) { // then finish the final TAL for the targetChromo findSNPsInTagLocus(currTAL, locusLogDOS); } else if (currPos!=null) { logRejectedTagLocus(currTAL,locusLogDOS); } myLogger.info("Number of marker sites recorded for chr" + targetChromo + ": " + siteCnt); } boolean nearbyTag(int[] newTagPos, int[] currTagPos) { if (newTagPos == null || currTagPos == null) { return false; } // because we move through the TOPM in positional order, the newTag startPosition is guaranteed to be >= that of the current tag if (newTagPos[CHR] == currTagPos[CHR] && newTagPos[START_POS] - currTagPos[START_POS] < locusBorder) { // &&newTagPos[STRAND]==currTagPos[STRAND] // grab all of the tags that align to a local region (until a gap > tolerance is reached) currTagPos[START_POS] = newTagPos[START_POS]; return true; } return false; } private synchronized int findSNPsInTagLocus(TagLocus theTAL, DataOutputStream locusLogDOS) { boolean refTagUsed = false; if (theTAL.getSize() < 2) { logRejectedTagLocus(theTAL,locusLogDOS); return 0; // need at least two (overlapping!) sequences to make an alignment } byte[][] callsBySite; if (includeReference) { if (fuzzyStartPositions) { String refSeqInRegion = getRefSeqInRegion(theTAL); callsBySite = theTAL.getSNPCallsQuant(refSeqInRegion, callBiallelicSNPsWithGap); } else { addRefTag(theTAL); refTagUsed = true; callsBySite = theTAL.getSNPCallsQuant(callBiallelicSNPsWithGap, includeReference); } } else { callsBySite = theTAL.getSNPCallsQuant(callBiallelicSNPsWithGap, includeReference); } if (callsBySite == null) { logAcceptedTagLocus(theTAL.getLocusReport(minTaxaWithLocus, null), locusLogDOS); return 0; } int[] positionsInLocus = theTAL.getPositionsOfVariableSites(); int strand = theTAL.getStrand(); boolean[] varSiteKept = new boolean[callsBySite.length]; // initializes to false TagLocusSiteQualityScores SiteQualityScores = new TagLocusSiteQualityScores(callsBySite.length); for (int s = 0; s < callsBySite.length; s++) { byte[] alleles = null; if ((alleles = isSiteGood(callsBySite[s])) == null) { continue; } if (includeReference && !fuzzyStartPositions && theTAL.getRefGeno(s) == NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE) { continue; } int position = (strand == -1) ? theTAL.getMinStartPosition() - positionsInLocus[s] : theTAL.getMinStartPosition() + positionsInLocus[s]; CustomSNPLogRecord mySNPLogRecord; if (customSNPLogging) { mySNPLogRecord = new CustomSNPLogRecord(s, theTAL, position, useTaxaForMinF, refTagUsed); myCustomSNPLog.writeEntry(mySNPLogRecord.toString()); SiteQualityScores.addSite(s, mySNPLogRecord.getInbredCoverage(), mySNPLogRecord.getInbredHetScore(), alleles, position); if (customFiltering && !mySNPLogRecord.isGoodSNP()) { continue; } } varSiteKept[s] = true; if (!customFiltering) { updateTOPM(theTAL, s, position, strand, alleles); } } logAcceptedTagLocus(theTAL.getLocusReport(minTaxaWithLocus, varSiteKept), locusLogDOS); if (customFiltering) { updateTOPM(theTAL, varSiteKept, SiteQualityScores); } return callsBySite.length; } private void updateTOPM(TagLocus myTAL, boolean[] varSiteKept, TagLocusSiteQualityScores SiteQualityScores) { SiteQualityScores.sortByQuality(); byte strand = myTAL.getStrand(); for (int s = 0; s < SiteQualityScores.getSize(); s++) { int siteInTAL = SiteQualityScores.getSiteInTAL(s); if (varSiteKept[siteInTAL]) { updateTOPM(myTAL, siteInTAL, SiteQualityScores.getPosition(s), strand, SiteQualityScores.getAlleles(s)); } } } private void updateTOPM(TagLocus myTAL, int variableSite, int position, int strand, byte[] alleles) { for (int tg = 0; tg < myTAL.getSize(); tg++) { int topmTagIndex = myTAL.getTOPMIndexOfTag(tg); if (topmTagIndex == Integer.MIN_VALUE) continue; // skip the reference genome tag (which may not be in the TOPM) byte baseToAdd = myTAL.getCallAtVariableSiteForTag(variableSite, tg); boolean matched = false; for (byte cb : alleles) { if (baseToAdd == cb) { matched = true; break; } } // so that all tags in the tagAlignment have the same corresponding variants in the TOPM, add a variant no matter what (set to missing if needed) byte offset = (byte) (position - myTAL.getMinStartPosition()); if (!matched) { baseToAdd = GenotypeTable.UNKNOWN_DIPLOID_ALLELE; } if (strand == -1) { baseToAdd = NucleotideAlignmentConstants.getNucleotideComplement(baseToAdd); // record everything relative to the plus strand } // convert from allele from 0-15 style to IUPAC ASCII character value (e.g., (byte) 'A') (maintains compatibility with Tassel3 TOPM) baseToAdd = getIUPACAllele(baseToAdd); theTOPM.addVariant(topmTagIndex, offset, baseToAdd); } } /** * * @param calls * @return */ private byte[] isSiteGood(byte[] calls) { int[][] allelesByFreq = GenotypeTableUtils.getAllelesSortedByFrequency(calls); if (allelesByFreq[0].length < 2) { return null; // quantitative SNP calling rendered the site invariant } int aCnt = allelesByFreq[1][0] + allelesByFreq[1][1]; double theMAF = (double) allelesByFreq[1][1] / (double) aCnt; if ((theMAF < minMAF) && (allelesByFreq[1][1] < minMAC)) return null; // note that a site only needs to pass one of the criteria, minMAF &/or minMAC byte majAllele = (byte) allelesByFreq[0][0]; byte minAllele = (byte) allelesByFreq[0][1]; if (!inclGaps && ((majAllele == NucleotideAlignmentConstants.GAP_ALLELE) || (minAllele == NucleotideAlignmentConstants.GAP_ALLELE))) { return null; } byte homMaj = (byte) ((majAllele << 4) | majAllele); byte homMin = (byte) ((minAllele << 4) | minAllele); byte hetG1 = GenotypeTableUtils.getDiploidValue(majAllele, minAllele); byte hetG2 = GenotypeTableUtils.getDiploidValue(minAllele, majAllele); if (minF > -1.0) { // only test for minF if the parameter has been set above the theoretical minimum double obsF = calculateF(calls, allelesByFreq, hetG1, hetG2, theMAF); if (obsF < minF) return null; } return getGoodAlleles(calls,allelesByFreq,homMaj,homMin,hetG1,hetG2,majAllele,minAllele); } private double calculateF(byte[] calls, int[][] alleles, byte hetG1, byte hetG2, double theMAF) { boolean report = false; double obsF; int hetGCnt = 0; if (usePedigree) { byte[] callsToUse = filterCallsForInbreds(calls); //int[][] allelesToUse = getSortedAlleleCounts(callsToUse); int[][] allelesToUse = GenotypeTableUtils.getAllelesSortedByFrequency(callsToUse); if (allelesToUse[0].length < 2) { return 1.0; // lack of variation in the known inbreds will NOT reject a SNP } int aCnt = allelesToUse[1][0] + allelesToUse[1][1]; double newMAF = (double) allelesToUse[1][1] / (double) aCnt; if (newMAF <= 0.0) { return 1.0; // lack of variation in the known inbreds will NOT reject a SNP } byte majAllele = (byte) allelesToUse[0][0]; byte minAllele = (byte) allelesToUse[0][1]; //byte newHetG = IUPACNucleotides.getDegerateSNPByteFromTwoSNPs(majAllele, minAllele); byte newHetG1 = GenotypeTableUtils.getDiploidValue(majAllele, minAllele); byte newHetG2 = GenotypeTableUtils.getDiploidValue(minAllele, majAllele); for (byte i : callsToUse) { if (i == newHetG1 || i == newHetG2) { hetGCnt++; } } int majGCnt = (allelesToUse[1][0] - hetGCnt) / 2; // number of homozygous major allele genotypes int minGCnt = (allelesToUse[1][1] - hetGCnt) / 2; // number of homozygous minor allele genotypes double propHets = (double) hetGCnt / (double) (hetGCnt + majGCnt + minGCnt); double expHets = 2.0 * newMAF * (1 - newMAF); obsF = 1.0 - (propHets / expHets); if (report) { System.out.printf("%d %d %d propHets:%g expHets:%g obsF:%g %n", majGCnt, minGCnt, hetGCnt, propHets, expHets, obsF); } return obsF; } else { for (byte i : calls) { if (i == hetG1 || i == hetG2) { hetGCnt++; } } int majGCnt = (alleles[1][0] - hetGCnt) / 2; // number of homozygous major allele genotypes int minGCnt = (alleles[1][1] - hetGCnt) / 2; // number of homozygous minor allele genotypes double propHets = (double) hetGCnt / (double) (hetGCnt + majGCnt + minGCnt); double expHets = 2.0 * theMAF * (1 - theMAF); obsF = 1.0 - (propHets / expHets); if (report) { System.out.printf("%d %d %d propHets:%g expHets:%g obsF:%g %n", majGCnt, minGCnt, hetGCnt, propHets, expHets, obsF); } return obsF; } } private byte[] getGoodAlleles(byte[] calls,int[][] allelesByFreq,byte homMaj,byte homMin,byte hetG1,byte hetG2,byte majAllele,byte minAllele) { if (inclRare) { byte[] byteAlleles = new byte[allelesByFreq[0].length]; for (int a = 0; a < allelesByFreq[0].length; a++) { byteAlleles[a] = (byte) allelesByFreq[0][a]; } return byteAlleles; } else { setBadCallsToMissing(calls,homMaj,homMin,hetG1,hetG2,majAllele,minAllele); allelesByFreq = GenotypeTableUtils.getAllelesSortedByFrequency(calls); // the allele frequency & number of alleles may have been altered by setBadCallsToMissing() if (allelesByFreq[0].length < 2) { return null; // setBadCallsToMissing() rendered the site invariant } else if (allelesByFreq[0].length == 2) { return getMajMinAllelesOnly(allelesByFreq); } else { if (callBiallelicSNPsWithGap) { boolean hasGap = false; for (int a = 2; a < allelesByFreq[0].length; a++) { // NOTE: the maj & min alleles are not checked (we know that they are NOT gap (inclGaps mutually exclusive with callBiallelicSNPsWithGap) if (((byte) allelesByFreq[0][a]) == NucleotideAlignmentConstants.GAP_ALLELE) { hasGap = true; break; } } if (hasGap) { byte[] byteAlleles = new byte[3]; byteAlleles[0] = (byte) allelesByFreq[0][0]; byteAlleles[1] = (byte) allelesByFreq[0][1]; byteAlleles[2] = NucleotideAlignmentConstants.GAP_ALLELE; return byteAlleles; } else { return getMajMinAllelesOnly(allelesByFreq); } } else { return getMajMinAllelesOnly(allelesByFreq); } } } } private byte[] getMajMinAllelesOnly(int[][] alleles) { byte[] byteAlleles = new byte[2]; byteAlleles[0] = (byte) alleles[0][0]; byteAlleles[1] = (byte) alleles[0][1]; return byteAlleles; } private void setBadCallsToMissing(byte[] calls, byte homMaj, byte homMin, byte hetG1, byte hetG2, byte majAllele, byte minAllele) { if (callBiallelicSNPsWithGap) { for (int i = 0; i < calls.length; i++) { if (isGoodBiallelicWithGapCall(calls[i],homMaj,homMin,hetG1,hetG2,majAllele,minAllele)) { continue; } else { calls[i] = GenotypeTable.UNKNOWN_DIPLOID_ALLELE; } } } else { for (int i = 0; i < calls.length; i++) { if ((calls[i] == homMaj) || (calls[i] == homMin) || (calls[i] == hetG1) || (calls[i] == hetG2)) { continue; } else { calls[i] = GenotypeTable.UNKNOWN_DIPLOID_ALLELE; } } } } private boolean isGoodBiallelicWithGapCall(byte call, byte homMaj, byte homMin, byte hetG1, byte hetG2, byte majAllele, byte minAllele) { if (call == homMaj) return true; if (call == homMin) return true; if (call == hetG1) return true; if (call == hetG2) return true; if (call == GenotypeTableUtils.getDiploidValue(majAllele,NucleotideAlignmentConstants.GAP_ALLELE)) return true; if (call == GenotypeTableUtils.getDiploidValue(NucleotideAlignmentConstants.GAP_ALLELE,majAllele)) return true; if (call == GenotypeTableUtils.getDiploidValue(minAllele,NucleotideAlignmentConstants.GAP_ALLELE)) return true; if (call == GenotypeTableUtils.getDiploidValue(NucleotideAlignmentConstants.GAP_ALLELE,minAllele)) return true; if (call == NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE) return true; return false; } private DataOutputStream openLocusLog(String logFileName) { try { DataOutputStream locusLogDOS = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File(logFileName)), 65536)); locusLogDOS.writeBytes( "chr\tstart\tend\tstrand\ttotalbp\tnTags\tnReads\tnTaxaCovered\tminTaxaCovered\tstatus\tnVariableSites\tposVariableSites\tnVarSitesKept\tposVarSitesKept\trefTag?\tmaxTagLen\tminTagLen\n"); return locusLogDOS; } catch (Exception e) { catchLocusLogException(e); } return null; } private void logRejectedTagLocus(TagLocus currTAL, DataOutputStream locusLogDOS) { int start, end; if (currTAL.getStrand() == -1) { end = currTAL.getMinStartPosition(); start = currTAL.getMinStartPosition()-currTAL.getMaxTagLength()+1; } else { start = currTAL.getMinStartPosition(); end = currTAL.getMinStartPosition()+currTAL.getMaxTagLength()-1; } int totalbp = end-start+1; String status, refTag; if (currTAL.getSize() == 1) { status = "invariant\t0"; refTag = currTAL.getDivergenceOfTag(0)==0 ? "1" : "0"; } else { status = "tooFewTaxa\tNA"; boolean refTagFound = false; int t = -1; while (!refTagFound && t < currTAL.getSize()-1) { t++; if (currTAL.getDivergenceOfTag(t)==0) { refTagFound=true; } } refTag = refTagFound ? "1" : "0"; } try { locusLogDOS.writeBytes( currTAL.getChromosome() +"\t"+ start +"\t"+ end +"\t"+ currTAL.getStrand() +"\t"+ totalbp +"\t"+ currTAL.getSize() +"\t"+ currTAL.getTotalNReads() +"\t"+ currTAL.getNumberTaxaCovered() +"\t"+ minTaxaWithLocus +"\t"+ status +"\t"+ "NA" +"\t"+ "0" +"\t"+ "NA" +"\t"+ refTag +"\t"+ currTAL.getMaxTagLength() +"\t"+ currTAL.getMinTagLength() +"\n" ); } catch (Exception e) { catchLocusLogException(e); } } private void logAcceptedTagLocus(String locusLogRecord, DataOutputStream locusLogDOS) { try { locusLogDOS.writeBytes(locusLogRecord); } catch (Exception e) { catchLocusLogException(e); } } private void catchLocusLogException(Exception e) { System.out.println("ERROR: Unable to write to locus log file: " + e); e.printStackTrace(); System.exit(1); } private byte[] filterCallsForInbreds(byte[] calls) { byte[] callsForInbredsOnly = new byte[nInbredTaxa]; int inbred = 0; for (int taxon = 0; taxon < calls.length; taxon++) { if (useTaxaForMinF[taxon]) { callsForInbredsOnly[inbred] = calls[taxon]; inbred++; } } return callsForInbredsOnly; } public static HashMap<String, Double> readTaxaFsFromFile(File pedigreeFile) { HashMap<String, Double> taxaFs = new HashMap<String, Double>(); String inputLine = "Nothing has been read from the pedigree input file yet"; int nameCol = -1, fCol = -1, nTaxa = 0; try { BufferedReader br = new BufferedReader(new FileReader(pedigreeFile), 65536); inputLine = br.readLine(); // header line String[] cells = inputLine.split("\t"); // headers for (int col = 0; col < cells.length; col++) { if (cells[col].equalsIgnoreCase("Name")) { nameCol = col; } if (cells[col].equalsIgnoreCase("F")) { fCol = col; } } if (nameCol > -1 && fCol > -1) { while ((inputLine = br.readLine()) != null) { cells = inputLine.split("\t"); if (cells[fCol].equals("NA")) { taxaFs.put(cells[nameCol], -2.0); } else { taxaFs.put(cells[nameCol], Double.parseDouble(cells[fCol])); } ++nTaxa; } } else { throw new Exception("Name and/or F column not found in header"); } } catch (Exception e) { myLogger.error("Catch in reading pedigree file e=" + e); e.printStackTrace(); System.out.println(inputLine); return null; } myLogger.info(nTaxa + " taxa read from the pedigree file"); return taxaFs; } private boolean maskNonInbredTaxa() { useTaxaForMinF = new boolean[theTBT.getTaxaCount()]; // initialized to false nInbredTaxa = 0; try { for (int taxon = 0; taxon < theTBT.getTaxaCount(); taxon++) { if (taxaFs.containsKey(theTBT.getTaxaName(taxon))) { if (taxaFs.get(theTBT.getTaxaName(taxon)) >= minF) { useTaxaForMinF[taxon] = true; nInbredTaxa++; } } else { throw new Exception("Taxon " + theTBT.getTaxaName(taxon) + " not found in the pedigree file"); } } myLogger.info(nInbredTaxa + " taxa with an Expected F >= the mnF of " + minF + " were found in the input TBT"); return true; } catch (Exception e) { myLogger.error("Mismatch between TBT and pedigree file e=" + e); e.printStackTrace(); return false; } } private long[] readReferenceGenomeChr(String inFileStr, int targetChr) { int nBases = getLengthOfReferenceGenomeChr(inFileStr, targetChr); if (nBases == 0) return null; int basesPerLong = BaseEncoder.chunkSize; int nLongs = (nBases % basesPerLong == 0) ? nBases / basesPerLong : (nBases / basesPerLong) + 1; long[] refGenomeChrAsLongs = new long[nLongs]; myLogger.info("\n\nReading in the target chromosome " + targetChr + " from the reference genome fasta file: " + inFileStr); String temp = "Nothing has been read yet from the reference genome fasta file"; try { BufferedReader br = new BufferedReader(new FileReader(new File(inFileStr))); StringBuilder currStrB = new StringBuilder(); int currChr = Integer.MIN_VALUE, chunk = 0; while (br.ready()) { temp = br.readLine().trim(); if (temp.startsWith(">")) { if (chunk > 0) { break; // finished reading the targetChr (no need to read the rest of the file) } String chrS = temp.replace(">", ""); chrS = chrS.replace("chr", ""); currChr = Integer.parseInt(chrS); // don't need to catch exception because getLengthOfReferenceGenomeChr() would have caught it already myLogger.info("Currently reading chromosome " + currChr + " (target chromosome = " + targetChr + ")"); } else if (currChr == targetChr) { currStrB.append(temp.replace("N", "A")); // BaseEncoder encodes sequences with N's as (long) -1 while (currStrB.length() >= basesPerLong) { refGenomeChrAsLongs[chunk] = BaseEncoder.getLongFromSeq(currStrB.substring(0, basesPerLong)); currStrB = (currStrB.length() > basesPerLong) ? new StringBuilder(currStrB.substring(basesPerLong)) : new StringBuilder(); chunk++; if (chunk % 1000000 == 0) { myLogger.info(chunk + " chunks of " + basesPerLong + " bases read from the reference genome fasta file for chromosome " + targetChr); } } } } if (currStrB.length() > 0) { refGenomeChrAsLongs[chunk] = BaseEncoder.getLongFromSeq(currStrB.toString()); chunk++; } myLogger.info("\n\nFinished reading target chromosome " + targetChr + " into a total of " + chunk + " " + basesPerLong + "bp chunks\n\n"); if (chunk != nLongs) { throw new Exception("The number of 32 base chunks read (" + chunk + ") was not equal to the expected number (" + nLongs + ")"); } br.close(); } catch (Exception e) { myLogger.error("Exception caught while reading the reference genome fasta file at line. Error=" + e); e.printStackTrace(); System.exit(1); } return refGenomeChrAsLongs; } private int getLengthOfReferenceGenomeChr(String inFileStr, int targetChr) { myLogger.info("\n\nDetermining the length (in bases) of target chromosome " + targetChr + " in the reference genome fasta file: " + inFileStr); String temp = "Nothing has been read yet from the reference genome fasta file"; int line = 0, nBases = 0; try { BufferedReader br = new BufferedReader(new FileReader(new File(inFileStr))); int currChr = Integer.MIN_VALUE; while (br.ready()) { temp = br.readLine().trim(); line++; if (line % 1000000 == 0) { myLogger.info(line + " lines read from the reference genome fasta file"); } if (temp.startsWith(">")) { if (nBases > 0) { break; // finished reading the targetChr (no need to read the rest of the file) } String chrS = temp.replace(">", ""); chrS = chrS.replace("chr", ""); try { currChr = Integer.parseInt(chrS); } catch (NumberFormatException e) { myLogger.error("\n\nTagsToSNPByAlignment detected a non-numeric chromosome name in the reference genome sequence fasta file: " + chrS + "\n\nPlease change the FASTA headers in your reference genome sequence to integers " + "(>1, >2, >3, etc.) OR to 'chr' followed by an integer (>chr1, >chr2, >chr3, etc.)\n\n"); System.exit(1); } myLogger.info("Currently reading chromosome " + currChr + " (target chromosome = " + targetChr + ")"); } else if (currChr == targetChr) { nBases += temp.length(); } } if (nBases == 0) { throw new Exception("Target chromosome ("+targetChr+") not found"); } myLogger.info("The target chromosome " + targetChr + " is " + nBases + " bases long"); br.close(); } catch (Exception e) { if (nBases == 0) { myLogger.warn("Exception caught while reading the reference genome fasta file at line " + line + "\n e=" + e +"\n Skipping this chromosome..."); } else { myLogger.error("Exception caught while reading the reference genome fasta file at line " + line + "\n e=" + e); e.printStackTrace(); System.exit(1); } } return nBases; } private String getRefSeqInRegion(TagLocus theTAL) { int basesPerLong = BaseEncoder.chunkSize; int refSeqStartPosition = theTAL.getMinStartPosition() - 128; int startIndex = Math.max((refSeqStartPosition / basesPerLong) - 1, 0); int refSeqEndPosition = theTAL.getMaxStartPosition() + 128; int endIndex = Math.min((refSeqEndPosition / basesPerLong) + 1, refGenomeChr.length - 1); StringBuilder sb = new StringBuilder(); for (int i = startIndex; i <= endIndex; ++i) { sb.append(BaseEncoder.getSequenceFromLong(refGenomeChr[i])); } theTAL.setMinStartPosition(startIndex * basesPerLong + 1); return sb.toString(); } private void addRefTag(TagLocus theTAL) { String refTag; int basesPerLong = BaseEncoder.chunkSize; int refSeqStartPos, refSeqEndPos; if (theTAL.getStrand() == -1) { refSeqEndPos = theTAL.getMinStartPosition(); refSeqStartPos = refSeqEndPos - theTAL.getMaxTagLength() + 1; } else { refSeqStartPos = theTAL.getMinStartPosition(); refSeqEndPos = refSeqStartPos + theTAL.getMaxTagLength() - 1; } int startIndex = Math.max((refSeqStartPos/basesPerLong)-1, 0); int endIndex = Math.min((refSeqEndPos/basesPerLong), refGenomeChr.length-1); StringBuilder sb = new StringBuilder(); for (int i = startIndex; i <= endIndex; ++i) { sb.append(BaseEncoder.getSequenceFromLong(refGenomeChr[i])); } refTag = sb.substring(Math.max(refSeqStartPos-startIndex*basesPerLong-1,0), Math.min(refSeqStartPos-startIndex*basesPerLong-1+theTAL.getMaxTagLength(),sb.length())); if (theTAL.getStrand() == -1) { refTag = revComplement(refTag); } theTAL.addRefTag(refTag, theTOPM.getTagSizeInLong(), theTOPM.getNullTag()); } //TODO remove this. It should be in some other class, like BaseEncoder public static byte getIUPACAllele(byte allele) { byte iupacAllele = (byte) 'N'; switch (allele) { case 0x00: iupacAllele = (byte) 'A'; break; case 0x01: iupacAllele = (byte) 'C'; break; case 0x02: iupacAllele = (byte) 'G'; break; case 0x03: iupacAllele = (byte) 'T'; break; case 0x05: iupacAllele = (byte) '-'; break; default: iupacAllele = (byte) 'N'; break; } return iupacAllele; } public static String revComplement(String seq) { StringBuilder sb = new StringBuilder(); for (int i = seq.length()-1; i >= 0; i--) { sb.append(NucleotideAlignmentConstants.getNucleotideDiploidIUPACComplement(seq.charAt(i))); } return sb.toString(); } } class CustomSNPLog { private final BufferedWriter myWriter; private final String HEADER = "Chr" +"\t"+ "TagLocusStartPos" +"\t"+ "TagLocusStrand" +"\t"+ "SNPPosition" +"\t"+ "Alleles" +"\t"+ "nTagsAtLocus" +"\t"+ "nReads" +"\t"+ "nTaxa" +"\t"+ "nTaxaCovered" +"\t"+ "nInbreds" +"\t"+ "nInbredsCovered" +"\t"+ "nInbreds1Read" +"\t"+ "nInbreds1ReadMaj" +"\t"+ "nInbreds1ReadMin" +"\t"+ "nInbredsGT1Read" +"\t"+ "nInbredsGT1ReadHomoMaj" +"\t"+ "nInbredsGT1ReadHomoMin" +"\t"+ "nInbredHets" +"\t"+ "inbredCoverage" +"\t"+ "inbredHetScore" +"\t"+ "nOutbreds" +"\t"+ "nOutbredsCovered" +"\t"+ "nOutbreds1Read" +"\t"+ "nOutbreds1ReadMaj" +"\t"+ "nOutbreds1ReadMin" +"\t"+ "nOutbredsGT1Read" +"\t"+ "nOutbredsGT1ReadHomoMaj" +"\t"+ "nOutbredsGT1ReadHomoMin" +"\t"+ "nOutbredHets" +"\t"+ "passed?" +"\n"; public CustomSNPLog(String locusLogFileName) { if ((locusLogFileName == null) || (locusLogFileName.length() == 0)) { myWriter = null; } else { String locusLogFileDir = locusLogFileName.substring(0,locusLogFileName.lastIndexOf(File.separator)+1); String snpLogFileName = locusLogFileDir + "CustomSNPLog.txt"; boolean exists = false; File file = new File(snpLogFileName); if (file.exists()) { exists = true; } myWriter = Utils.getBufferedWriter(snpLogFileName, false); if (!exists) { try { myWriter.append(HEADER); } catch (Exception e) { e.printStackTrace(); } } } } public void writeEntry(String entry) { try { myWriter.append(entry); } catch (Exception e) { e.printStackTrace(); } } public void close() { try { myWriter.close(); } catch (Exception e) { // do nothing; } } } class CustomSNPLogRecord { private int chr; private int tagLocusStartPos; private byte tagLocusStrand; private int snpPosition; private byte majAllele; private byte minAllele; private String alleles; private int nTagsAtLocus; private int nReads; private int nTaxa; private int nTaxaCovered; private int nInbreds; private int nInbredsCovered; private int nInbreds1Read; private int nInbreds1ReadMaj; private int nInbreds1ReadMin; private int nInbredsGT1Read; private int nInbredsGT1ReadHomoMaj; private int nInbredsGT1ReadHomoMin; private int nInbredHets; private int nOutbreds; private int nOutbredsCovered; private int nOutbreds1Read; private int nOutbreds1ReadMaj; private int nOutbreds1ReadMin; private int nOutbredsGT1Read; private int nOutbredsGT1ReadMajHomo; private int nOutbredsGT1ReadMinHomo; private int nOutbredHets; private double inbredCoverage; private double inbredHetScore; private boolean pass; private static final String DELIM = "\t"; public CustomSNPLogRecord(int site, TagLocus myTAL, int position, boolean[] isInbred, boolean includeReference) { chr = myTAL.getChromosome(); tagLocusStartPos = myTAL.getMinStartPosition(); tagLocusStrand = myTAL.getStrand(); snpPosition = position; byte[][] byteAlleles = myTAL.getCommonAlleles(); majAllele= tagLocusStrand==-1? getNucleotideComplement(byteAlleles[0][site]) : byteAlleles[0][site]; minAllele= tagLocusStrand==-1? getNucleotideComplement(byteAlleles[1][site]) : byteAlleles[1][site]; alleles = NUCLEOTIDE_ALLELES[0][majAllele] + "/" + NUCLEOTIDE_ALLELES[0][minAllele]; nTagsAtLocus = (includeReference) ? myTAL.getSize()-1 : myTAL.getSize(); nReads = myTAL.getTotalNReads(); nTaxaCovered = myTAL.getNumberTaxaCovered(); getCounts(site, myTAL.getAlleleDepthsInTaxa(), isInbred); } private void getCounts(int site, byte[][][] alleleDepthsInTaxa, boolean[] isInbred) { nTaxa = alleleDepthsInTaxa[0][site].length; int genoDepth, nAlleles; boolean majPresent; for (int tx = 0; tx < nTaxa; tx++) { genoDepth = 0; nAlleles = 0; majPresent = false; if (isInbred == null || isInbred[tx]) { // if no pedigree file was used, assume that all taxa are inbred ++nInbreds; for (int a = 0; a < 2; a++) { int alleleDepth = alleleDepthsInTaxa[a][site][tx]; if (alleleDepth > 0) { genoDepth += alleleDepth; ++nAlleles; if (a == 0) majPresent = true; } } if (nAlleles > 0) { ++nInbredsCovered; if (genoDepth > 1) { ++nInbredsGT1Read; if (nAlleles > 1) ++nInbredHets; else if (majPresent) ++nInbredsGT1ReadHomoMaj; else ++nInbredsGT1ReadHomoMin; } else { ++nInbreds1Read; if (majPresent) ++nInbreds1ReadMaj; else ++nInbreds1ReadMin; } } } else { ++nOutbreds; for (int a = 0; a < 2; a++) { int alleleDepth = alleleDepthsInTaxa[a][site][tx]; if (alleleDepth > 0) { genoDepth += alleleDepth; ++nAlleles; if (a == 0) majPresent = true; } } if (nAlleles > 0) { ++nOutbredsCovered; if (genoDepth > 1) { ++nOutbredsGT1Read; if (nAlleles > 1) ++nOutbredHets; else if (majPresent) ++nOutbredsGT1ReadMajHomo; else ++nOutbredsGT1ReadMinHomo; } else { ++nOutbreds1Read; if (majPresent) ++nOutbreds1ReadMaj; else ++nOutbreds1ReadMin; } } } } inbredCoverage = (double) nInbredsCovered/nInbreds; inbredHetScore = (double) nInbredHets/(nInbredsGT1ReadHomoMin + nInbredHets + 0.5); if (inbredCoverage > 0.15 && inbredHetScore < 0.21) pass = true; // machine learning cutoffs set by Ed } public boolean isGoodSNP() { return pass; } public double getInbredCoverage() { return inbredCoverage; } public double getInbredHetScore() { return inbredHetScore; } public String toString() { StringBuilder sBuilder = new StringBuilder(); sBuilder.append(String.valueOf(chr)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(tagLocusStartPos)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(tagLocusStrand)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(snpPosition)); sBuilder.append(DELIM); sBuilder.append(alleles); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nTagsAtLocus)).append(DELIM); sBuilder.append(String.valueOf(nReads)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nTaxa)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nTaxaCovered)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nInbreds)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nInbredsCovered)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nInbreds1Read)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nInbreds1ReadMaj)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nInbreds1ReadMin)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nInbredsGT1Read)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nInbredsGT1ReadHomoMaj)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nInbredsGT1ReadHomoMin)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nInbredHets)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(inbredCoverage)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(inbredHetScore)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nOutbreds)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nOutbredsCovered)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nOutbreds1Read)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nOutbreds1ReadMaj)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nOutbreds1ReadMin)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nOutbredsGT1Read)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nOutbredsGT1ReadMajHomo)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nOutbredsGT1ReadMinHomo)); sBuilder.append(DELIM); sBuilder.append(String.valueOf(nOutbredHets)); sBuilder.append(DELIM); if (pass) { sBuilder.append(String.valueOf(1)); } else { sBuilder.append(String.valueOf(0)); } sBuilder.append("\n"); return sBuilder.toString(); } } class TagLocusSiteQualityScores { private int[] siteIndicesInTAL; private double[] inbredCoverage; private double[] inbredHetScore; private byte[][] alleles; // [nSites][nAlleles] private int[] position; private int currSize; public TagLocusSiteQualityScores(int nSites) { siteIndicesInTAL = new int[nSites]; inbredCoverage = new double[nSites]; inbredHetScore = new double[nSites]; alleles = new byte[nSites][]; position = new int[nSites]; currSize = 0; } public void addSite(int siteIndex, double inbredCov, double inbredHetS, byte[] alleles, int position) { siteIndicesInTAL[currSize] = siteIndex; inbredCoverage[currSize] = inbredCov; inbredHetScore[currSize] = inbredHetS; this.alleles[currSize] = alleles; this.position[currSize] = position; ++currSize; } public int getSize() { return currSize; } public int getSiteInTAL(int site) { return siteIndicesInTAL[site]; } public byte[] getAlleles(int site) { return alleles[site]; } public int getPosition(int site) { return position[site]; } public void sortByQuality() { Swapper swapperQual = new Swapper() { public void swap(int a, int b) { int tempInt; tempInt = siteIndicesInTAL[a]; siteIndicesInTAL[a] = siteIndicesInTAL[b]; siteIndicesInTAL[b] = tempInt; double score = inbredCoverage[a]; inbredCoverage[a] = inbredCoverage[b]; inbredCoverage[b] = score; score = inbredHetScore[a]; inbredHetScore[a] = inbredHetScore[b]; inbredHetScore[b] = score; byte[] tempAlleles = alleles[a]; alleles[a] = alleles[b]; alleles[b] = tempAlleles; tempInt = position[a]; position[a] = position[b]; position[b] = tempInt; } }; IntComparator compQual = new IntComparator() { public int compare(int a, int b) { // reverse sort (high inbredCoverage is good) if (inbredCoverage[a] > inbredCoverage[b]) { return -1; } if (inbredCoverage[a] < inbredCoverage[b]) { return 1; } // normal sort (low inbredHetScore is good) if (inbredHetScore[a] < inbredHetScore[b]) { return -1; } if (inbredHetScore[a] > inbredHetScore[b]) { return 1; } // normal sort (low site indices are better because closer to start of read) if (siteIndicesInTAL[a] < siteIndicesInTAL[b]) { return -1; } if (siteIndicesInTAL[a] > siteIndicesInTAL[b]) { return 1; } return 0; } }; GenericSorting.quickSort(0, currSize, compQual, swapperQual); } }
package com.bestom.aihome.service; import android.os.Handler; import android.os.Message; import android.util.Log; import com.bestom.aihome.WebSocket.AIWSClient; import static com.bestom.aihome.common.constant.Const.AIHoneService_AIHoneServiceHandler_connectionWSClient; import static com.bestom.aihome.common.constant.Const.AIHoneService_AIHoneServiceHandler_reconnectionWSClient; public class AIWSClientThreadHandler extends Handler { private AIWSClient mAIWSClient; private static volatile AIWSClientThreadHandler instance; private static final String TAG = "AIWSClientThreadHandler"; private AIWSClientThreadHandler() { mAIWSClient=AIWSClient.getInstance(); } public static AIWSClientThreadHandler getInstance() { if (instance == null) { synchronized (AIWSClientThreadHandler.class) { if (instance == null) { instance = new AIWSClientThreadHandler(); } } } return instance; } @Override public void handleMessage(Message msg) { switch (msg.what){ case AIHoneService_AIHoneServiceHandler_reconnectionWSClient: mAIWSClient.reconnect(); Log.i(TAG, "handleMessage: reconnect"); break; case AIHoneService_AIHoneServiceHandler_connectionWSClient: mAIWSClient.connect(); Log.i(TAG, "handleMessage: connect"); break; default: break; } } }
package training.dao; import training.model.TrainingCourseFeedback; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Required; import java.util.List; public class TrainingCourseFeedbackDAOImpl implements TrainingCourseFeedbackDAO { private org.hibernate.SessionFactory sessionFactory; @Override public void save(TrainingCourseFeedback feedback) { sessionFactory.getCurrentSession().save(feedback); } @Override public List<TrainingCourseFeedback> loadAll() { return sessionFactory.getCurrentSession().createCriteria(TrainingCourseFeedback.class).list(); } @Override public void deleteFeedback(TrainingCourseFeedback feedback) { sessionFactory.getCurrentSession().delete(feedback); } @Override public TrainingCourseFeedback loadFeedback(Long recordId) { return (TrainingCourseFeedback) sessionFactory.getCurrentSession().get( TrainingCourseFeedback.class, recordId); } @Required public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
package cbedoy.barchetype.io.common; import cbedoy.barchetype.io.common.base.BaseCell; /** * RecyclerChatView * Created by Bedoy on 11/15/16. */ public class Detail extends BaseCell { private String title; private String description; public void setTitle(String title) { this.title = title; } public void setDescription(String description) { this.description = description; } public String getTitle() { return title; } public String getDescription() { return description; } public Detail(String title, String description) { this.title = title; this.description = description; setType(BASE_CELL_TYPE.DETAIL); } }
package kr.co.magiclms.mapper; import java.util.List; import kr.co.magiclms.domain.Review; public interface ReviewMapper { void insertReview(Review review); List<Review> detailGoodsReview(int goodsCode); void insertReviewPoint(int review); void updateReviewContent(String review); }
package com.adv.pojo; import java.util.ArrayList; import java.util.Date; import java.util.List; public class TakesTablesExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public TakesTablesExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andMaterialsIsNull() { addCriterion("materials is null"); return (Criteria) this; } public Criteria andMaterialsIsNotNull() { addCriterion("materials is not null"); return (Criteria) this; } public Criteria andMaterialsEqualTo(String value) { addCriterion("materials =", value, "materials"); return (Criteria) this; } public Criteria andMaterialsNotEqualTo(String value) { addCriterion("materials <>", value, "materials"); return (Criteria) this; } public Criteria andMaterialsGreaterThan(String value) { addCriterion("materials >", value, "materials"); return (Criteria) this; } public Criteria andMaterialsGreaterThanOrEqualTo(String value) { addCriterion("materials >=", value, "materials"); return (Criteria) this; } public Criteria andMaterialsLessThan(String value) { addCriterion("materials <", value, "materials"); return (Criteria) this; } public Criteria andMaterialsLessThanOrEqualTo(String value) { addCriterion("materials <=", value, "materials"); return (Criteria) this; } public Criteria andMaterialsLike(String value) { addCriterion("materials like", value, "materials"); return (Criteria) this; } public Criteria andMaterialsNotLike(String value) { addCriterion("materials not like", value, "materials"); return (Criteria) this; } public Criteria andMaterialsIn(List<String> values) { addCriterion("materials in", values, "materials"); return (Criteria) this; } public Criteria andMaterialsNotIn(List<String> values) { addCriterion("materials not in", values, "materials"); return (Criteria) this; } public Criteria andMaterialsBetween(String value1, String value2) { addCriterion("materials between", value1, value2, "materials"); return (Criteria) this; } public Criteria andMaterialsNotBetween(String value1, String value2) { addCriterion("materials not between", value1, value2, "materials"); return (Criteria) this; } public Criteria andTakesNameIsNull() { addCriterion("takes_name is null"); return (Criteria) this; } public Criteria andTakesNameIsNotNull() { addCriterion("takes_name is not null"); return (Criteria) this; } public Criteria andTakesNameEqualTo(String value) { addCriterion("takes_name =", value, "takesName"); return (Criteria) this; } public Criteria andTakesNameNotEqualTo(String value) { addCriterion("takes_name <>", value, "takesName"); return (Criteria) this; } public Criteria andTakesNameGreaterThan(String value) { addCriterion("takes_name >", value, "takesName"); return (Criteria) this; } public Criteria andTakesNameGreaterThanOrEqualTo(String value) { addCriterion("takes_name >=", value, "takesName"); return (Criteria) this; } public Criteria andTakesNameLessThan(String value) { addCriterion("takes_name <", value, "takesName"); return (Criteria) this; } public Criteria andTakesNameLessThanOrEqualTo(String value) { addCriterion("takes_name <=", value, "takesName"); return (Criteria) this; } public Criteria andTakesNameLike(String value) { addCriterion("takes_name like", value, "takesName"); return (Criteria) this; } public Criteria andTakesNameNotLike(String value) { addCriterion("takes_name not like", value, "takesName"); return (Criteria) this; } public Criteria andTakesNameIn(List<String> values) { addCriterion("takes_name in", values, "takesName"); return (Criteria) this; } public Criteria andTakesNameNotIn(List<String> values) { addCriterion("takes_name not in", values, "takesName"); return (Criteria) this; } public Criteria andTakesNameBetween(String value1, String value2) { addCriterion("takes_name between", value1, value2, "takesName"); return (Criteria) this; } public Criteria andTakesNameNotBetween(String value1, String value2) { addCriterion("takes_name not between", value1, value2, "takesName"); return (Criteria) this; } public Criteria andTakesNumberIsNull() { addCriterion("takes_number is null"); return (Criteria) this; } public Criteria andTakesNumberIsNotNull() { addCriterion("takes_number is not null"); return (Criteria) this; } public Criteria andTakesNumberEqualTo(Integer value) { addCriterion("takes_number =", value, "takesNumber"); return (Criteria) this; } public Criteria andTakesNumberNotEqualTo(Integer value) { addCriterion("takes_number <>", value, "takesNumber"); return (Criteria) this; } public Criteria andTakesNumberGreaterThan(Integer value) { addCriterion("takes_number >", value, "takesNumber"); return (Criteria) this; } public Criteria andTakesNumberGreaterThanOrEqualTo(Integer value) { addCriterion("takes_number >=", value, "takesNumber"); return (Criteria) this; } public Criteria andTakesNumberLessThan(Integer value) { addCriterion("takes_number <", value, "takesNumber"); return (Criteria) this; } public Criteria andTakesNumberLessThanOrEqualTo(Integer value) { addCriterion("takes_number <=", value, "takesNumber"); return (Criteria) this; } public Criteria andTakesNumberIn(List<Integer> values) { addCriterion("takes_number in", values, "takesNumber"); return (Criteria) this; } public Criteria andTakesNumberNotIn(List<Integer> values) { addCriterion("takes_number not in", values, "takesNumber"); return (Criteria) this; } public Criteria andTakesNumberBetween(Integer value1, Integer value2) { addCriterion("takes_number between", value1, value2, "takesNumber"); return (Criteria) this; } public Criteria andTakesNumberNotBetween(Integer value1, Integer value2) { addCriterion("takes_number not between", value1, value2, "takesNumber"); return (Criteria) this; } public Criteria andPriceIsNull() { addCriterion("price is null"); return (Criteria) this; } public Criteria andPriceIsNotNull() { addCriterion("price is not null"); return (Criteria) this; } public Criteria andPriceEqualTo(Long value) { addCriterion("price =", value, "price"); return (Criteria) this; } public Criteria andPriceNotEqualTo(Long value) { addCriterion("price <>", value, "price"); return (Criteria) this; } public Criteria andPriceGreaterThan(Long value) { addCriterion("price >", value, "price"); return (Criteria) this; } public Criteria andPriceGreaterThanOrEqualTo(Long value) { addCriterion("price >=", value, "price"); return (Criteria) this; } public Criteria andPriceLessThan(Long value) { addCriterion("price <", value, "price"); return (Criteria) this; } public Criteria andPriceLessThanOrEqualTo(Long value) { addCriterion("price <=", value, "price"); return (Criteria) this; } public Criteria andPriceIn(List<Long> values) { addCriterion("price in", values, "price"); return (Criteria) this; } public Criteria andPriceNotIn(List<Long> values) { addCriterion("price not in", values, "price"); return (Criteria) this; } public Criteria andPriceBetween(Long value1, Long value2) { addCriterion("price between", value1, value2, "price"); return (Criteria) this; } public Criteria andPriceNotBetween(Long value1, Long value2) { addCriterion("price not between", value1, value2, "price"); return (Criteria) this; } public Criteria andTakesDateIsNull() { addCriterion("takes_date is null"); return (Criteria) this; } public Criteria andTakesDateIsNotNull() { addCriterion("takes_date is not null"); return (Criteria) this; } public Criteria andTakesDateEqualTo(Date value) { addCriterion("takes_date =", value, "takesDate"); return (Criteria) this; } public Criteria andTakesDateNotEqualTo(Date value) { addCriterion("takes_date <>", value, "takesDate"); return (Criteria) this; } public Criteria andTakesDateGreaterThan(Date value) { addCriterion("takes_date >", value, "takesDate"); return (Criteria) this; } public Criteria andTakesDateGreaterThanOrEqualTo(Date value) { addCriterion("takes_date >=", value, "takesDate"); return (Criteria) this; } public Criteria andTakesDateLessThan(Date value) { addCriterion("takes_date <", value, "takesDate"); return (Criteria) this; } public Criteria andTakesDateLessThanOrEqualTo(Date value) { addCriterion("takes_date <=", value, "takesDate"); return (Criteria) this; } public Criteria andTakesDateIn(List<Date> values) { addCriterion("takes_date in", values, "takesDate"); return (Criteria) this; } public Criteria andTakesDateNotIn(List<Date> values) { addCriterion("takes_date not in", values, "takesDate"); return (Criteria) this; } public Criteria andTakesDateBetween(Date value1, Date value2) { addCriterion("takes_date between", value1, value2, "takesDate"); return (Criteria) this; } public Criteria andTakesDateNotBetween(Date value1, Date value2) { addCriterion("takes_date not between", value1, value2, "takesDate"); return (Criteria) this; } public Criteria andApplicationIsNull() { addCriterion("application is null"); return (Criteria) this; } public Criteria andApplicationIsNotNull() { addCriterion("application is not null"); return (Criteria) this; } public Criteria andApplicationEqualTo(String value) { addCriterion("application =", value, "application"); return (Criteria) this; } public Criteria andApplicationNotEqualTo(String value) { addCriterion("application <>", value, "application"); return (Criteria) this; } public Criteria andApplicationGreaterThan(String value) { addCriterion("application >", value, "application"); return (Criteria) this; } public Criteria andApplicationGreaterThanOrEqualTo(String value) { addCriterion("application >=", value, "application"); return (Criteria) this; } public Criteria andApplicationLessThan(String value) { addCriterion("application <", value, "application"); return (Criteria) this; } public Criteria andApplicationLessThanOrEqualTo(String value) { addCriterion("application <=", value, "application"); return (Criteria) this; } public Criteria andApplicationLike(String value) { addCriterion("application like", value, "application"); return (Criteria) this; } public Criteria andApplicationNotLike(String value) { addCriterion("application not like", value, "application"); return (Criteria) this; } public Criteria andApplicationIn(List<String> values) { addCriterion("application in", values, "application"); return (Criteria) this; } public Criteria andApplicationNotIn(List<String> values) { addCriterion("application not in", values, "application"); return (Criteria) this; } public Criteria andApplicationBetween(String value1, String value2) { addCriterion("application between", value1, value2, "application"); return (Criteria) this; } public Criteria andApplicationNotBetween(String value1, String value2) { addCriterion("application not between", value1, value2, "application"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.wrathOfLoD.Models.RangedEffect.HitBox.HitBoxEffects; import com.wrathOfLoD.Models.Entity.Entity; import java.util.Iterator; import java.util.List; /** * Created by luluding on 4/12/16. */ public abstract class HitBoxEffect { public abstract void doEffect(List<Entity> entities); }
package Vistas; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.WindowConstants; /** * Ejemplo de uso de JComboBox. * * @author chuidiang */ public class jComboBox { private JTextField tf; private JComboBox combo; private JFrame v; /** * @param args */ public static void main(String[] args) { new jComboBox(); } public jComboBox() { // Creacion del JTextField tf = new JTextField(20); // Creacion del JComboBox y a�adir los items. combo = new JComboBox(); combo.addItem("uno"); combo.addItem("dos"); combo.addItem("tres"); // Accion a realizar cuando el JComboBox cambia de item seleccionado. combo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tf.setText(combo.getSelectedItem().toString()); } }); // Creacion de la ventana con los componentes v = new JFrame(); v.getContentPane().setLayout(new FlowLayout()); v.getContentPane().add(combo); v.getContentPane().add(tf); v.pack(); v.setVisible(true); v.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } }
package quartz.job; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import analysis.service.AnalysisService; import analysis.service.impl.AnalysisServiceImpl; public class AnalysisJob implements Job { @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { AnalysisService analysisService = AnalysisServiceImpl.getInstance(); analysisService.getDailyStockAnalysis(); } }
package com.twitter.controller.rest; /** * @author gauri sawant * */ public final class HTTPResponseCodes { public static final int INTERNAL_SERVER_ERROR = 500; public static final int NOT_AUTHORIZED = 401; public static final int FORBIDDEN = 403; public static final int BAD_REQUEST = 400; public static final int NOT_FOUND = 404; public static final int NOT_ALLOWED = 405; public static final int CONFLICT = 409; public static final int ACCEPTED = 202; public static final int NO_CONTENT = 204; public static final int CREATED = 201; public static final int OK = 200; public static final String FAULT_CLASS = "HTTP_STATUS"; public static final String FAULT_PARAMETER = "CODE"; private HTTPResponseCodes() { throw new AssertionError(); } }
package com.citibank.ods.modules.client.mrdocprvt.functionality; import java.math.BigInteger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.struts.action.ActionForm; import com.citibank.ods.Globals; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.functionality.ODSListFnc; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO; import com.citibank.ods.common.util.ODSConstraintDecoder; import com.citibank.ods.modules.client.mrdocprvt.form.MrDocPrvtMovListForm; import com.citibank.ods.modules.client.mrdocprvt.functionality.valueobject.MrDocPrvtMovListFncVO; import com.citibank.ods.persistence.pl.dao.TplMrDocPrvtMovDAO; import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory; /** * @author m.nakamura * * Implementação da funcionalidade de consulta em lista do movimento da tabela * de Memória de Risco. */ public class MrDocPrvtMovListFnc extends BaseMrDocPrvtListFnc implements ODSListFnc { /** * @see com.citibank.ods.common.functionality.BaseFnc#createFncVO() */ public BaseFncVO createFncVO() { return new MrDocPrvtMovListFncVO(); } /** * @see com.citibank.ods.common.functionality.BaseFnc#updateFncVOFromForm(org.apache.struts.action.ActionForm, * com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void updateFncVOFromForm( ActionForm form_, BaseFncVO fncVO_ ) { super.updateFncVOFromForm( form_, fncVO_ ); // Faz cast para os tipos corretos MrDocPrvtMovListFncVO fncVO = ( MrDocPrvtMovListFncVO ) fncVO_; MrDocPrvtMovListForm form = ( MrDocPrvtMovListForm ) form_; //Código Documento MR (campo de pesquisa) BigInteger mrDocCode = ( form.getMrDocCodeSrc() != null && form.getMrDocCodeSrc().length() > 0 ? new BigInteger( form.getMrDocCodeSrc() ) : null ); String lastUpdUserId = ( form.getLastUpdUserIdSrc() != null && form.getLastUpdUserIdSrc().length() > 0 ? form.getLastUpdUserIdSrc() : null ); Date lastUpdDate = null; SimpleDateFormat formatter = new SimpleDateFormat( Globals.FuncionalityFormatKeys.C_FORMAT_DATE_DDMMYYYY ); try { lastUpdDate = ( form.getLastUpdDateSrc() != null && form.getLastUpdDateSrc().length() > 0 ? formatter.parse( form.getLastUpdDateSrc() ) : null ); } catch ( ParseException e ) { lastUpdDate = null; } fncVO.setMrDocCode( mrDocCode ); fncVO.setLastUpdUserId( lastUpdUserId ); fncVO.setLastUpdDate( lastUpdDate ); } /** * @see com.citibank.ods.common.functionality.ODSListFnc#list(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void list( BaseFncVO fncVO_ ) { validateList( fncVO_ ); if ( !fncVO_.hasErrors() ) { //Os campos critérios de pesquisa updateSearchFields( fncVO_ ); //Cria uma instancia do fncVO específico. MrDocPrvtMovListFncVO fncVO = ( MrDocPrvtMovListFncVO ) fncVO_; // Obtém a instância da Factory ODSDAOFactory factory = ODSDAOFactory.getInstance(); // Obtém a instância do DAO necessário TplMrDocPrvtMovDAO mrDocPrvtMovDAO = factory.getTplMrDocPrvtMovDAO(); // Recupera valores do DAO DataSet results = mrDocPrvtMovDAO.list( fncVO.getMrDocCode(), fncVO.getMrDocText(), fncVO.getMrInvstCurAcctInd(), fncVO.getCustNbr(), fncVO.getCustFullNameText(), fncVO.getCurAcctNbr(), fncVO.getLastUpdUserId(), fncVO.getLastUpdDate(), null, null ); // Atualiza o(s) atributo(s) do fncVO com o(s) dado(s) retornado(s) fncVO.setResults( results ); if ( results.size() > 0 ) { fncVO.addMessage( BaseODSFncVO.C_MESSAGE_SUCESS ); } else { fncVO.addMessage( BaseODSFncVO.C_NO_REGISTER_FOUND ); } } } /** * @see com.citibank.ods.common.functionality.ODSListFnc#load(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void load( BaseFncVO fncVO_ ) { super.load( fncVO_ ); MrDocPrvtMovListFncVO fncVO = ( MrDocPrvtMovListFncVO ) fncVO_; fncVO.setMrInvstCurAcctIndDomain( ODSConstraintDecoder.decodeIndicador() ); } /** * @see com.citibank.ods.common.functionality.ODSListFnc#validateList(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void validateList( BaseFncVO fncVO_ ) { } }
package com.whcd.app.service.impl; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.memory.platform.core.service.impl.BaseServiceImpl; import com.utils.CommonUtils; import com.utils.huanxin.Messages; import com.utils.qiniu.config.QiniuConfig; import com.whcd.app.dao.IRoomDao; import com.whcd.app.model.Room; import com.whcd.app.service.IRoomService; import com.whcd.app.web.controller.BasicController; @Service("roomService") public class RoomServiceImpl extends BaseServiceImpl<Object> implements IRoomService{ private static final Logger log = LoggerFactory.getLogger(BasicController.class); @Autowired @Qualifier("roomDao") private IRoomDao roomDao; @Override public boolean liveStatusCallback(InputStream is) throws Exception { String obj = CommonUtils.convertStreamToString(is); //解析对象流 //解析json对象 JSONObject jo = new JSONObject(obj); JSONObject data = jo.getJSONObject("data"); String id = data.getString("id"); /** * connected, 即流由断开状态变为推流状态 * disconnected, 断开 */ String status = data.getString("status"); //String status = "connected"; String userId = id.split(QiniuConfig.HUB)[1].replace(".", ""); //String userId = "600005"; Date now = new Date(); //当前时间 //获取最近的一条直播 Room room = roomDao.getByHql("from Room where userId='" + userId + "' and status <> 2 order by beginTime desc"); if(room == null){ return false; } log.error("房间ID =================>> " + room.getRoomId()); log.error("room =================>> " + room.toString()); if("connected".equals(status)){ //推流 log.error("开始推流 ===================>> "); if(room.getPushTime() == null){ log.error("第一次推流 ===================>> 设置开始推流时间 "); }else if(room.getBreakTime() != null){ log.error("断流后恢复推流 ===================>> "); Long breakTime = room.getBreakTime().getTime(); //断流时间戳 Long nowTime = now.getTime(); //当前时间戳 if((nowTime-breakTime) > 30000){ //如果超过三十秒 log.error("恢复推流时间超过30秒,开始关闭房间 ===================>> "); }else{ log.error("恢复推流时间未超过30秒,重置断流时间======================>> "); } } }else if("disconnected".equals(status)){ //断流 log.error("直播断流 ===================>> "); }else{ return false; } return true; } @Override public boolean videoCallback(InputStream is) throws Exception { String obj = CommonUtils.convertStreamToString(is); //解析对象流 log.info("videoCallback ==>> " + obj); //解析json对象 JSONObject jo = new JSONObject(obj); JSONObject items = (JSONObject) jo.getJSONArray("items").getJSONObject(0); String key = items.getString("key"); //根据key获取直播信息 Room room = roomDao.getByHql("from Room where interimReplayUrl=? ", key); if(room == null){ return false; } room.setReplayUrl(key); room.setInterimReplayUrl(null); update(room); return true; } }
package com.mhg.weixin.bean.base.vo; import lombok.Data; import org.springframework.beans.factory.annotation.Autowired; import javax.validation.constraints.NotNull; /** * @ClassName UserVO * @Description TODO * @Author PWT * @Date 2019/12/4 14:52 * @Version 1.0 **/ @Data public class LoginUserVO { @NotNull(message = "用户名不能为空") String userName; @NotNull(message = "密码不能为空") String password; }
package guillaumeagis.perk4you.models; import java.util.ArrayList; import java.util.List; /** * Created by guillaumeagis on 14/08/2016. */ public final class Context { private int context; private List<Chat> starts = new ArrayList<>(); public int getContext() { return context; } public List<Chat> getStarts() { return starts; } @Override public String toString() { return "Context{" + "context=" + context + ", start=" + starts + '}'; } }
package com.test.single.bm; /** * 坏字符串 * @author YLine * * 2019年3月29日 下午3:05:30 */ public class BMBadChar { /** * 单独使用,坏字符规则,进行字符串匹配 * @param mainStr 主串 * @param patternStr 模式串 * @return -1 if 不匹配 */ public static int badCharBm(String mainStr, String patternStr) { if (patternStr.length() == 0) { return 0; } char[] patternArray = patternStr.toCharArray(); int mainIndex = 0; int length = mainStr.length() - patternStr.length() + 1; while (mainIndex < length && mainIndex >= 0) { int badIndex = -1; for (int i = patternStr.length() - 1; i >= 0; i--) { if (patternStr.charAt(i) != mainStr.charAt(mainIndex + i)) { badIndex = i; break; } } // 完全匹配了 if (badIndex == -1) { return mainIndex; } char badChar = mainStr.charAt(mainIndex + badIndex); mainIndex += getNextMove(patternArray, badChar, badIndex); } return -1; } /** * 利用坏字符,计算下一个需要移动的距离 * @param patternArray 模式串 * @param badChar 坏字符在主串中,对应的值 * @param badIndex 坏字符,允许在模式串的任意位置【在模式串上的位置】 * @return 下一个移动的距离 */ private static int getNextMove(char[] patternArray, char badChar, int badIndex) { for (int i = badIndex - 1; i >= 0; i--) { if (badChar == patternArray[i]) { return badIndex - i; } } return badIndex + 1; } }
package hudson.plugins.parameterizedtrigger; import hudson.EnvVars; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.TaskListener; import hudson.model.Cause.UpstreamCause; import hudson.model.Hudson; import hudson.model.Node; import hudson.model.Run; import org.kohsuke.stapler.DataBoundConstructor; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.Future; /** * {@link BuildTriggerConfig} that supports blocking of the execution. * * @author Kohsuke Kawaguchi */ public class BlockableBuildTriggerConfig extends BuildTriggerConfig { private final BlockingBehaviour block; private final ConditionalTriggerConfig conditionalTrigger; public boolean buildAllNodesWithLabel; public BlockableBuildTriggerConfig(String projects, BlockingBehaviour block, List<AbstractBuildParameters> configs) { super(projects, ResultCondition.ALWAYS, false, configs); this.block = block; this.conditionalTrigger = null; } public BlockableBuildTriggerConfig(String projects, ConditionalTriggerConfig conditionalTrigger, BlockingBehaviour block, List<AbstractBuildParameters> configs) { super(projects, ResultCondition.ALWAYS, false, configs); this.block = block; this.conditionalTrigger = conditionalTrigger; } @DataBoundConstructor public BlockableBuildTriggerConfig(String projects, ConditionalTriggerConfig conditionalTrigger, BlockingBehaviour block, List<AbstractBuildParameterFactory> configFactories, List<AbstractBuildParameters> configs) { super(projects, ResultCondition.ALWAYS, false, configFactories, configs); this.block = block; this.conditionalTrigger = conditionalTrigger; } public BlockingBehaviour getBlock() { return block; } public ConditionalTriggerConfig getConditionalTrigger() { return conditionalTrigger; } public boolean isConditionMet(AbstractBuild build, TaskListener listener, EnvVars env) { // If no conditional trigger was specified, always return true. if (conditionalTrigger == null) { return true; } return conditionalTrigger.isConditionMet(build, listener, env); } @Override public List<Future<AbstractBuild>> perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { List<Future<AbstractBuild>> r = super .perform(build, launcher, listener); if (block == null) { return Collections.emptyList(); } return r; } @Override public ListMultimap<AbstractProject, Future<AbstractBuild>> perform2( AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { ListMultimap<AbstractProject, Future<AbstractBuild>> futures = super .perform2(build, launcher, listener); if (block == null) { return ArrayListMultimap.create(); } return futures; } @Override protected Future schedule(AbstractBuild<?, ?> build, AbstractProject project, List<Action> list) throws InterruptedException, IOException { if (block != null) { while (true) { // if we fail to add the item to the queue, wait and retry. // it also means we have to force quiet period = 0, or else // it'll never leave the queue Future f = project.scheduleBuild2(0, new UpstreamCause( (Run) build), list.toArray(new Action[list.size()])); // when a project is disabled or the configuration is not yet // saved f will always be null and we'ure caught in a loop, // therefore we need to check for it if (f != null || (f == null && !project.isBuildable())) { return f; } Thread.sleep(1000); } } else { return super.schedule(build, project, list); } } public Collection<Node> getNodes() { return Hudson.getInstance().getLabel("asrt").getNodes(); } @Extension public static class DescriptorImpl extends BuildTriggerConfig.DescriptorImpl { } }
package com.dexvis.javafx.scene.control; import java.util.ArrayList; import java.util.List; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.scene.Scene; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.image.ImageView; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Callback; import com.dexvis.dex.DexConstants; import com.dexvis.dex.wf.DexTask; import com.thoughtworks.xstream.annotations.XStreamOmitField; public class DexTaskList extends ListView<DexTaskItem> implements DexConstants { @XStreamOmitField private int insertionPoint = -1; @XStreamOmitField private ModalText modalText; @XStreamOmitField private Stage stage = null; @XStreamOmitField private List<DexTaskItem> copyTasks = new ArrayList<DexTaskItem>(); public DexTaskList() { super(); setCellFactory(new Callback<ListView<DexTaskItem>, ListCell<DexTaskItem>>() { @Override public ListCell<DexTaskItem> call(ListView<DexTaskItem> list) { return new DexTaskItemCell(); } }); getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); setOnKeyPressed(event -> keyPress(event)); setOnDragOver(event -> onDragOver(event)); setOnDragDropped(event -> onDragDropped(event)); ContextMenu ctxMenu = new ContextMenu(); MenuItem disableTask = new MenuItem("Disable"); MenuItem enableTask = new MenuItem("Enable"); MenuItem renameTask = new MenuItem("Rename"); MenuItem configTask = new MenuItem("Configure"); disableTask.setOnAction(action -> disableTask(action)); enableTask.setOnAction(action -> enableTask(action)); renameTask.setOnAction(action -> renameTask(action)); configTask.setOnAction(action -> configTask(action)); ctxMenu.getItems().addAll(disableTask, enableTask, renameTask, configTask); setOnDragDetected(event -> onDragDetected(event)); setContextMenu(ctxMenu); } public void setStage(Stage stage) { this.stage = stage; } public class DexTaskItemCell extends ListCell<DexTaskItem> { private HBox hbox = new HBox(); private ImageView imageView = new ImageView(); private Label label = new Label("UNNAMED"); public DexTaskItemCell() { this.hbox.getChildren().addAll(imageView, label); DexTaskItem item = getItem(); if (item != null) { imageView.setImage(getItem().getImage()); hbox.opacityProperty().bind(item.getOpacity()); label.textProperty().bind(item.getName()); setLabelColor(label, item); } setOnDragEntered(event -> onDragEntered(event)); setOnDragExited(event -> onDragExited(event)); } private void setLabelColor(Label label, DexTaskItem item) { if (item != null && item.getActive() != null && item.getActive().get()) { label.setTextFill(Color.BLACK); } else { label.setTextFill(Color.RED); } } @Override public void updateItem(DexTaskItem item, boolean empty) { super.updateItem(item, empty); if (empty) { setText(null); setGraphic(null); } else { if (item != null) { imageView.setImage(item.getImage()); label.textProperty().bind(item.getName()); setLabelColor(label, item); hbox.opacityProperty().bind(item.getOpacity()); } setGraphic(hbox); } } public void onDragEntered(DragEvent evt) { System.out.println("On Cell Drag Entered"); /* the drag-and-drop gesture entered the target */ /* show to the user that it is an actual gesture target */ int index = getIndex(); insertionPoint = index; label.setTextFill(Color.RED); evt.consume(); } public void onDragExited(DragEvent evt) { System.out.println("On Cell Drag Exited"); int index = getIndex(); insertionPoint = index; setLabelColor(label, getItem()); evt.consume(); } } public void renameTask(ActionEvent evt) { // TODO: Replaced the actioneventhandler with an expression, weirdly, it // worked. // I am actually not sure why, how, or if it truly did work or introduced // some // subtle bug that it will take me hours to find later. Hence the TODO. modalText = new ModalText(stage, "Change Name", "Enter New Name:", getSelectionModel().getSelectedItem().getName().get(), event -> changeName(event)); } public void configTask(ActionEvent evt) { try { Stage configStage = new Stage(); DexTask task = getSelectionModel().getSelectedItem().getTask().getValue(); JsonGuiPane configGui = task.getConfigurationGui(); Scene configScene = new Scene(configGui, 800, 600); configStage.setScene(configScene); configStage.show(); } catch(Exception ex) { ex.printStackTrace(); } } public void changeName(ActionEvent evt) { getSelectionModel().getSelectedItem().setName(modalText.getText()); } public void enableTask(ActionEvent evt) { System.out.println("ENABLE EVENT: " + evt); ObservableList<Integer> selected = getSelectionModel().getSelectedIndices(); ObservableList<DexTaskItem> items = getItems(); for (int i : selected) { DexTaskItem task = items.get(i); task.setActive(true); } forcedRefresh(); } public void disableTask(ActionEvent evt) { System.out.println("DISABLE EVENT: " + evt); ObservableList<Integer> selected = getSelectionModel().getSelectedIndices(); ObservableList<DexTaskItem> items = getItems(); for (int i : selected) { DexTaskItem task = items.get(i); task.setActive(false); } forcedRefresh(); } public void enableAll() { for (DexTaskItem item : getItems()) { item.setActive(true); } forcedRefresh(); } public void disableAll() { for (DexTaskItem item : getItems()) { item.setActive(false); } forcedRefresh(); } private void forcedRefresh() { ObservableList<DexTaskItem> items = getItems(); setItems(null); setItems(items); } public void keyPress(KeyEvent evt) { System.out.println("*** keypress: " + evt); if (evt.getCode().equals(KeyCode.DELETE)) { int delIndex = getSelectionModel().getSelectedIndex(); int size = getItems().size(); if (delIndex >= 0 && delIndex < size) { System.out.println("Deleting Task: " + (delIndex + 1) + " of " + size); getItems().remove(delIndex); } } else if (evt.getCode().equals(KeyCode.C) && evt.isControlDown()) { System.out.println("Control-C"); copyTasks.clear(); ObservableList<Integer> selected = getSelectionModel() .getSelectedIndices(); ObservableList<DexTaskItem> items = getItems(); for (int selectedIndex : selected) { copyTasks.add(items.get(selectedIndex).clone()); } } else if (evt.getCode().equals(KeyCode.V) && evt.isControlDown()) { if (copyTasks == null) { return; } int insertionIndex = getSelectionModel().getSelectedIndex(); // Need to clone the entire list. List<DexTaskItem> copiedTasks = new ArrayList<DexTaskItem>(); for (DexTaskItem task : copyTasks) { copiedTasks.add((DexTaskItem) (task.clone())); } getItems().addAll(insertionIndex, copiedTasks); } else { // System.out.println("Ignoring keypress"); } } public List<DexTaskItem> getCopyTasks() { return copyTasks; } public void setCopyTasks(List<DexTaskItem> copyTasks) { this.copyTasks = copyTasks; } public void clearCopyTasks() { this.copyTasks.clear(); } public void onDragOver(DragEvent evt) { evt.acceptTransferModes(TransferMode.ANY); evt.consume(); } public void onDragDropped(DragEvent evt) { // System.out.println("On Drag Dropped"); Dragboard db = evt.getDragboard(); boolean success = false; try { if (db.hasContent(DEX_TASK_CREATE)) { System.out.println("DND-RECEIVING: '" + db.getContent(DEX_TASK_CREATE) + "'"); Class clazz = (Class) db.getContent(DEX_TASK_CREATE); DexTask task = (DexTask) clazz.newInstance(); DexTaskItem item = new DexTaskItem(task); int insertionPoint = getInsertionPoint(); System.out.println("Inserting at: " + insertionPoint + ", list size: " + getItems().size()); if (insertionPoint >= 0 && insertionPoint <= getItems().size()) { getItems().add(insertionPoint - 1, item); } else { getItems().add(item); } success = true; } else if (db.hasContent(DEX_TASK_LIST_MOVE)) { int movingTo = getInsertionPoint(); if (movingTo < 0) { movingTo = 0; } int movingFrom = (int) db.getContent(DEX_TASK_LIST_MOVE); if (movingFrom < movingTo) { DexTaskItem movingItem = getItems().remove(movingFrom); getItems().add(movingTo - 1, movingItem); } else if (movingFrom > movingTo) { DexTaskItem movingItem = getItems().remove(movingFrom); getItems().add(movingTo, movingItem); } System.out.println("MOVING: " + movingFrom + "->" + movingTo); } // Kludgey, but resets all items to active/inactive default opacity. List<DexTaskItem> items = getItems(); for (DexTaskItem item : items) { System.out.println("Setting item: " + item.getName() + " opacity=" + (item.getActive().get() ? "1.0" : "0.5")); item.getOpacity().set(item.getActive().get() ? 1.0 : .5); } } catch(Exception ex) { ex.printStackTrace(); } evt.setDropCompleted(success); evt.consume(); } public void onDragDetected(MouseEvent evt) { System.out.println("On Drag Detected"); DexTaskList source = (DexTaskList) evt.getSource(); /* drag was detected, start a drag-and-drop gesture */ /* allow any transfer mode */ int movingFrom = source.getSelectionModel().getSelectedIndex(); DexTaskItem item = source.getSelectionModel().getSelectedItem(); Dragboard db = source.startDragAndDrop(TransferMode.COPY_OR_MOVE); /* Put a string on a dragboard */ ClipboardContent content = new ClipboardContent(); if (content != null && item != null && item.getTask() != null && item.getTask().get() != null) { content.put(DEX_TASK_LIST_MOVE, movingFrom); db.setContent(content); } evt.consume(); } public int getInsertionPoint() { return insertionPoint; } }
package com.ranpeak.ProjectX.activity.lobby.viewModel; import android.annotation.SuppressLint; import android.content.Context; import android.util.Log; import com.ranpeak.ProjectX.activity.lobby.DefaultSubscriber; import com.ranpeak.ProjectX.activity.lobby.commands.TaskNavigator; import com.ranpeak.ProjectX.base.BaseViewModel; import com.ranpeak.ProjectX.dataBase.App; import com.ranpeak.ProjectX.dataBase.local.LocalDB; import com.ranpeak.ProjectX.dataBase.local.dao.TaskDAO; import com.ranpeak.ProjectX.dto.TaskDTO; import com.ranpeak.ProjectX.networking.retrofit.ApiService; import com.ranpeak.ProjectX.networking.retrofit.RetrofitClient; import java.util.ArrayList; import java.util.List; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.observers.DisposableObserver; import io.reactivex.schedulers.Schedulers; public class TaskViewModel extends BaseViewModel<TaskNavigator> { private Context context; private List<TaskDTO> data = new ArrayList<>(); private LocalDB localDB = App.getInstance().getLocalDB(); private TaskDAO taskDAO = localDB.taskDao(); private ApiService apiService = RetrofitClient.getInstance() .create(ApiService.class); public TaskViewModel(Context context) { this.context = context; } @SuppressLint("CheckResult") public void getTasksFromServer(){ apiService.getAllTask() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(new DisposableObserver<List<TaskDTO>>() { @Override public void onNext(List<TaskDTO> taskDTOS) { addTasksToLocalDB(taskDTOS); getNavigator().getDataInAdapter(taskDTOS); Log.d("Task size from server", String.valueOf(taskDTOS.size())); } @Override public void onError(Throwable e) { Log.d("Error", e.getMessage()); getNavigator().handleError(e); getTasksFromLocalDB(); } @Override public void onComplete() { // Received all notes } }); } @SuppressLint("CheckResult") private void getTasksFromLocalDB(){ taskDAO.getAllTasks() .observeOn(AndroidSchedulers.mainThread()) .subscribe(taskDTOS -> { getNavigator().getDataInAdapter(taskDTOS); Log.d("Task size in LocalDB", String.valueOf(taskDTOS.size())); },throwable -> { getNavigator().handleError(throwable); }); } private void addTasksToLocalDB(List<TaskDTO> tasksDTOS) { Observable.fromCallable(() -> localDB.taskDao().insertAll(tasksDTOS)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new DefaultSubscriber<List<Long>>(){ @Override public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) { super.onSubscribe(d); } @Override public void onNext(@io.reactivex.annotations.NonNull List<Long> longs) { super.onNext(longs); Log.d("AddTasks","insert countries transaction complete"); } @Override public void onError(@io.reactivex.annotations.NonNull Throwable e) { super.onError(e); Log.d("AddTasks","error storing countries in db"+e); } @Override public void onComplete() { Log.d("AddTasks","insert countries transaction complete"); } }); } public List<TaskDTO> getData() { return data; } public void setData(List<TaskDTO> data) { this.data = data; } }
package com.jfronny.raut.blocks; import net.fabricmc.fabric.api.block.FabricBlockSettings; import net.minecraft.block.*; import net.minecraft.item.ItemPlacementContext; import net.minecraft.state.StateManager; import net.minecraft.util.BlockMirror; import net.minecraft.util.BlockRotation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.BlockView; import net.minecraft.world.World; import static com.jfronny.raut.modules.MiscModule.BLOCK_BREAKER; import static com.jfronny.raut.modules.MiscModule.UNBREAKABLE; public class BlockBreaker extends FacingBlock { public BlockBreaker() { super(FabricBlockSettings.of(Material.STONE).build()); this.setDefaultState(this.stateManager.getDefaultState().with(FACING, Direction.SOUTH)); } @Override public void neighborUpdate(BlockState state, World world, BlockPos pos, Block block, BlockPos neighborPos, boolean moved) { if (!world.isClient) { Direction direction = state.get(FACING); BlockPos mov = pos.offset(direction); BlockState target = world.getBlockState(mov); if (checkPowered(world, pos, direction) && (neighborPos.getX() != mov.getX() || neighborPos.getY() != mov.getY() || neighborPos.getZ() != mov.getZ()) && target.getBlock().getHardness(target, world, mov) >= 0 && !target.getBlock().matches(UNBREAKABLE)) { world.breakBlock(mov, true); } } } private boolean checkPowered(World world, BlockPos pos, Direction face) { Direction[] var4 = Direction.values(); int var5 = var4.length; int var6; for (var6 = 0; var6 < var5; ++var6) { Direction direction = var4[var6]; if (direction != face && world.isEmittingRedstonePower(pos.offset(direction), direction)) { return true; } } if (world.isEmittingRedstonePower(pos, Direction.DOWN)) { return true; } else { BlockPos blockPos = pos.up(); Direction[] var10 = Direction.values(); var6 = var10.length; for (int var11 = 0; var11 < var6; ++var11) { Direction direction2 = var10[var11]; if (direction2 != Direction.DOWN && world.isEmittingRedstonePower(blockPos.offset(direction2), direction2)) { return true; } } return false; } } @Override public boolean isSimpleFullBlock(BlockState state, BlockView view, BlockPos pos) { return false; } @Override protected void appendProperties(StateManager.Builder<Block, BlockState> builder) { builder.add(FACING); } @Override public BlockState rotate(BlockState state, BlockRotation rotation) { return state.with(FACING, rotation.rotate(state.get(FACING))); } @Override public BlockState mirror(BlockState state, BlockMirror mirror) { return state.rotate(mirror.getRotation(state.get(FACING))); } @Override public boolean canPlaceAtSide(BlockState world, BlockView view, BlockPos pos, BlockPlacementEnvironment env) { return false; } @Override public BlockState getPlacementState(ItemPlacementContext ctx) { return this.getDefaultState().with(FACING, ctx.getPlayerLookDirection().getOpposite().getOpposite()); } @Override public void onBlockAdded(BlockState state, World world, BlockPos pos, BlockState oldState, boolean moved) { neighborUpdate(state, world, pos, BLOCK_BREAKER, pos, moved); } }
package br.edu.infnet.appSistemaEspecialistaEmFreios.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.SessionAttribute; import br.edu.infnet.appSistemaEspecialistaEmFreios.model.domain.Produto; import br.edu.infnet.appSistemaEspecialistaEmFreios.model.domain.Usuario; import br.edu.infnet.appSistemaEspecialistaEmFreios.model.service.ProdutoService; @Controller public class ProdutoController { @Autowired private ProdutoService produtoService; @GetMapping (value = "produto/lista") public String telaLista(Model model, @SessionAttribute("user") Usuario usuario ) { model.addAttribute("produtos", produtoService.obterLista(usuario)); return "produto/lista"; } @GetMapping(value = "/produto/{id}/excluir") public String excluir(Model model, @PathVariable Integer id, @SessionAttribute("user") Usuario usuario) { Produto produto = produtoService.obterPorId(id); String mensagem = null; try { produtoService.excluir(id); mensagem = "Produto: "+ produto.getDescricao() + " excluido!"; } catch (Exception e) { mensagem = "Produto: "+ produto.getDescricao() + " não pode ser excluido!"; } model.addAttribute("msg", mensagem); return telaLista(model, usuario); } }
package com.logzc.webzic.annotation; /** * Created by lishuang on 2016/7/21. */ @RequestMapping public class TestBean1 { }
package ggwozdz.nordea.textsplitter; import java.io.IOException; import java.io.InputStream; import java.util.function.Consumer; public interface InputStreamSplitter { void split(InputStream is, Consumer<String> streamPartConsumer) throws IOException; }
package nl.kolkos.photoGallery.controllers; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import nl.kolkos.photoGallery.objects.Button; @Controller @RequestMapping("/photos") public class PhotoController { @GetMapping("/upload") public String registerGalleryForm(Model model) { List<Button> buttons = new ArrayList<>(); buttons.add(new Button("/photos/my", "btn-primary", "Show my photos", "fas fa-images")); model.addAttribute("title", "Upload photo's"); model.addAttribute("description", "This screen lets you upload photo's."); model.addAttribute("buttons", buttons); return "photos/upload"; } }
/* * Created by Angel Leon (@gubatron), Alden Torres (aldenml) * Copyright (c) 2011-2014, FrostWire(R). All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.frostwire.gui.bittorrent; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.gudy.azureus2.core3.download.DownloadManager; import org.limewire.util.FilenameUtils; import com.frostwire.util.DigestUtils; import com.frostwire.util.DigestUtils.DigestProgressListener; import com.frostwire.util.HttpClient; import com.frostwire.util.HttpClient.HttpClientListener; import com.frostwire.util.HttpClient.RangeNotSupportedException; import com.frostwire.util.HttpClientFactory; import com.frostwire.util.HttpClientType; import com.limegroup.gnutella.gui.I18n; import com.limegroup.gnutella.settings.SharingSettings; /** * @author gubatron * @author aldenml * */ public class HttpDownload implements BTDownload { /** TODO: Make this configurable */ private static final Executor HTTP_THREAD_POOL = Executors.newFixedThreadPool(6); private static final String STATE_DOWNLOADING = I18n.tr("Downloading"); private static final String STATE_ERROR = I18n.tr("Error"); private static final String STATE_ERROR_MD5 = I18n.tr("Error - corrupted file"); private static final String STATE_ERROR_MOVING_INCOMPLETE = I18n.tr("Error - can't save"); private static final String STATE_PAUSING = I18n.tr("Pausing"); private static final String STATE_PAUSED = I18n.tr("Paused"); private static final String STATE_CANCELING = I18n.tr("Canceling"); private static final String STATE_CANCELED = I18n.tr("Canceled"); private static final String STATE_WAITING = I18n.tr("Waiting"); private static final String STATE_CHECKING = I18n.tr("Checking"); private static final String STATE_FINISHED = I18n.tr("Finished"); private static final int SPEED_AVERAGE_CALCULATION_INTERVAL_MILLISECONDS = 1000; private final String url; private final String title; private final String saveAs; private File saveFile; private final File completeFile; private final File incompleteFile; private final String md5; //optional private final HttpClient httpClient; private final HttpClientListener httpClientListener; private final Date dateCreated; /** If false it should delete any temporary data and start from the beginning. */ private final boolean deleteDataWhenCancelled; private long size; private long bytesReceived; protected String state; private long averageSpeed; // in bytes // variables to keep the download rate of file transfer private long speedMarkTimestamp; private long totalReceivedSinceLastSpeedStamp; private int md5CheckingProgress; private boolean isResumable; public HttpDownload(String theURL, String theTitle, String saveFileAs, long fileSize, String md5hash, boolean shouldResume, boolean deleteFileWhenTransferCancelled) { url = theURL; title = theTitle; saveAs = saveFileAs; size = fileSize; md5 = md5hash; deleteDataWhenCancelled = deleteFileWhenTransferCancelled; completeFile = buildFile(SharingSettings.TORRENT_DATA_DIR_SETTING.getValue(), saveAs); incompleteFile = buildIncompleteFile(completeFile); bytesReceived = 0; dateCreated = new Date(); httpClientListener = new HttpDownloadListenerImpl(); httpClient = HttpClientFactory.newInstance(HttpClientType.PureJava); httpClient.setListener(httpClientListener); isResumable = shouldResume; start(shouldResume); } @Override public long getSize() { return size; } @Override public long getSize(boolean update) { return size; } @Override public String getDisplayName() { return title; } @Override public boolean isResumable() { return isResumable && state == STATE_PAUSED && size > 0; } @Override public boolean isPausable() { return isResumable && state == STATE_DOWNLOADING && size > 0; } @Override public boolean isCompleted() { return isComplete(); } @Override public int getState() { if (state == STATE_DOWNLOADING) { return DownloadManager.STATE_DOWNLOADING; } return DownloadManager.STATE_STOPPED; } @Override public void remove() { if (state != STATE_FINISHED) { state = STATE_CANCELING; httpClient.cancel(); } } private void cleanup() { cleanupIncomplete(); cleanupComplete(); } @Override public void pause() { state = STATE_PAUSING; httpClient.cancel(); } @Override public File getSaveLocation() { return saveFile; } @Override public void resume() { start(true); } @Override public int getProgress() { if (state == STATE_CHECKING) { return md5CheckingProgress; } if (size <= 0) { return -1; } int progress = (int) ((bytesReceived * 100) / size); return Math.min(100, progress); } @Override public String getStateString() { return state; } @Override public long getBytesReceived() { return bytesReceived; } @Override public long getBytesSent() { return 0; } @Override public double getDownloadSpeed() { double result = 0; if (state == STATE_DOWNLOADING) { result = averageSpeed / 1000; } return result; } @Override public double getUploadSpeed() { return 0; } @Override public long getETA() { if (size > 0) { long speed = averageSpeed; return speed > 0 ? (size - getBytesReceived()) / speed : -1; } else { return -1; } } @Override public DownloadManager getDownloadManager() { return null; } @Override public String getPeersString() { return ""; } @Override public String getSeedsString() { return ""; } @Override public boolean isDeleteTorrentWhenRemove() { return false; } @Override public boolean isDeleteDataWhenRemove() { return deleteDataWhenCancelled; } @Override public String getHash() { return md5; } @Override public String getSeedToPeerRatio() { return ""; } @Override public String getShareRatio() { return ""; } @Override public boolean isPartialDownload() { return false; } @Override public void updateDownloadManager(DownloadManager downloadManager) { } @Override public Date getDateCreated() { return dateCreated; } private void start(final boolean resume) { state = STATE_WAITING; saveFile = completeFile; HTTP_THREAD_POOL.execute(new Runnable() { @Override public void run() { try { File expectedFile = new File(SharingSettings.TORRENT_DATA_DIR_SETTING.getValue(), saveAs); if (md5 != null && expectedFile.length() == size && checkMD5(expectedFile)) { saveFile = expectedFile; bytesReceived = expectedFile.length(); state = STATE_FINISHED; onComplete(); return; } if (resume) { if (incompleteFile.exists()) { bytesReceived = incompleteFile.length(); } } httpClient.save(url, incompleteFile, resume); } catch (IOException e) { e.printStackTrace(); httpClientListener.onError(httpClient, e); } } }); } private void cleanupFile(File f) { if (f.exists()) { boolean delete = f.delete(); if (!delete) { f.deleteOnExit(); } } } private void cleanupIncomplete() { cleanupFile(incompleteFile); } private void cleanupComplete() { cleanupFile(completeFile); } private boolean checkMD5(File file) { state = STATE_CHECKING; md5CheckingProgress = 0; return file.exists() && DigestUtils.checkMD5(file, md5, new DigestProgressListener() { @Override public void onProgress(int progressPercentage) { md5CheckingProgress = progressPercentage; } @Override public boolean stopDigesting() { return httpClient.isCanceled(); } }); } /** files are saved with (1), (2),... if there's one with the same name already. */ private static File buildFile(File savePath, String name) { String baseName = FilenameUtils.getBaseName(name); String ext = FilenameUtils.getExtension(name); File f = new File(savePath, name); int i = 1; while (f.exists() && i < Integer.MAX_VALUE) { f = new File(savePath, baseName + " (" + i + ")." + ext); i++; } return f; } private static File getIncompleteFolder() { File incompleteFolder = new File(SharingSettings.TORRENT_DATA_DIR_SETTING.getValue().getParentFile(), "Incomplete"); if (!incompleteFolder.exists()) { incompleteFolder.mkdirs(); } return incompleteFolder; } private static File buildIncompleteFile(File file) { String prefix = FilenameUtils.getBaseName(file.getName()); String ext = FilenameUtils.getExtension(file.getAbsolutePath()); return new File(getIncompleteFolder(), prefix + ".incomplete." + ext); } public boolean isComplete() { if (bytesReceived > 0) { return bytesReceived == size || state == STATE_FINISHED; } else { return false; } } private void updateAverageDownloadSpeed() { long now = System.currentTimeMillis(); if (isComplete()) { averageSpeed = 0; speedMarkTimestamp = now; totalReceivedSinceLastSpeedStamp = 0; } else if (now - speedMarkTimestamp > SPEED_AVERAGE_CALCULATION_INTERVAL_MILLISECONDS) { averageSpeed = ((bytesReceived - totalReceivedSinceLastSpeedStamp) * 1000) / (now - speedMarkTimestamp); speedMarkTimestamp = now; totalReceivedSinceLastSpeedStamp = bytesReceived; } } private final class HttpDownloadListenerImpl implements HttpClientListener { @Override public void onError(HttpClient client, Exception e) { if (e instanceof RangeNotSupportedException) { isResumable = false; start(false); } else { state = STATE_ERROR; cleanup(); } } @Override public void onData(HttpClient client, byte[] buffer, int offset, int length) { if (state != STATE_PAUSING && state != STATE_CANCELING) { bytesReceived += length; updateAverageDownloadSpeed(); state = STATE_DOWNLOADING; } } @Override public void onComplete(HttpClient client) { if (md5 != null && !checkMD5(incompleteFile)) { state = STATE_ERROR_MD5; cleanupIncomplete(); return; } boolean renameTo = incompleteFile.renameTo(completeFile); if (!renameTo) { state = STATE_ERROR_MOVING_INCOMPLETE; } else { state = STATE_FINISHED; cleanupIncomplete(); HttpDownload.this.onComplete(); } } @Override public void onCancel(HttpClient client) { if (state == STATE_CANCELING) { if (deleteDataWhenCancelled) { cleanup(); } state = STATE_CANCELED; } else if (state == STATE_PAUSING) { state = STATE_PAUSED; } else { state = STATE_CANCELED; } } @Override public void onHeaders(HttpClient httpClient, Map<String, List<String>> headerFields) { if (headerFields.containsKey("Accept-Ranges")) { isResumable = headerFields.get("Accept-Ranges").contains("bytes"); } else if (headerFields.containsKey("Content-Range")) { isResumable = true; } else { isResumable = false; } //try figuring out file size from HTTP headers depending on the response. if (size < 0) { String responseCodeStr = headerFields.get(null).get(0); if (responseCodeStr.contains(String.valueOf(HttpURLConnection.HTTP_OK))) { if (headerFields.containsKey("Content-Length")) { try { size = Long.valueOf(headerFields.get("Content-Length").get(0)); } catch (Exception e) {} } } } } } /** Meant to be overwritten by children classes that want to do something special * after the download is completed. */ protected void onComplete() { } @Override public void setDeleteTorrentWhenRemove(boolean deleteTorrentWhenRemove) { } @Override public void setDeleteDataWhenRemove(boolean deleteDataWhenRemove) { } }
package com.imaprofessional.niko.projectmaplesyrip; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Random; /** * Created by Niko on 04-Feb-2016. */ public class Room { /* Cardinal directions are represented by ints 0 North 1 East 2 South 3 West */ //Properties Paint paint = new Paint(); Random random = new Random(); protected int[] connections = {-1, -1, -1, -1}; //-1 means no connection //home in the Floor private int x; private int y; //size private int left; private int top; private int right; private int bottom; //CONSTRUCTOR public Room(int row, int col) { this.x = row; this.y = col; } public void onDraw(Canvas c, CanvasView cv) { this.top = 0; this.right = c.getWidth(); this.bottom = c.getHeight(); this.left = cv.leftBound; //draw walls } }
package com.wrathOfLoD.Models.Map.AreaEffect; import com.wrathOfLoD.Models.Commands.ActionCommand; import com.wrathOfLoD.Models.Commands.FlowMovementCommand; import com.wrathOfLoD.Models.Entity.Entity; import com.wrathOfLoD.Utility.Direction; /** * Created by matthewdiaz on 4/16/16. */ public class Flow extends AreaEffect { private Direction flowDirection; private int flowStrength; public Flow(Direction flowDirection, int flowStrength){ super("Flow"); this.flowDirection = flowDirection; this.flowStrength = flowStrength; } public Direction getFlowDirection() { return this.flowDirection; } public int getFlowStrength() { return this.flowStrength; } private void createFlowMovementCommand(Entity entity){ ActionCommand flowMovementCommand = new FlowMovementCommand(entity, flowDirection, flowStrength); System.out.println("CREATE FLOW MOVEMNT"); flowMovementCommand.execute(); } @Override public void interact(Entity entity) { createFlowMovementCommand(entity); System.out.println("FLOW FLOW"); } }
package com.sinodynamic.hkgta.controller.crm.sales.presentation; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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 com.sinodynamic.hkgta.controller.ControllerBase; import com.sinodynamic.hkgta.entity.crm.PresentationBatch; import com.sinodynamic.hkgta.service.crm.TestService; @Controller @RequestMapping("/test") public class TestController extends ControllerBase<PresentationBatch> { @Autowired private TestService testService; @RequestMapping(value = "/caseone", method = RequestMethod.POST) public void test(HttpServletRequest request, HttpServletResponse response){ try { testService.updatePres(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.zhongyp.advanced.pattern.factory.functionfactory; /** * project: demo * author: zhongyp * date: 2018/3/27 * mail: zhongyp001@163.com */ public class DellMouseFactory implements MouseFactory { @Override public Mouse createMouse() { return new DellMouse(); } }