text
stringlengths
10
2.72M
package juez.david.transportbcn.provider.bicing; import java.util.Date; import android.content.Context; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import juez.david.transportbcn.provider.base.AbstractSelection; /** * Selection for the {@code bicing} table. */ public class BicingSelection extends AbstractSelection<BicingSelection> { @Override protected Uri baseUri() { return BicingColumns.CONTENT_URI; } /** * Query the given content resolver using this selection. * * @param contentResolver The content resolver to query. * @param projection A list of which columns to return. Passing null will return all columns, which is inefficient. * @return A {@code BicingCursor} object, which is positioned before the first entry, or null. */ public BicingCursor query(ContentResolver contentResolver, String[] projection) { Cursor cursor = contentResolver.query(uri(), projection, sel(), args(), order()); if (cursor == null) return null; return new BicingCursor(cursor); } /** * Equivalent of calling {@code query(contentResolver, null)}. */ public BicingCursor query(ContentResolver contentResolver) { return query(contentResolver, null); } /** * Query the given content resolver using this selection. * * @param context The context to use for the query. * @param projection A list of which columns to return. Passing null will return all columns, which is inefficient. * @return A {@code BicingCursor} object, which is positioned before the first entry, or null. */ public BicingCursor query(Context context, String[] projection) { Cursor cursor = context.getContentResolver().query(uri(), projection, sel(), args(), order()); if (cursor == null) return null; return new BicingCursor(cursor); } /** * Equivalent of calling {@code query(context, null)}. */ public BicingCursor query(Context context) { return query(context, null); } public BicingSelection id(long... value) { addEquals("bicing." + BicingColumns._ID, toObjectArray(value)); return this; } public BicingSelection idNot(long... value) { addNotEquals("bicing." + BicingColumns._ID, toObjectArray(value)); return this; } public BicingSelection orderById(boolean desc) { orderBy("bicing." + BicingColumns._ID, desc); return this; } public BicingSelection orderById() { return orderById(false); } public BicingSelection idbicing(Integer... value) { addEquals(BicingColumns.IDBICING, value); return this; } public BicingSelection idbicingNot(Integer... value) { addNotEquals(BicingColumns.IDBICING, value); return this; } public BicingSelection idbicingGt(int value) { addGreaterThan(BicingColumns.IDBICING, value); return this; } public BicingSelection idbicingGtEq(int value) { addGreaterThanOrEquals(BicingColumns.IDBICING, value); return this; } public BicingSelection idbicingLt(int value) { addLessThan(BicingColumns.IDBICING, value); return this; } public BicingSelection idbicingLtEq(int value) { addLessThanOrEquals(BicingColumns.IDBICING, value); return this; } public BicingSelection orderByIdbicing(boolean desc) { orderBy(BicingColumns.IDBICING, desc); return this; } public BicingSelection orderByIdbicing() { orderBy(BicingColumns.IDBICING, false); return this; } public BicingSelection name(String... value) { addEquals(BicingColumns.NAME, value); return this; } public BicingSelection nameNot(String... value) { addNotEquals(BicingColumns.NAME, value); return this; } public BicingSelection nameLike(String... value) { addLike(BicingColumns.NAME, value); return this; } public BicingSelection nameContains(String... value) { addContains(BicingColumns.NAME, value); return this; } public BicingSelection nameStartsWith(String... value) { addStartsWith(BicingColumns.NAME, value); return this; } public BicingSelection nameEndsWith(String... value) { addEndsWith(BicingColumns.NAME, value); return this; } public BicingSelection orderByName(boolean desc) { orderBy(BicingColumns.NAME, desc); return this; } public BicingSelection orderByName() { orderBy(BicingColumns.NAME, false); return this; } public BicingSelection lat(Double... value) { addEquals(BicingColumns.LAT, value); return this; } public BicingSelection latNot(Double... value) { addNotEquals(BicingColumns.LAT, value); return this; } public BicingSelection latGt(double value) { addGreaterThan(BicingColumns.LAT, value); return this; } public BicingSelection latGtEq(double value) { addGreaterThanOrEquals(BicingColumns.LAT, value); return this; } public BicingSelection latLt(double value) { addLessThan(BicingColumns.LAT, value); return this; } public BicingSelection latLtEq(double value) { addLessThanOrEquals(BicingColumns.LAT, value); return this; } public BicingSelection orderByLat(boolean desc) { orderBy(BicingColumns.LAT, desc); return this; } public BicingSelection orderByLat() { orderBy(BicingColumns.LAT, false); return this; } public BicingSelection lon(Double... value) { addEquals(BicingColumns.LON, value); return this; } public BicingSelection lonNot(Double... value) { addNotEquals(BicingColumns.LON, value); return this; } public BicingSelection lonGt(double value) { addGreaterThan(BicingColumns.LON, value); return this; } public BicingSelection lonGtEq(double value) { addGreaterThanOrEquals(BicingColumns.LON, value); return this; } public BicingSelection lonLt(double value) { addLessThan(BicingColumns.LON, value); return this; } public BicingSelection lonLtEq(double value) { addLessThanOrEquals(BicingColumns.LON, value); return this; } public BicingSelection orderByLon(boolean desc) { orderBy(BicingColumns.LON, desc); return this; } public BicingSelection orderByLon() { orderBy(BicingColumns.LON, false); return this; } public BicingSelection nearbyStations(String... value) { addEquals(BicingColumns.NEARBY_STATIONS, value); return this; } public BicingSelection nearbyStationsNot(String... value) { addNotEquals(BicingColumns.NEARBY_STATIONS, value); return this; } public BicingSelection nearbyStationsLike(String... value) { addLike(BicingColumns.NEARBY_STATIONS, value); return this; } public BicingSelection nearbyStationsContains(String... value) { addContains(BicingColumns.NEARBY_STATIONS, value); return this; } public BicingSelection nearbyStationsStartsWith(String... value) { addStartsWith(BicingColumns.NEARBY_STATIONS, value); return this; } public BicingSelection nearbyStationsEndsWith(String... value) { addEndsWith(BicingColumns.NEARBY_STATIONS, value); return this; } public BicingSelection orderByNearbyStations(boolean desc) { orderBy(BicingColumns.NEARBY_STATIONS, desc); return this; } public BicingSelection orderByNearbyStations() { orderBy(BicingColumns.NEARBY_STATIONS, false); return this; } public BicingSelection synctime(Date... value) { addEquals(BicingColumns.SYNCTIME, value); return this; } public BicingSelection synctimeNot(Date... value) { addNotEquals(BicingColumns.SYNCTIME, value); return this; } public BicingSelection synctime(Long... value) { addEquals(BicingColumns.SYNCTIME, value); return this; } public BicingSelection synctimeAfter(Date value) { addGreaterThan(BicingColumns.SYNCTIME, value); return this; } public BicingSelection synctimeAfterEq(Date value) { addGreaterThanOrEquals(BicingColumns.SYNCTIME, value); return this; } public BicingSelection synctimeBefore(Date value) { addLessThan(BicingColumns.SYNCTIME, value); return this; } public BicingSelection synctimeBeforeEq(Date value) { addLessThanOrEquals(BicingColumns.SYNCTIME, value); return this; } public BicingSelection orderBySynctime(boolean desc) { orderBy(BicingColumns.SYNCTIME, desc); return this; } public BicingSelection orderBySynctime() { orderBy(BicingColumns.SYNCTIME, false); return this; } }
package com.melhamra.schoolAPI.entities; import lombok.Data; @Data public class TeachersDto { private long id; private String first_name; private String last_name; }
package com.esum.as2.transaction; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.management.MBeanServerConnection; import javax.management.MBeanServerInvocationHandler; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.as2.AS2Exception; import com.esum.framework.core.exception.FrameworkException; import com.esum.framework.core.management.ManagementConstants; import com.esum.framework.core.management.ManagementException; import com.esum.framework.core.management.admin.XtrusAdminFactory; import com.esum.framework.core.management.mbean.queue.QueueControlMBean; import com.esum.framework.core.queue.JmsMessageHandler; import com.esum.framework.core.queue.QueueHandlerFactory; import com.esum.framework.jmx.MBeanQueryCreator; /** * 송수신 타입과 Routing정보를 이용하여 TransactionProcessor를 생성한다. * * Copyrights(c) eSum Technologies., Inc. All rights reserved. */ public class TransactionProcessorFactory { private Logger logger = LoggerFactory.getLogger(TransactionProcessorFactory.class); private static TransactionProcessorFactory factory; private List<TransactionProcessor> inTxProcessors; private Map<String, List<TransactionProcessor>> outTransactionMap; private Object lock = new Object(); public static TransactionProcessorFactory getInstance(){ if(factory==null) factory = new TransactionProcessorFactory(); return factory; } private TransactionProcessorFactory(){ this.inTxProcessors = new ArrayList<TransactionProcessor>(); this.outTransactionMap = new HashMap<String, List<TransactionProcessor>>(); } /** * Inbound를 처리하는 Transaction목록을 리턴한다. */ public List<TransactionProcessor> getInboundTransactionProcessors() { return this.inTxProcessors; } /** * Returns the Outbound transaction processors with a specific adapter Id. */ public Map<String, List<TransactionProcessor>> getOutboundTransactionProcessors() { return outTransactionMap; } /** * 특정 TransferType, RoutingID에 대한 TransactionProcessor들을 가져온다. * OUTBOUND - AS2_OUT_{routingId}_{thread}로 생성되며, 모든 thread에 대한 TransactionProcessor를 가져온다. */ public List<TransactionProcessor> getOutboundTransactionProcessorsWith(String routingId) { Iterator<String> i = outTransactionMap.keySet().iterator(); while(i.hasNext()) { String channelName = i.next(); if(channelName.endsWith(routingId)) return outTransactionMap.get(channelName); } return null; } public TransactionProcessor getInboundTransactionProcessorAt(int index) { return this.inTxProcessors.get(index); } /** * transferType에 대한 TransactionProcessor가 Map정보에 있는지 체크하여 리턴한다. * 없다면 null을 리턴한다. * Transaction처리하는 Processor가 여러개인 경우 첫번째 Processor를 리턴한다. */ public TransactionProcessor getOutboundTransactionProcessorAt(String routingId) { if(outTransactionMap.containsKey("AS2_OUT_"+routingId)) return outTransactionMap.get("AS2_OUT_"+routingId).get(0); throw new RuntimeException("Can not found TransactionProcessor. routingId : "+routingId); } // /** // * transferType을 이용하여 TransactionProcessor를 생성한다. // * 생성된 TransactionProcessor는 Map정보에 기록되며, 재사용가능하다. // */ // public TransactionProcessor getTransactionProcessor(int transferType, String routingId) { // // if(transferType==TransactionEvent.INBOUND_TRANSACTION) { // return inTxProcessors.get(0); // } else { // /** // * FQ가 아닌 직접 TransactionProcessor를 가져갈 때는 항상 0번을 가져간다. // * 또한 Retry, MDNRetry시에도 항상 0번을 가져간다. // */ // return findTransactionProcessor(transferType, routingId); // } // } /** * 새로운 TransactionProcessor를 생성하고 나서 Map정보에 어댑터 정보와 매칭하여 저장한다. */ public boolean createTransactionProcessor(int transferType, String routingId, int maxThreadCnt) throws AS2Exception { /** * 채널 생성시 Inbound는 AS2_IN_CHANNEL, OUTBOUND는 AS2_OUT를 prefix로 붙이도록 한다. */ String channelName = transferType==TransactionEvent.INBOUND_TRANSACTION?"AS2_IN_CHANNEL":"AS2_OUT_"+routingId; try { initChannel(channelName); } catch (AS2Exception e) { throw e; } if(transferType==TransactionEvent.INBOUND_TRANSACTION){ logger.info("["+channelName+"] Creating new inbound transaction. threads : "+maxThreadCnt); for(int i=0;i<maxThreadCnt;i++) { String txId = channelName+"-"+i; JmsMessageHandler queueHandler = null; try { queueHandler = QueueHandlerFactory.getInstance(channelName); } catch (FrameworkException e){ throw new AS2Exception(e.getErrorCode(), e.getErrorLocation(), e.getErrorMessage(), e); } catch (Exception e) { throw new AS2Exception(AS2Exception.ERROR_CONFIG, "createTransactionProcessor()", "'"+channelName+"' Channel create failed.", e); } InboundTransactionProcessor inTx = new InboundTransactionProcessor("["+txId+"] ", channelName, queueHandler); this.inTxProcessors.add(inTx); logger.info("["+channelName+"] New Inbound Transaction Processor created. channel : "+channelName); } } else { List<TransactionProcessor> outList = outTransactionMap.get(channelName); if(outList==null) { outList = new ArrayList<TransactionProcessor>(); outTransactionMap.put(channelName, outList); } /** maxThreadCount 만큼 MessageListener를 생성한다. */ logger.info("["+channelName+"] Creating new outbound transaction. threads : "+maxThreadCnt); for(int i=0;i<maxThreadCnt;i++) { String txId = channelName+"-"+i; JmsMessageHandler queueHandler = null; try { queueHandler = QueueHandlerFactory.getInstance(channelName); } catch (FrameworkException e){ throw new AS2Exception(e.getErrorCode(), e.getErrorLocation(), e.getErrorMessage(), e); } catch (Exception e) { throw new AS2Exception(AS2Exception.ERROR_CONFIG, "createTransactionProcessor()", "'"+channelName+"' Channel create failed.", e); } TransactionProcessor tp = new OutboundTransactionProcessor("["+txId+"] ", channelName, queueHandler); outList.add(tp); logger.info("["+channelName+"] New Outbound Transaction Processor created. channel : "+channelName); } } return true; } private boolean initChannel(final String channelName) throws AS2Exception { if(logger.isDebugEnabled()) logger.debug("Initialize '"+channelName+"' channel."); try { return XtrusAdminFactory.currentAdmin().query(new MBeanQueryCreator<Boolean>() { @Override public Boolean executeQuery(MBeanServerConnection connection) throws ManagementException, MalformedObjectNameException { ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL); QueueControlMBean queueControlMBean = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, QueueControlMBean.class, true); queueControlMBean.createQueue(channelName, true); return true; } }); } catch (ManagementException e) { throw new AS2Exception(AS2Exception.ERROR_CONFIG, "initChannel()", "'"+channelName+"' Channel create failed.", e); } } public void closeAll(){ if(this.inTxProcessors!=null) { for(TransactionProcessor inTx : inTxProcessors) inTx.close(); } this.inTxProcessors = null; if(outTransactionMap==null || outTransactionMap.size()==0) return; synchronized(lock) { Iterator<String> i = outTransactionMap.keySet().iterator(); while(i.hasNext()){ String channelName = i.next(); List<TransactionProcessor> txList = outTransactionMap.get(channelName); if(txList!=null) { for(TransactionProcessor p : txList) p.close(); } } outTransactionMap.clear(); } logger.info("All transactionHandler closed."); } /** * 동작중인 {@link TransactionProcessor}를 찾아서 삭제한다. */ public int removeTransactionProcessors(int transferType, String routingId) { if(transferType==TransactionEvent.INBOUND_TRANSACTION) { synchronized(lock) { for(TransactionProcessor tx : this.inTxProcessors) tx.close(); this.inTxProcessors.clear(); logger.info("AS2 Inbound Transaction removed."); } } else { synchronized(lock) { /** outbound tx */ List<TransactionProcessor> outList = removeOutboundTransactionMap(routingId); if(outList!=null && outList.size()!=0) { for(TransactionProcessor p : outList) { p.close(); } return outList.size(); } } } return 0; } /** * 특정 transactionId에 대한 TransactionProcessor를 삭제한다. */ private List<TransactionProcessor> removeOutboundTransactionMap(String routingId) { if(this.outTransactionMap.containsKey("AS2_OUT_"+routingId)) { synchronized(lock) { return this.outTransactionMap.remove("AS2_OUT_"+routingId); } } return null; } /** * 특정 TransferType과, RoutingID에 대한 TransactionProcessor를 Restart한다. */ public boolean restartTransactionProcessors(int transferType, String routingId) throws AS2Exception { synchronized(lock) { if(logger.isDebugEnabled()) logger.debug("{} Transaction processor restarting.", routingId); int threadCnt = removeTransactionProcessors(transferType, routingId); logger.info("{} Transaction processors removed.", threadCnt); if(logger.isDebugEnabled()) logger.debug("Creating Transaction processor for {} routing.", routingId); boolean created = createTransactionProcessor(transferType, routingId, threadCnt); if(created) logger.info("{} Transaction created for {} routing.", routingId, threadCnt); return created; } } public void reloadTransactionProcessors(int transferType, String routingId, int maxThreadCnt) throws AS2Exception { synchronized(lock) { if(logger.isDebugEnabled()) logger.debug("{} Transaction processor reloading.", routingId); int threadCnt = removeTransactionProcessors(transferType, routingId); logger.info("{} Transaction processors removed.", threadCnt); if(logger.isDebugEnabled()) logger.debug("Creating Transaction processor for "+routingId+" routing. maxThread : "+maxThreadCnt); boolean created = createTransactionProcessor(transferType, routingId, maxThreadCnt); if(created) logger.info("{} Transaction created for {} routing.", routingId); } } }
package com.ytdsuda.management.dto; import lombok.Data; @Data public class UserDTO { private Integer userId; private String userName; private String userRole; private String nickName; private String token; public UserDTO() { } }
package org.garret.perst.reflect; /** * Replacement of java.lang.reflect.Field. * This class should be created by programmer. To provide access the field, * programmer should derive its own subclass and override field set/get methods: * new Field(String.class, "someField") { public Object get(Object obj) { return ((MyClass)obj).someField; } } */ public class Field extends Member { String name; Class type; /** * Constructor of field descriptor * @param type field type. As far as J2ME provides no classes for builtin types, use correspndent wrapper classes, * i.e. instead of int.class, specify Integer.class * @param name field name */ public Field(Class type, String name) { this(type, name, 0); } /** * Constructor of field descriptor * @param type field type. As far as J2ME provides no classes for builtin types, use correspndent wrapper classes, * i.e. instead of int.class, specify Integer.class * @param name field name * @param modifiers bitmask of method modifiers. There are not predefined modifiers, such as PUBLIC - * iterpretation of modifiers bits is application dependent */ public Field(Class type, String name, int modifiers) { super(modifiers); this.type = type; this.name = name; } /** * Get name of the field * @return field name */ public String getName() { return name; } /** * Get type of the field * @return field type */ public Class getType() { return type; } /** * Get value of the field. This method is expected to be overridden in derived class by programmer. * @param obj target objects * @return field value */ public Object get(Object obj) { throw new RuntimeException("Getter not defined"); } /** * Get boolean value of the field. This method may be overridden in derived class by programmer for boolean field. * If this method is not overridden,then default implementation tries to extract boolean value from object returned by get method. * @param obj target objects * @return boolean field value */ public boolean getBoolean(Object obj) { return ((Boolean)get(obj)).booleanValue(); } /** * Get byte value of the field. This method may be overridden in derived class by programmer for byte field. * If this method is not overridden,then default implementation tries to extract byte value from object returned by get method. * @param obj target objects * @return byte field value */ public byte getByte(Object obj) { return ((Byte)get(obj)).byteValue(); } /** * Get char value of the field. This method may be overridden in derived class by programmer for char field. * If this method is not overridden,then default implementation tries to extract char value from object returned by get method. * @param obj target objects * @return char field value */ public char getChar(Object obj) { return ((Character)get(obj)).charValue(); } /** * Get short value of the field. This method may be overridden in derived class by programmer for short field. * If this method is not overridden,then default implementation tries to extract short value from object returned by get method. * @param obj target objects * @return short field value */ public short getShort(Object obj) { return ((Short)get(obj)).shortValue(); } /** * Get int value of the field. This method may be overridden in derived class by programmer for int field. * If this method is not overridden,then default implementation tries to extract int value from object returned by get method. * @param obj target objects * @return int field value */ public int getInt(Object obj) { if (obj instanceof Integer) { return ((Integer)get(obj)).intValue(); } else if (obj instanceof Short) { return ((Short)get(obj)).shortValue(); } else if (obj instanceof Character) { return ((Character)get(obj)).charValue(); } else { return ((Byte)get(obj)).byteValue(); } } /** * Get long value of the field. This method may be overridden in derived class by programmer for long field. * If this method is not overridden,then default implementation tries to extract long value from object returned by get method. * @param obj target objects * @return long field value */ public long getLong(Object obj) { if (obj instanceof Long) { return ((Long)get(obj)).longValue(); } else if (obj instanceof Short) { return ((Short)get(obj)).shortValue(); } else if (obj instanceof Byte) { return ((Byte)get(obj)).byteValue(); } else if (obj instanceof Character) { return ((Character)get(obj)).charValue(); } else { return ((Integer)get(obj)).intValue(); } } /** * Get float value of the field. This method may be overridden in derived class by programmer for float field. * If this method is not overridden,then default implementation tries to extract float value from object returned by get method. * @param obj target objects * @return float field value */ public float getFloat(Object obj) { return ((Float)get(obj)).floatValue(); } /** * Get double value of the field. This method may be overridden in derived class by programmer for double field. * If this method is not overridden,then default implementation tries to extract double value from object returned by get method. * @param obj target objects * @return double field value */ public double getDouble(Object obj) { return obj instanceof Double ? ((Double)get(obj)).doubleValue() : ((Float)get(obj)).floatValue(); } /** * Set value of the field. This method is expected to be overridden in derived class by programmer. * @param obj target objects * @param value field value */ public void set(Object obj, Object value) { throw new RuntimeException("Setter not defined"); } /** * Set boolean value of the field. This method may be overridden in derived class by programmer for boolean field. * If this method is not overridden, then default implementation tries to create wrapper object and assign it to the field using set method. * @param obj target objects * @param value field value */ public void setBoolean(Object obj, boolean value) { set(obj, new Boolean(value)); } /** * Set byte value of the field. This method may be overridden in derived class by programmer for byte field. * If this method is not overridden, then default implementation tries to create wrapper object and assign it to the field using set method. * @param obj target objects * @param value field value */ public void setByte(Object obj, byte value) { set(obj, new Byte(value)); } /** * Set char value of the field. This method may be overridden in derived class by programmer for char field. * If this method is not overridden, then default implementation tries to create wrapper object and assign it to the field using set method. * @param obj target objects * @param value field value */ public void setChar(Object obj, char value) { set(obj, new Character(value)); } /** * Set short value of the field. This method may be overridden in derived class by programmer for short field. * If this method is not overridden, then default implementation tries to create wrapper object and assign it to the field using set method. * @param obj target objects * @param value field value */ public void setShort(Object obj, short value) { set(obj, new Short(value)); } /** * Set int value of the field. This method may be overridden in derived class by programmer for int field. * If this method is not overridden, then default implementation tries to create wrapper object and assign it to the field using set method. * @param obj target objects * @param value field value */ public void setInt(Object obj, int value) { set(obj, new Integer(value)); } /** * Set long value of the field. This method may be overridden in derived class by programmer for long field. * If this method is not overridden, then default implementation tries to create wrapper object and assign it to the field using set method. * @param obj target objects * @param value field value */ public void setLong(Object obj, long value) { set(obj, new Long(value)); } /** * Set float value of the field. This method may be overridden in derived class by programmer for float field. * If this method is not overridden, then default implementation tries to create wrapper object and assign it to the field using set method. * @param obj target objects * @param value field value */ public void setFloat(Object obj, float value) { set(obj, new Float(value)); } /** * Set double value of the field. This method may be overridden in derived class by programmer for double field. * If this method is not overridden, then default implementation tries to create wrapper object and assign it to the field using set method. * @param obj target objects * @param value field value */ public void setDouble(Object obj, double value) { set(obj, new Double(value)); } }
package com.example.teamproject; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.GridLayout; import android.widget.LinearLayout; import android.widget.Toast; import android.widget.ToggleButton; import com.google.android.gms.common.SignInButton; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.lang.reflect.Array; import java.util.ArrayList; public class Play_beat_setting extends AppCompatActivity { DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference conditionRef = mRootRef.child("text"); String saveColor; int saveIndex; int[] saveIndex_array = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; String[] saveColor_array = {"0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"}; int save_beat_index; int[] saveGreenIndex_array = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; int[] saveGreenSound_array = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; String[] saveGreenSoundPath= {"no","no","no","no","no","no","no","no","no","no","no","no","no","no","no","no"}; float[] volume_array = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; int[] sync_sound_path={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; ArrayList<ToggleButton> savebtns; ArrayList<Button> beat_button; ArrayList<Button> soundbulebtns; ArrayList<ToggleButton> soundyellowbtns; ArrayList<ToggleButton> soundorangebtns; ArrayList<ToggleButton> soundindigobtns; ArrayList<ToggleButton> soundgreenbtns; String[] from_beat_saveColor_array = {"0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"}; int[] from_beat_saveIndex_array = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; int[] from_beat_saveGreenIndex_array = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; String[] from_beat_saveGreenSoundPath = {"no","no","no","no","no","no","no","no","no","no","no","no","no","no","no","no"}; int[] from_beat_btn_sound = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; int[] btn_sound = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; LinearLayout sound_select_layout, insert_btn_layout; LinearLayout green_layout,original_layout; Button go_record, go_load; Button back,insert; Button complete; Button beat_1row_1button,beat_1row_2button,beat_1row_3button,beat_1row_4button; Button beat_2row_1button,beat_2row_2button,beat_2row_3button,beat_2row_4button; Button beat_3row_1button,beat_3row_2button,beat_3row_3button,beat_3row_4button; Button beat_4row_1button,beat_4row_2button,beat_4row_3button,beat_4row_4button; int green_btn1,green_btn2,green_btn3,green_btn4,green_btn5,green_btn6,green_btn7,green_btn8, green_btn9,green_btn10,green_btn11,green_btn12,green_btn13,green_btn14,green_btn15,green_btn16; int[] green_btns = {green_btn1,green_btn2,green_btn3,green_btn4,green_btn5,green_btn6,green_btn7,green_btn8, green_btn9,green_btn10,green_btn11,green_btn12,green_btn13,green_btn14,green_btn15,green_btn16}; ToggleButton green_button1,green_button2,green_button3,green_button4,green_button5,green_button6,green_button7,green_button8, green_button9,green_button10,green_button11,green_button12,green_button13,green_button14,green_button15,green_button16; public String getSaveColor(){ return this.saveColor; } public Button get_beat(String color, int index){ Button btn =null; if(color.equals("blue")){ btn = this.soundbulebtns.get(index); } return btn; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play_beat_setting); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); Button btn_insert = (Button)findViewById(R.id.btn_insert); complete = findViewById(R.id.btn_complete); beat_1row_1button = findViewById(R.id.beat_1row_1button); beat_1row_2button = findViewById(R.id.beat_1row_2button); beat_1row_3button = findViewById(R.id.beat_1row_3button); beat_1row_4button = findViewById(R.id.beat_1row_4button); beat_2row_1button = findViewById(R.id.beat_2row_1button); beat_2row_2button = findViewById(R.id.beat_2row_2button); beat_2row_3button = findViewById(R.id.beat_2row_3button); beat_2row_4button = findViewById(R.id.beat_2row_4button); beat_3row_1button = findViewById(R.id.beat_3row_1button); beat_3row_2button = findViewById(R.id.beat_3row_2button); beat_3row_3button = findViewById(R.id.beat_3row_3button); beat_3row_4button = findViewById(R.id.beat_3row_4button); beat_4row_1button = findViewById(R.id.beat_4row_1button); beat_4row_2button = findViewById(R.id.beat_4row_2button); beat_4row_3button = findViewById(R.id.beat_4row_3button); beat_4row_4button = findViewById(R.id.beat_4row_4button); Intent get__intent =getIntent(); if(get__intent.getStringArrayExtra("saveColorArray_from_beat") != null) { saveColor_array = get__intent.getStringArrayExtra("saveColorArray_from_beat"); saveIndex_array = get__intent.getIntArrayExtra("not_green_arrays_from_beat"); saveGreenIndex_array = get__intent.getIntArrayExtra("GreenIndex_array_from_beat"); saveGreenSoundPath = get__intent.getStringArrayExtra("GreenSoundPath_from_beat"); btn_sound = get__intent.getIntArrayExtra("btn_sounds_from_beat"); } final Button[] beat_btn = {beat_1row_1button, beat_1row_2button, beat_1row_3button, beat_1row_4button, beat_2row_1button, beat_2row_2button, beat_2row_3button, beat_2row_4button, beat_3row_1button, beat_3row_2button, beat_3row_3button, beat_3row_4button, beat_4row_1button, beat_4row_2button, beat_4row_3button, beat_4row_4button}; back = findViewById(R.id.play_beat_back); insert = findViewById(R.id.play_beat_setting_save_button); sound_select_layout = findViewById(R.id.sound_select_layout); insert_btn_layout = findViewById(R.id.insert_btn_layout); btn_insert.setOnClickListener(new View.OnClickListener() { //파란색,노란색,오렌지 누르고나서 버튼에 넣기 버튼 눌렀을때 @Override public void onClick(View view) { if(saveColor == null) { Context c = view.getContext(); Toast.makeText(c, "비트을 선택하세요", Toast.LENGTH_LONG).show(); } else if(saveColor != null){ for(int i = 0; i<16; i++) { if (saveIndex_array[i] == 0) { if (saveColor.equals("blue") || saveColor_array[i].equals("blue")) { beat_btn[i].setBackgroundResource(R.drawable.no_select_style_blue); } else if (saveColor.equals("yellow") || saveColor_array[i].equals("yellow")) { beat_btn[i].setBackgroundResource(R.drawable.no_select_style_yellow); } else if (saveColor.equals("orange") || saveColor_array[i].equals("orange")) { beat_btn[i].setBackgroundResource(R.drawable.no_select_style_orange); } else if (saveColor.equals("indigo") || saveColor_array[i].equals("indigo")) { beat_btn[i].setBackgroundResource(R.drawable.no_select_style_indigo); } else if (saveColor.equals("green") || saveColor_array[i].equals("green")) { beat_btn[i].setBackgroundResource(R.drawable.no_select_style_green); } } } sound_select_layout.setVisibility(View.INVISIBLE); insert_btn_layout.setVisibility(View.VISIBLE); } } }); insert.setOnClickListener(new View.OnClickListener() { //버튼에 넣고 넣기버튼 눌렀을때 @Override public void onClick(View v) { insert_btn_layout.setVisibility(View.INVISIBLE); sound_select_layout.setVisibility(View.VISIBLE); saveColor_array[save_beat_index] = saveColor; saveColor = null; saveIndex = 0; for(int i = 0; i<16; i++) { if(saveIndex_array[i] == 1){ saveIndex_array[i] = -1; } soundbulebtns.get(i).setBackgroundResource(R.drawable.button_1row_style); soundyellowbtns.get(i).setBackgroundResource(R.drawable.button_2row_style); soundorangebtns.get(i).setBackgroundResource(R.drawable.button_3row_style); soundindigobtns.get(i).setBackgroundResource(R.drawable.button_4row_style); } } }); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { insert_btn_layout.setVisibility(View.INVISIBLE); sound_select_layout.setVisibility(View.VISIBLE); } }); complete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), Play_beat.class); Intent getIntent = getIntent(); intent.putExtra("saveColorArray",saveColor_array); intent.putExtra("not_green_arrays",saveIndex_array); intent.putExtra("GreenIndex_array",saveGreenIndex_array); intent.putExtra("GreenSoundPath",saveGreenSoundPath); intent.putExtra("btn_sounds",btn_sound); intent.putExtra("select_index",saveIndex); intent.putExtra("sync_array",sync_sound_path); intent.putExtra("saveGreenSoundPath",saveGreenSoundPath); intent.putExtra("sync23",sync_sound_path); intent.putExtra("sound1234",btn_sound); intent.putExtra("go_from_setting",500); startActivity(intent); } }); go_record = findViewById(R.id.go_record_btn); go_load = findViewById(R.id.go_load_btn); go_record.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), Play_beat_setting_record.class); intent.putExtra("getted_index",saveIndex); //지금 누른 인덱스 intent.putExtra("saveColorArray",saveColor_array); intent.putExtra("not_green_arrays",saveIndex_array); intent.putExtra("save_sound_array",saveGreenSound_array); //소리가 담긴 배열 intent.putExtra("saved_index", saveGreenIndex_array); //누른곳의 인덱스에 100부터 넣어져있는 배열 intent.putExtra("saved_path", saveGreenSoundPath); //path가 담긴 배열 intent.putExtra("sync",sync_sound_path); //path랑 소리인덱스 startActivity(intent); } }); go_load.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), Play_beat_setting_load.class); intent.putExtra("saveColorArray",saveColor_array); intent.putExtra("not_green_arrays",saveIndex_array); intent.putExtra("GreenIndex_array",saveGreenIndex_array); intent.putExtra("GreenSoundPath",saveGreenSoundPath); intent.putExtra("btn_sounds",btn_sound); intent.putExtra("select_index",saveIndex); intent.putExtra("sync_array",sync_sound_path); Log.d("고로드",saveGreenIndex_array+" "+saveGreenSound_array+" "+String.valueOf(btn_sound)); startActivity(intent); } }); Play_beat_setting_SoundPlayer soundPlayer = new Play_beat_setting_SoundPlayer(getApplicationContext()); savebtns = new ArrayList<ToggleButton>(); beat_button = new ArrayList<Button>(); addbeatbtn(); soundbulebtns = new ArrayList<Button>(); addsoundblue(); soundyellowbtns = new ArrayList<ToggleButton>(); addsoundyellow(); soundorangebtns = new ArrayList<ToggleButton>(); addsoundorange(); soundindigobtns = new ArrayList<ToggleButton>(); addsoundindigo(); soundgreenbtns = new ArrayList<ToggleButton>(); addsoundgreen(); green_layout = findViewById(R.id.green_layout); original_layout = findViewById(R.id.original_layout); final ArrayList<String> items = new ArrayList<String>(); final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_single_choice,items); final GridLayout beatmaker_one = (GridLayout)findViewById(R.id.beatmaker_one); Button beatmaker_btn1 = (Button) findViewById(R.id.beatmaker_btn1); Button beatmaker_btn2 = (Button) findViewById(R.id.beatmaker_btn2); Button beatmaker_btn3 = (Button) findViewById(R.id.beatmaker_btn3); Button beatmaker_btn4 = (Button) findViewById(R.id.beatmaker_btn4); Button beatmaker_btn5 = (Button) findViewById(R.id.beatmaker_btn5); beatmaker_btn1.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { changeView(0); } }); beatmaker_btn2.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { changeView(1); } }); beatmaker_btn3.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v){ changeView(2); } }); beatmaker_btn4.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v){ changeView(3); } }); beatmaker_btn5.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v){ changeView(4); } }); beatmaker_btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changeView(0); green_layout.setVisibility(View.INVISIBLE); original_layout.setVisibility(View.VISIBLE); } }); beatmaker_btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changeView(1); green_layout.setVisibility(View.INVISIBLE); original_layout.setVisibility(View.VISIBLE); } }); beatmaker_btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changeView(2); green_layout.setVisibility(View.INVISIBLE); original_layout.setVisibility(View.VISIBLE); } }); beatmaker_btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changeView(3); green_layout.setVisibility(View.INVISIBLE); original_layout.setVisibility(View.VISIBLE); } }); beatmaker_btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changeView(4); original_layout.setVisibility(View.INVISIBLE); green_layout.setVisibility(View.VISIBLE); } }); // } public void addbeatbtn(){ beat_button.add((Button) findViewById(R.id.beat_1row_1button)); beat_button.add((Button) findViewById(R.id.beat_1row_2button)); beat_button.add((Button) findViewById(R.id.beat_1row_3button)); beat_button.add((Button) findViewById(R.id.beat_1row_4button)); beat_button.add((Button) findViewById(R.id.beat_2row_1button)); beat_button.add((Button) findViewById(R.id.beat_2row_2button)); beat_button.add((Button) findViewById(R.id.beat_2row_3button)); beat_button.add((Button) findViewById(R.id.beat_2row_4button)); beat_button.add((Button) findViewById(R.id.beat_3row_1button)); beat_button.add((Button) findViewById(R.id.beat_3row_2button)); beat_button.add((Button) findViewById(R.id.beat_3row_3button)); beat_button.add((Button) findViewById(R.id.beat_3row_4button)); beat_button.add((Button) findViewById(R.id.beat_4row_1button)); beat_button.add((Button) findViewById(R.id.beat_4row_2button)); beat_button.add((Button) findViewById(R.id.beat_4row_3button)); beat_button.add((Button) findViewById(R.id.beat_4row_4button)); for(final Button select_btn : beat_button){ //버튼 셋팅하는 그 버튼들 클릭시 select_btn.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { save_beat_index = Integer.parseInt(String.valueOf(v.getTag())) - 1; for (int i = 0; i < 16; i++) { if (saveIndex_array[i] >= 0) { saveIndex_array[i] = 0; } } if (saveIndex_array[(Integer.parseInt(String.valueOf(v.getTag())) - 1)] == -1) { //원래 설정해놓은 버튼을 클릭시 } else if (saveIndex_array[(Integer.parseInt(String.valueOf(v.getTag())) - 1)] == 0) { saveIndex_array[(Integer.parseInt(String.valueOf(v.getTag())) - 1)] = 1; for (int i = 0; i < 16; i++) { if (saveIndex_array[i] != -1 && saveIndex_array[i] != 1) { saveIndex_array[i] = 0; } } for (int i = 0; i < 16; i++) { if (saveIndex_array[i] == 0) { if (saveColor.equals("blue")) { beat_button.get(i).setBackgroundResource(R.drawable.no_select_style_blue); } else if (saveColor.equals("yellow")) { beat_button.get(i).setBackgroundResource(R.drawable.no_select_style_yellow); } else if (saveColor.equals("orange")) { beat_button.get(i).setBackgroundResource(R.drawable.no_select_style_orange); } else if (saveColor.equals("indigo")) { beat_button.get(i).setBackgroundResource(R.drawable.no_select_style_indigo); } else if (saveColor.equals("green")) { beat_button.get(i).setBackgroundResource(R.drawable.no_select_style_green); } } } if (saveColor.equals("blue")) { beat_button.get(Integer.parseInt(String.valueOf(v.getTag())) - 1).setBackgroundResource(R.drawable.button_1row_style); } else if (saveColor.equals("yellow")) { beat_button.get(Integer.parseInt(String.valueOf(v.getTag())) - 1).setBackgroundResource(R.drawable.button_2row_style); } else if (saveColor.equals("orange")) { beat_button.get(Integer.parseInt(String.valueOf(v.getTag())) - 1).setBackgroundResource(R.drawable.button_3row_style); } else if (saveColor.equals("indigo")) { beat_button.get(Integer.parseInt(String.valueOf(v.getTag())) - 1).setBackgroundResource(R.drawable.button_4row_style); } else if (saveColor.equals("green")) { beat_button.get(Integer.parseInt(String.valueOf(v.getTag())) - 1).setBackgroundResource(R.drawable.button_5row_style); } if (saveColor.equals("green")) { btn_sound[Integer.parseInt(String.valueOf(v.getTag())) - 1] = Play_beat_setting_SoundPlayer.loadSound(saveColor, saveIndex + 65); for(int i = 0; i<16; i++){ if (saveIndex_array[i] == 0) { btn_sound[i] = 0; } } } else { if (saveIndex_array[Integer.parseInt(String.valueOf(v.getTag())) - 1] == 1) { btn_sound[Integer.parseInt(String.valueOf(v.getTag())) - 1] = Play_beat_setting_SoundPlayer.loadSound(saveColor, saveIndex); for(int i = 0; i<16; i++){ if (saveIndex_array[i] == 0) { btn_sound[i] = 0; } } Toast.makeText(getApplicationContext(), String.valueOf(btn_sound[Integer.parseInt(String.valueOf(v.getTag())) - 1]), Toast.LENGTH_LONG).show(); } } } } return false; } }); } } public void addsoundblue(){ soundbulebtns.add((Button) findViewById(R.id.blue_btn1)); soundbulebtns.add((Button) findViewById(R.id.blue_btn2)); soundbulebtns.add((Button) findViewById(R.id.blue_btn3)); soundbulebtns.add((Button) findViewById(R.id.blue_btn4)); soundbulebtns.add((Button) findViewById(R.id.blue_btn5)); soundbulebtns.add((Button) findViewById(R.id.blue_btn6)); soundbulebtns.add((Button) findViewById(R.id.blue_btn7)); soundbulebtns.add((Button) findViewById(R.id.blue_btn8)); soundbulebtns.add((Button) findViewById(R.id.blue_btn9)); soundbulebtns.add((Button) findViewById(R.id.blue_btn10)); soundbulebtns.add((Button) findViewById(R.id.blue_btn11)); soundbulebtns.add((Button) findViewById(R.id.blue_btn12)); soundbulebtns.add((Button) findViewById(R.id.blue_btn13)); soundbulebtns.add((Button) findViewById(R.id.blue_btn14)); soundbulebtns.add((Button) findViewById(R.id.blue_btn15)); soundbulebtns.add((Button) findViewById(R.id.blue_btn16)); for (final Button soundPad : soundbulebtns){ soundPad.setOnTouchListener(new View.OnTouchListener() { // EditText edittext = (EditText)findViewById(R.id.edittext); @Override public boolean onTouch(View view, MotionEvent motionEvent) { Button btn_insert = (Button)findViewById(R.id.btn_insert); if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { Play_beat_setting_SoundPlayer.playBlueSound(Integer.parseInt(String.valueOf(view.getTag()))); saveColor = "blue"; saveIndex = Integer.parseInt(String.valueOf(view.getTag())); } if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS) { return true; } if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_RELEASE) { return true; } else { for(int i = 0; i<16; i++){ soundyellowbtns.get(i).setBackgroundResource(R.drawable.button_2row_style); soundorangebtns.get(i).setBackgroundResource(R.drawable.button_3row_style); soundindigobtns.get(i).setBackgroundResource(R.drawable.button_4row_style); } for( int i = 0; i<(Integer.parseInt(String.valueOf(view.getTag()))); i++) { soundbulebtns.get(i).setBackgroundResource(R.drawable.button_1row_style); } for(int i= (Integer.parseInt(String.valueOf(view.getTag()))); i<16; i++ ){ soundbulebtns.get(i).setBackgroundResource(R.drawable.button_1row_style); } soundPad.setBackgroundResource(R.drawable.selected_1row_style); } return false; } }); } } public void addsoundyellow() { View beatmaker_yellow = (View) findViewById(R.id.main_beatmaker_yellow); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn1)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn2)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn3)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn4)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn5)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn6)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn7)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn8)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn9)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn10)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn11)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn12)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn13)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn14)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn15)); soundyellowbtns.add((ToggleButton) beatmaker_yellow.findViewById(R.id.yellow_btn16)); for (int i = 0; i < 16; i++) { soundyellowbtns.get(i).setChecked(true); } for (final ToggleButton soundPad : soundyellowbtns) { soundPad.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (soundPad.isChecked()) { soundPad.setBackgroundColor(Color.BLACK); if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { Play_beat_setting_SoundPlayer.playYellowSound(Integer.parseInt(String.valueOf(view.getTag()))); soundPad.setChecked(false); } if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS) { return true; } if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_RELEASE) { return true; } } else { for(int i = 0; i<16; i++){ soundbulebtns.get(i).setBackgroundResource(R.drawable.button_1row_style); soundorangebtns.get(i).setBackgroundResource(R.drawable.button_3row_style); soundindigobtns.get(i).setBackgroundResource(R.drawable.button_4row_style); } for (int i = 16; i < (Integer.parseInt(String.valueOf(view.getTag()))); i++) { soundyellowbtns.get(i-16).setBackgroundResource(R.drawable.button_2row_style); saveColor = "yellow"; saveIndex = Integer.parseInt(String.valueOf(view.getTag())); } for (int i = (Integer.parseInt(String.valueOf(view.getTag()))); i < 32; i++) { soundyellowbtns.get(i-16).setBackgroundResource(R.drawable.button_2row_style); } soundPad.setBackgroundResource(R.drawable.selected_2row_style); } return false; } }); } } public void addsoundorange(){ View beatmaker_orange = (View)findViewById(R.id.main_beatmaker_orange); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn1)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn2)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn3)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn4)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn5)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn6)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn7)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn8)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn9)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn10)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn11)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn12)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn13)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn14)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn15)); soundorangebtns.add((ToggleButton) beatmaker_orange.findViewById(R.id.orange_btn16)); for (int i = 0; i < 16; i++) { soundorangebtns.get(i).setChecked(true); } for (final ToggleButton soundPad : soundorangebtns){ soundPad.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (soundPad.isChecked()) { soundPad.setBackgroundColor(Color.BLACK); if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { Play_beat_setting_SoundPlayer.playOrangeSound(Integer.parseInt(String.valueOf(view.getTag()))); saveColor = "orange"; saveIndex = Integer.parseInt(String.valueOf(view.getTag())); soundPad.setChecked(false); } if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS) { return true; } if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_RELEASE) { return true; } } else{ for(int i = 0; i<16; i++){ soundbulebtns.get(i).setBackgroundResource(R.drawable.button_1row_style); soundyellowbtns.get(i).setBackgroundResource(R.drawable.button_2row_style); soundindigobtns.get(i).setBackgroundResource(R.drawable.button_4row_style); } for (int i = 32; i < (Integer.parseInt(String.valueOf(view.getTag()))); i++) { soundorangebtns.get(i-32).setBackgroundResource(R.drawable.button_3row_style); } for (int i = (Integer.parseInt(String.valueOf(view.getTag()))); i < 48; i++) { soundorangebtns.get(i-32).setBackgroundResource(R.drawable.button_3row_style); } soundPad.setBackgroundResource(R.drawable.selected_3row_style); } return false; } }); } } public void addsoundindigo(){ View beatmaker_indigo = (View)findViewById(R.id.main_beatmaker_indogo); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn1)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn2)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn3)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn4)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn5)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn6)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn7)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn8)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn9)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn10)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn11)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn12)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn13)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn14)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn15)); soundindigobtns.add((ToggleButton) beatmaker_indigo.findViewById(R.id.indigo_btn16)); for (int i = 0; i < 16; i++) { soundindigobtns.get(i).setChecked(true); } for (final ToggleButton soundPad : soundindigobtns){ soundPad.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (soundPad.isChecked()) { soundPad.setBackgroundColor(Color.BLACK); if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { Play_beat_setting_SoundPlayer.playIndigoSound(Integer.parseInt(String.valueOf(view.getTag()))); saveColor = "indigo"; saveIndex = Integer.parseInt(String.valueOf(view.getTag())); Log.d("??ㅇㅇㅇㅇㅇㅇ?", "잘됬냐? "+ saveColor+String.valueOf(saveIndex)); soundPad.setChecked(false); } if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS) { return true; } if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_RELEASE) { return true; } } else{ for(int i = 0; i<16; i++){ soundbulebtns.get(i).setBackgroundResource(R.drawable.button_1row_style); soundyellowbtns.get(i).setBackgroundResource(R.drawable.button_2row_style); soundorangebtns.get(i).setBackgroundResource(R.drawable.button_3row_style); } for (int i = 48; i < (Integer.parseInt(String.valueOf(view.getTag()))); i++) { soundindigobtns.get(i-48).setBackgroundResource(R.drawable.button_4row_style); } for (int i = (Integer.parseInt(String.valueOf(view.getTag()))); i < 64; i++) { soundindigobtns.get(i-48).setBackgroundResource(R.drawable.button_4row_style); } soundPad.setBackgroundResource(R.drawable.selected_4row_style); } return false; } }); } } public void setSaveGreenIndex_array(int index, int minus){ this.saveGreenIndex_array[index] = minus; } public void setSaveGreenIndex_array(int[] array){ this.saveGreenIndex_array = array; } public int[] getSaveGreenIndex_array(){ return this.saveGreenIndex_array; } public void setSaveGreenSoundPath(String[] array){ this.saveGreenSoundPath = array; } public String[] getSaveGreenSoundPath(){ return this.saveGreenSoundPath; } public void addsoundgreen(){ View beatmaker_green = (View)findViewById(R.id.main_beatmaker_green); final SoundPool sp; sp = new SoundPool(100, AudioManager.STREAM_MUSIC, 0); green_button1 = findViewById(R.id.green_btn1); green_button2 = findViewById(R.id.green_btn2); green_button3 = findViewById(R.id.green_btn3); green_button4 = findViewById(R.id.green_btn4); green_button5 = findViewById(R.id.green_btn5); green_button6 = findViewById(R.id.green_btn6); green_button7 = findViewById(R.id.green_btn7); green_button8 = findViewById(R.id.green_btn8); green_button9 = findViewById(R.id.green_btn9); green_button10 = findViewById(R.id.green_btn10); green_button11 = findViewById(R.id.green_btn11); green_button12 = findViewById(R.id.green_btn12); green_button13 = findViewById(R.id.green_btn13); green_button14 = findViewById(R.id.green_btn14); green_button15 = findViewById(R.id.green_btn15); green_button16 = findViewById(R.id.green_btn16); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn1)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn2)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn3)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn4)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn5)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn6)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn7)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn8)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn9)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn10)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn11)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn12)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn13)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn14)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn15)); soundgreenbtns.add((ToggleButton) beatmaker_green.findViewById(R.id.green_btn16)); final ToggleButton[] green_buttons = {green_button1,green_button2,green_button3,green_button4,green_button5,green_button6,green_button7,green_button8, green_button9,green_button10,green_button11,green_button12,green_button13,green_button14,green_button15,green_button16}; Intent intent = getIntent(); final float loaded_volume = intent.getFloatExtra("sound",-1); int loaded_index; if(loaded_volume != -1.0){ loaded_index = intent.getIntExtra("select_index",-1); int[] array = intent.getIntArrayExtra("GreenIndex_array"); String[] patharr = intent.getStringArrayExtra("GreenSoundPath"); saveIndex_array = intent.getIntArrayExtra("not_green_array"); saveColor_array = intent.getStringArrayExtra("saveColorArray"); String[] saveColor_array_two = intent.getStringArrayExtra("saveColorArray2"); saveGreenIndex_array = array; saveGreenSoundPath = patharr; if(intent.getIntArrayExtra("from_setvolume_btn_sound") != null) { btn_sound = intent.getIntArrayExtra("from_setvolume_btn_sound"); } String loaded_sound = intent.getStringExtra("file"); for(int i=0; i<16; i++){ if(saveIndex_array[i] <0){ if (saveColor_array[i].equals("blue")) { beat_button.get(i).setBackgroundResource(R.drawable.button_1row_style); } else if (saveColor_array[i].equals("yellow")) { beat_button.get(i).setBackgroundResource(R.drawable.button_2row_style); } else if (saveColor_array[i].equals("orange")) { beat_button.get(i).setBackgroundResource(R.drawable.button_3row_style); } else if (saveColor_array[i].equals("indigo")) { beat_button.get(i).setBackgroundResource(R.drawable.button_4row_style); } else if (saveColor_array[i].equals("green")) { beat_button.get(i).setBackgroundResource(R.drawable.button_5row_style); } } } int plus = 0; //-1을 주는게아니고 들어올때마다 순서를 정해주기 위함 for(int i=0;i<16;i++) { if(saveGreenIndex_array[i] >99){ plus= plus+1; } } saveGreenSoundPath[loaded_index] = loaded_sound; saveGreenIndex_array[loaded_index] = 100+plus; for(int i=0;i<16;i++) { saveGreenSound_array[i] = sp.load(saveGreenSoundPath[i],1); } for(int i = 0; i<16; i++) { if (saveGreenIndex_array[i] > 99) { //차있는 경우에 초록색으로 세팅 green_buttons[i].setBackgroundResource(R.drawable.button_5row_style); } } } int sival = intent.getIntExtra("original_index",-1); //인덱스 String recorded_sound = intent.getStringExtra("record_sound"); //사운드path int[] getted_save_sound = intent.getIntArrayExtra("loaded_saved_sound"); sync_sound_path = intent.getIntArrayExtra("sync"); Log.d("시발 되는겨?"," "+String.valueOf(sival)+" "+recorded_sound); if(intent.getIntExtra("into_the_unknown",1) == 1000){ for(int i=0;i<16;i++) { saveGreenSound_array[i] = sp.load(saveGreenSoundPath[i],1); } for(int i = 0; i<16; i++) { if (saveGreenIndex_array[i] > 99) { //차있는 경우에 초록색으로 세팅 green_buttons[i].setBackgroundResource(R.drawable.button_5row_style); } } } if(sival !=-1 && !recorded_sound.isEmpty()) { saveGreenSoundPath = intent.getStringArrayExtra("loaded_sound_path"); saveGreenIndex_array = intent.getIntArrayExtra("loaded_saved_index"); String[] saveColor_array_two = intent.getStringArrayExtra("saveColorArray2"); saveGreenSoundPath[sival] = recorded_sound; //가져온 소리 저장 int plus = 0; //-1을 주는게아니고 들어올때마다 순서를 정해주기 위함 for(int i=0;i<16;i++) { if(saveGreenIndex_array[i] >99){ plus= plus+1; } } saveGreenIndex_array[sival] = 100+plus; for(int i=0;i<16;i++) { saveGreenSound_array[i] = sp.load(saveGreenSoundPath[i],1); } for(int i = 0; i<16; i++) { if (saveGreenIndex_array[i] > 99) { //차있는 경우에 초록색으로 세팅 green_buttons[i].setBackgroundResource(R.drawable.button_5row_style); } } saveIndex_array = intent.getIntArrayExtra("not_green_arrays2"); for(int i=0; i<16; i++){ if(saveIndex_array[i] <0){ if (saveColor_array[i].equals("blue") || saveColor_array_two[i].equals("blue")) { beat_button.get(i).setBackgroundResource(R.drawable.button_1row_style); } else if (saveColor_array[i].equals("yellow") || saveColor_array_two[i].equals("yellow")) { beat_button.get(i).setBackgroundResource(R.drawable.button_2row_style); } else if (saveColor_array[i].equals("orange") || saveColor_array_two[i].equals("orange")) { beat_button.get(i).setBackgroundResource(R.drawable.button_3row_style); } else if (saveColor_array[i].equals("indigo") || saveColor_array_two[i].equals("indigo")) { beat_button.get(i).setBackgroundResource(R.drawable.button_4row_style); } else if (saveColor_array[i].equals("green") || saveColor_array_two[i].equals("green")) { beat_button.get(i).setBackgroundResource(R.drawable.button_5row_style); } } } } for (int i = 0; i < 16; i++) { green_buttons[i].setChecked(true); } for (final ToggleButton soundPad : green_buttons){ soundPad.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (soundPad.isChecked()) { if (saveGreenIndex_array[Integer.parseInt(String.valueOf(view.getTag())) -65] < 100) { //선택안된거 눌렀을때 for (int i = 0; i < 16 ; i++) { if (saveGreenIndex_array[i] < 99) { green_buttons[i].setBackgroundColor(Color.rgb(255, 255, 255)); } green_buttons[Integer.parseInt(String.valueOf(view.getTag())) - 65].setBackgroundResource(R.drawable.selected_5row_style); } soundPad.setChecked(false); original_layout.setVisibility(View.INVISIBLE); green_layout.setVisibility(View.VISIBLE); Log.d("11111111111111111111111111","88888888888888888888888"); } else if (saveGreenIndex_array[Integer.parseInt(String.valueOf(view.getTag()))-65] >= 100) { sp.play(saveGreenSound_array[Integer.parseInt(String.valueOf(view.getTag()))-65],loaded_volume,loaded_volume,0,0,1f); saveColor="green"; saveIndex = Integer.parseInt(String.valueOf(view.getTag()))-65; green_layout.setVisibility(View.INVISIBLE); original_layout.setVisibility(View.VISIBLE); } Log.d("2222222222222222222222","아쎾쓰 "+String.valueOf(saveGreenIndex_array[Integer.parseInt(String.valueOf(view.getTag()))-65])); if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { // Play_beat_setting_SoundPlayer.playGreenSound(Integer.parseInt(String.valueOf(view.getTag()))); saveColor = "green"; saveIndex = Integer.parseInt(String.valueOf(view.getTag()))-65; setSaveIndex(saveIndex); soundPad.setChecked(false); } if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS) { return true; } if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_RELEASE) { return true; } } else { if (saveGreenIndex_array[Integer.parseInt(String.valueOf(view.getTag()))-65] < 100) { Log.d("뭔데씨이이이이발",String.valueOf(Integer.parseInt(String.valueOf(view.getTag())))); for (int i = 0; i < 16; i++) { soundbulebtns.get(i).setBackgroundResource(R.drawable.button_1row_style); soundyellowbtns.get(i).setBackgroundResource(R.drawable.button_2row_style); soundorangebtns.get(i).setBackgroundResource(R.drawable.button_3row_style); soundindigobtns.get(i).setBackgroundResource(R.drawable.button_4row_style); } soundPad.setBackgroundResource(R.drawable.selected_5row_style); } else if(saveGreenIndex_array[Integer.parseInt(String.valueOf(view.getTag()))-65] < 0){ } } return false; } }); } } public void setSaveIndex(int index){ this.saveIndex = index; } public int getsaveIndex(){ return this.saveIndex; } private void changeView(int index){ GridLayout beatmaker_one = (GridLayout) findViewById(R.id.beatmaker_one); View beatmaker_yellow = (View) findViewById(R.id.main_beatmaker_yellow); View beatmaker_orange = (View)findViewById(R.id.main_beatmaker_orange); View beatmaker_indigo = (View)findViewById(R.id.main_beatmaker_indogo); View beatmaker_green = (View)findViewById(R.id.main_beatmaker_green); switch (index) { case 0: beatmaker_one.setVisibility(View.VISIBLE); beatmaker_yellow.setVisibility(View.INVISIBLE); beatmaker_orange.setVisibility(View.INVISIBLE); beatmaker_indigo.setVisibility(View.INVISIBLE); beatmaker_green.setVisibility(View.INVISIBLE); break; case 1: beatmaker_one.setVisibility(View.INVISIBLE); beatmaker_yellow.setVisibility(View.VISIBLE); beatmaker_orange.setVisibility(View.INVISIBLE); beatmaker_indigo.setVisibility(View.INVISIBLE); beatmaker_green.setVisibility(View.INVISIBLE); break; case 2: beatmaker_one.setVisibility(View.INVISIBLE); beatmaker_yellow.setVisibility(View.INVISIBLE); beatmaker_orange.setVisibility(View.VISIBLE); beatmaker_indigo.setVisibility(View.INVISIBLE); beatmaker_green.setVisibility(View.INVISIBLE); break; case 3: beatmaker_one.setVisibility(View.INVISIBLE); beatmaker_yellow.setVisibility(View.INVISIBLE); beatmaker_orange.setVisibility(View.INVISIBLE); beatmaker_indigo.setVisibility(View.VISIBLE); beatmaker_green.setVisibility(View.INVISIBLE); break; case 4: beatmaker_one.setVisibility(View.INVISIBLE); beatmaker_yellow.setVisibility(View.INVISIBLE); beatmaker_orange.setVisibility(View.INVISIBLE); beatmaker_indigo.setVisibility(View.INVISIBLE); beatmaker_green.setVisibility(View.VISIBLE); } } }
package arcs.android.client; import android.content.ServiceConnection; /** * Starts up the {@link arcs.android.api.IArcsService} in the client app. A concrete implementation * must be provided by the app which implements the {@code IArcsService}. */ public interface ArcsServiceStarter { void start(ServiceConnection connection); }
package com.esum.as2.transaction; import com.esum.as2.AS2Exception; /** * Defines TransactionException. * * Copyrights(c) eSum Technologies., Inc. All rights reserved. */ public class TransactionException extends AS2Exception { public static final String ERROR_SQL_INSERT = "ATNS01"; public static final String ERROR_FILE_SAVE = "ATNS02"; public static final String ERROR_READ_MESSAGE = "ATNS03"; public static final String ERROR_DATA_READ = "ATNS04"; /** Queue 생성 중에 발생하는 에러 */ public static final String ERROR_QUEUE_CREATION = "MSH050"; /** Inbound Transaction 시작 중에 발생하는 에러 */ public static final String ERROR_INBOUND_TRANSACTION_START = "MSH051"; /** Outbound Transaction 시작 중에 발생하는 에러 */ public static final String ERROR_OUTBOUND_TRANSACTION_START = "MSH052"; /** Queue로 메시지 전송 중에 발생하는 에러 */ public static final String ERROR_QUEUE_SEND = "MSH053"; public TransactionException(String errorCode, String location, String msg){ super(errorCode, location, msg); } public TransactionException(String errorCode, String location, String msg,Throwable cause) { super(errorCode, location, msg, cause); } public TransactionException(String location, String msg,Throwable cause) { super(location, msg, cause); } }
package commandLineMenus.examples; import commandLineMenus.Menu; public class Cycle { public static void main(String[] args) { Menu root = new Menu("root", "r"), leaf = new Menu("leaf", "r"); root.add(leaf); leaf.add(root); root.start(); } }
package com.tide.demo16; public class Demo03MyInterface { public static void main(String[] args) { MyInterface obj=new MyInterface() { @Override public void method() { System.out.println("匿名内部类覆盖重写"); } }; obj.method(); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.util; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Arjen Poutsma * @author Juergen Hoeller * @author Rossen Stoyanchev */ class UriTemplateTests { @Test void getVariableNames() { UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); List<String> variableNames = template.getVariableNames(); assertThat(variableNames).as("Invalid variable names").isEqualTo(Arrays.asList("hotel", "booking")); } @Test void expandVarArgs() { UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); URI result = template.expand("1", "42"); assertThat(result).as("Invalid expanded template").isEqualTo(URI.create("/hotels/1/bookings/42")); } @Test // SPR-9712 void expandVarArgsWithArrayValue() { UriTemplate template = new UriTemplate("/sum?numbers={numbers}"); URI result = template.expand(new int[] {1, 2, 3}); assertThat(result).isEqualTo(URI.create("/sum?numbers=1,2,3")); } @Test void expandVarArgsNotEnoughVariables() { UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); assertThatIllegalArgumentException().isThrownBy(() -> template.expand("1")); } @Test void expandMap() { Map<String, String> uriVariables = new HashMap<>(2); uriVariables.put("booking", "42"); uriVariables.put("hotel", "1"); UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); URI result = template.expand(uriVariables); assertThat(result).as("Invalid expanded template").isEqualTo(URI.create("/hotels/1/bookings/42")); } @Test void expandMapDuplicateVariables() { UriTemplate template = new UriTemplate("/order/{c}/{c}/{c}"); assertThat(template.getVariableNames()).isEqualTo(Arrays.asList("c", "c", "c")); URI result = template.expand(Collections.singletonMap("c", "cheeseburger")); assertThat(result).isEqualTo(URI.create("/order/cheeseburger/cheeseburger/cheeseburger")); } @Test void expandMapNonString() { Map<String, Integer> uriVariables = new HashMap<>(2); uriVariables.put("booking", 42); uriVariables.put("hotel", 1); UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); URI result = template.expand(uriVariables); assertThat(result).as("Invalid expanded template").isEqualTo(URI.create("/hotels/1/bookings/42")); } @Test void expandMapEncoded() { Map<String, String> uriVariables = Collections.singletonMap("hotel", "Z\u00fcrich"); UriTemplate template = new UriTemplate("/hotel list/{hotel}"); URI result = template.expand(uriVariables); assertThat(result).as("Invalid expanded template").isEqualTo(URI.create("/hotel%20list/Z%C3%BCrich")); } @Test void expandMapUnboundVariables() { Map<String, String> uriVariables = new HashMap<>(2); uriVariables.put("booking", "42"); uriVariables.put("bar", "1"); UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); assertThatIllegalArgumentException().isThrownBy(() -> template.expand(uriVariables)); } @Test void expandEncoded() { UriTemplate template = new UriTemplate("/hotel list/{hotel}"); URI result = template.expand("Z\u00fcrich"); assertThat(result).as("Invalid expanded template").isEqualTo(URI.create("/hotel%20list/Z%C3%BCrich")); } @Test void matches() { UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); assertThat(template.matches("/hotels/1/bookings/42")).as("UriTemplate does not match").isTrue(); assertThat(template.matches("/hotels/bookings")).as("UriTemplate matches").isFalse(); assertThat(template.matches("")).as("UriTemplate matches").isFalse(); assertThat(template.matches(null)).as("UriTemplate matches").isFalse(); } @Test void matchesCustomRegex() { UriTemplate template = new UriTemplate("/hotels/{hotel:\\d+}"); assertThat(template.matches("/hotels/42")).as("UriTemplate does not match").isTrue(); assertThat(template.matches("/hotels/foo")).as("UriTemplate matches").isFalse(); } @Test void match() { Map<String, String> expected = new HashMap<>(2); expected.put("booking", "42"); expected.put("hotel", "1"); UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); Map<String, String> result = template.match("/hotels/1/bookings/42"); assertThat(result).as("Invalid match").isEqualTo(expected); } @Test void matchCustomRegex() { Map<String, String> expected = new HashMap<>(2); expected.put("booking", "42"); expected.put("hotel", "1"); UriTemplate template = new UriTemplate("/hotels/{hotel:\\d}/bookings/{booking:\\d+}"); Map<String, String> result = template.match("/hotels/1/bookings/42"); assertThat(result).as("Invalid match").isEqualTo(expected); } @Test // SPR-13627 void matchCustomRegexWithNestedCurlyBraces() { UriTemplate template = new UriTemplate("/site.{domain:co.[a-z]{2}}"); Map<String, String> result = template.match("/site.co.eu"); assertThat(result).as("Invalid match").isEqualTo(Collections.singletonMap("domain", "co.eu")); } @Test void matchDuplicate() { UriTemplate template = new UriTemplate("/order/{c}/{c}/{c}"); Map<String, String> result = template.match("/order/cheeseburger/cheeseburger/cheeseburger"); Map<String, String> expected = Collections.singletonMap("c", "cheeseburger"); assertThat(result).as("Invalid match").isEqualTo(expected); } @Test void matchMultipleInOneSegment() { UriTemplate template = new UriTemplate("/{foo}-{bar}"); Map<String, String> result = template.match("/12-34"); Map<String, String> expected = new HashMap<>(2); expected.put("foo", "12"); expected.put("bar", "34"); assertThat(result).as("Invalid match").isEqualTo(expected); } @Test // SPR-16169 void matchWithMultipleSegmentsAtTheEnd() { UriTemplate template = new UriTemplate("/account/{accountId}"); assertThat(template.matches("/account/15/alias/5")).isFalse(); } @Test void queryVariables() { UriTemplate template = new UriTemplate("/search?q={query}"); assertThat(template.matches("/search?q=foo")).isTrue(); } @Test void fragments() { UriTemplate template = new UriTemplate("/search#{fragment}"); assertThat(template.matches("/search#foo")).isTrue(); template = new UriTemplate("/search?query={query}#{fragment}"); assertThat(template.matches("/search?query=foo#bar")).isTrue(); } @Test // SPR-13705 void matchesWithSlashAtTheEnd() { assertThat(new UriTemplate("/test/").matches("/test/")).isTrue(); } @Test void expandWithDollar() { UriTemplate template = new UriTemplate("/{a}"); URI uri = template.expand("$replacement"); assertThat(uri.toString()).isEqualTo("/$replacement"); } @Test void expandWithAtSign() { UriTemplate template = new UriTemplate("http://localhost/query={query}"); URI uri = template.expand("foo@bar"); assertThat(uri.toString()).isEqualTo("http://localhost/query=foo@bar"); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.chatdemo; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.Socket; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Quoc Huy Ngo */ public class Sender{ int port; String ip; public Sender(String ip ,int port) throws IOException, SQLException { this.port = port; this.ip = ip; connetClient(); } public void connetClient() throws IOException, SQLException{ Socket clientSocket = new Socket(ip , port); ObjectOutputStream objectMessage = new ObjectOutputStream(clientSocket.getOutputStream()); //Message message = new Message(tbUserName.getText(), to , tbMessage.getText()); objectMessage.writeObject(ClientChat.message); ClientChat.connectDB.InsertToDB(ClientChat.message); ClientChat.modelMessage.addElement(ClientChat.message.getFrom().toUpperCase() + " :" + ClientChat.message.getMessage()); } }
package se.eskilson.buildengine.filemonitor; import java.io.File; import java.util.Date; import java.util.concurrent.BlockingQueue; public class AbstractMonitoredFile implements IMonitoredFile { private final BlockingQueue<FileEvent> queue; private final File file; public AbstractMonitoredFile(File file, BlockingQueue<FileEvent> queue) { this.file = file; this.queue = queue; } @Override public File getFile() { return file; } @Override public BlockingQueue<FileEvent> getQueue() { return queue; } @Override public String toString() { return String.format("MonitoredFile<%s, mtime=%s>", file, new Date(file .lastModified())); } @Override public void poll() { } @Override public void startMonitor() { } @Override public void stopMonitor() throws InterruptedException { } }
package com.pages; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import com.excelutillity.Exceldata; public class Signup_page { WebDriver driver; public Signup_page(WebDriver driver) { this.driver=driver; } public void Launchingbrowser(String browser) //Method to launch the browser { try { // To launch Chrome Browser if (browser.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver","src\\test\\resources\\Drivers\\chromedriver.exe"); driver=new ChromeDriver(); } //To launch firefox Browser else if (browser.equalsIgnoreCase("firefox")) { System.setProperty("webdriver.gecko.driver","src\\test\\resources\\Drivers\\geckodriver.exe"); driver = new FirefoxDriver(); } //To maximize the window driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } catch (WebDriverException e) { System.out.println("Browser could not be launched"); } } public void Launch_Application(String Url) { // Method to launch the application driver.get(Url); } public void Signup_link() throws InterruptedException { //To click on Signup_button driver.findElement(By.xpath("//a[@id='signin2']")).click(); Thread.sleep(1000); } public void Signup_details(int i) throws IOException { //Method to send username and password from Excelsheet Exceldata ex=new Exceldata(); driver.findElement(By.xpath("//*[@id=\"sign-username\"]")).sendKeys(ex.excel_username(i)); driver.findElement(By.xpath("//*[@id=\"sign-password\"]")).sendKeys(ex.excel_password(i)); } public void Signup_buttonclick() throws InterruptedException { //Method to click sign up button driver.findElement(By.xpath("//*[@id=\"signInModal\"]/div/div/div[3]/button[2]")).click(); Thread.sleep(5000); //Popup window alert handling Alert alert=driver.switchTo().alert(); String s=driver.switchTo().alert().getText(); //Getting the the text from popup window System.out.println(s); //To print the text acquired from the popup window Thread.sleep(1000); alert.accept(); } public void Screenshot_signupform() throws IOException, InterruptedException { //Method to take screen shot of sign up form Thread.sleep(1000); TakesScreenshot ts=((TakesScreenshot)driver); File Store=ts.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(Store,new File("E:\\SVSSNR\\SVSSNRPROJECT\\844834_Project\\src\\test\\resources\\Screenshots\\Signup1.png")); Thread.sleep(1000); driver.close(); //Closes the current window } }
package com.learning.bank.abilities.balance; import com.learning.bank.Account; /** * Class represented ATMs with no possibility to show balance */ public class AbsenceBalance implements Balance { @Override public void showBalance(Account acc) { System.out.println("This kind of ATM doesn't maintain balance mapping"); } }
package com.alpha.toy.vo; public class ChattingVo { private int chatting_no; private int channel_no; private int member_no; private String content; private String content_date; public ChattingVo() { // TODO Auto-generated constructor stub } public ChattingVo(int chatting_no, int channel_no, int member_no, String content, String content_date) { super(); this.chatting_no = chatting_no; this.channel_no = channel_no; this.member_no = member_no; this.content = content; this.content_date = content_date; } public int getChatting_no() { return chatting_no; } public void setChatting_no(int chatting_no) { this.chatting_no = chatting_no; } public int getChannel_no() { return channel_no; } public void setChannel_no(int channel_no) { this.channel_no = channel_no; } public int getMember_no() { return member_no; } public void setMember_no(int member_no) { this.member_no = member_no; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getContent_date() { return content_date; } public void setContent_date(String content_date) { this.content_date = content_date; } }
package com.syntax.class04; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class WebElementC { public static String url = "http://secure.smartbearsoftware.com/samples/TestComplete11/WebOrders/Login.aspx/"; public static String userName="Tester"; public static String password="test"; public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "drivers/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get(url); WebElement userNam = driver.findElement(By.xpath("//input[contains(@id,'username')]")); userNam.clear(); userNam.sendKeys(userName); Thread.sleep(3000); WebElement pass = driver.findElement(By.cssSelector("input[name*='$password']")); pass.clear(); Thread.sleep(3000); pass.sendKeys(password); WebElement loginBtn = driver.findElement(By.cssSelector("input[value='Login']")); Thread.sleep(3000); loginBtn.click(); // loginBtn.submit(); WebElement user = driver.findElement(By.xpath("//*[@id=\"ctl00_MainContent_username\"]")); user.sendKeys(userName); WebElement passwor = driver.findElement(By.xpath("//*[@id=\"ctl00_MainContent_password\"]")); passwor.sendKeys(password); WebElement login = driver.findElement(By.xpath("//*[@id=\"ctl00_MainContent_login_button\"]")); login.click(); boolean logoIsDisplayed = driver.findElement(By.xpath("//*[@id=\"aspnetForm\"]/table/tbody/tr/td[1]/h1")) .isDisplayed(); if (logoIsDisplayed) { System.out.println("Logo is displayed, and Test case passed"); } else { System.out.println("Logo is Not displayed, and test case failed"); } WebElement loginInfo = driver.findElement(By.xpath("//div[@class='login_info']")); String text=loginInfo.getText();//used to retrieve the inner text of a web element if(text.contains(userName)) { System.out.println("User successfuly logged in, and Test case passed"); }else { System.out.println("User not logged in, and Test case failed"); } Thread.sleep(3000); driver.quit(); } }
package com.haku.light.graphics.gl.shader; import com.haku.light.Light; import com.haku.light.graphics.Graphics; import com.haku.light.graphics.gl.GL20; import com.haku.light.utils.BufferUtils; import java.nio.IntBuffer; import java.util.HashMap; public class GLShaderUniforms extends HashMap<String, Integer> { public final GLShader shader; public GLShaderUniforms(GLShader parent) { this.shader = parent; } public void update() { IntBuffer type = BufferUtils.getIntBuffer(1); IntBuffer size = BufferUtils.getIntBuffer(1); Graphics.gl.glGetProgramiv(shader.getId(), GL20.GL_ACTIVE_UNIFORMS, size); int count = size.get(); //Light.log.d("\t%s Uniform/s Found", count); size.flip(); for (int i = 0; i < count; i++) { String name = Graphics.gl.glGetActiveUniform(shader.getId(), i, size, type); int location = Graphics.gl.glGetUniformLocation(shader.getId(), name); this.put(name, location); } } public void setBoolean(String uniform, boolean value) { this.setInteger(uniform, value ? 1 : 0); } public void setInteger(String uniform, int... values) { Integer index = this.get(uniform); if (index != null) this.setInteger(index, values); } public void setInteger(int location, int... values) { Graphics.gl.glUniform(location, values); } public void setFloat(String uniform, float... values) { Integer index = this.get(uniform); if (index != null) this.setFloat(index, values); } public void setFloat(int location, float... values) { Graphics.gl.glUniform(location, values); } public void setMatrix(String uniform, float... values) { Integer index = this.get(uniform); if (index != null) this.setMatrix(index, values); } public void setMatrix(int location, float... values) { Graphics.gl.glUniformMatrix(location, false, values); } public void setTexture(String name, int unit) { Integer index = this.get(name); if (index != null) Graphics.gl.glUniform(index, unit); } }
package com.example.karen.lop_android; import android.content.Context; import android.os.StrictMode; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * Created by hebi5 on 9/24/2015. */ public class Informatron { private String urlTest="http://hmkcode.appspot.com/jsonservlet"; public String URL = "http://192.168.1.39:8080/InformatronYX/informatron/user/signup"; boolean registerSuccess = false; String jsonRegister = "a"; public void setRegisterUrl(String url){ this.URL = url; } public void registerUser(Context ctx, String username, String password, String email, String firstName, String lastName){ InputStream inputStream = null; String result = ""; try { JSONObject jsonObject = new JSONObject(); jsonObject.put("username", username); jsonObject.put("password", password); jsonObject.put("firstName", firstName); jsonObject.put("lastName", lastName); jsonObject.put("email", email); jsonRegister = jsonObject.toString(); HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(URL); StringEntity se = new StringEntity(jsonRegister); httpPost.setEntity(se); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); HttpResponse httpResponse = httpclient.execute(httpPost); inputStream = httpResponse.getEntity().getContent(); result = convertInputStreamToString(inputStream); registerSuccess = true; Toast.makeText(ctx, "\n"+result, Toast.LENGTH_LONG).show(); } catch(IllegalStateException e){ Toast.makeText(ctx, "Cannot be null! \nERROR:"+e.toString(), Toast.LENGTH_LONG).show(); Toast.makeText(ctx, "Registration Failed", Toast.LENGTH_LONG).show(); } catch(Exception e){ Toast.makeText(ctx, "ERROR: "+e.toString(), Toast.LENGTH_LONG).show(); Toast.makeText(ctx, "Registration Failed", Toast.LENGTH_LONG).show(); }; } public String loginUser(Context ctx, String username, String password){ InputStream inputStream = null; String result = ""; try { JSONObject jsonObject = new JSONObject(); jsonObject.put("username", username); jsonObject.put("password", password); jsonRegister = jsonObject.toString(); HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(URL); StringEntity se = new StringEntity(jsonRegister); httpPost.setEntity(se); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); HttpResponse httpResponse = httpclient.execute(httpPost); inputStream = httpResponse.getEntity().getContent(); result = convertInputStreamToString(inputStream); registerSuccess = true; } catch(IllegalStateException e){ Toast.makeText(ctx, "Cannot be null! \nERROR:"+e.toString(), Toast.LENGTH_LONG).show(); } catch(Exception e){ Toast.makeText(ctx, "ERROR: "+e.toString(), Toast.LENGTH_LONG).show(); }; return result; } private static String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); String line = ""; String result = ""; while((line = bufferedReader.readLine()) != null) result += line; inputStream.close(); return result; } }
/* * Created on Jan 28, 2007 */ package com.citibank.ods; /** * @author User * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Style - Code Templates */ public abstract class Globals { /** * Constantes utilizadas pelo JSP para formatação de dados através do tag * Bean:write */ public abstract class FormatKeys { public static final String C_FORMAT_CURRENCY_2DEC = "view.format.currency.2dec"; public static final String C_FORMAT_TAX_6DEC = "view.format.tax.6dec"; public static final String C_FORMAT_DATE_DDMMYYYY = "view.format.date.ddMMyyyy"; public static final String C_FORMAT_DATETIME_DDMMYYYY_HHMM = "view.format.datetime.ddMMyyyy.hhmm"; public static final String C_FORMAT_NUMBER_INTEGER = "view.format.number.integer"; } /** * Constantes utilizadas pelas funcionalidades para formatação de dados */ public abstract class FuncionalityFormatKeys { public static final String C_FORMAT_DATE_DDMMYYYY = "dd/MM/yyyy"; public static final String C_FORMAT_DATE_DDMM = "dd/MM"; public static final String C_FORMAT_TIMESTAMP = "yyyy-MM-dd HH:mm:ss.S"; public static final String C_FORMAT_PRESENTATION = "dd/MM/yyyy HH:mm:ss"; public static final String C_FORMAT_DATETIME_DDMMYYYY_HHMM = "dd/MM/yyyy HH:mm"; public static final String C_FORMAT_DATETIME_HHMM = "HH:mm"; } /** * Constantes utilizadas por propriedades do JSP e camadas de persistência * para indicadores booleanos */ public abstract class BooleanIndicatorKeys { public static final String C_BOOLEAN_IND_SIM = "S"; public static final String C_BOOLEAN_IND_NAO = "N"; } public abstract class GetVersionSystem { public static final String C_VERSION_SYSTEM ="v.1.03"; } }
package br.com.madness.madness; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.media.MediaPlayer.OnCompletionListener; /** * Created by Juan-Note on 30/05/2015. * * Indice da classe = 4 */ public class PlantaDaCasaActivity extends ActionBarActivity implements OnCompletionListener { ListView lv; MediaPlayer audio; Integer controle_play_pause = 0; public void onCompletion(MediaPlayer mp) { Intent tela = new Intent(this, DormitorioActivity.class); startActivity(tela); } public void playMadness() { audio.start(); audio.setOnCompletionListener(this); } public void pauseMadness(View v) { Button botao = (Button) findViewById(R.id.BtnPause); if (controle_play_pause == 0) { audio.pause(); controle_play_pause = 1; botao.setBackgroundResource(R.drawable.play_inicio); } else { audio.start(); controle_play_pause = 0; botao.setBackgroundResource(R.drawable.pause_inicio); } } public void stopMadness(View v) { audio.stop(); Intent tela = new Intent(this, MadnessGameActivity.class); startActivity(tela); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.planta_da_casa); lv = (ListView)findViewById(R.id.listView); audio = MediaPlayer.create(this, R.raw.vamos_vamos); playMadness(); } }
package modele; import java.util.ArrayList; import java.util.Iterator; import java.util.Spliterator; import java.util.function.Consumer; /** * Créé par victor le 28/03/18. */ public class Chemin implements Iterable<Case> { private final ArrayList<Case> trace; public Chemin(Case depart) { this.trace = new ArrayList<>(); this.ajouterCase(depart); } public void ajouterCase(Case suivante) { this.trace.add(suivante); suivante.setChemin(this); if (this.trace.size() > 1) { Case precedente = this.trace.get(this.trace.size() - 2); precedente.setSortie(suivante); suivante.setEntree(precedente); } } @Override public Iterator<Case> iterator() { Iterator<Case> it = new Iterator<Case>() { private int index = 0; @Override public boolean hasNext() { return index < trace.size(); } @Override public Case next() { return trace.get(index++); } }; return it; } @Override public void forEach(Consumer<? super Case> action) { throw new UnsupportedOperationException(); } @Override public Spliterator<Case> spliterator() { throw new UnsupportedOperationException(); } public Case getPremiere() { return this.trace.get(0); } public Case getDerniere() { return this.trace.get(this.trace.size() - 1); } }
/* * Copyright (c) 2004 Steve Northover and Mike Wilson * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ package part1; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; public class Fragments2 { Display display; Shell shell, shell1, shell2; boolean done; Font textFont; Runnable timer; GC gc; Control control; public void f1() { display.addListener(SWT.Dispose, new Listener() { public void handleEvent(Event event) { // the display is getting disposed } }); } public void f1a() { display.addFilter(SWT.KeyDown, new Listener() { public void handleEvent(Event event) { event.type = SWT.None; event.doit = false; } }); } public void f2() { display.disposeExec(new Runnable() { public void run() { // dispose the shared font textFont.dispose(); } }); } public void f3() { while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } } public void f3a() { while (!done) display.readAndDispatch(); } public void f3b() { while (display.readAndDispatch()); } public void f4() { // this code is running in the event loop thread while (!done) { if (!display.readAndDispatch()) display.sleep(); } } public void f5() { // this code is not running in the event loop thread done = true; display.wake (); } public void f6() { if (display.getThread() == Thread.currentThread()) { // current thread is the UI thread } } public void f6a() { display.timerExec(2000, new Runnable() { public void run() { System.out.println("Once, after 2 seconds."); } }); } public void f6b() { display.timerExec(2000, new Runnable() { public void run() { System.out.println("Every 2 seconds."); display.timerExec(2000, this); } }); } public void f6c() { display.timerExec(2000, timer); display.timerExec(5000, timer); } public void f6d() { display.timerExec (-1, timer); } public void f7() { Monitor[] list = display.getMonitors(); System.out.println(list.length + " monitors."); for (int i = 0; i < list.length; i++) { String string = "\t" + i + " - " + list[i].getBounds(); System.out.println(string); } System.out.println("Total bounds: " + display.getBounds()); } public void f7a() { Shell shell = display.getActiveShell(); if (shell != null) shell.dispose(); } public void f8() { Shell shell = display.getActiveShell(); if (shell != null) { while (shell.getParent() != null) { shell = shell.getParent().getShell(); } } if (shell != null) { Shell[] shells = display.getShells(); for (int i = 0; i < shells.length; i++) { if (shells[i].getParent() == null) { if (shells[i] != shell) { shells[i].setMinimized(true); } } } } } public void f9 () { Control control = display.getFocusControl(); System.out.println("Focus control is " + control); } public void f9a () { Point location = display.getCursorLocation(); } public void f9b () { Point dpi = display.getDPI (); gc.drawRectangle (10, 10, dpi.x, dpi.y); } public void f10 () { Color red = display.getSystemColor (SWT.COLOR_RED); } public void f11 () { Font font = display.getSystemFont(); control.setFont(font); } public void f12 () { Button b1 = new Button(shell, SWT.PUSH); Button b2 = new Button(shell, SWT.PUSH); Button okButton = null, cancelButton = null; if (display.getDismissalAlignment() == SWT.LEFT) { okButton = b1; cancelButton = b2; } else { cancelButton = b1; okButton = b2; } okButton.setText("Ok"); cancelButton.setText("Cancel"); } public void f13 () { shell2.dispose(); while (display.readAndDispatch()); Rectangle rect = shell1.getBounds(); } }
package be.mxs.common.util.tools; import java.net.InetAddress; import java.net.URI; import java.net.URLEncoder; import java.util.Base64; import java.util.Enumeration; import java.util.List; import java.util.Vector; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.smslib.AGateway.*; import org.smslib.*; import org.smslib.modem.*; import com.africastalking.AfricasTalking; import com.africastalking.SmsService; import com.africastalking.sms.Recipient; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.Debug; import be.openclinic.system.SH; import be.openclinic.system.URLParamEncoder; import ie.omk.smpp.Address; import ie.omk.smpp.Connection; import ie.omk.smpp.message.BindResp; import ie.omk.smpp.message.SMPPPacket; import ie.omk.smpp.message.SubmitSM; import ie.omk.smpp.message.SubmitSMResp; import ie.omk.smpp.message.UnbindResp; import ie.omk.smpp.net.TcpLink; import ie.omk.smpp.util.Latin1Encoding; public class SendSMS { public static boolean sendSMPP(String to, String message){ boolean bSuccess=false; Debug.println("Trying to send message to "+to+" using SMPP gateway "+MedwanQuery.getInstance().getConfigString("smppgateway","")); if(MedwanQuery.getInstance().getConfigString("smppgateway","").equalsIgnoreCase("orangemali")){ bSuccess=true; try { // First get the java.net.InetAddress for the SMSC: //Orange SMSC can only be reached from ip 41.73.116.155 (ANTIM server) //Create tunnel that maps 127.0.0.1:3339 onto 41.73.126.165:3339 (Orange SMSC) InetAddress smscAddr = InetAddress.getByName(MedwanQuery.getInstance().getConfigString("smppsmscaddress","Orange SMSC")); TcpLink smscLink = new TcpLink(smscAddr, MedwanQuery.getInstance().getConfigInt("smppsmscport",3339)); smscLink.open(); Debug.println("Connection open<br/>"); Connection connection = new Connection(smscLink); BindResp smppResponse = connection.bind(Connection.TRANSCEIVER,"RCV","Orange","SMPP",1,1,"3000"); if (smppResponse.getCommandStatus() == 0) { Debug.println("Link established</br>"); } else{ Debug.println("Error: "+smppResponse.getCommandStatus()+"</br>"); bSuccess=false; } SubmitSM smppmessage = (SubmitSM) connection.newInstance(SMPPPacket.SUBMIT_SM); if(MedwanQuery.getInstance().getConfigInt("enableSmppSource",0)==1){ Debug.println("Setting source address = "+MedwanQuery.getInstance().getConfigString("smppSourceAddress","Orange")); smppmessage.setSource(new Address(MedwanQuery.getInstance().getConfigInt("smppSourceNPI",1), MedwanQuery.getInstance().getConfigInt("smppSourceTON",0), MedwanQuery.getInstance().getConfigString("smppSourceAddress","Orange"))); } smppmessage.setDestination(new Address(1, 1, to)); smppmessage.setMessageText(message); smppmessage.setAlphabet(new Latin1Encoding()); SubmitSMResp messageResponse = (SubmitSMResp) connection.sendRequest(smppmessage); Debug.println("Submitted message ID: " + messageResponse.getMessageId()+"</br>"); // Unbind. UnbindResp unbindResponse = connection.unbind(); if (unbindResponse.getCommandStatus() == 0) { Debug.println("Successfully unbound from the SMSC</br>"); } else { Debug.println("There was an error unbinding.</br>"); bSuccess=false; } } catch(Exception ux) { Debug.println(ux.getMessage()); bSuccess=false; } } else if(MedwanQuery.getInstance().getConfigString("smppgateway","").equalsIgnoreCase("smpp")){ bSuccess=true; try { InetAddress smscAddr = InetAddress.getByName(MedwanQuery.getInstance().getConfigString("smppsmscaddress","smsc")); TcpLink smscLink = new TcpLink(smscAddr, MedwanQuery.getInstance().getConfigInt("smppsmscport",10501)); smscLink.open(); Debug.println("Connection open<br/>"); Connection connection = new Connection(smscLink); BindResp smppResponse = connection.bind(Connection.TRANSCEIVER,MedwanQuery.getInstance().getConfigString("smppsmscusername","username"),MedwanQuery.getInstance().getConfigString("smppsmscpassword","password"),MedwanQuery.getInstance().getConfigString("smppsmscid","id"),1,1,null); if (smppResponse.getCommandStatus() == 0) { Debug.println("Link established</br>"); } else{ Debug.println("Error: "+smppResponse.getCommandStatus()+"</br>"); bSuccess=false; } SubmitSM smppmessage = (SubmitSM) connection.newInstance(SMPPPacket.SUBMIT_SM); if(MedwanQuery.getInstance().getConfigInt("enableSmppSource",0)==1){ Debug.println("Setting source address = "+MedwanQuery.getInstance().getConfigString("smppSourceAddress","source phone number")); Debug.println("Setting source NPI = "+MedwanQuery.getInstance().getConfigInt("smppSourceNPI",1)); Debug.println("Setting source TON = "+MedwanQuery.getInstance().getConfigInt("smppSourceTON",1)); smppmessage.setSource(new Address(MedwanQuery.getInstance().getConfigInt("smppSourceNPI",1), MedwanQuery.getInstance().getConfigInt("smppSourceTON",1), MedwanQuery.getInstance().getConfigString("smppSourceAddress","source phone number"))); } Debug.println("Setting destination address = "+to); Debug.println("Setting destination NPI = "+MedwanQuery.getInstance().getConfigInt("smppDestinationNPI",1)); Debug.println("Setting destination TON = "+MedwanQuery.getInstance().getConfigInt("smppDestinationTON",1)); String sDestinationNumber = (to+"").replaceAll("\\+", ""); if(MedwanQuery.getInstance().getConfigInt("cellPhoneRemoveLeadingZero",1)==1){ if(sDestinationNumber.startsWith("0")){ sDestinationNumber=sDestinationNumber.substring(1); } } String countryPrefix=MedwanQuery.getInstance().getConfigString("cellPhoneCountryPrefix","-1"); if(!countryPrefix.equalsIgnoreCase("-1")){ if(!sDestinationNumber.startsWith(countryPrefix)){ sDestinationNumber=countryPrefix+sDestinationNumber; } } Debug.println("Setting cleaned destination address = "+sDestinationNumber); smppmessage.setDestination(new Address(MedwanQuery.getInstance().getConfigInt("smppDestinationNPI",1), MedwanQuery.getInstance().getConfigInt("smppDestinationTON",1), sDestinationNumber)); smppmessage.setMessageText(message); smppmessage.setAlphabet(new Latin1Encoding()); SubmitSMResp messageResponse = (SubmitSMResp) connection.sendRequest(smppmessage); Debug.println("Submitted message ID: " + messageResponse.getMessageId()+"</br>"); Debug.println("Response message status: " + messageResponse.getMessageStatus()+"</br>"); Debug.println("Response message text: " + messageResponse.getMessageText()+"</br>"); Debug.println("Response error code: " + messageResponse.getErrorCode()+"</br>"); Debug.println("Response command status: " + messageResponse.getCommandStatus()+"</br>"); Debug.println("Response destination: " + messageResponse.getDestination()+"</br>"); Debug.println("Response delivery time: " + messageResponse.getDeliveryTime()+"</br>"); bSuccess=(messageResponse.getCommandStatus()==0); // Unbind. UnbindResp unbindResponse = connection.unbind(); if (unbindResponse.getCommandStatus() == 0) { Debug.println("Successfully unbound from the SMSC</br>"); } else { Debug.println("There was an error unbinding.</br>"); bSuccess=false; } } catch(Exception ux) { Debug.println(ux.getMessage()); bSuccess=false; } } return bSuccess; } public static boolean sendSMS(String to, String message) { return sendSMS(to, message, ""); } public static boolean sendSMS(String to, String message, String gateway){ Debug.println("ORIGINAL MESSAGE: "+message); boolean bSuccess=false; String sOriginalTo=to+""; //if country prefix already included, don't do anything if(!to.startsWith("+") && !(MedwanQuery.getInstance().getConfigString("cellPhoneCountryPrefix","").length()>0 && to.startsWith(MedwanQuery.getInstance().getConfigString("cellPhoneCountryPrefix","")))){ if(MedwanQuery.getInstance().getConfigInt("cellPhoneRemoveLeadingZero",0)==1){ while(to.startsWith("0")){ to=to.substring(1); } } if(MedwanQuery.getInstance().getConfigString("cellPhoneCountryPrefix","").length()>0){ to=MedwanQuery.getInstance().getConfigString("cellPhoneCountryPrefix","")+to; } } to=to.replace("+", ""); String defaultGateway=MedwanQuery.getInstance().getConfigString("smsgateway",""); if(MedwanQuery.getInstance().getConfigString("cellPhoneCountryPrefix","").length()>0 && !to.startsWith(MedwanQuery.getInstance().getConfigString("cellPhoneCountryPrefix","")) && MedwanQuery.getInstance().getConfigString("smsinternationalgateway","").length()>0) { defaultGateway=MedwanQuery.getInstance().getConfigString("smsinternationalgateway",""); } //Check content filter String smsFilter = SH.cs("labsmsfilter", ""); for(int n=0;n<smsFilter.split(";").length;n++) { if(smsFilter.split(";")[n].length()>0) { String smsKey = smsFilter.split(";")[n].split("\\|")[0]; String smsMessage = smsFilter.split(";")[n].split("\\|")[1]; if(message.contains(smsKey)) { //Send extra message with filter content SendSMS.sendSMS(sOriginalTo, smsMessage.replaceAll("<br>", "\n")); } } } Debug.println("Trying to send message to "+to+" using SMS gateway "+(gateway.length()>0?gateway:defaultGateway)); if(gateway.equalsIgnoreCase("smsglobal") || (gateway.length()==0 && defaultGateway.equalsIgnoreCase("smsglobal"))){ try { HttpClient client = new HttpClient(); Debug.println(MedwanQuery.getInstance().getConfigString("smsglobal.url","https://api.smsglobal.com/http-api.php")+"?action=sendsms" + "&user="+MedwanQuery.getInstance().getConfigString("smsglobal.user","") + "&password="+MedwanQuery.getInstance().getConfigString("smsglobal.password","") + "&from="+MedwanQuery.getInstance().getConfigString("smsglobal.from","") + "&to="+to + "&text="+URLEncoder.encode(message,"utf-8")); PostMethod method = new PostMethod(MedwanQuery.getInstance().getConfigString("smsglobal.url","https://api.smsglobal.com/http-api.php")); Vector<NameValuePair> vNvp = new Vector<NameValuePair>(); vNvp.add(new NameValuePair("action","sendsms")); vNvp.add(new NameValuePair("user",MedwanQuery.getInstance().getConfigString("smsglobal.user",""))); vNvp.add(new NameValuePair("password",MedwanQuery.getInstance().getConfigString("smsglobal.password",""))); vNvp.add(new NameValuePair("from",MedwanQuery.getInstance().getConfigString("smsglobal.from",""))); vNvp.add(new NameValuePair("to",to)); vNvp.add(new NameValuePair("text",URLParamEncoder.encode(message))); NameValuePair[] nvp = new NameValuePair[vNvp.size()]; vNvp.copyInto(nvp); method.setQueryString(nvp); client.executeMethod(method); String sResponse=method.getResponseBodyAsString(); if(sResponse.contains("OK: 0")){ bSuccess=true; } else { Debug.println("SMSGLOBAL ERROR: "+sResponse); } } catch (Exception e) { e.printStackTrace(); } } else if(gateway.equalsIgnoreCase("bulksms") || (gateway.length()==0 && defaultGateway.equalsIgnoreCase("bulksms"))){ try { org.apache.http.client.HttpClient httpclient = org.apache.http.impl.client.HttpClients.createDefault(); String baseurl=SH.cs("bulksms.url","https://api.bulksms.com/v1"); URIBuilder builder = new URIBuilder(baseurl+"/messages"); URI uri = builder.build(); HttpPost req = new HttpPost(uri); String authStr = SH.cs("bulksms.username", "nil") + ":" + SH.cs("bulksms.password", "nil"); String authEncoded = Base64.getEncoder().encodeToString(authStr.getBytes()); req.setHeader("Authorization", "Basic "+authEncoded); req.setHeader("Content-Type", "application/json"); StringEntity reqEntity = new StringEntity("{\"to\": \""+to+"\", \"from\": \""+SH.cs("bulksms.from","OpenClinic")+"\", \"body\": \""+message+"\"}"); req.setEntity(reqEntity); HttpResponse resp = httpclient.execute(req); HttpEntity entity = resp.getEntity(); Debug.println("BULKSMS STATUS CODE: "+resp.getStatusLine().getStatusCode()); if (entity!=null && resp.getStatusLine().getStatusCode()==201) { bSuccess=true; } else { Debug.println("BULKSMS ERROR: "+resp.getStatusLine().getReasonPhrase()); } } catch(Exception e) { e.printStackTrace(); } } else if(gateway.equalsIgnoreCase("releans") || (gateway.length()==0 && defaultGateway.equalsIgnoreCase("releans"))){ try { org.apache.http.client.HttpClient httpclient = org.apache.http.impl.client.HttpClients.createDefault(); String baseurl=SH.cs("releans.url","https://platform.releans.com/api/v2"); URIBuilder builder = new URIBuilder(baseurl+"/message"); builder.setParameter("sender", SH.cs("releans.sender","OpenClinic")); builder.setParameter("mobile", to); builder.setParameter("content", message); URI uri = builder.build(); HttpPost req = new HttpPost(uri); //StringEntity reqEntity = new StringEntity("sender="+SH.cs("releans.sender","OpenClinic")+"&mobile=+"+to+"&content="+message); //req.setEntity(reqEntity); req.setHeader("Authorization", "Bearer "+SH.cs("releans.auth", "nil")); req.setHeader("Content-Type", "text/plain"); HttpResponse resp = httpclient.execute(req); HttpEntity entity = resp.getEntity(); Debug.println("RELEANS STATUS CODE: "+resp.getStatusLine().getStatusCode()); if (entity!=null && resp.getStatusLine().getStatusCode()==201) { bSuccess=true; } else { Debug.println("RELEANS ERROR: "+resp.getStatusLine().getReasonPhrase()); } } catch(Exception e) { e.printStackTrace(); } } else if(gateway.equalsIgnoreCase("experttexting") || (gateway.length()==0 && defaultGateway.equalsIgnoreCase("experttexting"))){ try { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(SH.cs("experttexting.url","https://www.experttexting.com/ExptRestApi/sms/json/Message/Send")); NameValuePair[] nvp = new NameValuePair[7]; nvp[0]=(new NameValuePair("username", SH.cs("experttexting.username", ""))); nvp[1]=(new NameValuePair("api_key", SH.cs("experttexting.api_key", ""))); nvp[2]=(new NameValuePair("api_secret", SH.cs("experttexting.api_secret", ""))); nvp[3]=(new NameValuePair("from", SH.cs("experttexting.from", "OpenClinic"))); nvp[4]=(new NameValuePair("to",to)); nvp[5]=(new NameValuePair("text",message)); nvp[6]=(new NameValuePair("type", SH.cs("experttexting.type", "text"))); method.setQueryString(nvp); int statusCode = client.executeMethod(method); if(statusCode==200 && method.getResponseBodyAsString().contains("message_id")) { Debug.println("EXPERTTEXTING: message delivered to "+to+": "+message); bSuccess=true; } else { Debug.println("EXPERTTEXTING ERROR: "+statusCode+": "+method.getResponseBodyAsString()); } } catch(Exception e) { e.printStackTrace(); } } else if(gateway.equalsIgnoreCase("d7") || (gateway.length()==0 && defaultGateway.equalsIgnoreCase("d7"))){ try { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(MedwanQuery.getInstance().getConfigString("d7.url","https://http-api.d7networks.com/send")); Vector<NameValuePair> vNvp = new Vector<NameValuePair>(); vNvp.add(new NameValuePair("username",MedwanQuery.getInstance().getConfigString("d7.username",""))); vNvp.add(new NameValuePair("password",MedwanQuery.getInstance().getConfigString("d7.password",""))); vNvp.add(new NameValuePair("from",MedwanQuery.getInstance().getConfigString("d7.from","OpenClinic"))); vNvp.add(new NameValuePair("coding",MedwanQuery.getInstance().getConfigString("d7.coding","0"))); vNvp.add(new NameValuePair("to",to)); vNvp.add(new NameValuePair("content",message)); NameValuePair[] nvp = new NameValuePair[vNvp.size()]; vNvp.copyInto(nvp); method.setQueryString(nvp); client.executeMethod(method); String sResponse=method.getResponseBodyAsString(); if(sResponse.contains("Success")){ bSuccess=true; } else { Debug.println("D7 ERROR: "+sResponse); } } catch (Exception e) { e.printStackTrace(); } } else if(gateway.equalsIgnoreCase("africastalking") || (gateway.length()==0 && defaultGateway.equalsIgnoreCase("africastalking"))){ try { AfricasTalking.initialize(SH.cs("africastalking.username",""), SH.cs("africastalking.api_key","")); SmsService sms = AfricasTalking.getService(AfricasTalking.SERVICE_SMS); String[] sTo = {"+"+to}; List<Recipient> resp = null; if(SH.cs("africastalking.senderid","").length()>0) { resp=sms.send(message, SH.cs("africastalking.senderid",""), sTo, true); } else { resp=sms.send(message, sTo, true); } if(resp.size()>0) { Recipient recipient = resp.get(0); if(recipient.statusCode<200) { bSuccess=true; } } if(!bSuccess) { Debug.println("AfricasTalking ERROR"); } } catch (Exception e) { e.printStackTrace(); } } else if(gateway.equalsIgnoreCase("hqsms") || (gateway.length()==0 && defaultGateway.equalsIgnoreCase("hqsms"))){ try { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(MedwanQuery.getInstance().getConfigString("hqsms.url","https://api2.smsapi.com/sms.do")); Vector<NameValuePair> vNvp = new Vector<NameValuePair>(); vNvp.add(new NameValuePair("normalize","1")); vNvp.add(new NameValuePair("username",MedwanQuery.getInstance().getConfigString("hqsms.user","frank.verbeke@post-factum.be"))); vNvp.add(new NameValuePair("password",MedwanQuery.getInstance().getConfigString("hqsms.password","MD5 password from http://ssl.smsapi.com"))); vNvp.add(new NameValuePair("from",MedwanQuery.getInstance().getConfigString("hqsms.from","OpenClinic"))); vNvp.add(new NameValuePair("to",to)); vNvp.add(new NameValuePair("message",message)); NameValuePair[] nvp = new NameValuePair[vNvp.size()]; vNvp.copyInto(nvp); method.setQueryString(nvp); client.executeMethod(method); String sResponse=method.getResponseBodyAsString(); if(sResponse.contains("OK:")){ bSuccess=true; } else { Debug.println("HQSMS ERROR: "+sResponse); } } catch (Exception e) { e.printStackTrace(); } } else if(defaultGateway.equalsIgnoreCase("nokia")){ try{ String sPinCode = MedwanQuery.getInstance().getConfigString("smsPincode","0000"); String sPort= MedwanQuery.getInstance().getConfigString("smsDevicePort","/dev/ttyS20"); int nBaudrate=MedwanQuery.getInstance().getConfigInt("smsBaudrate",115200); System.setProperty("smslib.serial.polling", MedwanQuery.getInstance().getConfigString("smsPolling","false")); SendSMS sendSMS = new SendSMS(); if (message.length() > 160){ Vector vSMSs = new Vector(); vSMSs = splitSMSText(message); Enumeration<String> eSMSs = vSMSs.elements(); String sSMS; while (eSMSs.hasMoreElements()){ sSMS = eSMSs.nextElement(); sendSMS.send("modem.nokia",sPort, nBaudrate, "Nokia", "2690", sPinCode, to, sSMS); } } else { sendSMS.send("modem.nokia", sPort, nBaudrate, "Nokia", "2690", sPinCode, to, message); } bSuccess=true; } catch(Exception m){ } } else if(defaultGateway.equalsIgnoreCase("ccbrt-tigo")){ try{ //************************************** //TODO: CCBRT Tigo communication code * //************************************** } catch(Exception m){ } } else { Debug.println("NO SMS GATEWAY DEFINED!"); } return bSuccess; } public void send(String portname,String port,int baud,String brand,String model,String pin,String destination,String message) throws Exception { OutboundNotification outboundNotification = new OutboundNotification(); SerialModemGateway gateway = new SerialModemGateway(portname, port, baud, brand,model); gateway.setInbound(true); gateway.setOutbound(true); gateway.setProtocol(Protocols.PDU); gateway.setSimPin(pin); Service.getInstance().setOutboundMessageNotification(outboundNotification); Service.getInstance().addGateway(gateway); Service.getInstance().startService(); OutboundMessage msg = new OutboundMessage(destination, message); Service.getInstance().sendMessage(msg); gateway.stopGateway(); Service.getInstance().stopService(); Service.getInstance().removeGateway(gateway); } public class OutboundNotification implements IOutboundMessageNotification { public void process(AGateway gateway, OutboundMessage msg) { } } public static Vector<String> splitSMSText(String sResult){ Vector<String> vSMSs = new Vector<String>(); String[] aLines = sResult.split("\n"); if (aLines[0].length() < 160) { int iMsgsSend = 1; String sMsgToSend = aLines[0]+" (" + iMsgsSend + ")"; int iLabLineToAdd = 1; int iLabLinesSent = 0; String sNextLabLine; while (iLabLinesSent < aLines.length - 1) { // eg from 0 to 2 sNextLabLine = aLines[iLabLineToAdd]; if (sMsgToSend.length() + sNextLabLine.length() <= 160) { sMsgToSend = sMsgToSend + "\n" + sNextLabLine; iLabLineToAdd = iLabLineToAdd + 1; iLabLinesSent = iLabLinesSent + 1; if (iLabLinesSent == aLines.length - 1){ // last line vSMSs.add(sMsgToSend); } } else { // Longer than 160 ==>> Send earlier one vSMSs.add(sMsgToSend); iMsgsSend = iMsgsSend + 1; sMsgToSend = aLines[0]+" (" + iMsgsSend + ")"; } } } return vSMSs; } }
package com.creactiviti.spring.boot.starter.graphql; import graphql.schema.GraphQLInterfaceType; import graphql.schema.GraphQLList; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLType; import graphql.schema.GraphQLTypeReference; /** * This class consists exclusively of static methods that operate on or return * GraphQL types. * * @author Arik Cohen * @since Feb 10, 2018 */ public final class Types { private Types () {} public static GraphQLInterfaceType.Builder interfaceTypeBuilder () { return new GraphQLInterfaceType.Builder (); } public static GraphQLObjectType.Builder objectTypeBuilder () { return new GraphQLObjectType.Builder(); } public static GraphQLTypeReference ref (String aName) { return new GraphQLTypeReference(aName); } public static GraphQLList list (GraphQLType aWrappedType) { return new GraphQLList(aWrappedType); } }
package model; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import jade.core.AID; import jade.core.Agent; import jade.core.behaviours.CyclicBehaviour; import jade.lang.acl.ACLMessage; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class ManagerAgent extends Agent implements DecisionAgent { private AID eligibility, provider, service, facility; private boolean elig, prov, serv; private boolean denied; private int demo_step = 0; private KieSession kSession; private FactHandle agentFH; public AID getEligibility() { return eligibility; } public void setEligibility(AID eligibility) { this.eligibility = eligibility; } public AID getProvider() { return provider; } public void setProvider(AID provider) { this.provider = provider; } public AID getService() { return service; } public void setService(AID service) { this.service = service; } public AID getFacility() { return facility; } public void setFacility(AID facility) { this.facility = facility; } public boolean isElig() { return elig; } public void setElig(boolean elig) { this.elig = elig; } public boolean isProv() { return prov; } public void setProv(boolean prov) { this.prov = prov; } public boolean isServ() { return serv; } public void setServ(boolean serv) { this.serv = serv; } public int getDemo_step() { return demo_step; } public void setDemo_step(int demo_step) { this.demo_step = demo_step; } public FactHandle getAgentFH() { return agentFH; } public void setAgentFH(FactHandle agentFH) { this.agentFH = agentFH; } public boolean isDenied() { return denied; } public void setDenied(boolean denied) { this.denied = denied; } public void deny() { System.out.println("Prior Authorization Denied. For request #" + "2"); setElig(false); setProv(false); setServ(false); setDenied(true); } @SuppressWarnings("restriction") private static String nodeListToString(NodeList nodes) throws TransformerException { DOMSource source = new DOMSource(); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); for (int i = 0; i < nodes.getLength(); ++i) { source.setNode(nodes.item(i)); transformer.transform(source, result); } return writer.toString(); } protected void setup() { // Start KieSession for drools KieServices ks = KieServices.Factory.get(); KieContainer kContainer = ks.getKieClasspathContainer(); this.kSession = kContainer.newKieSession("ksession-manager"); // Adding agent to controller session DecisionAgent.kSession2.insert(this); // Register the manager in the yellow pages registerAgent(this, getAID(), "manager"); // Try receiving message addBehaviour(new Messaging(this.kSession, this)); } // Drools calls this when facility sends form @SuppressWarnings("restriction") public void breakdownForm(String str_xml) { // Break apart form // Send parts to approriate agents // i.e. patient_info xml send to Elig. agent as string in ACL Message try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); InputSource inputData = new InputSource(); inputData.setCharacterStream(new StringReader(str_xml)); Document doc = dBuilder.parse(inputData); doc.getDocumentElement().normalize(); NodeList patientInfo = doc.getElementsByTagName("patient_info"); NodeList physicianInfo = doc.getElementsByTagName("physician_info"); NodeList medicalInfo = doc.getElementsByTagName("medical_info"); NodeList insuranceInfo = doc.getElementsByTagName("insurance_info"); // This function will send 3 ACLMessage total String eligibilityInfoMessage = "<info>\n" + nodeListToString(patientInfo) + "\n" + nodeListToString(medicalInfo) + "\n" + nodeListToString(physicianInfo) + "\n" + "</info>"; String providerInfoMessage = "<info>\n" + nodeListToString(physicianInfo) + "\n" + nodeListToString(medicalInfo) + "\n" + "</info>"; String serviceInfoMessage = "<info>\n" + nodeListToString(patientInfo) + "\n" + nodeListToString(medicalInfo) + "\n" + "</info>"; quickMessage(getEligibility(),this,eligibilityInfoMessage,"initial-info"); quickMessage(getProvider(),this,providerInfoMessage,"initial-info"); quickMessage(getService(),this,serviceInfoMessage,"initial-info"); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings("restriction") public void breakdownClinicalDoc(String str_xml) { // Break apart form // Send parts to approriate agents // i.e. patient_info xml send to Elig. agent as string in ACL Message try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); InputSource inputData = new InputSource(); inputData.setCharacterStream(new StringReader(str_xml)); Document doc = dBuilder.parse(inputData); doc.getDocumentElement().normalize(); NodeList medicalInfo = doc.getElementsByTagName("medical_info"); String serviceInfoMessage = nodeListToString(medicalInfo); quickMessage(getService(),this,serviceInfoMessage,"clinical-report"); } catch (Exception e) { e.printStackTrace(); } } public void nextStep() { demo_step++; this.kSession.update(agentFH, this); this.kSession.fireAllRules(); } private class Messaging extends CyclicBehaviour { private KieSession kSession; public Messaging(KieSession k, Agent a) { super(a); kSession = k; setAgentFH(kSession.insert(myAgent)); kSession.fireAllRules(); // Find eligibility while (getEligibility() == null) { setEligibility(findAgent(myAgent, "eligibility")); } // Find provider while (getProvider() == null) { setProvider(findAgent(myAgent, "provider")); } // Find service while (getService() == null) { setService(findAgent(myAgent, "service")); } // Find facility while (getFacility() == null) { setFacility(findAgent(myAgent, "facility")); } } // Cycles forever public void action() { // Wait for message ACLMessage msg = myAgent.blockingReceive(); if (msg != null) { kSession.insert(msg); kSession.fireAllRules(); } else { block(); } } } }
// ********************************************************** // 1. 제 목: // 2. 프로그램명: CommunityAdminRoomBean.java // 3. 개 요: // 4. 환 경: JDK 1.3 // 5. 버 젼: 0.1 // 6. 작 성: Administrator 2003-08-29 // 7. 수 정: // // ********************************************************** package com.ziaan.community; import java.sql.PreparedStatement; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.Vector; import com.ziaan.library.ConfigSet; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.DataBox; import com.ziaan.library.ErrorManager; import com.ziaan.library.FormatDate; import com.ziaan.library.ListSet; import com.ziaan.library.RequestBox; import com.ziaan.library.SQLString; import com.ziaan.library.StringManager; /** * @author Administrator * * To change the template for this generated type comment go to * Window > Preferences > Java > Code Generation > Code and Comments */ public class CommunityAdminRoomBean { private ConfigSet config; private static int row=10; // private String v_type = "PQ"; // private static final String FILE_TYPE = "p_file"; // 파일업로드되는 tag name // private static final int FILE_LIMIT = 1; // 페이지에 세팅된 파일첨부 갯수 public CommunityAdminRoomBean() { try { config = new ConfigSet(); row = Integer.parseInt(config.getProperty("page.bulletin.row") ); // 이 모듈의 페이지당 row 수를 셋팅한다 row = 10; // 강제로 지정 } catch( Exception e ) { e.printStackTrace(); } } /** * 커뮤니티 조회리스트 * @param box receive from the form object and session * @return ArrayList 커뮤니티 조회리스트 * @throws Exception */ public ArrayList selectList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = new ArrayList(); String sql = ""; // String sql1 = ""; // String sql2 = ""; DataBox dbox = null; String v_searchtext = box.getString("p_searchtext"); String v_select = box.getString("p_select"); String v_orderby = box.getStringDefault("p_orderby","cmu_nm"); String v_if_close_fg = box.getStringDefault("p_if_close_fg","1"); int v_pageno = box.getInt("p_pageno"); // String s_userid = box.getSession("userid"); // String s_name = box.getSession("name"); try { connMgr = new DBConnectionManager(); // sql = " select a.*,rownum rowseq " sql = "select a.cmuno cmuno , a.cmu_nm cmu_nm , a.in_method_fg in_method_fg , a.search_fg search_fg" + " , a.data_passwd_fg data_passwd_fg , a.display_fg display_fg , a.type_l type_l ,a.type_m type_m" + " , a.intro intro , a.img_path img_path , a.layout_fg layout_fg , a.html_skin_fg html_skin_fg" + " , a.read_cnt read_cnt , a.member_cnt member_cnt , a.close_fg close_fg" + " , a.close_reason close_reason , a.close_dte close_dte , a.close_userid close_userid" + " , a.hold_fg hold_fg , a.accept_dte accept_dte , a.accept_userid accept_userid , a.register_dte register_dte" + " , a.register_userid register_userid , a.modifier_dte modifier_dte, a.modifier_userid modifier_userid " + " , b.userid userid, b.kor_name kor_name , c.codenm grade_nm,d.codenm type_l_nm,e.codenm type_m_nm" + " from tz_cmubasemst a " + " ,(select cmuno,userid,kor_name,grade from tz_cmuusermst where grade='01' and close_fg='1') b" + " ,(select cmuno cmuno,grcode grcode,kor_nm codenm from tz_cmugrdcode) c" + " ,(select code code,codenm codenm from tz_code where gubun='0052' and levels=1)d" + " ,(select code code,codenm codenm from tz_code where gubun='0052' and levels=2)e" + " where a.cmuno = b.cmuno" + " and b.cmuno = c.cmuno" + " and a.type_l = d.code" + " and a.type_m = e.code" + " and b.grade = c.grcode" + " and a.close_fg = '" +v_if_close_fg + "'" ; if ( !v_searchtext.equals("") ) { // 검색어가 있으면 if ( v_select.equals("cmu_nm")) sql += " and lower(a.cmu_nm) like lower ( " + StringManager.makeSQL("%" + v_searchtext + "%") + ")"; if ( v_select.equals("intro")) sql += " and lower(a.intro) like lower ( " + StringManager.makeSQL("%" + v_searchtext + "%") + ")"; if ( v_select.equals("kor_name")) sql += " and lower(b.kor_name) like lower ( " + StringManager.makeSQL("%" + v_searchtext + "%") + ")"; } if ( v_orderby.equals("cmu_nm")) sql += " order by a.cmu_nm asc"; if ( v_orderby.equals("kor_name")) sql += " order by b.kor_name asc"; if ( v_orderby.equals("accept_dte"))sql += " order by a.accept_dte asc"; // sql += " ) a"; ls = connMgr.executeQuery(sql); ls.setPageSize(row); // 페이지당 row 갯수를 세팅한다 ls.setCurrentPage(v_pageno); // 현재페이지번호를 세팅한다. int total_page_count = ls.getTotalPage(); // 전체 페이지 수를 반환한다 int total_row_count = ls.getTotalCount(); // 전체 row 수를 반환한다 while ( ls.next() ) { dbox = ls.getDataBox(); dbox.put("d_dispnum" , new Integer(total_row_count - ls.getRowNum() + 1)); dbox.put("d_totalpage", new Integer(total_page_count)); dbox.put("d_rowcount" , new Integer(row)); list.add(dbox); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** * 커뮤니티 거부 및 폐쇄 /승인처리 * @param box receive from the form object and session * @return isOk 1:insert success,0:insert fail * @throws Exception */ public int updateCommunity(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; int isOk = 0; // int v_seq = 0; String v_token_cmuno = box.getString("p_token_cmuno"); Vector v_cbx_cmuno = new Vector(); String v_close_fg = box.getString("p_close_fg"); //String v_content = box.getString("p_content"); String s_userid = box.getSession("userid"); // String s_name = box.getSession("name"); // v_close_fg 0.신청 1.승인 2.폐쇄 3.거부 try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); StringTokenizer stok = new StringTokenizer(v_token_cmuno, "/"); String[] sTokens = new String[stok.countTokens()]; for ( int i = 0; stok.hasMoreElements();i++ ) { sTokens[i] = ((String)stok.nextElement() ).trim(); v_cbx_cmuno.addElement(sTokens[i]); } for ( int i = 0;i<v_cbx_cmuno.size();i++ ) { String v_tmp_cmuno = (String)v_cbx_cmuno.elementAt(i) ; if ( "1".equals(v_close_fg)) { sql =" update tz_cmubasemst set close_fg =? " + " , accept_dte = to_char(sysdate,'YYYYMMDDHH24MISS') " + " , accept_userid =? " + " where cmuno = ?" ; pstmt = connMgr.prepareStatement(sql); pstmt.setString(1, v_close_fg );// 구분 pstmt.setString(2, s_userid );// 처리자 pstmt.setString(3, v_tmp_cmuno );// 커뮤니티번호 } else { sql =" update tz_cmubasemst set close_fg =? " + " , close_dte =to_char(sysdate,'YYYYMMDDHH24MISS') " + " , close_userid =? " + " where cmuno = ?" ; pstmt = connMgr.prepareStatement(sql); pstmt.setString(1, v_close_fg );// 구분 pstmt.setString(2, s_userid );// 처리자 pstmt.setString(3, v_tmp_cmuno );// 커뮤니티번호 } isOk = pstmt.executeUpdate(); if ( pstmt != null ) { pstmt.close(); } // if ( "1".equals(v_close_fg) ) // MileageManager.insertMileage("00000000000000000011", getRegisterUserId(v_tmp_cmuno)); // else if ( "3".equals(v_close_fg) ) // MileageManager.insertMileage("00000000000000000012", getRegisterUserId(v_tmp_cmuno)); } if ( isOk > 0 ) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql - > " +FormatDate.getDate("yyyyMMdd") + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** * 인기커뮤니티 관리 * @param box receive from the form object and session * @return isOk 1:insert success,0:insert fail * @throws Exception */ public int updateHold(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; int isOk = 0; // int v_seq = 0; Vector v_cmuno = box.getVector("p_cmuno"); Vector v_hold_fg = box.getVector("p_hold_fg"); // String s_userid = box.getSession("userid"); // String s_name = box.getSession("name"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); for ( int i = 0;i<v_cmuno.size();i++ ) { String v_tmp_cmuno = (String)v_cmuno.elementAt(i) ; String v_tmp_hold = (String)v_hold_fg.elementAt(i) ; sql =" update tz_cmubasemst set hold_fg =? " + " where cmuno = ?" ; pstmt = connMgr.prepareStatement(sql); pstmt.setString(1, v_tmp_hold );// 인기구분 pstmt.setString(2, v_tmp_cmuno );// 커뮤니티번호 isOk = pstmt.executeUpdate(); if ( pstmt != null ) { pstmt.close(); } } if ( isOk > 0 ) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql - > " +FormatDate.getDate("yyyyMMdd") + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** * 일반메일전송 * @param box receive from the form object and session * @return isOk 1:insert success,0:insert fail * @throws Exception */ public int sendMail(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; String sql1 = ""; int isOk = 1; // int v_seq = 0; String v_token_cmuno = box.getString("p_token_cmuno"); // String v_cmuno = box.getString("p_close_fg"); Vector v_cbx_cmuno = new Vector(); String v_title = box.getString("p_title"); String v_intro = StringManager.replace(box.getString("p_content"),"<br > ","\n"); String s_userid = box.getSession("userid"); // String s_name = box.getSession("name"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); StringTokenizer stok = new StringTokenizer(v_token_cmuno, "/"); String[] sTokens = new String[stok.countTokens()]; for ( int i = 0; stok.hasMoreElements();i++ ) { sTokens[i] = ((String)stok.nextElement() ).trim(); v_cbx_cmuno.addElement(sTokens[i]); } // 발신자 이메일 String v_tmp_send_email= ""; sql1 = "select email from tz_member where userid = '" +s_userid + "' "; ls = connMgr.executeQuery(sql1); while ( ls.next() ) v_tmp_send_email = ls.getString(1); for ( int i = 0;i<v_cbx_cmuno.size();i++ ) { String v_tmp_cmuno = (String)v_cbx_cmuno.elementAt(i) ; // 커뮤니티명구하기 String v_tmp_cmu_nm= ""; sql1 = "select cmu_nm from tz_cmubasemst where cmuno = '" +v_tmp_cmuno + "' "; ls = connMgr.executeQuery(sql1); while ( ls.next() ) v_tmp_cmu_nm = ls.getString(1); // 일련번호 구하기 int v_mailno=0; sql1 = "select nvl(max(MAILNO), 0) from TZ_CMUMAIL "; ls = connMgr.executeQuery(sql1); while ( ls.next() ) v_mailno = ls.getInt(1); sql =" insert into TZ_CMUMAIL ( mailno, userid, kor_nm, recv_email" + " ,cmuno, cmu_nm, SEND_USERID,send_email, title, content" + " ,loc_fg,loc_nm,regster_dte, send_fg)" + " values (?,?,?,?" + " ,?,?,?,?,?,?" + " ,?,?,to_char(sysdate,'YYYYMMDDHH24MISS'),'N')" ; pstmt = connMgr.prepareStatement(sql); sql1 = "select a.cmuno,b.cmu_nm,a.userid,a.kor_name,a.email from tz_cmuusermst a,tz_cmubasemst b where a.cmuno = b.cmuno and a.cmuno = '" +v_tmp_cmuno + "' "; ls = connMgr.executeQuery(sql1); while ( ls.next() ) { v_mailno =v_mailno +1; pstmt.setInt (1, v_mailno );// 일련번호 pstmt.setString(2, ls.getString(3) );// 수신자아이디 pstmt.setString(3, ls.getString(4) );// 수신자명 pstmt.setString(4, ls.getString(5) );// 수신자이메일 pstmt.setString(5, v_tmp_cmuno );// 커뮤니티먼호 pstmt.setString(6, v_tmp_cmu_nm );// 커뮤니티명 pstmt.setString(7 ,s_userid );// 발신자아이디 pstmt.setString(8 ,v_tmp_send_email );// 발신자이메일 pstmt.setString(9 , v_title );// 제목 pstmt.setString(10, v_intro );// 제목 pstmt.setString(11, "5" );// 구분 pstmt.setString(12, "커뮤니티 승인관련" );// 구분명 isOk = pstmt.executeUpdate(); if ( pstmt != null ) { pstmt.close(); } // sql1 = "select content from TZ_CMUMAIL where mailno = '" +v_mailno + "'"; // connMgr.setOracleCLOB(sql1, v_intro); if ( isOk > 0 ) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } } }// end for } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql - > " +FormatDate.getDate("yyyyMMdd") + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** * 커뮤니티 개설자 가져오기 * @param box receive from the form object and session * @return isOk 1:insert success,0:insert fail * @throws Exception */ public String getRegisterUserId(String p_cmuno) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; String v_reguserid = ""; try { connMgr = new DBConnectionManager(); sql = "select register_userid from tz_cmubasemst where cmuno = " + SQLString.Format(p_cmuno) + " "; ls = connMgr.executeQuery(sql); while ( ls.next() ) v_reguserid = ls.getString("register_userid"); } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, null, sql); throw new Exception("sql - > " +FormatDate.getDate("yyyyMMdd") + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return v_reguserid; } }
package controller.command.imlementation; import controller.command.Command; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ShowTaskCommand implements Command<ResultSet,Integer> { public ResultSet execute(Connection connection, Integer request) throws SQLException { Statement statement = connection.createStatement(); String query = "SELECT Task_Number, concat(Task_description, ' - employee:'), LastName, FirstName FROM Task" +" Inner JOIN Employee on Employee.Employee_Number= Task.Employee_Number"; if(request!=null){ query+=" WHERE Task.Employee_Number = "+ request; } return statement.executeQuery(query); } }
package javaProject; import java.util.ArrayList; import java.util.HashMap; public class ProteinProcessor { HashMap<String, ArrayList<Integer>> hm = new HashMap<String, ArrayList<Integer>>(20); String[] aminoKeys = {"G","A","V","L","I","M","P","F","W","S","T","N","Q","Y","C","R","H" ,"K","E","D"}; ArrayList<Integer> printArray; String[] output; ArrayList<Integer> G = new ArrayList<Integer>(); ArrayList<Integer> A = new ArrayList<Integer>(); ArrayList<Integer> V = new ArrayList<Integer>(); ArrayList<Integer> L = new ArrayList<Integer>(); ArrayList<Integer> I = new ArrayList<Integer>(); ArrayList<Integer> M = new ArrayList<Integer>(); ArrayList<Integer> P = new ArrayList<Integer>(); ArrayList<Integer> F = new ArrayList<Integer>(); ArrayList<Integer> W = new ArrayList<Integer>(); ArrayList<Integer> S = new ArrayList<Integer>(); ArrayList<Integer> T = new ArrayList<Integer>(); ArrayList<Integer> N = new ArrayList<Integer>(); ArrayList<Integer> Q = new ArrayList<Integer>(); ArrayList<Integer> Y = new ArrayList<Integer>(); ArrayList<Integer> C = new ArrayList<Integer>(); ArrayList<Integer> R = new ArrayList<Integer>(); ArrayList<Integer> H = new ArrayList<Integer>(); ArrayList<Integer> K = new ArrayList<Integer>(); ArrayList<Integer> E = new ArrayList<Integer>(); ArrayList<Integer> D = new ArrayList<Integer>(); int seqlength = 0; public ProteinProcessor(String seq) { hm.put("G", G); hm.put("A", A); hm.put("V", V); hm.put("L", L); hm.put("I", I); hm.put("M", M); hm.put("P", P); hm.put("F", F); hm.put("W", W); hm.put("S", S); hm.put("T", T); hm.put("N", N); hm.put("Q", Q); hm.put("Y", Y); hm.put("C", C); hm.put("R", R); hm.put("H", H); hm.put("K", K); hm.put("E", E); hm.put("D", D); String[] sequence = seq.toUpperCase().split(""); for (int i = 0; i < sequence.length; i++) { //System.out.print(i + " "); if(!sequence[i].equals(" ")) { hm.get(sequence[i]).add(i); seqlength++; } } } public String toString() { String result = "" ; for (int i =0; i < seqlength; i++) { if( i >= 10 && i%10 == 0) { result += " "; } if ( i >= 40 && i%40 == 0) { result += "\n"; } result += getKeyWhere(i); } return result; } public int[] getResidueCounts() { int[] results = new int[20]; for ( int i = 0; i < hm.size(); i ++) { results[i] = hm.get(aminoKeys[i]).size(); } return results; } public String getKeyWhere(int searched) { ArrayList<Integer> x; String result = ""; for (int i = 0; i < aminoKeys.length; i++) { x = hm.get(aminoKeys[i]); for(int j = 0; j < x.size(); j++ ) { if (searched == x.get(j)) { result = aminoKeys[i]; break; } } } return result; } public int getSeqLength() { return seqlength; } }
package com.thoughtworks.maomao.orm; import com.google.common.base.Charsets; import com.google.common.io.Files; import org.junit.AfterClass; import org.junit.BeforeClass; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.List; public abstract class AbstractNoamTest { private static Connection connection; @BeforeClass public static void initDB() throws Exception { Class.forName("org.h2.Driver"); connection = DriverManager. getConnection("jdbc:h2:~/test", "sa", ""); } public void setUp() throws SQLException { Statement statement = connection.createStatement(); try { File sqlFile = new File(getClass().getResource("/com/thoughtworks/maomao/orm/create.sql").getFile()); if (sqlFile.exists()) { List<String> sqls = Files.readLines(sqlFile, Charsets.UTF_8); for (String sql : sqls) { statement.execute(sql); } } } catch (IOException e) { e.printStackTrace(); } statement.close(); } @AfterClass public static void close() throws SQLException { connection.close(); } }
package com.company.task; import com.company.command.Command; import java.sql.SQLException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class CommandQueue { private final BlockingQueue<Command> queue; public CommandQueue(int capacity) { this.queue = new LinkedBlockingQueue<>(capacity); } public void add(Command command) throws InterruptedException { queue.put(command); } public void remove() throws InterruptedException, SQLException { Command command = queue.take(); command.execute(); } }
import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class Day16 { public static void main(String[] args) { try { File tickets = new File("Day16.txt"); Scanner sc = new Scanner(tickets); List<String> validRangeList = new ArrayList<>(); List<String> nearbyTicketList = new ArrayList<>(); while (sc.hasNextLine()) { String input = sc.nextLine(); if (!input.equals("")) validRangeList.add(input); else break; } sc.nextLine(); String myTicket = sc.nextLine(); sc.nextLine(); sc.nextLine(); while (sc.hasNextLine()) nearbyTicketList.add(sc.nextLine()); System.out.println(PartOne(validRangeList, myTicket, nearbyTicketList)); } catch (FileNotFoundException e) { System.out.println("An error occurred."); e.printStackTrace(); } } private static long PartOne(List<String> validRangeList, String myTicket, List<String> nearbyTicketList) { int result = 0; SortedSet<Integer> validNumbers = new TreeSet<>(); List<String> validTickets = new ArrayList<>(); for (String line : validRangeList) { String[] ranges = line.split(": ")[1].split(" or "); for (String range : ranges) { for (int i = Integer.parseInt(range.split("-")[0]); i <= Integer.parseInt(range.split("-")[1]); i++) validNumbers.add(i); } } for (String ticket : nearbyTicketList){ String[] numsToSearch = ticket.split(","); boolean valid = true; for (String toSearch : numsToSearch) { if (!validNumbers.contains(Integer.parseInt(toSearch))) { valid = false; result += Integer.parseInt(toSearch); } } if (valid) validTickets.add(ticket); } System.out.println(result); return PartTwo(validRangeList, myTicket, validTickets); } private static long PartTwo(List<String> validRangeList, String myTicket, List<String> nearbyTicketList) { long result = 1; List<String[]> ranges = new ArrayList<>(); for (String rangeString : validRangeList) ranges.add(rangeString.split(": ")[1].split(" or ")); boolean[][] nearbyTicketsValid = new boolean[validRangeList.size()][validRangeList.size()]; for (boolean[] booleans : nearbyTicketsValid) Arrays.fill(booleans, true); for (String s : nearbyTicketList) { String[] numsToCheck = s.split(","); for (int j = 0; j < numsToCheck.length; j++) { for (int k = 0; k < ranges.size(); k++) { int numToCheck = Integer.parseInt(numsToCheck[j]); int rangeOne0 = Integer.parseInt(ranges.get(k)[0].split("-")[0]); int rangeOne1 = Integer.parseInt(ranges.get(k)[0].split("-")[1]); int rangeTwo0 = Integer.parseInt(ranges.get(k)[1].split("-")[0]); int rangeTwo1 = Integer.parseInt(ranges.get(k)[1].split("-")[1]); if (!(numToCheck >= rangeOne0 && numToCheck <= rangeOne1) && !(numToCheck >= rangeTwo0 && numToCheck <= rangeTwo1)) nearbyTicketsValid[j][k] = false; } } } SortedMap<Integer, Integer> orderOfColumns = new TreeMap<>(); for (int i = 0; i < nearbyTicketsValid.length; i++) { int count = 0; for (int j = 0; j < nearbyTicketsValid[i].length; j++) { if (nearbyTicketsValid[i][j]) count++; } orderOfColumns.put(count, i); } SortedMap<Integer, Integer> solvedFields = solveFields(nearbyTicketsValid, orderOfColumns); for (int i = 0; i < 20; i++) { String[] myTicketValues = myTicket.split(","); if (validRangeList.get(solvedFields.get(i)).startsWith("departure")) result *= Long.parseLong(myTicketValues[i]); } return result; } private static SortedMap<Integer, Integer> solveFields(boolean[][] validPairs, SortedMap<Integer, Integer> orderOfColumns) { SortedMap<Integer, Integer> solvedFields = new TreeMap<>(); for (int i = orderOfColumns.firstKey(); i <= orderOfColumns.lastKey(); i++) { for (int j = 0; j < validPairs[orderOfColumns.get(i)].length; j++) { if (validPairs[orderOfColumns.get(i)][j]) { solvedFields.put(orderOfColumns.get(i), j); for (int k = 0; k < validPairs.length; k++) validPairs[k][j] = false; break; } } } return solvedFields; } }
package com.github.niwaniwa.whitebird.core.command; import java.util.ArrayList; import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import com.github.niwaniwa.whitebird.core.player.WhiteBirdPlayer; public class SettingCommand implements BaseCommand, TabCompleter { @Override public boolean runCommand(CommandSender sender, Command command, String[] args) { if(!(sender instanceof Player)){ sender.sendMessage(pre+"ゲーム内から実行してください"); return true; } Player player = (Player) sender; WhiteBirdPlayer whitePlayer = WhiteBirdPlayer.getPlayer(player); if(args.length==0){ sender.sendMessage("§6----- 設定内容 -----"); sender.sendMessage("§6Chat : "+whitePlayer.isChat()); sender.sendMessage("§6ConnectionMessage : "+whitePlayer.isConnectionMsg()); return true; } else if(args.length >= 1){ if(args.length == 1 ||args[0].equalsIgnoreCase("help")){ help(sender); return true; } if(args[0].equalsIgnoreCase("chat")){ if(checkString(args[1])){ sender.sendMessage("§6Chat : "+whitePlayer.isChat() +" --> "+args[1]); whitePlayer.setChat(getBoolean(args[1])); return true; } } else if(args[0].equalsIgnoreCase("ConnectionMessage")){ if(checkString(args[1])){ sender.sendMessage("§6ConnectionMessage : "+whitePlayer.isConnectionMsg() +" --> "+args[1]); whitePlayer.setConnectionMsg(getBoolean(args[1])); return true; } } help(sender); return true; } return false; } @Override public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) { List<String> tab = new ArrayList<String>(); if(args.length==1){ tab.add("help"); tab.add("chat"); tab.add("ConnectionMessage"); return tab; } else if(args.length == 2){ tab.clear(); tab.add("true"); tab.add("false"); } return null; } private boolean checkString(String str){ if(str.equalsIgnoreCase("true") || str.equalsIgnoreCase("false")){ return true; } return false; } private void help(CommandSender sender){ sender.sendMessage("§6----- Help -----"); sender.sendMessage("§6/setting : 現在の設定を確認"); sender.sendMessage("§6/setting help : ヘルプを表示"); sender.sendMessage("§6/setting chat <true or false> : チャットのオン、オフ"); sender.sendMessage("§6/setting ConnectionMessage <true or false> : サーバー接続関係のオン、オフ"); } private boolean getBoolean(String str){ if(str.equalsIgnoreCase("true")){ return true; } else if(str.equals("false")){ return false; } else { return false; } } }
package com.atguigu.mr.custominputformat; import java.io.IOException; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; /* * FileInputFormat<K, V>: key-value指RR所读取的k-v类型 */ public class MyInputFormat extends FileInputFormat<Text, BytesWritable>{ // 控制每个文件只切1片 @Override protected boolean isSplitable(JobContext context, Path filename) { return false; } // 提供RecordReader @Override public RecordReader<Text, BytesWritable> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { return new MyRecordReader(split,context); } }
package com.olga_o.course_work.musicplayer; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.BottomSheetDialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; public class SettingsBottomSheet extends BottomSheetDialogFragment { private BottomSheetListener mListener; RadioGroup radioGroup; RecyclerView_Adapter adapter; public void setAdapter(RecyclerView_Adapter adapter) { this.adapter = adapter; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.settings_bottom_sheet, container, false); RadioButton file_nameRadioButton = (RadioButton) v.findViewById(R.id.radioButtonFileName); file_nameRadioButton.setOnClickListener(radioButtonClickListener); file_nameRadioButton.setChecked(adapter.file_name); RadioButton titleRadioButton = (RadioButton) v.findViewById(R.id.radioButtonTitle); titleRadioButton.setOnClickListener(radioButtonClickListener); titleRadioButton.setChecked(adapter.title); RadioButton artistRadioButton = (RadioButton) v.findViewById(R.id.radioButtonArtist); artistRadioButton.setOnClickListener(radioButtonClickListener); artistRadioButton.setChecked(adapter.artist); RadioButton albumRadioButton = (RadioButton) v.findViewById(R.id.radioButtonAlbum); albumRadioButton.setOnClickListener(radioButtonClickListener); albumRadioButton.setChecked(adapter.album); Button button1 = v.findViewById(R.id.accept_settings); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.onButtonClicked("Button 1 clicked"); dismiss(); } }); return v; } public interface BottomSheetListener { void onButtonClicked(String text); } @Override public void onAttach(Context context) { super.onAttach(context); try { mListener = (BottomSheetListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement BottomSheetListener"); } } View.OnClickListener radioButtonClickListener = new View.OnClickListener() { @Override public void onClick(View v) { RadioButton rb = (RadioButton) v; switch (rb.getId()) { case R.id.radioButtonFileName: adapter.file_name = !adapter.file_name; rb.setChecked(adapter.file_name); break; case R.id.radioButtonTitle: adapter.title = !adapter.title; rb.setChecked(adapter.title); break; case R.id.radioButtonArtist: adapter.artist = !adapter.artist; rb.setChecked(adapter.artist); break; case R.id.radioButtonAlbum: adapter.album = !adapter.album; rb.setChecked(adapter.album); break; default: break; } } }; }
package io.github.futurewl.imooc.java.authority.management.dto; import com.google.common.collect.Lists; import io.github.futurewl.imooc.java.authority.management.model.SysDept; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.springframework.beans.BeanUtils; import java.util.List; /** * 功能描述:部门层级转换对象 * * @author weilai create by 2019-04-19:14:28 * @version 1.0 */ @Getter @Setter @ToString public class DeptLevelDto extends SysDept { private List<DeptLevelDto> deptList = Lists.newArrayList(); public static DeptLevelDto adapt(SysDept dept) { DeptLevelDto dto = new DeptLevelDto(); BeanUtils.copyProperties(dept, dto); return dto; } }
/** */ package iso20022.impl; import org.eclipse.emf.ecore.EClass; import iso20022.ISO15022MessageSet; import iso20022.Iso20022Package; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>ISO15022 Message Set</b></em>'. * <!-- end-user-doc --> * * @generated */ public class ISO15022MessageSetImpl extends IndustryMessageSetImpl implements ISO15022MessageSet { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ISO15022MessageSetImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Iso20022Package.eINSTANCE.getISO15022MessageSet(); } } //ISO15022MessageSetImpl
package codesquad.dto; import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.util.List; @Data @Slf4j public class BasketDTO { private Long id; private Long ea; public List<BasketDTO> updateBasket(List<BasketDTO> basketDtoList) { BasketDTO basketDto = basketDtoList.stream().filter(bDto -> bDto.getId() == id).findFirst().orElse(null); if (basketDto == null) { basketDtoList.add(this); return basketDtoList; } basketDto.setEa(basketDto.getEa() + ea); return basketDtoList; } }
package za.co.vzap.dao.interfaces; import java.sql.SQLException; import za.co.vzap.dto.BookingDTO; import za.co.vzap.dto.ClientDTO; import za.co.vzap.dto.DepartmentDTO; import za.co.vzap.dto.EquipmentDTO; import za.co.vzap.dto.RoomEquipmentDTO; import za.co.vzap.dto.WaitingListDTO; public interface MySqlIInsertDAO { public BookingDTO insertBooking(BookingDTO bookingObject) throws SQLException; public ClientDTO insertClient(ClientDTO clientObject) throws SQLException; public DepartmentDTO insertDepartment(DepartmentDTO departmentObject) throws SQLException; public EquipmentDTO insertEquipment(EquipmentDTO equipmentObject) throws SQLException; public WaitingListDTO insertWaitingList(WaitingListDTO waitingListObject) throws SQLException; public RoomEquipmentDTO insertRoomEquipment(RoomEquipmentDTO roomEquipmentObject) throws SQLException; public String RoomCancellations(String roomName,BookingDTO bookingObject) throws SQLException; //help with adding equipment to a room }
package com.example.okta_cust_sign_in.util; import android.app.Activity; import android.view.inputmethod.InputMethodManager; public class CommonUtil { public static void hideSoftKeyboard(Activity activity) { if(activity == null) return; InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService( Activity.INPUT_METHOD_SERVICE); if(activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) { inputMethodManager.hideSoftInputFromWindow( activity.getCurrentFocus().getWindowToken(), 0); } } }
package br.com.mixfiscal.prodspedxnfe.dao.own; import br.com.mixfiscal.prodspedxnfe.dao.EDirecaoOrdenacao; import br.com.mixfiscal.prodspedxnfe.dao.SuperDAO; import br.com.mixfiscal.prodspedxnfe.domain.own.CST; import br.com.mixfiscal.prodspedxnfe.dao.util.ConstroyerHibernateUtil; import br.com.mixfiscal.prodspedxnfe.util.StringUtil; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; public class CSTDAO extends SuperDAO<CST> { public CSTDAO(){ super(CST.class, ConstroyerHibernateUtil.getSessionFactory().getCurrentSession()); } @Override protected void addFiltros(CST obj, Criteria ctr){ if(obj == null)return; if(obj.getId()!= null) ctr.add(Restrictions.eq("id", obj.getId())); if(!StringUtil.isNullOrEmpty(obj.getCodigo())) ctr.add(Restrictions.like("codigo", "%" + obj.getCodigo() + "%")); if(!StringUtil.isNullOrEmpty(obj.getDescricao())) ctr.add(Restrictions.like("descricao", "%" + obj.getDescricao() + "%")); } @Override protected void addOrd(Criteria ctr, String orderProp, EDirecaoOrdenacao orderDir) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
/* Write a program that prompts the user to enter an integer. If the number is a multiple of 5, print HiFive. If the number is divisible by 2, print HiEven. */ import javax.swing.*; public class Multiple2Or5 { public static void main(String[] args) { //Takes integer input and stores in variable strInputedInteger as String. String strInputedInteger = JOptionPane.showInputDialog(null, "Enter Integer"); //stores original integr in InputedInteger variable as Integer. int inputedInteger = Integer.parseInt(strInputedInteger); if (0 == inputedInteger % 2) { System.out.println("HiEven"); } if (0 == inputedInteger % 5) { System.out.println("HiFive"); } } }
/* * 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 byui.cit260.LehisDream.model; /** * * @author smith */ public enum SceneType { start, frontDoor, laundryRoom, livingRoom, bedroom, // kitchen, cafeteria, auditorium, office, library, playground, meatDept, deliShoppe, dairyAisle, produceAisle, customerService, theatreOne, theatreTwo, theatreThree, theatreFour, theatreFive, chapel, primaryRoom, culturalHall, reliefSocietyRoom, classroom; }
package com.mgseb.wordgame.domain; import com.mgseb.wordgame.game.Difficulty; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class QuestionTest { private Question question1; private Question question2; private final String hint1; private final String hint2; private final String answer1; private final String answer2; public QuestionTest() { this.hint1 = "The favorite fruit of a monkey."; this.hint2 = "Synonymous with \"tyrannical.\""; this.answer1 = "banana"; this.answer2 = "despotic"; } @Before public void setUp() { this.question1 = new Question(hint1, answer1); this.question2 = new Question(hint2, answer2); } @Test public void getHint() { assertEquals(hint1, question1.getQuestion()); } @Test public void isCorrect() { assertTrue(question1.isCorrect(answer1)); } @Test public void isCorrectCanReturnFalse() { assertFalse(question1.isCorrect(answer2)); } @Test public void isCorrectIsCaseInsensitive() { assertTrue(question1.isCorrect(answer1.toUpperCase())); } @Test public void hideLettersEasy() { String visibleAnswer = question2.getPartialAnswer(Difficulty.EASY); int length = question2.getAnswer().length(); int expected = length / 2; assertTrue(correctNumberOfUnderscores(expected, visibleAnswer, length)); } @Test public void hideLettersMedium() { String visibleAnswer = question2.getPartialAnswer(Difficulty.MEDIUM); int length = question2.getAnswer().length(); int expected = length / 4 * 3; assertTrue(correctNumberOfUnderscores(expected, visibleAnswer, length)); } @Test public void hideLettersHard() { String visibleAnswer = question2.getPartialAnswer(Difficulty.HARD); int length = question2.getAnswer().length(); int expected = length; assertTrue(correctNumberOfUnderscores(expected, visibleAnswer, length)); } @Test public void hideLettersRepeatedUseHasNoEffect() { question2.getPartialAnswer(Difficulty.EASY); String visibleAnswer = question2.getPartialAnswer(Difficulty.EASY); int length = question2.getAnswer().length(); int expected = length / 2; assertTrue(correctNumberOfUnderscores(expected, visibleAnswer, length)); } private boolean correctNumberOfUnderscores(int expected, String visibleAnswer, int length) { int normalLetters = 0; for (char c : visibleAnswer.toCharArray()) { int charCode = (int) c; System.out.println("charCode: "+charCode); if (charCode >= 97 && charCode <= 122) { normalLetters++; } } int underscores = length - normalLetters; return underscores == expected; } }
package at.kalauner.dezsys06.station.enums; /** * Status after prepare phase * * @author Paul Kalauner 5BHIT * @version 20160204 */ public enum PrepareStatus { READY, ABORT, TIMEOUT }
/** * Nathan West * CSMC 255 – Project 7 * This is a Tester class meant to test the setter methods of the classes Bicycle and Customer */ public class Tester { public static void main(String[] args) { // TODO Auto-generated method stub Customer testCustomer = new Customer(); // new Customer object Bicycle testBicycle = new Bicycle(); // new Bicycle object System.out.println("========== TESTS Customer CLASS ==========="); // tests setFirstName of Customer // try { testCustomer.setFirstName(null); // checks for null } catch (NullPointerException e) { System.out.println("Test setFirstName(null): " + e + ": First name cannot be blank!"); } try { testCustomer.setFirstName(""); // checks for empty string } catch (IllegalArgumentException e) { System.out.println("Test setFirstName(''): " + e); } testCustomer.setFirstName("Nathan"); System.out.print("Test setFirstName('Nathan') – Expected: Nathan; Actual: "); System.out.println(testCustomer.getFirstName()); System.out.println(); // tests setLastName of Customer // try { testCustomer.setLastName(null); // checks for null } catch (NullPointerException e) { System.out.println("Test setLastName(null): " + e + ": Last name cannot be blank!"); } try { testCustomer.setLastName(""); // checks for empty string } catch (IllegalArgumentException e) { System.out.println("Test setLastName(''): " + e); } testCustomer.setLastName("West"); System.out.print("Test setLastName('West') – Expected: West; Actual: "); System.out.println(testCustomer.getLastName()); System.out.println(); // tests setEmailAddress of Customer // try { testCustomer.setEmailAddress(null); // checks for null } catch (NullPointerException e) { System.out.println("Test setEmailAddress(null): " + e + ": Email address cannot be blank!"); } try { testCustomer.setEmailAddress(""); // checks for empty string } catch (IllegalArgumentException e) { System.out.println("Test setEmailAddress(''): " + e); } try { testCustomer.setEmailAddress("westemail.com"); // checks for @ sign } catch (IllegalArgumentException e) { System.out.println("Test setEmailAddress('westemail.com'): " + e); } testCustomer.setEmailAddress("west@email.com"); System.out.print("Test setEmailAddress('west@email.com') – Expected: west@email.com; Actual: "); System.out.println(testCustomer.getEmailAddress()); System.out.println(); // tests setPhoneNumber of Customer // try { testCustomer.setPhoneNumber(null); // checks for null } catch (NullPointerException e) { System.out.println("Test setPhoneNumber(null): " + e + ": Phone number cannot be blank!"); } try { testCustomer.setPhoneNumber(""); // checks for empty string } catch (IllegalArgumentException e) { System.out.println("Test setPhoneNumber(''): " + e); } testCustomer.setPhoneNumber("(804) 123-4567"); System.out.print("Test setPhoneNumber('(804) 123-4567') – Expected: West; Actual: "); System.out.println(testCustomer.getPhoneNumber()); System.out.println("\n========= TESTS Bicycle CLASS =========="); // tests setColor of Bicycle // try { testBicycle.setColor(null); // checks for null } catch (NullPointerException e) { System.out.println("Test setColor(null): " + e + ": Color cannot be blank!"); } try { testBicycle.setColor(""); // checks for empty string } catch (IllegalArgumentException e) { System.out.println("Test setColor(''): " + e); } testBicycle.setColor("Blue"); System.out.print("Test setColor('Blue') – Expected: Blue; Actual: "); System.out.println(testBicycle.getColor()); System.out.println(); // tests setBrand of Bicycle // try { testBicycle.setBrand(null); // checks for null } catch (NullPointerException e) { System.out.println("Test setBrand(null): " + e + ": Brand cannot be blank!"); } try { testBicycle.setBrand(""); // checks for empty string } catch (IllegalArgumentException e) { System.out.println("Test setBrand(''): " + e); } testBicycle.setBrand("REI"); System.out.print("Test setBrand('REI') – Expected: REI; Actual: "); System.out.println(testBicycle.getBrand()); System.out.println(); // tests setNumGears of Bicycle // try { testBicycle.setNumGears(0); // checks for 0 } catch (IllegalArgumentException e) { System.out.println("Test setNumGears(0): " + e); } try { testBicycle.setNumGears(-4); // checks for negative } catch (IllegalArgumentException e) { System.out.println("Test setNumGears(-4): " + e); } testBicycle.setNumGears(4); System.out.print("Test setNumGears(4) – Expected: 4; Actual: "); System.out.println(testBicycle.getNumGears()); System.out.println(); // tests setWeight of Bicycle // try { testBicycle.setWeight(0); // checks for 0 } catch (IllegalArgumentException e) { System.out.println("Test setWeight(0): " + e); } try { testBicycle.setWeight(-10); // checks for negative } catch (IllegalArgumentException e) { System.out.println("Test setWeight(-10): " + e); } testBicycle.setWeight(10); System.out.print("Test setWeight(10) – Expected: 10; Actual: "); System.out.println(testBicycle.getWeight()); System.out.println(); // tests setWheelSize of Bicycle // try { testBicycle.setWheelSize(0); // checks for 0 } catch (IllegalArgumentException e) { System.out.println("Test setWheelSize(0): " + e); } try { testBicycle.setWheelSize(-1); // checks for negative } catch (IllegalArgumentException e) { System.out.println("Test setWheelSize(-1): " + e); } testBicycle.setWheelSize(26); System.out.print("Test setWheelSize(26) – Expected: 26; Actual: "); System.out.println(testBicycle.getWheelSize()); } }
package scouts; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; /** * * @author Rafael Martin Carrion, Joaquin Terrasa Moya */ @Entity public class Coordinador extends Usuario implements Serializable { private static final long serialVersionUID = 1L; @Column(nullable = false, length = 40) private String CorreoContacto; @Column(nullable = false, length = 9) private String DNI; @Column(nullable = false, length = 12) private Long TelefonoContacto; //! Getters y Setters public Long getTelefonoContacto() { return TelefonoContacto; } public void setTelefonoContacto(Long TelefonoContacto) { this.TelefonoContacto = TelefonoContacto; } public String getDNI() { return DNI; } public void setDNI(String DNI) { this.DNI = DNI; } public String getCorreoContacto() { return CorreoContacto; } public void setCorreoContacto(String CorreoContacto) { this.CorreoContacto = CorreoContacto; } }
package com.dongh.baselib.mvp; import android.content.Context; public interface BasePresenter { // Context setContxt(); void start(); void destroy(); }
package tr.com.taughtworks.hw.model; import java.util.ArrayList; import java.util.List; /** * This class represents graph data structure. * * Created by Mert on 18.3.2015. */ public class Graph { /** * Vertex list of the graph. */ private final List<Vertex> vertexes; /** * Edge list of the graph. */ private final List<Edge> edges; /** * Constructor. */ public Graph(List<Vertex> vertexes, List<Edge> edges) { this.vertexes = vertexes; this.edges = edges; } /** * Returns adjacent vertices of a given vertex. */ public List<Vertex> getAdjacentVertices(Vertex vertex){ List<Vertex> result = new ArrayList<Vertex>(); for(Edge edge : edges){ if( edge.getSource().equals(vertex)){ result.add(edge.getDestination()); } } return result; } /** * Returns outgoing edge list of a given vertex. */ public List<Edge> getOutgoingEdges( Vertex vertex){ List<Edge> outgoingEdgeList = new ArrayList<Edge>(); for( Edge edge : edges){ if( edge.getSource().equals(vertex)){ outgoingEdgeList.add(edge); } } return outgoingEdgeList; } /** * Returns cost of travelling from source to destination. */ public int getEdgeWeightBetweenTwoVertices(Vertex source, Vertex destination){ for(Edge e : edges){ if(e.getSource().equals(source) && e.getDestination().equals(destination)){ return e.getWeight(); } } return -1; } /** * Accessor methods. */ public List<Vertex> getVertexes() { return vertexes; } public List<Edge> getEdges() { return edges; } }
package assignment3.client; import java.io.Serializable; /** * Defines structure of possible entries in the log */ public class LogEntry implements Serializable { private static final long serialVersionUID = -8923661346264251689L; String authorName; String authorAddress; Client.Action action; int size; byte[] hash; public LogEntry(String authorName, String authorAddress, Client.Action action, int size, byte[] hash) { this.authorName = authorName; this.authorAddress = authorAddress; this.action = action; this.size = size; this.hash = hash; } /** * Returns a human readable, printable string representing the log entry object */ public String toString() { return authorAddress + ((authorName != null) ? "/" + authorName : "") + " " + action.name() + " " + ((size > -1) ? size : "") + " " + ((hash != null) ? hashToString() : ""); } /** * Returns a human readable, printable string representing the (problem) hash */ public String hashToString(){ StringBuilder sb = new StringBuilder(); for (byte b : hash) { sb.append(String.format("%02x", b & 0xff)); } return sb.toString(); } }
/* * 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 javaapplication17; /** * * @author My */ public class JavaApplication17 { /** * @param args the command line arguments */ public static void main(String[] args) { // Student s1=new Student("RAm",23,"235235"); String[] names={"Ram23553","Shyam","BKK"}; // for(int i=0;i<names.length;i++){ // Student s1=new Student(names[i],(int)(Math.random()*100.0),"235235"); // } Student s1=new Student(names[0],(int)(Math.random()*100.0),"235235"); s1.setAge(23); s1.setName("Rahul"); // Student s2=s1; // s2.setName("Dummy Name"); // System.out.println(s1.name); // Student[] studentList={s1,s2}; // s1.setName("Hari"); //// s1.name="sdgdsh"; // s1.setAge(28); // s1.setMobileNumber("346436"); // s1. // s1.getStudentInfo(); // // Student s2=new Student(); // System.out.println(s1.getAge()); // TODO code application logic here // System.out.println("Hello World"); // for(int i=1;i<65500;i++){ // System.out.println((char)i); // } // short score; // System.out.println(""); // String fname="RAm"; // String lname="Sharma"; // System.out.println(fname+" "+lname); // String[] names={"Ram","Shyam","Hari","RAhul","Rita","Gita"}; // for(int i=0;i<5;i++){ // if(names[0].equals("Hari")){ // break; // } // System.out.println(names[i]); // } // for(String name:names){ // if(name.equals("Hari")){ // continue; // } // System.out.println(name); // } // // // // System.out.println(names[0]); // System.out.println("THe array has "+names.length+" items"); // // // for(String name : names){ // System.out.println(name); // if(name.equals("Shyam") || name.equals("Rita") ){ // break; // } // } // for(int j=1;j<10;j++){ // for(int i=1;i<10;i++){ // System.out.print(j+" X "+i+" = "+j*i+"\t"); // } // System.out.println(""); // } // int[] numbers=new int[100]; // for(int i=0;i<100;i++){ // numbers[i]=i+1; // } // // for(int i=0;i<=100;i+=5){ // System.out.println(i); // }w // String fName="Nepal, Kathmandu,Putalisadak"; //// String converted=fName.toUpperCase(); //// System.out.println(converted); // System.out.println(fName.substring(7,12)); // String userInput="Ram Sharma"; // String userName=userInput.substring(1,3)+userInput.substring(2,4); // System.out.println(userName); // StringBuilder sb=new StringBuilder("Shyam"); // System.out.println(sb.reverse()); // short a,b; // int c=0; // a=34; // b=23; // c=a+b; // // // System.out.println(b); int max=Util.maximum(34, 67); // Math. Runtime r=Runtime.getRuntime(); // r.ring System.out.println("\u2344"); System.out.println(Math.PI); double area=Util.getAreaOfCircle(23); System.out.println("THe area of circle is "+area); Util.printPattern("3"); Util.printPattern("3"); } }
/* * 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 app.model; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author bruceoutdoors */ @Entity @Table(name = "user") @Inheritance(strategy = InheritanceType.JOINED) @DiscriminatorColumn(name = "role_id", discriminatorType = DiscriminatorType.INTEGER) @XmlRootElement @NamedQueries({ @NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"), @NamedQuery(name = "User.findByUserId", query = "SELECT u FROM User u WHERE u.userId = :userId"), @NamedQuery(name = "User.findByUserName", query = "SELECT u FROM User u WHERE u.userName = :userName"), @NamedQuery(name = "User.findByUserEmail", query = "SELECT u FROM User u WHERE u.userEmail = :userEmail"), @NamedQuery(name = "User.findByUserTel", query = "SELECT u FROM User u WHERE u.userTel = :userTel"), @NamedQuery(name = "User.findByUserActive", query = "SELECT u FROM User u WHERE u.userActive = :userActive"), @NamedQuery(name = "User.findByUserlastSignIn", query = "SELECT u FROM User u WHERE u.userlastSignIn = :userlastSignIn")}) public class User implements Serializable { @Basic(optional = false) @NotNull @Size(min = 5, max = 45) @Column(name = "user_password") private String userPassword; @Column(name = "user_active") private Boolean userActive = true; private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "user_id") private Integer userId; @Size(max = 45) @NotNull @Column(name = "user_name") private String userName; @Size(max = 45) @Column(name = "user_email") private String userEmail; @Size(max = 45) @Column(name = "user_tel") private String userTel; @Column(name = "user_lastSignIn") @Temporal(TemporalType.TIMESTAMP) private Date userlastSignIn; @OneToOne(cascade = CascadeType.ALL, mappedBy = "user") private Student student; @OneToOne(cascade = CascadeType.ALL, mappedBy = "user") private Admin admin; @OneToOne(cascade = CascadeType.ALL, mappedBy = "user") private Lecturer lecturer; @OneToMany(cascade = CascadeType.ALL, mappedBy = "userId") private List<Comment> commentList; @JoinColumn(name = "role_id", referencedColumnName = "role_id") @ManyToOne(optional = false) private Role roleId; public User() { } public User(Integer userId) { this.userId = userId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public String getUserTel() { return userTel; } public void setUserTel(String userTel) { this.userTel = userTel; } public Date getUserlastSignIn() { return userlastSignIn; } public void setUserlastSignIn(Date userlastSignIn) { this.userlastSignIn = userlastSignIn; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public Admin getAdmin() { return admin; } public void setAdmin(Admin admin) { this.admin = admin; } public Lecturer getLecturer() { return lecturer; } public void setLecturer(Lecturer lecturer) { this.lecturer = lecturer; } @XmlTransient public List<Comment> getcommentList() { return commentList; } public void setcommentList(List<Comment> commentList) { this.commentList = commentList; } public Role getRoleId() { return roleId; } public void setRoleId(Role roleId) { this.roleId = roleId; } @Override public int hashCode() { int hash = 0; hash += (userId != null ? userId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof User)) { return false; } User other = (User) object; if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) { return false; } return true; } @Override public String toString() { return "app.model.User[ userId=" + userId + " ]"; } public Boolean getUserActive() { return userActive; } public void setUserActive(Boolean userActive) { this.userActive = userActive; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public Boolean isAdmin() { return roleId.getRoleId() == 0; } public Boolean isStudent() { return roleId.getRoleId() == 2; } public Boolean isLecturer() { return roleId.getRoleId() == 1; } }
package com.lenovohit.hwe.treat.web.his; import org.springframework.beans.factory.annotation.Autowired; 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.bind.annotation.RestController; import com.lenovohit.core.utils.JSONUtils; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.hwe.org.web.rest.OrgBaseRestController; import com.lenovohit.hwe.treat.model.Schedule; import com.lenovohit.hwe.treat.service.HisScheduleService; import com.lenovohit.hwe.treat.transfer.RestListResponse; // 排班 @RestController @RequestMapping("/hwe/treat/his/schedule") public class ScheduleHisController extends OrgBaseRestController { @Autowired private HisScheduleService hisScheduleService; // 3.4.9 科室排班列表查询 @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forList(@RequestParam(value = "data", defaultValue = "") String data) { try { log.info("\n======== forList Start ========\ndata:\n"+data); Schedule query = JSONUtils.deserialize(data, Schedule.class); log.info("\n======== forList Before hisScheduleService.findList ========\nquery:\n"+JSONUtils.serialize(query)); RestListResponse<Schedule> result=this.hisScheduleService.findList(query, null); log.info("\n======== forList After hisScheduleService.findList ========\nresult:\n"+JSONUtils.serialize(result)); if (result.isSuccess()){ return ResultUtils.renderSuccessResult(result.getList()); } else { return ResultUtils.renderFailureResult(result.getMsg()); } } catch (Exception e) { log.error("\n======== forList Failure End ========\nmsg:\n"+e.getMessage()); return ResultUtils.renderFailureResult(e.getMessage()); } } }
package com.git.cloud.request.action; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.git.cloud.common.action.BaseAction; import com.git.cloud.request.dao.IBmSrDao; import com.git.cloud.request.model.vo.VirtualExtendVo; import com.git.cloud.request.model.vo.VirtualSupplyVo; import com.git.cloud.request.service.IVirtualExtendService; /** * 云服务扩容Action * @ClassName:VirtualExtendAction * @Description:TODO * @author sunhailong * @date 2014-10-28 下午6:37:17 */ public class VirtualExtendAction extends BaseAction<Object> { private static Logger logger = LoggerFactory.getLogger(VirtualExtendAction.class); private static final long serialVersionUID = 1L; private IVirtualExtendService virtualExtendService; private VirtualSupplyVo virtualSupplyVo; private IBmSrDao bmSrDao; /** * 查找扩容服务申请 * @author huangrongsheng */ public void findVirtualExtendById(){ try { String srId = this.getRequest().getParameter("srId"); VirtualExtendVo virtualExtendVo = virtualExtendService.findVirtualExtendById(srId); this.jsonOut(virtualExtendVo); } catch (Exception e) { logger.error("查找扩容服务申请时发生异常:"+e); } } public void queryVEBmSrRrinfoList() throws Exception { this.jsonOut(virtualExtendService.queryVEBmSrRrinfoList(this.getPaginationParam())); } public void queryVmSrDeviceinfoList() throws Exception { this.jsonOut(virtualExtendService.queryVmSrDeviceinfoList(this.getPaginationParam())); } public void getHostName() throws Exception { HttpServletResponse response = this.getResponse(); response.setContentType("text/json;charset=utf-8"); String deviceId = this.getRequest().getParameter("paramName"); String hostName = virtualExtendService.getDeviceName(deviceId); response.getWriter().print(hostName); } public VirtualSupplyVo getVirtualSupplyVo() { return virtualSupplyVo; } public void setVirtualSupplyVo(VirtualSupplyVo virtualSupplyVo) { this.virtualSupplyVo = virtualSupplyVo; } public void setVirtualExtendService(IVirtualExtendService virtualExtendService) { this.virtualExtendService = virtualExtendService; } public IBmSrDao getBmSrDao() { return bmSrDao; } public void setBmSrDao(IBmSrDao bmSrDao) { this.bmSrDao = bmSrDao; } }
package modelos; public class Curso { String nome; int qtdcreditostotais; }
package com.bharath.trainings.jsp.customtags; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.Tag; import javax.servlet.jsp.tagext.TagSupport; public class ResultHandler extends TagSupport { Connection con; PreparedStatement stmt; public ResultHandler() { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "test"); stmt = con.prepareStatement("select * from user where email=?"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } @Override public int doStartTag() throws JspException { ServletRequest request = pageContext.getRequest(); String email = request.getParameter("email"); try { stmt.setString(1, email); ResultSet rs = stmt.executeQuery(); JspWriter out = null; if(rs.next()){ out = pageContext.getOut(); out.print("User Details are:<br/> First Name:"); out.print(rs.getString(1)); out.print("<br/>Last name:"); out.print(rs.getString(2)); } else{ out.print("Invalid email entered"); } } catch (SQLException | IOException e) { e.printStackTrace(); } return Tag.SKIP_BODY; } @Override public void release() { try { stmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.appcloud.httpgetprocessor.extensions.swagger.utils; import org.apache.synapse.rest.API; import org.apache.synapse.rest.Resource; import org.apache.synapse.rest.dispatch.DispatcherHelper; import org.apache.synapse.rest.dispatch.URLMappingBasedDispatcher; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Matcher; /** * Generalized object structure for Swagger definitions of APIs. This structure contains set of Maps which compatible * with both JSON and YAML formats */ public class GenericApiObjectDefinition { private API api; public GenericApiObjectDefinition(API api) { this.api = api; } /** * Returns Map containing the structure of swagger definition created based on API instance properties * * @return Map of the swagger definition structure */ public Map<String, Object> getDefinitionMap() { Map<String, Object> apiMap = new LinkedHashMap<>(); Map<String, Object> pathMap; //Create main elements in definition apiMap.put(SwaggerConstants.SWAGGER, SwaggerConstants.SWAGGER_VERSION); if (SwaggerConstants.HOST_NAME != null) { apiMap.put(SwaggerConstants.HOST, SwaggerConstants.HOST_NAME); } apiMap.put(SwaggerConstants.BASE_PATH, getUrlWithoutTenant(api.getContext())); apiMap.put(SwaggerConstants.INFO, getInfoMap()); //Create paths pathMap = getPathMap(); if (!pathMap.isEmpty()) { apiMap.put(SwaggerConstants.PATHS, getPathMap()); } //Create scehemes apiMap.put(SwaggerConstants.SCHEMES, getSchemes()); return apiMap; } private Map<String, Object> getResponsesMap() { Map<String, Object> responsesMap = new LinkedHashMap<>(); Map<String, Object> responseDetailsMap = new LinkedHashMap<>(); responseDetailsMap.put(SwaggerConstants.DESCRIPTION, SwaggerConstants.DEFAULT_RESPONSE); responsesMap.put(SwaggerConstants.DEFAULT_VALUE, responseDetailsMap); return responsesMap; } private Map<String, Object> getInfoMap() { Map<String, Object> infoMap = new LinkedHashMap<>(); infoMap.put(SwaggerConstants.DESCRIPTION, (SwaggerConstants.API_DESC_PREFIX + api.getAPIName())); infoMap.put(SwaggerConstants.TITLE, api.getName()); infoMap.put(SwaggerConstants.VERSION, (api.getVersion() != null && !api.getVersion().equals("")) ? api.getVersion() : SwaggerConstants.DEFAULT_API_VERSION); return infoMap; } private Map<String, Object> getPathMap() { Map<String, Object> pathsMap = new LinkedHashMap<>(); //Process each resource in the API for (Resource resource : api.getResources()) { Map<String, Object> methodMap = new LinkedHashMap<>(); DispatcherHelper resourceDispatcherHelper = resource.getDispatcherHelper(); //Populate properties for each method (GET, POST, PUT ect) available for (String method : resource.getMethods()) { if (method != null) { Map<String, Object> methodInfoMap = new LinkedHashMap<>(); methodInfoMap.put(SwaggerConstants.RESPONSES, getResponsesMap()); if (resourceDispatcherHelper != null) { Object[] parameters = getResourceParameters(resource); if (parameters.length > 0) { methodInfoMap.put(SwaggerConstants.PARAMETERS, parameters); } } methodMap.put(method.toLowerCase(), methodInfoMap); } } pathsMap.put(getPathFromUrl(resourceDispatcherHelper == null ? SwaggerConstants.PATH_SEPARATOR : resourceDispatcherHelper.getString()), methodMap); } return pathsMap; } private String[] getSchemes() { String[] protocols; switch (api.getProtocol()) { case SwaggerConstants.PROTOCOL_HTTP_ONLY: protocols = new String[]{SwaggerConstants.PROTOCOL_HTTP}; break; case SwaggerConstants.PROTOCOL_HTTPS_ONLY: protocols = new String[]{SwaggerConstants.PROTOCOL_HTTPS}; break; default: protocols = new String[]{SwaggerConstants.PROTOCOL_HTTP, SwaggerConstants.PROTOCOL_HTTPS}; break; } return protocols; } private Object[] getResourceParameters(Resource resource) { ArrayList<Map<String, Object>> parameterList = new ArrayList<>(); String uri = resource.getDispatcherHelper().getString(); if (resource.getDispatcherHelper() instanceof URLMappingBasedDispatcher) { generateParameterList(parameterList, uri, false); } else { //If it is uri-template, process both path and query parameters generateParameterList(parameterList, uri, true); } return parameterList.toArray(); } private void generateParameterList(ArrayList<Map<String, Object>> parameterList, String uriString, boolean generateBothTypes) { if (uriString == null) { return; } //Process query parameters if (generateBothTypes) { String[] params = getQueryStringFromUrl(uriString).split("\\&"); for (String parameter : params) { if (parameter != null) { int pos = parameter.indexOf('='); if (pos > 0) { parameterList.add(getParametersMap(parameter.substring(0, pos), SwaggerConstants.PARAMETER_IN_QUERY)); } } } } //Process path parameters Matcher matcher = SwaggerConstants.PATH_PARAMETER_PATTERN.matcher(getPathFromUrl(uriString)); while (matcher.find()) { parameterList.add(getParametersMap(matcher.group(1), SwaggerConstants.PARAMETER_IN_PATH)); } } private Map<String, Object> getParametersMap(String parameterName, String parameterType) { Map<String, Object> parameterMap = new LinkedHashMap<>(); parameterMap.put(SwaggerConstants.PARAMETER_DESCRIPTION, parameterName); parameterMap.put(SwaggerConstants.PARAMETER_IN, parameterType); parameterMap.put(SwaggerConstants.PARAMETER_NAME, parameterName); parameterMap.put(SwaggerConstants.PARAMETER_REQUIRED, true); //Consider parameter type as 'String' by default since no such information available in API config parameterMap.put(SwaggerConstants.PARAMETER_TYPE, SwaggerConstants.PARAMETER_TYPE_STRING); return parameterMap; } private String getPathFromUrl(String uri) { int pos = uri.indexOf("?"); if (pos > 0) { return uri.substring(0, pos); } return uri; } private String getQueryStringFromUrl(String uri) { int pos = uri.indexOf("?"); if (pos > 0) { return uri.substring(pos + 1); } return ""; } private String getUrlWithoutTenant(String pathUrl) { String updatedUrl = null; if (pathUrl != null) { updatedUrl = pathUrl.replaceAll(SwaggerConstants.TENANT_REPLACEMENT_REGEX, SwaggerConstants.PATH_SEPARATOR); } return updatedUrl; } }
package com.example.breno.pokemobile.adapter; 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 android.widget.ProgressBar; import android.widget.TextView; import com.example.breno.pokemobile.R; import com.example.breno.pokemobile.Service.PokemonTreinadorService; import com.example.breno.pokemobile.modelo.PokemonTreinador; import java.util.ArrayList; /** * Created by Breno on 15/11/2016. */ public class PokemonsAdapter extends BaseAdapter { private Context ctx; private ArrayList<PokemonTreinador> lista; private PokemonTreinadorService pokemonTreinadorService = new PokemonTreinadorService(); public PokemonsAdapter(Context ctx, ArrayList<PokemonTreinador> lista) { this.ctx = ctx; this.lista = lista; } @Override public int getCount() { return lista.size(); } @Override public Object getItem(int position) { return lista.get(position); } @Override public long getItemId(int position) { return lista.get(position).getTreinador().getIdTreinador(); } @Override public View getView(int position, View convertView, ViewGroup parent) { PokemonTreinador pokemonTreinador = lista.get(position); LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.pokemon, null); ImageView icone = (ImageView) layout.findViewById(R.id.iconeImageViewPokemons); icone.setImageResource(pokemonTreinador.getPokemon().getIcone()); TextView nome = (TextView) layout.findViewById(R.id.nomeTextViewPokemons); nome.setText(pokemonTreinadorService.apelidoOuNome(pokemonTreinador)); TextView lvl = (TextView) layout.findViewById(R.id.lvlTextViewPokemons); lvl.setText("Lv." + pokemonTreinador.getLevel()); ProgressBar hpBar = (ProgressBar) layout.findViewById(R.id.hpProgressBarPokemons); Double porcentagemHP = pokemonTreinadorService.calcularPorcentagemHP(pokemonTreinador); hpBar.setProgress(porcentagemHP.intValue()); TextView hpText = (TextView) layout.findViewById(R.id.hpTextViewPokemons); hpText.setText("HP: " + pokemonTreinador.getHpAtual().intValue() + " / " + pokemonTreinador.getHpTotal().intValue()); return layout; } }
package com.metoo.modul.app.game.manager.tree; 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.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.iskyshop.core.tools.CommUtil; import com.metoo.core.tools.WebForm; import com.metoo.foundation.domain.Game; import com.metoo.foundation.domain.GameAward; import com.metoo.foundation.domain.GameTask; import com.metoo.foundation.service.IGameAwardService; import com.metoo.foundation.service.IGameService; import com.metoo.foundation.service.IGameTaskService; import com.metoo.module.app.buyer.domain.Result; @Controller @RequestMapping("/php/game/tree/task") public class GameTaskManageAction { @Autowired private IGameTaskService gameTaskService; @Autowired private IGameService gameService; @Autowired private IGameAwardService gameAwardService; @RequestMapping("/save.json") @ResponseBody public Object save(HttpServletRequest request, HttpServletResponse response, String id, String game_id, String type, String game_award_id) { int code = -1; String msg = ""; GameTask task = null; WebForm wf = new WebForm(); if(id.equals("")){ task = wf.toPo(request, GameTask.class); }else{ GameTask obj = this.gameTaskService.getObjById(CommUtil.null2Long(id)); task = (GameTask) wf.toPo(request, obj); } if(!game_id.equals("")){ Game game = this.gameService.getObjById(CommUtil.null2Long(game_id)); task.setGame(game); } if(type.equals("water")){ task.setType(0); }else if(type.equals("gather")){ task.setType(1); }else if(type.equals("browse")){ task.setType(2); }else if(type.equals("order")){ task.setType(3); }else if(type.equals("new")){ task.setType(4); }else if(type.equals("email")){ task.setType(6); }else if(type.equals("article")){ task.setType(7); }else if(type.equals("goods")){ task.setType(8); }else if(type.equals("assign")){ task.setType(9); } GameAward gameAward = this.gameAwardService.getObjById(CommUtil.null2Long(game_award_id)); if(gameAward !=null ){ task.setGameAward(gameAward); } if(id.equals("")){ this.gameTaskService.save(task); }else{ this.gameTaskService.update(task); } return new Result(5200, "Successfully"); } // update 关闭任务时,清楚游戏关联的任务记录 /*@RequestMapping("/task/insert.json") @ResponseBody public Object insert(HttpServletRequest request, HttpServletResponse response, @RequestBody GameTask gametask, String game_id) { int code = -1; String msg = ""; GameTask task = null; WebForm wf = new WebForm(); if(gametask.getId().equals("")){ task = wf.toPo(request, GameTask.class); }else{ GameTask obj = this.gameTaskService.getObjById(CommUtil.null2Long(gametask.getId())); task = (GameTask) wf.toPo(request, obj); } if(!game_id.equals("")){ GameTree gameTree = this.gameTreeService.getObjById(CommUtil.null2Long(game_id)); task.setGameTree(gameTree); } if(gametask.getId().equals("")){ this.gameTaskService.save(task); }else{ this.gameTaskService.update(task); } return new Result(5200, "Successfully"); }*/ }
/** * Copyright (C), 2012-2016, 江苏中地集团有限公司 * Author: LG * Date: 2016年9月2日 上午8:38:45 * Description: //模块目的、功能描述 */ package com.way.mobile.property.config; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.util.PropertyPlaceholderHelper; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; /** * 功能描述:自定义资源文件解析类,将配置参数装配到map * * @ClassName PropertyConfigurerWithWhite * @Author:xinpei.xu * @Date:2017/08/16 19:55 */ public class PropertyConfigurerWithWhite extends PropertyPlaceholderConfigurer { // 装配配置文件属性到内存 private static Map<String, String> properties = new HashMap<String, String>(); /** * 功能描述: 获取全量配置属性<br> * 〈功能详细描述〉 * * @return * @see [相关类/方法](可选) * @since [产品/模块版本](可选) */ public static Map<String, String> getProperties() { return properties; } /** * 功能描述: 获取指定配置属性<br> * 〈功能详细描述〉 * * @param key * @return * @see [相关类/方法](可选) * @since [产品/模块版本](可选) */ public static String getProperty(String key) { return properties.get(key); } @Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(DEFAULT_PLACEHOLDER_PREFIX, DEFAULT_PLACEHOLDER_SUFFIX, DEFAULT_VALUE_SEPARATOR, false); for (Entry<Object, Object> entry : props.entrySet()) { String stringKey = String.valueOf(entry.getKey()); String stringValue = String.valueOf(entry.getValue()); stringValue = helper.replacePlaceholders(stringValue, props); properties.put(stringKey, stringValue); } super.processProperties(beanFactoryToProcess, props); } }
package com.cs192.foodwatch; import java.util.Calendar; import java.util.GregorianCalendar; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; public class Record extends Activity { String id; Spinner spinner1, spinner2; Button clear; EditText cholesterol, totalCarbs, totalFats, sugar,calories,amountofFood,etDate,etTime,foodname; int day,month,year; int minute,hour; int checker=0; String displayMinute; String[] timeOfMealChoices = {"Breakfast","Lunch","Dinner","Others(snack)"}; String[] mealChoices = {"Home-made", "Lunch-out"}; /*declaration of variables needed to take input*/ String date; String time; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_record); initializeVariables(); Bundle bundle = getIntent().getExtras(); id = bundle.getString("ID"); GregorianCalendar date = new GregorianCalendar(); day = date.get(Calendar.DAY_OF_MONTH); month = date.get(Calendar.MONTH); year = date.get(Calendar.YEAR); minute = date.get(Calendar.MINUTE); switch(minute) { case 1: displayMinute ="01"; checker++; break; case 2: displayMinute ="02"; checker++; break; case 3: displayMinute ="03"; checker++; break; case 4: displayMinute ="04"; checker++; break; case 5: displayMinute ="05"; checker++; break; case 6: displayMinute ="06"; checker++; break; case 7: displayMinute ="07"; checker++; break; case 8: displayMinute ="08"; checker++; break; case 9: displayMinute ="09"; checker++; break; case 0: displayMinute ="00"; checker++; break; default: break; } hour = date.get(Calendar.HOUR); etDate.setText((month+1)+"/"+day+"/"+year); if(checker>0) { etTime.setText(hour+":"+displayMinute); } else { etTime.setText(hour+":"+minute); } clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub foodname.setText(""); cholesterol.setText(""); totalCarbs.setText(""); totalFats.setText(""); sugar.setText(""); calories.setText(""); amountofFood.setText(""); } }); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Notice"); alert.setMessage("Please provide as much information as you can. Thank You!"); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //String value = input.getText(); // Do something with value! } }); alert.show(); ArrayAdapter<String> adapter = new ArrayAdapter<String>(Record.this, android.R.layout.simple_spinner_item, timeOfMealChoices); ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(Record.this, android.R.layout.simple_spinner_item, mealChoices); spinner1.setAdapter(adapter); spinner2.setAdapter(adapter2); } private void initializeVariables() { // TODO Auto-generated method stub foodname = (EditText) findViewById(R.id.etRecordFoodName); etDate = (EditText) findViewById(R.id.etRecordDate); etTime = (EditText) findViewById(R.id.etRecordTime); cholesterol = (EditText) findViewById(R.id.etCholesterol); totalCarbs = (EditText) findViewById(R.id.etCarbohydrates); totalFats = (EditText) findViewById(R.id.etTotalFats); sugar = (EditText) findViewById(R.id.etSugar); calories = (EditText) findViewById(R.id.etCalories); amountofFood = (EditText) findViewById(R.id.etAmountOfFood); clear = (Button) findViewById(R.id.buttonRecordClear); spinner1 = (Spinner) findViewById(R.id.sTMeal); spinner2 = (Spinner) findViewById(R.id.sMeal); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_record, menu); return true; } public void recordSuccess(View view) { try { date = etDate.getText().toString(); time = etTime.getText().toString(); String foodName = foodname.getText().toString(); String cho = cholesterol.getText().toString(); String ca = totalCarbs.getText().toString(); String fa = totalFats.getText().toString(); String su = sugar.getText().toString(); String cal = calories.getText().toString(); String quantity = amountofFood.getText().toString(); String timeOfMeal = spinner1.getSelectedItem().toString(); String meal = spinner2.getSelectedItem().toString(); DatabaseManager database = new DatabaseManager(this); database.open(); database.addToNutritionalFactsDatabase(foodName,cho,ca,fa,su,cal,quantity,date,time,timeOfMeal, meal,id); database.close(); } catch (Exception e) { Log.d("ErrorTag", e.toString()); } finally { //tar = target.getText().toString(); Intent intent =new Intent(getApplicationContext(),ViewRecords.class); intent.putExtra("ID", id); startActivity(intent); } } }
package com.esum.comp.ws.inbound; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.wss4j.dom.handler.WSHandlerConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.comp.ws.WsCode; import com.esum.comp.ws.WsConfig; import com.esum.comp.ws.WsException; import com.esum.comp.ws.security.SecurityUtils; import com.esum.comp.ws.security.UTPasswordCallback; import com.esum.comp.ws.table.WsInfoRecord; import com.esum.comp.ws.table.WsInfoTable; import com.esum.framework.FrameworkSystemVariables; import com.esum.framework.common.util.ArrayUtil; import com.esum.framework.common.util.ClassUtil; import com.esum.framework.core.component.ComponentException; import com.esum.framework.core.component.config.ComponentConfigFactory; import com.esum.framework.core.component.listener.LegacyListener; import com.esum.framework.core.component.listener.http.BasicHttpServlet; import com.esum.framework.core.component.listener.http.HTTPListener; import com.esum.framework.core.component.table.InfoTableManager; import com.esum.framework.core.config.Configurator; import com.esum.framework.core.exception.FrameworkException; import com.esum.framework.core.exception.SystemException; import com.esum.framework.net.http.server.tomcat.Tomcat70; import com.esum.framework.product.ProductInfo; import com.esum.framework.security.pki.manager.PKIStoreManager; import com.esum.framework.security.pki.manager.info.PKIJKSInfo; import com.esum.framework.security.pki.manager.info.PKIStoreInfo; import com.esum.framework.security.xml.manager.encrypt.XMLEncryptInfo; import com.esum.framework.security.xml.manager.encrypt.XMLEncryptInfoManager; import com.esum.router.RouterMain; public class WsInboundLegacyListener extends LegacyListener { private Logger log = LoggerFactory.getLogger(WsInboundLegacyListener.class); private String nodeId; private String traceId=""; private String contextPath = ""; private Map<String, Servlet> wsList = new HashMap<String, Servlet>(); @Override protected void startupLegacy() throws SystemException { this.nodeId = System.getProperty(FrameworkSystemVariables.NODE_ID, "MAIN"); traceId = "[" + getComponentId() + "]["+nodeId+"] "; WsInfoTable infoTable = (WsInfoTable)InfoTableManager.getInstance().getInfoTable(WsConfig.WS_INFO_TABLE_ID); List<WsInfoRecord> infoRecordList = infoTable.getInboundInfoList(); if(infoRecordList==null || infoRecordList.size()==0) return; try { createDefaultContext(); } catch (Exception e) { throw new ComponentException("process()", " EmbeddedTomcat is not started !! "); } for(int i=0;i<infoRecordList.size();i++) { WsInfoRecord infoRecord = infoRecordList.get(i); if(infoRecord.isUseInbound() && infoRecord.containsNodeId(nodeId)) createWsService(infoRecord); } } private void createWsService(WsInfoRecord infoRecord) throws WsException { log.info(traceId+"Creating WebService. Service : "+infoRecord.getInboundServiceName()); WsInboundServlet servlet = new WsInboundServlet(); servlet.setTraceId(traceId+"["+infoRecord.getInterfaceId()+"] "); servlet.setServiceName(infoRecord.getInboundServiceName()); servlet.setInboundHandler(new WsInboundHandler(getComponentId(), infoRecord)); Map<String, String> params = new HashMap<String, String>(); log.info(traceId+"Use http auth is "+infoRecord.isInboundClientAuth()); params.put("useAuth", Boolean.toString(infoRecord.isInboundClientAuth())); params.put("componentId", infoRecord.getInterfaceId()); try { servlet.setUseHttpAuth(infoRecord.isInboundClientAuth()); servlet.setServiceClass(ClassUtil.forName(infoRecord.getInboundServiceClass(), null)); servlet.setServiceBean(ClassUtil.forName(infoRecord.getInboundServiceImpl(), null).newInstance()); // ws-addressing configuration. servlet.setUseWSAddressing(infoRecord.isUseInboundWsAddressing()); // ws-security configuration. if(infoRecord.isUseInboundWsSecurity()) { boolean noSecurity = StringUtils.contains(infoRecord.getInboundWsSecurityInfo().getInActions(), WSHandlerConstants.NO_SECURITY); if(!noSecurity) { Map<String, Object> inProps = new HashMap<String, Object>(); inProps.put(WSHandlerConstants.ACTION, infoRecord.getInboundWsSecurityInfo().getInActions()); inProps.put(WSHandlerConstants.PASSWORD_TYPE, "PasswordText"); inProps.put(WSHandlerConstants.PW_CALLBACK_REF, new UTPasswordCallback()); String[] inActions = StringUtils.split(infoRecord.getInboundWsSecurityInfo().getInActions(), ' '); for(String action : inActions) { if(action.equals(WSHandlerConstants.SIGNATURE )){ inProps.put("truststoreProperties", SecurityUtils.createWssTruststoreProperties()); inProps.put(WSHandlerConstants.SIG_VER_PROP_REF_ID, "truststoreProperties"); } else if(action.equals(WSHandlerConstants.ENCRYPT )){ inProps.put("keystoreProperties", SecurityUtils.createWssKeystoreProperties()); inProps.put(WSHandlerConstants.DEC_PROP_REF_ID, "keystoreProperties"); inProps.put(WSHandlerConstants.ENC_KEY_ID, "IssuerSerial"); inProps.put(WSHandlerConstants.ENC_KEY_TRANSPORT, infoRecord.getInboundWsSecurityInfo().getInEncKeyAlg()); } } servlet.setInProps(inProps); } noSecurity = StringUtils.contains(infoRecord.getInboundWsSecurityInfo().getOutActions(), WSHandlerConstants.NO_SECURITY); if(!noSecurity) { Map<String, Object> outProps = new HashMap<String, Object>(); outProps.put(WSHandlerConstants.ACTION, infoRecord.getInboundWsSecurityInfo().getOutActions()); outProps.put(WSHandlerConstants.PASSWORD_TYPE, "PasswordText"); outProps.put(WSHandlerConstants.USER, WsConfig.DEFAULT_KEYSTORE_ALIAS); outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new UTPasswordCallback()); String[] outActions = StringUtils.split(infoRecord.getInboundWsSecurityInfo().getOutActions(), ' '); for(String action : outActions) { if(action.equals(WSHandlerConstants.SIGNATURE)){ outProps.put("signProperties", SecurityUtils.createWssKeystoreProperties()); outProps.put(WSHandlerConstants.SIGNATURE_USER, WsConfig.DEFAULT_KEYSTORE_ALIAS); outProps.put(WSHandlerConstants.SIG_PROP_REF_ID, "signProperties"); outProps.put(WSHandlerConstants.SIG_KEY_ID, "IssuerSerial"); outProps.put(WSHandlerConstants.SIG_ALGO, infoRecord.getInboundWsSecurityInfo().getOutSignAlgo()); outProps.put(WSHandlerConstants.SIG_DIGEST_ALGO, infoRecord.getInboundWsSecurityInfo().getOutDigestAlgo()); outProps.put(WSHandlerConstants.SIGNATURE_PARTS, infoRecord.getInboundWsSecurityInfo().getOutSignParts()); } else if(action.equals(WSHandlerConstants.ENCRYPT)){ XMLEncryptInfo encInfo = XMLEncryptInfoManager.getInstance().getXMLEncInfo(infoRecord.getInboundWsSecurityInfo().getOutEncUser()); if(encInfo==null) throw new WsException(WsCode.ERROR_ADD_SERVLET_CLASS, "createWsService()", "Could not found PKI alias for Encryption."); PKIStoreInfo pkiInfo = PKIStoreManager.getInstance().getPKIStoreInfo(encInfo.getPKIAlias()); outProps.put("encryptProperties", SecurityUtils.createWssKeystoreProperties(pkiInfo)); outProps.put(WSHandlerConstants.ENCRYPTION_USER, ((PKIJKSInfo)pkiInfo).getAlias()); outProps.put(WSHandlerConstants.ENC_PROP_REF_ID, "encryptProperties"); outProps.put(WSHandlerConstants.ENC_KEY_ID, "IssuerSerial"); outProps.put(WSHandlerConstants.ENC_SYM_ALGO, encInfo.getDataEncryptMethod()); outProps.put(WSHandlerConstants.ENC_KEY_TRANSPORT, encInfo.getKeyEncryptMethod()); outProps.put(WSHandlerConstants.ENCRYPTION_PARTS, infoRecord.getInboundWsSecurityInfo().getOutEncParts()); } } servlet.setOutProps(outProps); } } } catch (FrameworkException e) { log.error(traceId+"["+infoRecord.getInboundServiceName()+"] Could not set the Servlet.", e); throw new WsException(e.getErrorCode(), e.getErrorLocation(), e.getErrorMessage()); } catch (Exception e) { log.error(traceId+"["+infoRecord.getInboundServiceName()+"] Could not set the Servlet.", e); throw new WsException(WsCode.ERROR_INVALID_SERVICE_CLASS, "createWsService()", e.getMessage()); } try { String confId = ComponentConfigFactory.getInstance(this.getComponentId()).getConfigId(); String docBase = Configurator.getInstance(confId).getString("tomcat.deploy.path"); Tomcat70.getInstance().createContext(contextPath+"/"+infoRecord.getInterfaceId(), docBase, infoRecord.getInterfaceId(), params, servlet); } catch (Exception e) { throw new WsException(WsCode.ERROR_ADD_SERVLET_CLASS, "createWsService()", e.getMessage()); } wsList.put(infoRecord.getInterfaceId(), servlet); log.info(traceId+"["+infoRecord.getInterfaceId()+"] New Web Service Servlet added. URL : "+contextPath+"/"+infoRecord.getInterfaceId()); } private void createDefaultContext() throws Exception { Tomcat70 tomcat = Tomcat70.getInstance(); if(tomcat==null || !tomcat.isAlived()) { tomcat = Tomcat70.newInstance(); } log.info(traceId+"Creating Default WebService Context."); String confId = ComponentConfigFactory.getInstance(this.getComponentId()).getConfigId(); contextPath = Configurator.getInstance(confId).getString("tomcat.context.path"); BasicHttpServlet servlet = BasicHttpServlet.createHttpServlet(getComponentId(), "handler"); servlet.setListener(new HTTPListener() { @Override public void doPost(HttpServletRequest req, HttpServletResponse res, String senderCode) throws ServletException, IOException { doGet(req, res, senderCode); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res, String senderCode) throws ServletException, IOException { ProductInfo productInfo = new ProductInfo(RouterMain.PRODUCT_NAME, RouterMain.VERSION); PrintWriter writer = res.getWriter(); writer.println("<html><head><title>Message Handler</title></head>"); writer.println("<body>"); writer.println("<center><font size=10><b>Message Handler is running.</b></font></center>"); writer.println("<p><center><font size=5>" + productInfo + "</font></center>"); writer.println("</body></html>"); writer.close(); } @Override public void doPostLargeMessage(String savedPath) { } @Override public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } @Override public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }); servlet.startup(); } @Override protected void shutdownLegacy() throws SystemException { wsList.clear(); if(this.contextPath!=null) { try { Tomcat70.getInstance().removeContext(contextPath); } catch (Exception e) { log.warn(traceId+"Context remove error.", e); } } } @Override public void reload(String[] reloadIds) throws SystemException { log.info(traceId+"Reloading WebServices. ids : "+ArrayUtil.toString(reloadIds)); if (wsList.containsKey(reloadIds[0])) { String wsContextName = contextPath+"/"+reloadIds[0]; try { Tomcat70.getInstance().removeContext(wsContextName); } catch (Exception e) { log.error(traceId+"Could not remove context. context name : "+reloadIds[0]); } wsList.remove(reloadIds[0]); } WsInfoTable wsInfoTable = (WsInfoTable)InfoTableManager.getInstance().getInfoTable(WsConfig.WS_INFO_TABLE_ID); WsInfoRecord wsInfoRecord = null; try{ wsInfoRecord = (WsInfoRecord)wsInfoTable.getInfoRecord(reloadIds); }catch(ComponentException e){ log.error("reload()", e); } if (wsInfoRecord != null && wsInfoRecord.isUseInbound() && wsInfoRecord.containsNodeId(nodeId)) { createWsService(wsInfoRecord); } log.info(traceId+"WebService("+wsInfoRecord.getInterfaceId()+") reloading completed."); } }
package com.javarush.test.level04.lesson06.task04; /* Compare names Write a program that reads two names from keyboard, and if the names are the same, displays «Names are identical». Display «Name lengths are equal» if the names are different, but their lengths are equal. */ import java.io.*; public class Solution { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String names1 = br.readLine(); String names2 = br.readLine(); if (names1.equals(names2)) { System.out.println("Names are identical"); } else if (names1.length() == names2.length()) { System.out.println("Name lengths are equal"); } } }
package nl.finalist.liferay.oidc; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.module.configuration.ConfigurationProvider; import com.liferay.portal.kernel.security.auto.login.AutoLogin; import com.liferay.portal.kernel.security.auto.login.BaseAutoLogin; import com.liferay.portal.kernel.service.UserLocalService; import com.liferay.portal.kernel.util.Portal; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.kernel.util.PortalUtil; import com.liferay.portal.kernel.model.User; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; /** * @see LibAutoLogin */ @Component( immediate = true, service = AutoLogin.class, configurationPid = "nl.finalist.liferay.oidc.OpenIDConnectOCDConfiguration" ) public class OpenIDConnectAutoLogin extends BaseAutoLogin { private static final Log LOG = LogFactoryUtil.getLog(OpenIDConnectAutoLogin.class); @Reference private Portal _portal; @Reference private UserLocalService _userLocalService; private LibAutoLogin libAutologin; private ConfigurationProvider _configurationProvider; @Reference protected void setConfigurationProvider(ConfigurationProvider configurationProvider) { _configurationProvider = configurationProvider; } public OpenIDConnectAutoLogin() { super(); } @Activate protected void activate() { libAutologin = new LibAutoLogin(new Liferay70Adapter(_userLocalService, _configurationProvider)); } @Override protected String[] doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { String currentURL = _portal.getCurrentURL(request); LOG.debug("[doLogin] currentURL: " + currentURL); String[] credentials = { "", "", "" }; credentials = libAutologin.doLogin(request, response); // Take care of redirection if(credentials != null && currentURL.contains("login") && credentials[0].equals("@other_auth@")) { User user = PortalUtil.getUser(request); credentials[0] = "" + user.getUserId(); LOG.debug("[doLogin] External authentication, userId: " + credentials[0]); String redirect = _portal.getPathMain(); request.setAttribute(AutoLogin.AUTO_LOGIN_REDIRECT, redirect); LOG.debug("[doLogin] redirect: " + redirect); } else if(currentURL.contains("login") && credentials[0].length() != 0) { // User just SignedIn String redirect = _portal.getPathMain(); request.setAttribute(AutoLogin.AUTO_LOGIN_REDIRECT, redirect); LOG.debug("[doLogin] redirect: " + redirect); } LOG.debug("[doLogin] Leaving credentials"); return credentials; } }
package rs2.model.game.entity.character.player; import rs2.model.game.entity.character.npc.NPCUpdating; /** * * @author Jake Bellotti * @since 1.0 */ public class PlayerUpdatingWorker implements Runnable { private final Player player; public PlayerUpdatingWorker(Player player) { this.player = player; } @Override public void run() { synchronized (player) { updatePlayer(); } } public final void updatePlayer() { try { PlayerUpdating.update(player); NPCUpdating.update(player); } catch (Exception ex) { ex.printStackTrace(); player.despawn(); } finally { onCompletion(); } } /** * Called when the synchronization is complete, override if you need to. */ public void onCompletion() { } }
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class Trie { private class TrieNode{ Map<Character, TrieNode> children; boolean isEndOfWord; public TrieNode(){ children = new HashMap<>(); //(Character, TrieNode); isEndOfWord = false; } } private final TrieNode root; public Trie(){ root = new TrieNode(); } /** Function to insert a TrieNode **/ public void insert(String word){ TrieNode current = root; for(int i=0; i<word.length(); i++){ char c = word.charAt(i); TrieNode node = current.children.get(c); if(node == null){ node = new TrieNode(); current.children.put(c,node); } current = node; } current.isEndOfWord = true; } /** Utility function 1 to insert a TrieNode. **/ public void insertRecursive(String word){ insertRecursive(root,word,0); } /** Utility function 2 to insert a TrieNode. **/ private void insertRecursive(TrieNode current, String word, int index){ if(index == word.length()){ current.isEndOfWord = true; return; } TrieNode node = current.children.get(word.charAt(index)); if(node == null){ node = new TrieNode(); current.children.put(word.charAt(index), node); } insertRecursive(node, word, index+1); } /** Function used to search if an entire string is present in the Tree. **/ public boolean search(String word){ TrieNode current = root; for(int i=0; i<word.length(); i++){ TrieNode node = current.children.get(word.charAt(i)); if(node == null) return false; current = node; } return current.isEndOfWord; } /** Utility function to search for the entire string in the Trie. **/ public boolean searchRecursive(String word){ return searchRecursive(root, word, 0); } /** Utility function to search for the entrie string in the Trie. **/ private boolean searchRecursive(TrieNode current, String word, int index){ if(index == word.length()) return current.isEndOfWord; TrieNode node = current.children.get(word.charAt(index)); if(node == null) return false; return searchRecursive(node, word, index+1); } /** Function to search for a prefix of a string alone in the Trie. **/ public boolean searchForPrefix(String prefix){ TrieNode current = root; TrieNode node; for(int i=0; i<prefix.length(); i++){ node = current.children.get(prefix.charAt(i)); if(node == null) return false; current = node; } return true; } /** Function to delete a String from the Tree. **/ public void delete(String word){ delete(root,word,0); } /** Utility function to delete a String from the Tree. **/ public boolean delete(TrieNode current, String word, int index){ if(index == word.length()){ if(!current.isEndOfWord) return false; current.isEndOfWord = true; return current.children.size()==0; } TrieNode node = current.children.get(word.charAt(index)); if(node == null) return false; boolean shouldDeleteCurrentNode = delete(node, word, index+1); if(shouldDeleteCurrentNode){ current.children.remove(word.charAt(index)); return current.children.size()==0; } return false; } public static void main(String[] args){ Trie TrieObject = new Trie(); /** Demo Data Structure Setup **/ TrieObject.insert("148908433"); TrieObject.insert("283133290"); TrieObject.insert("1050450"); TrieObject.insert("754243590"); TrieObject.insert("098248459"); TrieObject.insert("012948569"); /** Search iterating over a bag of words **/ /** List<String> bagOfWords = new ArrayList(); * bagOfWords => ["Hello", "the", "complaint", "is", "for", "LoanNo:", "1050450"]; */ // String emailContent = "Hello, I want to enquire for the Loan Number 283133290 and my complaint is that something isn't working."; String emailContent = "Hello, I want to enquire for my Loan Number 1050450. My complaint is that something isn't working. Bla Bla Bla."; System.out.println("EmailText: " + emailContent); System.out.println("Extracting the bag of words..."); String[] words = emailContent.replace(".", "").replace(",", "").replace("?", "").replace("!","").split(" "); System.out.print("Bag of Words: "); for(int i=0; i<words.length; i++) System.out.print(words[i] + " "); System.out.println(); List<String> bagOfWords = Arrays.asList(words); boolean doesExist = false; for(String word: bagOfWords) { doesExist = TrieObject.search(word); if (doesExist) { System.out.println("The loan number is: " + word); break; } } if(!doesExist) System.out.println("No Loan Number found in the text!"); /* TrieObject.insert("abc"); TrieObject.insert("abgl"); TrieObject.insert("cdf"); TrieObject.insert("abcd"); TrieObject.insert("lmn"); System.out.println("Words inserted!"); boolean doesExist = TrieObject.search("ab"); System.out.println(doesExist); TrieObject.delete("abgl"); System.out.println("Deleted abgl"); doesExist = TrieObject.search("abcd"); System.out.println(doesExist); TrieObject.delete("lmn"); System.out.println("Deleted lmn"); doesExist = TrieObject.searchForPrefix("l"); System.out.println(doesExist); */ } }
package peace.developer.serj.photoloader.interfaces; public interface ApiCallback extends BaseCallBack { void onResponse(String response); }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; public class DBItems { public ArrayList<FoodItem> getMenuFromDB(String cusine) throws SQLException { Connection conn = null; Statement stmt = null; ResultSet rs = null; ArrayList<FoodItem> menuItems = new ArrayList<>(); try { // DB parameters\ String url = "jdbc:sqlite:/home/harid/workspace_java/RestaurantMine/db/restaurantDB.db"; // Create a connection to the database conn = DriverManager.getConnection(url); stmt = conn.createStatement(); String where = ""; if (cusine != null) { where = "WHERE Cuisine LIKE '%" + cusine + "%'"; } String query = "SELECT * FROM foodMenu " + where; rs = stmt.executeQuery(query); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (conn != null) { while (rs.next()) { FoodItem foodItem = new FoodItem(); foodItem.setDishName(rs.getString("Dish")); foodItem.setPrice(rs.getInt("Price")); menuItems.add(foodItem); } conn.close(); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } } return menuItems; } }
/** * */ package de.mOS.client.model; import de.smartmirror.smf.client.model.Model; /** * @author julianschultehullern * */ public interface HomeModel extends Model{ }
package com.luthfi.taxcalculator.common; public class EndPointConstant { public static final String TAX = "/tax"; }
package Vetor; public class Vet4 { //Atributos de classe do tipo float para cada posição do vetor: x, y e z para vet3; public float x; public float y; public float z; public float w; //Método construtor padrão, sem parâmetros, que zera os valores do vetor; public Vet4(){ this.x = 0; this.y = 0; this.z = 0; this.w = 0; } //Método construtor que recebe os valores do vetor, e estes são atribuídos aos atributos de classe; public Vet4(float x, float y, float z, float w){ this.x = x; this.y = x; this.z = z; this.w = w; } //Método que retorna o tamanho do vetor; public float getTamanho(){ float tamanho = (float) Math.sqrt(x * x + y * y + z * z + w * w); return tamanho; } //Método que normaliza o vetor; public Vet4 getNormalizado(){ Vet4 novo = new Vet4(); float tamanho = getTamanho(); novo.x = this.x / tamanho; novo.y = this.y / tamanho; novo.z = this.z / tamanho; novo.w = this.w / tamanho; return novo; } /*Método para adição de outro vetor. Estes deverão receber por parâmetro um outro vetor do mesmo tipo da classe, que deverá ser somado ao vetor atual;*/ public Vet4 adicionaVetor(Vet4 outro){ Vet4 novo = new Vet4(); novo.x = this.x + outro.x; novo.y = this.y + outro.y; novo.z = this.z + outro.z; novo.w = this.w + outro.w; return novo; } /*Métodos para subtração de outro vetor. Estes deverão receber por parâmetro um outro vetor do mesmo tipo da classe, que deverá ser subtraído ao vetor atual;*/ public Vet4 subtraiVetor(Vet4 outro){ Vet4 novo = new Vet4(); novo.x = this.x - outro.x; novo.y = this.y - outro.y; novo.z = this.z - outro.z; novo.w = this.w + outro.w; return novo; } //Método para a multiplicação do vetor por um escalar recebido por parâmetro; public Vet4 multiplicaEscalar(float escalar){ Vet4 novo = new Vet4(); novo.x = this.x * escalar; novo.y = this.y * escalar; novo.z = this.z * escalar; novo.w = this.w * escalar; return novo; } //Método para a divisão do vetor por um escalar recebido por parâmetro; public Vet4 divideEscalar(float escalar){ Vet4 novo = new Vet4(); novo.x = this.x / escalar; novo.y = this.y / escalar; novo.z = this.z / escalar; novo.w = this.w / escalar; return novo; } //Método para cálculo do produto escalar do vetor por outro vetor recebido por parâmetro, cujo resultado deve ser retornado; public float produtoEscalar(Vet4 outro){ float prod = this.x * outro.x + this.y * outro.y + this.z * outro.z + this.w * outro.w; return prod; } //Método que retorna uma nova cópia do vetor atual. public Vet4 getCopia(){ Vet4 novo = new Vet4(this.x, this.y, this.z, this.w); return novo; } //Método que retorna um vetor de floats com os valores do vetor. public float[] getVetor(){ float vet[] = new float[4]; vet[0] = this.x; vet[1] = this.y; vet[2] = this.z; vet[3] = this.w; return vet; } }
package com.lviv.football.constants; /** * Created by rudnitskih on 4/11/17. */ public interface Profiles { String DEV = "DEV"; String PROD = "PROD"; }
package execution; import definition.ContactList; import definition.Person; import helper.ContactListHelper; import java.util.Scanner; public class ContactListApp { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ContactList contactList = new ContactList(); ContactListHelper contactListHelper = new ContactListHelper(); int choice = 0; while (choice != 5) { System.out.println("Welcome to KDP's Contact List App\n" + "Press 1 to add a new contact\n" + "Press 2 to view all contacts\n" + "Press 3 to search for a contact\n" + "Press 4 to delete a contact\n" + "Press 5 to exit program "); choice = sc.nextInt(); switch (choice) { case 1: System.out.println("You have chosen to add a new contact:"); Person person = contactListHelper.addContactMenu(); contactList.add(person); contactList.sort(); break; case 2: System.out.println("---Here are all your contacts---"); contactListHelper.viewContactMenu(contactList); break; case 3: System.out.println("You could search for a contact from their first names: "); contactListHelper.searchContactMenu(contactList); break; } } } }
package com.weathair.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; import com.weathair.entities.User; import com.weathair.repositories.UserRepository; @Service public class SecurityMethodsService { @Autowired private UserRepository userRepository; public boolean isConnectedUser(Integer userId, UserDetails connectedUser) { User user = userRepository.findById(userId).orElse(null); return user != null && user.getEmail().equals(connectedUser.getUsername()); } }
package com.ivirych.qaapplication.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.ivirych.qaapplication.model.Answer; import com.ivirych.qaapplication.model.Question; @Repository public class AnswerDaoImpl implements AnswerDao { @Autowired private SessionFactory sessionFactory; @Autowired private UserDao userDao; @SuppressWarnings("unchecked") @Override public List<Answer> getAnswers(int id) { return sessionFactory.getCurrentSession(). createQuery("from Answer where questionid = " + id).list(); } @Override public Answer getAnswer(int id) { Answer answer = (Answer)sessionFactory.getCurrentSession().get(Answer.class, id); return answer; } @Override public void add(int id, String username, Answer answer) { Question existingQuestion = (Question)sessionFactory.getCurrentSession(). get(Question.class, id); answer.setQuestion(existingQuestion); answer.setUser(userDao.findUserByName(username)); sessionFactory.getCurrentSession().save(answer); } @Override public void edit(int id, Answer answer) { Session session = sessionFactory.getCurrentSession(); Question existingQuestion = (Question)session.get(Question.class, id); Answer existingAnswer = (Answer)session.get(Answer.class, answer.getId()); existingAnswer.setQuestion(existingQuestion); existingAnswer.setDescription(answer.getDescription()); session.save(existingAnswer); } @Override public void delete(int id) { Session session = sessionFactory.getCurrentSession(); Answer answer = (Answer)session.get(Answer.class, id); session.delete(answer); } @Override public void deleteAll(int id) { Session session = sessionFactory.getCurrentSession(); session.createQuery("DELETE FROM Answer WHERE questionid=" + id).executeUpdate(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package stability; import application.ExpoGenerator; import network.Node; import network.Scenario; import network.TDMAScheduller; /** * * @author bruker */ public class ExpoTest { /** * @param args the command line arguments */ public static void main(String[] args) { // SimpleDynamic.verbose = SimpleDynamic.Verbose.PRINT_QUEUE_LENGTHS; // LocalVoting.verbose = LocalVoting.Verbose.PRINT_QUEUE_LENGTHS; // LocalVoting.verbose = LocalVoting.Verbose.PRINT_SLOTS; // LocalVoting.verbose = LocalVoting.Verbose.PRINT_X; // LocalVoting.verbose.add(LocalVoting.Verbose.PRINT_SLOTS); // LocalVoting.verbose.add(LocalVoting.Verbose.PRINT_QUEUE_LENGTHS); // LocalVoting.verbose.add(LocalVoting.Verbose.PRINT_X); // LocalVoting.verbose.add(LocalVoting.Verbose.PRINT_SLOT_EXCHANGE); int nodes = 100; double transmissionRange = 10; double topologySize = 100; int slots = 10; double arrivalRate = 0.0001; Scenario.SchedulerType type = Scenario.SchedulerType.Lobats; Node.packet_loss = 0.0D; // Scenario scenario = new Scenario(10, 10, 50, 10, Scenario.SchedulerType.Balanced); Scenario scenario = new Scenario(nodes, transmissionRange, topologySize, slots, type); ExpoGenerator expoGen = new ExpoGenerator(scenario, arrivalRate, 0.001); scenario.network.stats = expoGen.stats; // Set<Connection> connectionSet = expoGen.conSet; scenario.simulator.run(); // scenario.printStats(); // for (Connection conn : connectionSet) { // System.out.println("Connection: " + conn.getTotalTime()); // conn.dump(); // } expoGen.stats.dump(); expoGen.stats.dump_hist(); } }
package com.atguigu.springboot.controller; import com.atguigu.springboot.properties.DataSourceProperties; import com.atguigu.springboot.properties.DataSourceProperties2; import com.atguigu.springboot.properties.JdbcProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @EnableConfigurationProperties(JdbcProperties.class) public class HelloController { @Autowired DataSourceProperties dataSourceProperties; // @Autowired // DataSourceProperties2 dataSourceProperties2; @Autowired JdbcProperties jdbcProperties; //获取端口号 // @Value("${server.port}") // private String port; @RequestMapping("/hello") public String hello(){ System.out.println(dataSourceProperties); // System.out.println(dataSourceProperties2); // System.out.println("port"+port); System.out.println(jdbcProperties); return "hello spring"; } }
package com.streetsnax.srinidhi.streetsnax.adapters; /** * Created by I15230 on 12/31/2015. */ import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.streetsnax.srinidhi.streetsnax.R; import com.streetsnax.srinidhi.streetsnax.utilities.ItemDetails; import java.io.InputStream; import java.util.ArrayList; public class ItemListBaseAdapter extends BaseAdapter { private static ArrayList<ItemDetails> itemDetailsrrayList; private LayoutInflater l_Inflater; public ItemListBaseAdapter(Context context, ArrayList<ItemDetails> results) { itemDetailsrrayList = results; l_Inflater = LayoutInflater.from(context); } public int getCount() { return itemDetailsrrayList.size(); } public Object getItem(int position) { return itemDetailsrrayList.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = l_Inflater.inflate(R.layout.search_item_list, null); holder = new ViewHolder(); holder.searchImageContent = (ImageView) convertView.findViewById(R.id.searchImageContent); holder.searchTextContent = (TextView) convertView.findViewById(R.id.searchTextContent); holder.searchSnackContent = (TextView) convertView.findViewById(R.id.searchSnackContent); holder.snackPlaceName = (TextView) convertView.findViewById(R.id.snackPlaceName); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.searchTextContent.setText(itemDetailsrrayList.get(position).getplaceAddress()); new DownloadImageTask(holder.searchImageContent).execute(itemDetailsrrayList.get(position).getItemImageSrc()); holder.searchSnackContent.setText(itemDetailsrrayList.get(position).getsnackType()); holder.snackPlaceName.setText(itemDetailsrrayList.get(position).getsnackPlaceName()); return convertView; } static class ViewHolder { TextView snackPlaceName; TextView searchTextContent; ImageView searchImageContent; TextView searchSnackContent; } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } } }
package kr.co.shop.batch.sample.vo.xml.generator; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlValue; import lombok.Data; @XmlRootElement(name="property") @XmlAccessorType(XmlAccessType.FIELD) @Data public class Property { @XmlAttribute private String key; @XmlValue private String value; }
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class Serialize { public static void main(String[] args) throws IOException { User user = new User("saba", "saba@gmail.com", 1234); FileOutputStream fos = new FileOutputStream("1.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(user); oos.close(); fos.close(); } }
package pl.kur.firstapp; import java.util.Scanner; public class Zadanie3 { public void Trojkat() { Scanner scan = new Scanner(System.in); System.out.println("TROJKAT"); System.out.println(" "); System.out.println("Podaj bok a: "); int a = scan.nextInt(); System.out.println("Podaj bok b: "); int b = scan.nextInt(); System.out.println("Podaj bok c: "); int c = scan.nextInt(); if (a<=0||b<=0||c<=0) { System.out.println("Cos popsules!"); } else { if ((a*a)+(b*b) ==(c*c)) { System.out.println("Trojkat jest prostokatny"); } else { System.out.println("Trojkat nie jest prostokatny"); } } } }
package com.crmiguez.aixinainventory.apirest; import com.crmiguez.aixinainventory.entities.Brand; import com.crmiguez.aixinainventory.exception.ResourceNotFoundException; import com.crmiguez.aixinainventory.service.brand.IBrandService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController //@RequestMapping("/api_aixina/v1") @RequestMapping("/api_aixina/v1/brandmanage") @CrossOrigin(origins = "*", methods= {RequestMethod.GET,RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}) public class BrandController { @Autowired @Qualifier("brandService") private IBrandService brandService; @PreAuthorize("hasAuthority('PERM_READ_ALL_BRANDS')") @GetMapping("/brands") public List<Brand> getAllBrands() { return brandService.findAllBrands(); } @PreAuthorize("hasAuthority('PERM_READ_BRAND')") @GetMapping("/brands/{id}") public ResponseEntity<Brand> getBrandById( @PathVariable(value = "id") String brandId) throws ResourceNotFoundException { Brand brand = brandService.findBrandById(brandId) .orElseThrow(() -> new ResourceNotFoundException("Brand not found on :: "+ brandId)); return ResponseEntity.ok().body(brand); } @PreAuthorize("hasAuthority('PERM_CREATE_BRAND')") @PostMapping("/brand") public Brand createBrand(@Valid @RequestBody Brand brand) { return brandService.addBrand(brand); } @PreAuthorize("hasAuthority('PERM_UPDATE_BRAND')") @PutMapping("/brands/{id}") public ResponseEntity<Brand> updateBrand( @PathVariable(value = "id") String brandId, @Valid @RequestBody Brand brandDetails) throws ResourceNotFoundException { Brand brand = brandService.findBrandById(brandId) .orElseThrow(() -> new ResourceNotFoundException("Brand not found on :: "+ brandId)); final Brand updatedBrand = brandService.updateBrand(brandDetails, brand); if (updatedBrand == null){ return new ResponseEntity<Brand>(HttpStatus.EXPECTATION_FAILED); } else { return ResponseEntity.ok(updatedBrand); } } @PreAuthorize("hasAuthority('PERM_DELETE_BRAND')") @DeleteMapping("/brand/{id}") public Map<String, Boolean> deleteBrand( @PathVariable(value = "id") String brandId) throws Exception { Brand Brand = brandService.findBrandById(brandId) .orElseThrow(() -> new ResourceNotFoundException("Brand not found on :: "+ brandId)); brandService.deleteBrand(Brand); Map<String, Boolean> response = new HashMap<>(); response.put("deleted", Boolean.TRUE); return response; } }
package org.isc.certanalysis.repository; import org.isc.certanalysis.domain.CrlMailLog; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * @author p.dzeviarylin */ @Repository public interface CrlMailLogRepository extends JpaRepository<CrlMailLog, Long> { }
package mc.server.servlets; import mc.server.comm.CommAPI; import mc.server.types.TypeVectorDouble; import mc.server.types.TypeMatrixDouble; import mc.server.types.TypeVectorInt; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Random; import org.apache.commons.lang3.ArrayUtils; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; /** * Defines the tasks done at the master nodes * This is the Main Server to be run on master node, with the custom functions * * @author Yaoqing Yang */ public class AppMaster { final private static int RecThreshold = 10; final private static int OverallSize = 105000; final private static int NumWorkers_initial = 20; final private static int SendSize = 10000; final private static int SamplePerWorker = OverallSize/NumWorkers_initial; final private static int CodedSamplePerWorker = SamplePerWorker*(NumWorkers_initial/RecThreshold); private static int[] NumWorkersSet = {10, 12, 15, 18, 20}; private static int NumWorkers = NumWorkers_initial; // This number can change over time private static int ReceiveSize = CodedSamplePerWorker/NumWorkers*RecThreshold; private static int elastic_size = CodedSamplePerWorker/NumWorkers; final private static Logger logger = LogManager.getLogger(AppMaster.class); private List<String> dns_arr_workers = CommAPI.getEC2DNSList("worker", ","); private static AtomicReference<String> shared = new AtomicReference<>(); private volatile TypeMatrixDouble xt_receive = new TypeMatrixDouble(NumWorkers,ReceiveSize,0,0); private static TypeMatrixDouble Decoding_matrix = new TypeMatrixDouble(NumWorkers_initial,RecThreshold,-1,1); private TypeMatrixDouble[] Decoding_matrix_collections; private Random rand = new Random(); private boolean ChangeNumMachinesCall = false; // Indicate a change on the number of machines public void initTask() { try { logger.info("------------------- Start the master task -------------------"); Decoding_matrix_collections = select_encoding_matrix(Decoding_matrix); TypeMatrixDouble[] Received_rearranged = new TypeMatrixDouble[NumWorkers]; long iter_num_all = 1000; long iter_num_not_count = 100; // The time_ave is for logging the average time for different configurations long[] time_ave = new long[NumWorkersSet.length]; java.util.Arrays.fill(time_ave, 0); // The time_length is for logging the number of queries from different configurations long[] time_length = new long[NumWorkersSet.length]; java.util.Arrays.fill(time_length, 0); // The time_log is for logging the time for each iteration long[] time_log = new long[(int) (iter_num_all-iter_num_not_count)]; java.util.Arrays.fill(time_log, 0); for (long iter_num = 0; iter_num < iter_num_all + 1; iter_num++) { logger.info("------------------- This is the " + iter_num + "-th iteration -------------------"); if (iter_num > 0 && Math.random() < 0.02) { int NumWorkers_old = NumWorkers; while (NumWorkers_old == NumWorkers) { NumWorkers = NumWorkersSet[rand.nextInt(NumWorkersSet.length)]; } logger.info("The number of machines changes to " + NumWorkers + "!!"); // Change the settings on the master ChangeNumMachinesCall = true; UpdateSettingsWhenNumMachinesChange(); } // Generate a random input vector TypeVectorDouble vect = new TypeVectorDouble(SendSize + 1, 0, 100); vect.SetValue((double) NumWorkers, SendSize); // Serialize // Set the input vector to the atomic reference for different threads to access shared.set(CommAPI.stringURLEncode(vect.serialize(","))); // Start the threads long ThreadTimeStart = System.nanoTime(); ExecutorService executor = Executors.newFixedThreadPool(NumWorkers); int count = 0; for (String dns : dns_arr_workers) { // Only send data to the remaining workers count++; if (count > NumWorkers) { break; } int ind = dns_arr_workers.indexOf(dns); Runnable worker = new MyRunnable(dns, ind, ReceiveSize, ThreadTimeStart, iter_num); executor.execute(worker); } // Shut down threads executor.shutdown(); while (!executor.isTerminated()) { } logger.info("Time taken to complete all communication round is " + (System.nanoTime() - ThreadTimeStart) / 1000000); if (iter_num == 0 || ChangeNumMachinesCall) { // the first iteration is only for sending the worker id // when NumWorkers changes, broadcast the NumWorkers // no need to decode in these two situations // Also skip the logging phase to show a verticle line in the plot ChangeNumMachinesCall = false; continue; } else { // Decoding long DecodingTimeStart = System.nanoTime(); // rearrange the received vectors for (int group_ind = 0; group_ind < NumWorkers; group_ind++) { Received_rearranged[group_ind] = new TypeMatrixDouble(RecThreshold, elastic_size); int start_block_in_node = (1 + group_ind) % NumWorkers; for (int node_in_this_group = 0; node_in_this_group < RecThreshold; node_in_this_group++) { int node_id = (start_block_in_node + node_in_this_group) % NumWorkers; int row_id = (NumWorkers - 1 - node_in_this_group) % RecThreshold; Received_rearranged[group_ind].set_row(node_in_this_group, xt_receive.sub_row(node_id, row_id * elastic_size, elastic_size)); } TypeMatrixDouble prodMatrix = Decoding_matrix_collections[group_ind].matMatMultGiveMat(Received_rearranged[group_ind]); if (iter_num == 1 && group_ind == 0) { try { prodMatrix.writeMatToFile("/home/ubuntu/result.txt", " ", "\n"); double vectSum = vect.vecSum(); TypeVectorDouble vectSum0 = new TypeVectorDouble(1, new double[]{vectSum}); vectSum0.writeVectToFile("/home/ubuntu/vector_sum.txt", " "); } catch (IOException e) { e.printStackTrace(); } } } logger.info("Time taken to complete decoding is " + (System.nanoTime() - DecodingTimeStart) / 1000000); // Update the timing statistics if (iter_num > iter_num_not_count) { // Log the timing information long timeSpent = (System.nanoTime() - ThreadTimeStart) / 1000000; time_log[(int) (iter_num - 1 - iter_num_not_count)] = timeSpent; int configureInd = ArrayUtils.indexOf(NumWorkersSet, NumWorkers); if (configureInd == -1) { throw new ArithmeticException("Number of workers is not properly updated!!"); } time_length[configureInd] += 1; time_ave[configureInd] += timeSpent; } } } for (int i = 0; i < time_ave.length; i++) { logger.info("Average time per iteration when NumWorkers = " + NumWorkersSet[i] + " is " + time_ave[i] / time_length[i] + " and the number of iterations is " + time_length[i]); } logger.info("The following is the log of the per-iteration time:\n"); String u = ""; for (int i = 0; i < time_log.length; i++) { u += time_log[i]+", "; } logger.info(u + "\n"); TypeVectorInt time_log_to_file = new TypeVectorInt((int) (iter_num_all - iter_num_not_count), time_log); time_log_to_file.writeVectToFile("/home/ubuntu/time_log.txt", " "); } catch (Exception e) { logger.error(e.toString()); e.printStackTrace(); } } private void UpdateSettingsWhenNumMachinesChange() { // Randomly generate the number of machines ReceiveSize = CodedSamplePerWorker/NumWorkers*RecThreshold; elastic_size = CodedSamplePerWorker/NumWorkers; xt_receive = new TypeMatrixDouble(NumWorkers,ReceiveSize,0,0); Decoding_matrix_collections = select_encoding_matrix(Decoding_matrix); } private TypeMatrixDouble[] select_encoding_matrix(TypeMatrixDouble Decoding_matrix) { TypeMatrixDouble[] Generator_matrix_collections = new TypeMatrixDouble[NumWorkers]; TypeMatrixDouble[] Decoding_matrix_collections = new TypeMatrixDouble[NumWorkers]; int start_ind; int ind; for (int i=0; i<NumWorkers; i++) { Generator_matrix_collections[i] = new TypeMatrixDouble(RecThreshold,RecThreshold,0,100); Decoding_matrix_collections[i] = new TypeMatrixDouble(RecThreshold,RecThreshold,0,100); start_ind = i+1; for (int j=0; j<RecThreshold; j++) { // The ind is calculated using the cyclic shift method ind = (start_ind + j)%NumWorkers; Generator_matrix_collections[i].set_row(j,Decoding_matrix,ind); } Decoding_matrix_collections[i] = Generator_matrix_collections[i].matInv(); } return Decoding_matrix_collections; } public class MyRunnable implements Runnable { private final String dns; private final int ind; private final int length; private final long iter_num; MyRunnable(String dns, int ind, int length, long multithreading_time_start, long iter_num) { this.dns = dns; this.ind = ind; this.length = length; this.iter_num = iter_num; } @Override public void run() { try { if (this.iter_num==0) { double[] vectInd = new double[1]; vectInd[0] = this.ind; double[] vectG = Decoding_matrix.toVect(); TypeVectorDouble vectConcat = new TypeVectorDouble(1+NumWorkers_initial*RecThreshold); vectConcat.Concate(vectG, vectInd); String vect = CommAPI.stringURLEncode(vectConcat.serialize(",")); String vectResp = CommAPI.sendGetRequest("http", dns, "/worker", new HashMap<String, Object>() {{ put("vectIn", vect); }}); logger.info("Send the worker id to worker "+ind); } else { String vect = shared.get(); String vectResp = CommAPI.sendGetRequest("http", dns, "/worker", new HashMap<String, Object>() {{ put("vectIn", vect); }}); TypeVectorDouble finVect = new TypeVectorDouble(length); finVect.deserialize(CommAPI.stringURLDecode(vectResp), ","); xt_receive.set_row(this.ind, finVect); } } catch (Exception e) { e.printStackTrace(); } } } }
package com.onightperson.hearken.scroll; import android.os.Bundle; import android.widget.ListView; import com.onightperson.hearken.R; import com.onightperson.hearken.base.BaseActivity; /** * Created by liubaozhu on 17/8/21. */ public class HorizontalScrollViewTestActivity extends BaseActivity { private ListView mListView; private InfoAdapter mInfoAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_horizontal_scroll_layout); initViews(); } private void initViews() { mListView = (ListView) findViewById(R.id.class_info); mInfoAdapter = new InfoAdapter(this, ScrollUtils.getData()); mListView.setAdapter(mInfoAdapter); } }
package com.daexsys.automata.gui; import com.daexsys.automata.Tile; import com.daexsys.automata.gui.util.ImageUtil; import com.daexsys.automata.world.Chunk; import com.daexsys.automata.world.ChunkCoord; import com.daexsys.automata.world.ChunkManager; import com.daexsys.automata.world.structures.Structure; import com.daexsys.automata.world.structures.StructureElement; import com.daexsys.automata.world.World; import com.daexsys.automata.world.tiletypes.TileType; import java.awt.*; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class WorldRenderer implements Renderable { private GUI gui; private World world; private BufferedImage chargedSolarPanel = ImageUtil.loadImage("images/chargedsolarpanel.png"); public WorldRenderer(GUI gui) { this.gui = gui; this.world = gui.getGame().getWorld(); } public GUI getGUI() { return gui; } @Override public void render(Graphics graphics) { ChunkManager chunkManager = world.getChunkManager(); List<Chunk> toRender = getChunksToRender(chunkManager); for(Chunk chunk : toRender) { ChunkCoord chunkCoordinate = chunk.getChunkCoordinate(); for (int x = 0; x < Chunk.DEFAULT_CHUNK_SIZE; x++) { for (int y = 0; y < Chunk.DEFAULT_CHUNK_SIZE; y++) { for (int layer = 0; layer < 2; layer++) { Tile tile = chunk.getTile(layer, x, y); if (tile.getType() != TileType.AIR) { BufferedImage imageToRender = tile.getType().getImage();; if(tile.getType() == TileType.SOLAR_PANEL) { if(tile.getEnergy() > 0) imageToRender = chargedSolarPanel; } // If it's small enough, we don't have to render the whole image if (getGUI().getZoomLevel() <= 4) { graphics.setColor(new Color(imageToRender.getRGB(0, 0))); graphics.fillRect(chunkCoordinate.amplifyLocalX(x) * getGUI().getZoomLevel() + getGUI().getOffsets().getOffsetX(), chunkCoordinate.amplifyLocalY(y) * getGUI().getZoomLevel() + getGUI().getOffsets().getOffsetY(), getGUI().getZoomLevel(), getGUI().getZoomLevel()); } else { graphics.drawImage(imageToRender, chunkCoordinate.amplifyLocalX(x) * getGUI().getZoomLevel() + getGUI().getOffsets().getOffsetX(), chunkCoordinate.amplifyLocalY(y) * getGUI().getZoomLevel() + getGUI().getOffsets().getOffsetY(), getGUI().getZoomLevel(), getGUI().getZoomLevel(), null ); } } } } } } graphics.setColor(new Color(50, 50, 50, 155)); Structure structure = getGUI().getGame().getPlayerState().getSelectedStructure(); if(structure == null) { graphics.fillRect( getGUI().getMouseMotionHandler().getTileX() * getGUI().getZoomLevel(), getGUI().getMouseMotionHandler().getTileY() * getGUI().getZoomLevel(), getGUI().getZoomLevel(), getGUI().getZoomLevel() ); } else { for (StructureElement structureElement : structure.getStructureElements()) { graphics.fillRect( (getGUI().getMouseMotionHandler().getTileX() + structureElement.getX()) * getGUI().getZoomLevel(), (getGUI().getMouseMotionHandler().getTileY() + structureElement.getY()) * getGUI().getZoomLevel(), getGUI().getZoomLevel(), getGUI().getZoomLevel()); } } } public List<Chunk> getChunksToRender(ChunkManager chunkManager) { Collection<Chunk> allChunks = chunkManager.getChunks(); List<Chunk> toRender = new ArrayList<Chunk>(); Rectangle screen = new Rectangle(0, 0, (int) getGUI().getWindowSize().getWidth(), (int) getGUI().getWindowSize().getHeight()); for(Chunk c : allChunks) { int sx = c.getChunkCoordinate().x * 16 * gui.getZoomLevel() + gui.getOffsets().getOffsetX(); int sy = c.getChunkCoordinate().y * 16 * gui.getZoomLevel() + gui.getOffsets().getOffsetY(); int xcf = 16 * gui.getZoomLevel(); int ycf = 16 * gui.getZoomLevel(); Rectangle chunkTangle = new Rectangle(sx, sy, xcf, ycf); if(screen.intersects(chunkTangle)) { toRender.add(c); } } return toRender; } }
package mx.com.mentoringit.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { //private static final SessionFactory SESSION_FACTORY = buildSessionFactory(); public static SessionFactory buildSessionFactory() { SessionFactory sessionFactory = null; try { sessionFactory = new Configuration().configure() .buildSessionFactory(); } catch (Exception e) { e.printStackTrace(); } return sessionFactory; } public static SessionFactory buildSessionFactory(String fileHbm) { SessionFactory sessionFactory = null; try { sessionFactory = new Configuration().configure(fileHbm) .buildSessionFactory(); } catch (Exception e) { e.printStackTrace(); } return sessionFactory; } }
package com.alibaba.datax.plugin.writer.dolphindbwriter; import com.alibaba.datax.common.element.*; import com.alibaba.datax.common.plugin.RecordReceiver; import com.alibaba.datax.common.spi.Writer; import com.alibaba.datax.common.util.Configuration; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.xxdb.DBConnection; import com.xxdb.data.*; import com.xxdb.io.Long2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by apple on 2020/2/6. * python /Users/apple/Documents/datax/datax/bin/datax.py /Users/apple/Documents/datax/datax/job/plugin_job_template.json * auth by stx */ public class DolphinDbWriter extends Writer { public static class Job extends Writer.Job { private static final Logger LOG = LoggerFactory.getLogger(Job.class); private Configuration writerConfig = null; @Override public List<Configuration> split(int mandatoryNumber) { List<Configuration> configurations = new ArrayList<Configuration>(mandatoryNumber); for (int i = 0; i < mandatoryNumber; i++) { configurations.add(writerConfig); } return configurations; } @Override public void init() { this.writerConfig = this.getPluginJobConf(); this.validateParameter(); LOG.info("dolphindbwriter params:{}", this.writerConfig.toJSON()); } @Override public void destroy() { } /** * */ private void validateParameter() { this.writerConfig.getNecessaryValue(Key.HOST, DolphinDbWriterErrorCode.REQUIRED_VALUE); this.writerConfig.getNecessaryValue(Key.PORT, DolphinDbWriterErrorCode.REQUIRED_VALUE); this.writerConfig.getNecessaryValue(Key.PWD, DolphinDbWriterErrorCode.REQUIRED_VALUE); this.writerConfig.getNecessaryValue(Key.USER_ID, DolphinDbWriterErrorCode.REQUIRED_VALUE); } } public static class Task extends Writer.Task { private static final Logger LOG = LoggerFactory.getLogger(Job.class); private HashMap<String, List> cols = null; private Configuration writerConfig = null; private DBConnection dbConnection = null; private String functionSql = ""; @Override public void startWrite(RecordReceiver lineReceiver) { LOG.info("start to writer DolphinDB"); Record record = null; List<Object> tableField = this.writerConfig.getList(Key.TABLE); JSONArray fieldArr = JSONArray.parseArray(JSON.toJSONString(tableField)); Integer batchSize = this.writerConfig.getInt(Key.BATCH_SIZE); if(batchSize==null){ batchSize = 10000000; } while ((record = lineReceiver.getFromReader()) != null) { recordToBasicTable(record, fieldArr); List firstColumn = this.cols.get(fieldArr.getJSONObject(0).getString("name")); if (firstColumn.size() >= batchSize.intValue()) { insertToDolphinDB(createUploadTable(fieldArr)); initColumn(fieldArr); } } } private void insertToDolphinDB(BasicTable bt) { LOG.info("begin to write BasicTable rows = " + String.valueOf(bt.rows())); List<Entity> args = new ArrayList<>(); args.add(bt); try { dbConnection.run(this.functionSql, args); LOG.info("end write BasicTable"); } catch (IOException ex) { LOG.error(ex.getMessage()); } } private void recordToBasicTable(Record record, JSONArray fieldArr) { int recordLength = record.getColumnNumber(); Column column; for (int i = 0; i < recordLength; i++) { JSONObject field = fieldArr.getJSONObject(i); String colName = field.getString("name"); Entity.DATA_TYPE type = Entity.DATA_TYPE.valueOf(field.getString("type")); column = record.getColumn(i); setData(colName, column, type); } } private void setData(String colName, Column column, Entity.DATA_TYPE targetType) { List colData = this.cols.get(colName); switch (targetType) { case DT_DOUBLE: if (column.getRawData() == null) colData.add(-Double.MAX_VALUE); else colData.add(column.asDouble()); break; case DT_FLOAT: if (column.getRawData() == null) colData.add(-Float.MAX_VALUE); else colData.add(Float.parseFloat(column.asString())); break; case DT_BOOL: if (column.getRawData() == null) colData.add((byte) -128); else colData.add(column.asBoolean() == true ? (byte) 1 : (byte) 0); break; case DT_DATE: if (column.getRawData() == null) colData.add(Integer.MIN_VALUE); else colData.add(Utils.countDays(column.asDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())); break; case DT_MONTH: if (column.getRawData() == null) colData.add(Integer.MIN_VALUE); else { LocalDate d = column.asDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); colData.add(Utils.countMonths(d.getYear(),d.getMonthValue())); } break; case DT_DATETIME: if (column.getRawData() == null) colData.add(Integer.MIN_VALUE); else colData.add(Utils.countSeconds(column.asDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime())); break; case DT_TIME: if (column.getRawData() == null) colData.add(Integer.MIN_VALUE); else colData.add(Utils.countSeconds(column.asDate().toInstant().atZone(ZoneId.systemDefault()).toLocalTime())); break; case DT_TIMESTAMP: if (column.getRawData() == null) colData.add(Long.MIN_VALUE); else colData.add(Utils.countMilliseconds(column.asDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime())); break; case DT_NANOTIME: if (column.getRawData() == null) colData.add(Long.MIN_VALUE); else colData.add(Utils.countNanoseconds(column.asDate().toInstant().atZone(ZoneId.systemDefault()).toLocalTime())); break; case DT_NANOTIMESTAMP: if (column.getRawData() == null) colData.add(Long.MIN_VALUE); else colData.add(Utils.countNanoseconds(column.asDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime())); break; case DT_LONG: if (column.getRawData() == null) colData.add(Long.MIN_VALUE); else colData.add(column.asLong()); break; case DT_INT: if (column.getRawData() == null) colData.add(Integer.MIN_VALUE); else colData.add(Integer.parseInt(column.asString())); break; case DT_UUID: if (column.getRawData() == null) colData.add(new Long2(0,0)); else colData.add(BasicUuid.fromString(column.asString()).getLong2()); break; case DT_SHORT: if (column.getRawData() == null) colData.add(Short.MIN_VALUE); else colData.add(Short.parseShort(column.asString())); break; case DT_STRING: case DT_SYMBOL: if (column.getRawData() == null) colData.add(""); else colData.add(column.asString()); break; case DT_BYTE: if (column.getRawData() == null) colData.add((byte) -128); else colData.add(column.asBytes()); break; } } private List getListFromColumn(Entity.DATA_TYPE targetType) { List vec = null; switch (targetType) { case DT_DOUBLE: vec = new ArrayList<Double>(); break; case DT_FLOAT: vec = new ArrayList<Float>(); break; case DT_BOOL: vec = new ArrayList<Boolean>(); break; case DT_DATE: case DT_MONTH: case DT_DATETIME: case DT_TIME: case DT_INT: vec = new ArrayList<Integer>(); break; case DT_TIMESTAMP: case DT_NANOTIME: case DT_NANOTIMESTAMP: case DT_LONG: vec = new ArrayList<Long>(); break; case DT_UUID: vec = new ArrayList<Long2>(); break; case DT_SHORT: vec = new ArrayList<Short>(); break; case DT_STRING: case DT_SYMBOL: vec = new ArrayList<String>(); break; case DT_BYTE: vec = new ArrayList<Byte>(); break; } if (vec == null) LOG.info(targetType.toString() + " get Vec is NULL!!!!!"); return vec; } private BasicTable createUploadTable(JSONArray fieldArr) { List<Vector> columns = new ArrayList<>(); List<String> columnNames = new ArrayList<>(); for (int i = 0; i < fieldArr.size(); i++) { JSONObject field = fieldArr.getJSONObject(i); String colName = field.getString("name"); columnNames.add(colName); Entity.DATA_TYPE type = Entity.DATA_TYPE.valueOf(field.getString("type")); columns.add(getDDBColFromColumn(this.cols.get(colName), type)); } BasicTable bt = new BasicTable(columnNames, columns); return bt; } private Vector getDDBColFromColumn(List colData, Entity.DATA_TYPE targetType) { Vector vec = null; switch (targetType) { case DT_DOUBLE: vec = new BasicDoubleVector(colData); break; case DT_FLOAT: vec = new BasicFloatVector(colData); break; case DT_BOOL: vec = new BasicBooleanVector(colData); break; case DT_DATE: vec = new BasicDateVector(colData); break; case DT_MONTH: vec = new BasicMonthVector(colData); break; case DT_DATETIME: vec = new BasicDateTimeVector(colData); break; case DT_TIME: vec = new BasicTimeVector(colData); break; case DT_TIMESTAMP: vec = new BasicTimestampVector(colData); break; case DT_NANOTIME: vec = new BasicNanoTimeVector(colData); break; case DT_NANOTIMESTAMP: vec = new BasicNanoTimestampVector(colData); break; case DT_LONG: vec = new BasicLongVector(colData); break; case DT_INT: vec = new BasicIntVector(colData); break; case DT_UUID: vec = new BasicUuidVector(colData); break; case DT_SHORT: vec = new BasicShortVector(colData); break; case DT_STRING: case DT_SYMBOL: vec = new BasicStringVector(colData); break; case DT_BYTE: vec = new BasicByteVector(colData); } return vec; } private void initColumn(JSONArray fieldArr) { this.cols = new HashMap<>(); for (int i = 0; i < fieldArr.size(); i++) { JSONObject field = fieldArr.getJSONObject(i); String colName = field.getString("name"); Entity.DATA_TYPE type = Entity.DATA_TYPE.valueOf(field.getString("type")); List colData = getListFromColumn(type); this.cols.put(colName, colData); } } @Override public void init() { this.writerConfig = super.getPluginJobConf(); String host = this.writerConfig.getString(Key.HOST); int port = this.writerConfig.getInt(Key.PORT); String userid = this.writerConfig.getString(Key.USER_ID); String pwd = this.writerConfig.getString(Key.PWD); String saveFunctionDef = this.writerConfig.getString(Key.SAVE_FUNCTION_DEF); String saveFunctionName = this.writerConfig.getString(Key.SAVE_FUNCTION_NAME); String dbName = this.writerConfig.getString(Key.DB_NAME); String tbName = this.writerConfig.getString(Key.TABLE_NAME); this.functionSql = String.format("tableInsert{loadTable('%s','%s')}", dbName, tbName); List<Object> tableField = this.writerConfig.getList(Key.TABLE); JSONArray fieldArr = JSONArray.parseArray(JSON.toJSONString(tableField)); initColumn(fieldArr); if (saveFunctionName != null && !saveFunctionName.equals("")) { if (saveFunctionDef == null || saveFunctionDef.equals("")) { switch (saveFunctionName) { case "savePartitionedData": saveFunctionDef = DolphinDbTemplate.getDfsTableUpdateScript(userid, pwd, fieldArr); break; case "saveDimensionData": saveFunctionDef = DolphinDbTemplate.getDimensionTableUpdateScript(userid, pwd, fieldArr); break; } } this.functionSql = String.format("%s{'%s','%s'}", saveFunctionName, dbName, tbName); } dbConnection = new DBConnection(); try { if (saveFunctionDef == null || saveFunctionDef.equals("")) { dbConnection.connect(host, port, userid, pwd); } else { LOG.info(saveFunctionDef); dbConnection.connect(host, port, userid, pwd, saveFunctionDef); } } catch (IOException e) { LOG.error(e.getMessage(),e); LOG.info(saveFunctionDef); } } @Override public void post() { LOG.info("post is invoked"); List<Object> tableField = this.writerConfig.getList(Key.TABLE); JSONArray fieldArr = JSONArray.parseArray(JSON.toJSONString(tableField)); insertToDolphinDB(createUploadTable(fieldArr)); } @Override public void destroy() { if (dbConnection != null) { dbConnection.close(); } } } }
package com.example.repository; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.postgresql.util.PGInterval; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; import com.example.model.SQLStatements; import com.example.model.TimeEntry; import com.nurkiewicz.jdbcrepository.JdbcRepository; import com.nurkiewicz.jdbcrepository.RowUnmapper; import com.nurkiewicz.jdbcrepository.TableDescription; @Component public class TimeEntryRepository extends JdbcRepository<TimeEntry, Long> { public static ProjectRepository taskRepository; public TimeEntryRepository() { this("timeentry"); } public TimeEntryRepository(String tableName) { super(ROW_MAPPER, ROW_UNMAPPER, new TableDescription(tableName, null, "id")); } public static final RowMapper<TimeEntry> ROW_MAPPER = new RowMapper<TimeEntry>() { public TimeEntry mapRow(ResultSet rs, int rowNum) throws SQLException { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd"); String dateInString = rs.getString("entrydate"); Date date; try { date = formatter.parse(dateInString); return new TimeEntry(rs.getLong("tid"), rs.getInt("userprofile_id"), rs.getInt("project_id"), rs.getString("description"), date, (PGInterval) rs.getObject("worktime"), rs.getInt("client_id")); } catch (ParseException e) { e.printStackTrace(); } return null; } }; public static final RowUnmapper<TimeEntry> ROW_UNMAPPER = new RowUnmapper<TimeEntry>() { public Map<String, Object> mapColumns(TimeEntry timeentry) { Map<String, Object> mapping = new LinkedHashMap<String, Object>(); mapping.put("tid", timeentry.getId()); mapping.put("userprofile_id", timeentry.getUserprofileID()); mapping.put("project_id", timeentry.getProjectID()); mapping.put("description", timeentry.getDescription()); mapping.put("entrydate", timeentry.getEntryDate()); mapping.put("worktime", timeentry.getWorktime()); mapping.put("client_id", timeentry.getClientID()); return mapping; } }; public List<TimeEntry> findByPersonID(long id) { List<TimeEntry> entries = getJdbcOperations().query(SQLStatements.FIND_ENTRIES_BY_USERPROFILEID, ROW_MAPPER, id); return entries; } public TimeEntry createTimeEntry(TimeEntry timeEntry) { getJdbcOperations().update(SQLStatements.CREATE_ENTRY, timeEntry.getUserprofileID(), timeEntry.getProjectID(), timeEntry.getDescription(), timeEntry.getEntryDate(), timeEntry.getWorktime(), timeEntry.getClientID()); return timeEntry; } public int updateTimeEntry(long userprofile_id, long project_id, long client_id, String description, Date entryDate, PGInterval worktime, long id) { int update = getJdbcOperations().update(SQLStatements.UPDATE_ENTRY_BY_ID, userprofile_id, project_id, description, entryDate, worktime, client_id, id); return update; } public List<TimeEntry> findAllByDates(String fromDate, String toDate, long userprofile_id) { return getJdbcOperations().query(SQLStatements.FIND_ENTRIES_BY_DATES, ROW_MAPPER, fromDate, toDate, userprofile_id); } public List<TimeEntry> findAllEntriesByDates(String fromDate, String toDate) { return getJdbcOperations().query(SQLStatements.FIND_ALL_ENTRIES_BY_DATES, ROW_MAPPER, fromDate, toDate); } public void deleteEntry(long id) { getJdbcOperations().update(SQLStatements.DELETE_ENTRY, id); } }
package net.kkolyan.elements.game.tmx.model; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Element; /** * @author nplekhanov */ public class TmxLayer { @Attribute private String name; @Attribute private int width; @Attribute private int height; @Element private TmxData data; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public TmxData getData() { return data; } public void setData(TmxData data) { this.data = data; } }
package com.binarysprite.evemat.entity; import org.seasar.doma.jdbc.entity.EntityListener; import org.seasar.doma.jdbc.entity.PostDeleteContext; import org.seasar.doma.jdbc.entity.PostInsertContext; import org.seasar.doma.jdbc.entity.PostUpdateContext; import org.seasar.doma.jdbc.entity.PreDeleteContext; import org.seasar.doma.jdbc.entity.PreInsertContext; import org.seasar.doma.jdbc.entity.PreUpdateContext; /** * */ public class ProductGroupListener implements EntityListener<ProductGroup> { @Override public void preInsert(ProductGroup entity, PreInsertContext context) { } @Override public void preUpdate(ProductGroup entity, PreUpdateContext context) { } @Override public void preDelete(ProductGroup entity, PreDeleteContext context) { } @Override public void postInsert(ProductGroup entity, PostInsertContext context) { } @Override public void postUpdate(ProductGroup entity, PostUpdateContext context) { } @Override public void postDelete(ProductGroup entity, PostDeleteContext context) { } }
package com.cts.bta.dao; import java.util.List; import com.cts.bta.model.Transaction; public interface TransactionsRepo { List<Transaction> getAll(); Transaction getById(Long txId); Transaction add(Transaction txn); void delete(Long txId); }
//package xlong.classifier; // //import xlong.cell.instances.TreeInstances; // //public abstract class TreeClassifier<XInstances extends TreeInstances<?>> extends Classifier { // public abstract void train(XInstances instances); // //}
package com.itheima.service; import com.itheima.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; import java.util.List; public class UserService { public static void main(String[] args) throws Exception { //加载mybatis配置文件 InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml"); //获取对象 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); //通过builder对象得到SqlSessionFactory对象 SqlSessionFactory factory = builder.build(is); //通过factory对象得到SqlSession对象(SqlSession = Connection + Statement) SqlSession sqlSession = factory.openSession(); /* List<User> list = sqlSession.selectList("com.itheima.dao.UserDao.findAll"); for (User user : list) { System.out.println(user); } */ /*User user = sqlSession.selectOne("com.itheima.dao.UserDao.findByName", "zhangsan"); System.out.println(user);*/ /* User user = new User(); user.setId(null); user.setName("wangwu"); user.setAge(25); user.setGender("男"); */ // sqlSession.insert("com.itheima.dao.UserDao.add", user); sqlSession.delete("com.itheima.dao.UserDao.deleteById",4); //提交事务 sqlSession.commit(); sqlSession.close(); } }
package NEWERAPOKEMON; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.InputMismatchException; public class MyForm0 extends JFrame { /** * */ private static final long serialVersionUID = 1L; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { MyForm0 form = new MyForm0(); form.setVisible(true); } }); } public MyForm0() { // Create Form Frame super("NEWERAPOGEMON"); // Set defalt of window setSize(800, 600); setLocation(400, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().setLayout(new FlowLayout() ); // add base item ADDBASEITEM.addBaseItem(); // Create Label JLabel labelHead = new JLabel("Wellcome to GUNGEMON "); JLabel label = new JLabel("Please Enter your name "); // Create Button JButton btnOpen = new JButton(" OK "); Icon imageBG = new ImageIcon(getClass().getResource("/bgd.png")); // FOOD JLabel imgBg = new JLabel(imageBG); imgBg.setBounds(0, 0, 800, 600); getContentPane().add(imgBg); // Set x,y,w,h // Label labelHead.setBounds(160, 43, 300,14); label.setBounds(160, 53, 200, 14); // Button btnOpen.setBounds(171, 95, 100, 23); // Create TextField JTextField NamePlayer; NamePlayer = new JTextField(25); // Create Event for Button btnOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { String Name; // set name form input try { Name = NamePlayer.getText(); ACTIONONWORLD.setNamePlayer(Name); } catch ( InputMismatchException e ) { final ImageIcon icon = new ImageIcon(getClass().getResource("/logo_fail.png")); JOptionPane.showMessageDialog(null," Success to Use Your Mana -1 ","USE MANA",JOptionPane.INFORMATION_MESSAGE,icon); } // New Page MyForm1 form1 = new MyForm1(); form1.setVisible(true); // Hide Current Form setVisible(false); } }); // Call to Layout getContentPane().add(labelHead); getContentPane().add(label); getContentPane().add(NamePlayer); getContentPane().add(btnOpen); getContentPane().add(imgBg); } } // https://youtu.be/3KwKKWUyfTU
package inatel.br.nfccontrol.utils; /** * Created by guilhermeyabu on 06/06/2018. */ public class ValidationConstants { public static final String IP_MASK_WITH_12_NUMBERS = "###.###.###.###"; public static final String IP_MASK_WITH_8_NUMBERS = "###.###.#.#"; public static final String IP_MASK_WITH_9_NUMBERS = "###.###.##.#"; public static final String IP_MASK_WITH_10_NUMBERS = "###.###.##.##"; public static final String HOUR_MASK = "##:##"; public static final String DATE_MASK = "##/##"; public static final String NAME_REGEX = "[A-Za-z0-9:._@-]+(?:[ ][A-Za-z0-9:._@-]+)*$"; public static final String PHONE_REGEX = "[0-9,#*]+"; public static final String PASSWORD_REGEX = "^\\d{4}(?:\\d{2})?$"; public static final String IP_ADDRESS_REGEX = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" + "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"; public static final String HOUR_REGEX = "^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$"; public static final String DATE_REGEX = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])"; public static final String TIME_REGEX = "[0-9]+"; public static final String PARTITION_ACCOUNT_REGEX = "[B-F0-9]+"; public static final String SERIAL_NUMBER_REGEX = "^\\d{1,9}$"; public static final String EMAIL_REGEX = "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+"; public static final String USER_NAME_REGEX = "(?=^.{2,60}$)^[a-zA-ZÀÁÂĖÈÉÊÌÍÒÓÔÕÙÚÛÇ][a-zàáâãèéêìíóôõùúç]+(?:[ ]" + "(?:das?|dos?|de|e|[A-Z][a-z]+))*$"; public static final String INPUT_TYPE_DECIMAL = "INPUT TYPE DECIMAL"; public static final String INPUT_TYPE_DECIMAL_PASSWORD = "INPUT TYPE DECIMAL PASSWORD"; public static final String INPUT_TYPE_TEXT_NORMAL = "INPUT TYPE TEXT NORMAL"; public static final String INPUT_TYPE_TEXT_PASSWORD = "INPUT TYPE TEXT PASSWORD"; public static final String INPUT_TYPE_NUMBER_PHONE = "INPUT TYPE NUMBER PHONE"; public static final int TEXT_NAME_MAX_LENGTH = 9; public static final int PASSWORD_MAX_LENGTH = 6; public static final int PARTITION_ACCOUNT_MAX_LENGTH = 4; public static final int PORT_MAX_LENGTH = 4; public static final int IP_ADDRESS_MAX_LENGTH = 15; public static final int HOUR_MAX_LENGTH = 5; public static final int DATE_MAX_LENGTH = 5; public static final int KEYBOARD_MESSAGE_MAX_LENGTH = 16; public static final int TIMES_INPUT_MAX_LENGTH = 3; public static final int SSID_NAME_MAX_LENGTH = 32; public static final int DDNS_ADDRESS_MAX_LENGTH = 32; public static final int SSID_PASSWORD_MAX_LENGTH = 24; public static final int PHONE_MAX_LENGTH = 24; public static final int APN_MAX_LENGTH = 48; public static final int SERIAL_NUMBER_MAX_LENGTH = 9; public static final int USER_NAME_MAX_LENGTH = 25; public static final int USER_EMAIL_MAX_LENGTH = 60; public static final int USER_PASSWORD_MAX_LENGTH = 12; public static final int DESTINATION_IP_MAX_LENGTH = 40; public static final int TIMES_INPUT_MAX_NUMBER = 255; public static final int TEXT_MAX_NUMBER = 0; public static final int PORT_MAX_NUMBER = 9999; public static final int PASSWORD_MAX_NUMBER = 9999; public static final int SERIAL_NUMBER_MAX_NUMBER = 999999999; public static final int MAX_LENGTH_24 = 24; public static final int MAX_LENGTH_4 = 4; public static final int MAX_LENGTH_3 = 3; public static final int MAX_NUMBER_OF_24_POSITIONS = 0; public static final int MAX_NUMBER_15 = 15; public static final int MAX_NUMBER_9999 = 9999; public static final String EMAIL_IMAGE = "email image"; public static final String PASSWORD_IMAGE = "password image"; }
package FX.RDA_users; import FX.User_menu; import Tools.Deshifr; import Tools.Shifr; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; public class Delete_U extends JFrame { JLabel l1 = new JLabel("Выберите пользователя."); JComboBox cb1; JButton b1 = new JButton("Удалить"); String[] Usrs, names; BufferedReader R; BufferedWriter W; eHandler handler = new eHandler(); public Delete_U(BufferedReader rd, BufferedWriter wr) throws IOException { super("Delete"); R = rd; W = wr; setLayout(new GridLayout(3,1)); Usrs = R.readLine().split("/"); names = new String[Integer.parseInt(Usrs[Usrs.length - 1])]; Catch(); cb1 = new JComboBox(names); add(l1); add(cb1); add(b1); b1.addActionListener(handler); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setSize(300,250); setResizable(false); setLocationRelativeTo(null); } private void Catch() throws IOException { for(int i = 0; i < Usrs.length - 1; i++) { names[i] = Usrs[i].split(" ")[0]; } } public class eHandler implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == b1) { try { W.write(cb1.getSelectedIndex() + "\n"); W.flush(); } catch (IOException ex) { ex.printStackTrace(); } dispose(); } } } }
package com.catmylife.android.catmylife; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; public class SleepPage extends AppCompatActivity { ProgressBar progressBar; Button start_timer, stop_timer; MyCountDownTimer myCountDownTimer; ImageView normalCat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sleep); normalCat = (ImageView) findViewById(R.id.catImageView); if (Cat.weight == 1) { switchToSuperThinCat(); } else if (Cat.weight == 2) { switchToThinCat(); } else if (Cat.weight == 3) { switchToNormalCat(); } else if (Cat.weight == 4) { switchToFatCat(); } AnimationDrawable normalCatAnimation = (AnimationDrawable) normalCat.getDrawable(); normalCatAnimation.setCallback(normalCat); normalCatAnimation.setVisible(true, true); normalCatAnimation.start(); progressBar = (ProgressBar) findViewById(R.id.progressBar); start_timer = (Button) findViewById(R.id.button); stop_timer = (Button) findViewById(R.id.button3); start_timer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myCountDownTimer = new MyCountDownTimer(10000, 1000); myCountDownTimer.start(); } }); stop_timer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myCountDownTimer.cancel(); } }); } public class MyCountDownTimer extends CountDownTimer { public MyCountDownTimer(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onTick(long millisUntilFinished) { int progress = (int) (millisUntilFinished / 1000); progressBar.setProgress(progressBar.getMax() - progress); } @Override public void onFinish() { finish(); } } private void switchToFatCat() { normalCat.setImageResource(R.drawable.sleep_fat_animation); AnimationDrawable normalCatAnimation = (AnimationDrawable) normalCat.getDrawable(); normalCatAnimation.setCallback(normalCat); normalCatAnimation.setVisible(true, true); normalCatAnimation.start(); } private void switchToNormalCat() { normalCat.setImageResource(R.drawable.sleep_normal_animation); AnimationDrawable normalCatAnimation = (AnimationDrawable) normalCat.getDrawable(); normalCatAnimation.setCallback(normalCat); normalCatAnimation.setVisible(true, true); normalCatAnimation.start(); } private void switchToThinCat() { normalCat.setImageResource(R.drawable.sleep_thin_animation); AnimationDrawable normalCatAnimation = (AnimationDrawable) normalCat.getDrawable(); normalCatAnimation.setCallback(normalCat); normalCatAnimation.setVisible(true, true); normalCatAnimation.start(); } private void switchToSuperThinCat() { normalCat.setImageResource(R.drawable.sleep_super_thin_animation); AnimationDrawable normalCatAnimation = (AnimationDrawable) normalCat.getDrawable(); normalCatAnimation.setCallback(normalCat); normalCatAnimation.setVisible(true, true); normalCatAnimation.start(); } }
package com.docker.utils; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; public class CmdUtils { /** * 执行 * @param cmd * @return */ public static List<String> exec(String cmd) { try { String[] cmdA = { "/bin/sh", "-c", cmd }; Process process = Runtime.getRuntime().exec(cmdA); LineNumberReader br = new LineNumberReader(new InputStreamReader( process.getInputStream())); StringBuilder sb = new StringBuilder(); String line; List<String> logList = new ArrayList<String>(); while ((line = br.readLine()) != null) { // System.out.println(line); // sb.append(line).append("\n"); logList.add(new String(line.getBytes("utf-8"), "utf-8") + "\r"); } return logList; } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { String grep = ""; String cmd = "tail -n100 /home/Baihua/workspace/TalentChat/logs/server.log"; if(!StringUtils.isEmpty(grep)) { cmd = cmd + " | grep " + grep; } List<String> logList = exec(cmd); System.out.println(logList); } }
package com.xixiwan.platform.sys.form; import com.xixiwan.platform.module.web.form.BaseForm; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) public class SysUserForm extends BaseForm { /** * 账号 */ private String username; /** * 名字 */ private String name; /** * 原密码 */ private String originalPassword; /** * 密码 */ private String password; /** * 通知id */ private String noticeid; /** * 单一选择 */ private boolean singleSelect; }