text
stringlengths
10
2.72M
package controller; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import view.View; import model.*; public class Controller { private View view; public Controller(View view) { this.view=view; this.view.start(new Start()); } class Start implements ActionListener { public void actionPerformed(ActionEvent e) { int nrq,minA,maxA,minS,maxS,duration,nrClient; nrq= view.nrQueues(); minA=view.minA(); maxA=view.maxA(); minS=view.minS(); maxS=view.maxS(); nrClient=view.getNrClient(); duration=view.getDuration(); Logger.setReal_Time(view.getEvolution()); List<Client> list= new ArrayList<Client>(Generator.generateClients(nrClient,minA,maxA,minS,maxS)); Simulation sim1 = new Simulation(list,duration,nrq); sim1.startSimulation(); view.getLog().append(Logger.getReport()+"\n"+sim1.getReport()); } } }
package Lesson3.sockets.hw2.final_chat; import java.io.*; import java.net.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; public class Server implements IPortAndAddress { private static int uniqueId; private static ArrayList<ClientThread> clients; private static HashMap<Integer, List<Integer>>rooms; // id's of Client threads private SimpleDateFormat simpleDateFormat; private AtomicBoolean isWorking; public Server() { simpleDateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss"); clients = new ArrayList<>(); rooms = new HashMap<>(); isWorking = new AtomicBoolean(); uniqueId = 0; } public void start() { isWorking.set(true); try { ServerSocket serverSocket = new ServerSocket(PORT); while (isWorking.get()) { display("Waiting for new clients.."); // delete or add logging Socket socket = serverSocket.accept(); if (!isWorking.get()) break; uniqueId++; ClientThread t = new ClientThread(socket, uniqueId); clients.add(t); t.start(); } try { serverSocket.close(); for (ClientThread item : clients) { try { // close all data streams and socket item.socket.close(); item.ois.close(); item.oos.close(); } catch (IOException ioE) { } } } catch (IOException e) { display("Exception in closing server/clients: " + e); } } catch (IOException e) { String mes = simpleDateFormat.format(new Date()) + "ServerSocketException: " + e + "\n"; //isWorking.set(false); display(mes); } } /** * Broadcast message into definite room * @param mes - message to send * @param room - room ro which users message is sent */ private synchronized void broadcast(String mes, int room) { String time = simpleDateFormat.format(new Date()); String broadcastMes = time + " " + mes + "\n"; System.out.print(broadcastMes); int roomClientID = rooms.get(room).size(); for(int i = roomClientID; --i >= 0;) { int id = rooms.get(room).get(i); ClientThread ct = clients.get(id-1); // Remove disconnected clients if(!ct.writeMes(broadcastMes)) { clients.remove(id-1); rooms.get(room).remove(i); display("Disconnected Client " + ct.username + " is removed"); } } // Loop in reverse order in order to delete client which has disconnected for(int i = clients.size(); --i >= 0;) { ClientThread ct = clients.get(i); if(!ct.writeMes(broadcastMes)) { clients.remove(i); display("Disconnected Client " + ct.username + " is removed"); } } } synchronized void logout(int id, int room) { String disconnectedClient = ""; for (ClientThread item : clients) { if(item.id == id) { disconnectedClient = item.getUsername(); clients.remove(item); break; } } broadcast(disconnectedClient + " has left the chat room.", room); } /** * Show message in server console * @param mes - message to be displayed */ private void display(String mes) { String time = simpleDateFormat.format(new Date()) + " " + mes; System.out.println(time); } /** * Active client thread on server */ class ClientThread extends Thread { int id; String username; Socket socket; ObjectInputStream ois; ObjectOutputStream oos; //SocketReaderWriter sockerReaderWriter; Message message; int chatRoom; ClientThread(Socket socket, int id) { //this.socket = socket; this.id = id; this.socket = socket; chatRoom = 0; System.out.println("Create stream"); try { oos = new ObjectOutputStream(socket.getOutputStream()); ois = new ObjectInputStream(socket.getInputStream()); username = (String) ois.readObject(); if (rooms.size() == 0) { oos.writeObject("Number of available rooms for chatting: 0 \nType N to create new room"); }else { int temp = rooms.size(); oos.writeObject("Number of available rooms for chatting: " + temp + "\n" + "- Type N to create new room\nType number from 1 to " + temp+" to join existing room"); } display(username + " has loginned"); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public String getUsername() { return username; } public void run() { boolean isRunning = true; while(isRunning) { try { message = (Message) ois.readObject(); } catch (IOException e) { display("Connection is reset by client"); e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } String mes = message.getMessage(); switch(message.getType()) { case Message.USERSLIST: try { oos.writeObject("List of the users connected at " + simpleDateFormat.format(new Date()) + "\n"); for(int i = 0; i < clients.size(); ++i) { ClientThread ct = clients.get(i); oos.writeObject((i+1) + ") " + ct.username); } } catch (IOException e) { e.printStackTrace(); } break; case Message.NEWROOM: chatRoom = rooms.size()+1; rooms.put(rooms.size()+1, new ArrayList<>()); rooms.get(chatRoom).add(id); writeMes("Welcome to the room number "+rooms.size()); display(username + " created a new room"); break; case Message.ROOMS: display(message.getMessage()); chatRoom = (int) message.getMessage().charAt(0); rooms.get(chatRoom).add(id); writeMes("Welcome to the room number "+chatRoom); display(username + " joined room "+ chatRoom); break; case Message.MESSAGE: broadcast(username + ": " + mes, chatRoom); break; case Message.QUIT: display(username + " disconnected"); isRunning = false; break; } } logout(id, chatRoom); close(); } /** * Method for closing connection */ private void close() { try { if (ois != null) ois.close(); if (oos != null) oos.close(); if (socket != null) socket.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Method for sending message to client console * @param mes - message * @return */ private boolean writeMes(String mes) { if(!socket.isConnected()) { close(); return false; } try { oos.writeObject(mes); } catch(IOException e) { display("Error sending message to " + username); } return true; } } }
package socialapp.user.slack; import socialapp.user.SocialAppUser; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class User extends SocialAppUser { private String id; private String team_id; private String name; private boolean deleted; private String color; private String real_name; private String tz; private String tz_label; private int tz_offset; private Profile profile; private boolean is_admin; private boolean is_owner; private boolean is_primary_owner; private boolean is_restricted; private boolean is_ultra_restricted; private boolean is_bot; private int updated; private boolean is_app_user; private boolean has_2fa; public User() { profile = new Profile(); } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } public String getTeam_id() { return team_id; } public void setTeam_id(String team_id) { this.team_id = team_id; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getReal_name() { return real_name; } public void setReal_name(String real_name) { this.real_name = real_name; } public String getTz() { return tz; } public void setTz(String tz) { this.tz = tz; } public String getTz_label() { return tz_label; } public void setTz_label(String tz_label) { this.tz_label = tz_label; } public int getTz_offset() { return tz_offset; } public void setTz_offset(int tz_offset) { this.tz_offset = tz_offset; } public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } public boolean isIs_admin() { return is_admin; } public void setIs_admin(boolean is_admin) { this.is_admin = is_admin; } public boolean isIs_owner() { return is_owner; } public void setIs_owner(boolean is_owner) { this.is_owner = is_owner; } public boolean isIs_primary_owner() { return is_primary_owner; } public void setIs_primary_owner(boolean is_primary_owner) { this.is_primary_owner = is_primary_owner; } public boolean isIs_restricted() { return is_restricted; } public void setIs_restricted(boolean is_restricted) { this.is_restricted = is_restricted; } public boolean isIs_ultra_restricted() { return is_ultra_restricted; } public void setIs_ultra_restricted(boolean is_ultra_restricted) { this.is_ultra_restricted = is_ultra_restricted; } public boolean isIs_bot() { return is_bot; } public void setIs_bot(boolean is_bot) { this.is_bot = is_bot; } public int getUpdated() { return updated; } public void setUpdated(int updated) { this.updated = updated; } public boolean isIs_app_user() { return is_app_user; } public void setIs_app_user(boolean is_app_user) { this.is_app_user = is_app_user; } public boolean isHas_2fa() { return has_2fa; } public void setHas_2fa(boolean has_2fa) { this.has_2fa = has_2fa; } @Override public String getEmail() { if(profile != null) { return profile.getEmail(); } else { return ""; } } @Override public void setEmail(String email) { if(profile != null) { profile.setEmail(email); } } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(" User : { "); stringBuilder.append(" id : '"); stringBuilder.append(id); stringBuilder.append("', team_id : "); stringBuilder.append(team_id); stringBuilder.append(", name : '"); stringBuilder.append(name); stringBuilder.append("', deleted : "); stringBuilder.append(deleted); stringBuilder.append(", color : '"); stringBuilder.append(color); stringBuilder.append("', real_name : '"); stringBuilder.append(real_name); stringBuilder.append("', tz : '"); stringBuilder.append(tz); stringBuilder.append("', tz_label : '"); stringBuilder.append(tz_label); stringBuilder.append("', : "); stringBuilder.append(tz_offset); stringBuilder.append(", "); stringBuilder.append(profile.toString()); stringBuilder.append(", is_admin : "); stringBuilder.append(is_admin); stringBuilder.append(", is_owner : "); stringBuilder.append(is_owner); stringBuilder.append(", is_primary_owner : "); stringBuilder.append(is_primary_owner); stringBuilder.append(", is_restricted :" ); stringBuilder.append(is_restricted); stringBuilder.append(", is_ultra_restricted : "); stringBuilder.append(is_ultra_restricted); stringBuilder.append(", is_bot : "); stringBuilder.append(is_bot); stringBuilder.append(", updated :"); stringBuilder.append(updated); stringBuilder.append(", is_app_user :"); stringBuilder.append(is_app_user); stringBuilder.append(", has_2fa :"); stringBuilder.append(has_2fa); stringBuilder.append(" }"); return stringBuilder.toString(); } }
package org.osource.scd.param; import lombok.Data; import org.osource.scd.constant.ParseType; import org.osource.scd.parse.BusinessDefineParse; import org.osource.scd.parse.error.DefaultErrorRecord; import org.osource.scd.parse.error.ErrorRecord; import org.osource.scd.parse.format.CellFormat; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.function.Consumer; /** * @author chengdu * */ @Data public class ParseParam<T> { private int startLine; private int sheetNum; private Map<String, Method> fieldSetterMap; private BusinessDefineParse businessDefineParse; private String encode; private ErrorRecord errorRecord; private CellFormat cellFormat; private ParseType parseType; private Consumer<List<T>> consumer; private int batchNum = 1000; public ParseParam() { errorRecord = new DefaultErrorRecord(new StringBuilder("")); } public ParseParam setStartLine(int startLine) { this.startLine = startLine; return this; } public ParseParam setSheetNum(int sheetNum) { this.sheetNum = sheetNum; return this; } public ParseParam setFieldSetterMap(Map<String, Method> fieldSetterMap) { this.fieldSetterMap = fieldSetterMap; return this; } public ParseParam setBusinessDefineParse(BusinessDefineParse businessDefineParse) { this.businessDefineParse = businessDefineParse; return this; } public ParseParam setEncode(String encode) { this.encode = encode; return this; } public ParseParam setErrorRecord(ErrorRecord errorRecord) { this.errorRecord = errorRecord; return this; } public ParseParam setCellFormat(CellFormat cellFormat) { this.cellFormat = cellFormat; return this; } public ParseParam setParseType(ParseType parseType) { this.parseType = parseType; return this; } public ParseParam setConsumer(Consumer<List<T>> consumer) { this.consumer = consumer; return this; } public ParseParam setBatchNum(int batchNum) { this.batchNum = batchNum; return this; } }
package com.huotn.bootjsp.bootjsp.mapper; import com.huotn.bootjsp.bootjsp.pojo.Role; import org.apache.ibatis.annotations.*; import java.util.List; /** * @Description: RoleMapper * * @Auther: leichengyang * @Date: 2019/4/29 0029 * @Version 1.0 */ @Mapper public interface RoleMapper { @Select("select * from t_role") List<Role> findAll(); @Insert("insert into t_role(name,type)values(#{name},#{type})") int add(Role role); @Delete("delete from t_role where id=#{id}") int delRole(Role role); @Select("select * from t_role where name=#{name}") Role getRole(String rolename); @Update("update t_role set name=#{name} where id=#{id}") int updateRole(Role role); @Select("select * from t_role where id=#{id}") Role getRoleById(String id); }
/* * Copyright 2002-2023 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.cache.jcache.interceptor; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import javax.cache.annotation.CacheInvocationParameter; import javax.cache.annotation.CacheMethodDetails; import org.junit.jupiter.api.Test; import org.springframework.cache.jcache.AbstractJCacheTests; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll */ public abstract class AbstractCacheOperationTests<O extends JCacheOperation<?>> extends AbstractJCacheTests { protected final SampleObject sampleInstance = new SampleObject(); protected abstract O createSimpleOperation(); @Test public void simple() { O operation = createSimpleOperation(); assertThat(operation.getCacheName()).as("Wrong cache name").isEqualTo("simpleCache"); assertThat(operation.getAnnotations()).as("Unexpected number of annotation on " + operation.getMethod()) .hasSize(1); assertThat(operation.getAnnotations().iterator().next()).as("Wrong method annotation").isEqualTo(operation.getCacheAnnotation()); assertThat(operation.getCacheResolver()).as("cache resolver should be set").isNotNull(); } protected void assertCacheInvocationParameter(CacheInvocationParameter actual, Class<?> targetType, Object value, int position) { assertThat(actual.getRawType()).as("wrong parameter type for " + actual).isEqualTo(targetType); assertThat(actual.getValue()).as("wrong parameter value for " + actual).isEqualTo(value); assertThat(actual.getParameterPosition()).as("wrong parameter position for " + actual).isEqualTo(position); } protected <A extends Annotation> CacheMethodDetails<A> create(Class<A> annotationType, Class<?> targetType, String methodName, Class<?>... parameterTypes) { Method method = ReflectionUtils.findMethod(targetType, methodName, parameterTypes); Assert.notNull(method, () -> "requested method '" + methodName + "'does not exist"); A cacheAnnotation = method.getAnnotation(annotationType); return new DefaultCacheMethodDetails<>(method, cacheAnnotation, getCacheName(cacheAnnotation)); } private static String getCacheName(Annotation annotation) { Object cacheName = AnnotationUtils.getValue(annotation, "cacheName"); return (cacheName != null ? cacheName.toString() : "test"); } }
package main; public class Mediu { int x=0; //variabila globala void method1( ) { int x=1,y;//variabil;e locale metodei method1 y=x; // y=1; } void method2( ) { int z=1;//variabila locala metodei method2 System.out.println(x); x=3+z; // y este necunoscuta -> deci nu se poate face aceasta operatie System.out.println(x); } }
package uz.pdp.lesson5task1.repository; import org.springframework.data.jpa.repository.JpaRepository; import uz.pdp.lesson5task1.entity.Turnikit; import uz.pdp.lesson5task1.entity.User; import java.util.UUID; public interface TurniketRepository extends JpaRepository<Turnikit, UUID> { Turnikit findByOwner(User owner); void deleteByUniqueNumber(String uniqueNumber); boolean existsByOwner(User owner); }
package vista.Cartas; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.WindowConstants; import controlador.*; public class FormModificarCarta extends javax.swing.JFrame { private JButton btnEliminar; private AbstractAction aceptarAccion; private JComboBox cmbDiaNuevo; private JLabel jLabel2; private JComboBox cmbDiaViejo; private JLabel jLabel1; public FormModificarCarta() { super(); initGUI(); } private void initGUI() { try { getContentPane().setLayout(null); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); this.setTitle("Modificar Dia de Carta"); { btnEliminar = new JButton(); getContentPane().add(btnEliminar); btnEliminar.setText("MODIFICAR"); btnEliminar.setBounds(86, 108, 118, 34); btnEliminar.setAction(getAceptarAccion()); } { jLabel1 = new JLabel(); getContentPane().add(jLabel1); getContentPane().add(getJDias()); getContentPane().add(getJComboBox1()); getContentPane().add(getJLabel2()); jLabel1.setText("Carta Original:"); jLabel1.setBounds(12, 12, 119, 34); } pack(); setSize(300, 180); } catch (Exception e) { e.printStackTrace(); } } private JComboBox getJDias() { if(cmbDiaViejo == null) { ComboBoxModel jDiasModel = new DefaultComboBoxModel( new String[] { "lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo"}); cmbDiaViejo = new JComboBox(); cmbDiaViejo.setModel(jDiasModel); cmbDiaViejo.setBounds(149, 12, 131, 34); } return cmbDiaViejo; } private JComboBox getJComboBox1() { if(cmbDiaNuevo == null) { ComboBoxModel jComboBox1Model = new DefaultComboBoxModel( new String[] { "lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo"}); cmbDiaNuevo = new JComboBox(); cmbDiaNuevo.setModel(jComboBox1Model); cmbDiaNuevo.setBounds(149, 58, 131, 34); } return cmbDiaNuevo; } private JLabel getJLabel2() { if(jLabel2 == null) { jLabel2 = new JLabel(); jLabel2.setText("Carta Destino: "); jLabel2.setBounds(12, 58, 119, 34); } return jLabel2; } private AbstractAction getAceptarAccion() { if(aceptarAccion == null) { aceptarAccion = new AbstractAction("MODIFICAR", null) { public void actionPerformed(ActionEvent evt) { if(Restaurante.getRestaurante().modificarCarta(cmbDiaViejo.getSelectedItem().toString(), cmbDiaNuevo.getSelectedItem().toString())){ JOptionPane.showMessageDialog(null, "Cartas modificadas con exito.", "MENSAJE", JOptionPane.WARNING_MESSAGE); }else{ JOptionPane.showMessageDialog(null, "El dia original NO posee carta o el dia destino YA posee carta asignada", "Prohibido", JOptionPane.WARNING_MESSAGE); } } }; } return aceptarAccion; } }
package com.ylz.dto; import com.ylz.entity.Seckill; import com.ylz.enums.SeckillEnums; import java.util.Date; /** * Created by liuburu on 2017/2/18. */ public class ExposerResult { private boolean exposed; //是否暴露秒杀地址 private int seckillId; //秒杀产品ID private String md5; //加密秒杀地址 private Seckill seckill; //秒杀产品信息 private SeckillEnums seckillEnum; //秒杀错误信息 private Date beginTime; //秒杀开始时间 private Date endTime; //秒杀结束时间 private Date nowTime; //当前秒杀时间 /** * 成功数据构造器 * @param exposed * @param seckillId * @param md5 * @param seckill */ public ExposerResult(boolean exposed, int seckillId, String md5, Seckill seckill) { this.exposed = exposed; this.seckillId = seckillId; this.md5 = md5; this.seckill = seckill; } /** * 失败数据构造器 * @param exposed * @param seckillId * @param seckillEnum * @param beginTime * @param endTime * @param nowTime */ public ExposerResult(boolean exposed, int seckillId, SeckillEnums seckillEnum, Date beginTime, Date endTime, Date nowTime) { this.exposed = exposed; this.seckillId = seckillId; this.seckillEnum = seckillEnum; this.beginTime = beginTime; this.endTime = endTime; this.nowTime = nowTime; } public boolean isExposed() { return exposed; } public void setExposed(boolean exposed) { this.exposed = exposed; } public int getSeckillId() { return seckillId; } public void setSeckillId(int seckillId) { this.seckillId = seckillId; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } public Seckill getSeckill() { return seckill; } public void setSeckill(Seckill seckill) { this.seckill = seckill; } public SeckillEnums getSeckillEnum() { return seckillEnum; } public void setSeckillEnum(SeckillEnums seckillEnum) { this.seckillEnum = seckillEnum; } public Date getBeginTime() { return beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Date getNowTime() { return nowTime; } public void setNowTime(Date nowTime) { this.nowTime = nowTime; } }
package com.nisira.core.dao; import com.nisira.core.entity.*; import java.util.List; import android.database.sqlite.SQLiteDatabase; import com.nisira.core.database.DataBaseClass; import android.content.ContentValues; import android.database.Cursor; import com.nisira.core.util.ClaveMovil; import java.util.ArrayList; import java.util.LinkedList; import java.text.SimpleDateFormat; import java.util.Date; public class Concepto_cuentaDao extends BaseDao<Concepto_cuenta> { public Concepto_cuentaDao() { super(Concepto_cuenta.class); } public Concepto_cuentaDao(boolean usaCnBase) throws Exception { super(Concepto_cuenta.class, usaCnBase); } public void mezclarLocal(Concepto_cuenta obj)throws Exception{ List<Concepto_cuenta> lst= listar("LTRIM(RTRIM(t0.IDEMPRESA)) =? AND LTRIM(RTRIM(t0.IDCONCEPTO))=?",obj.getIdempresa().trim(),obj.getIdconcepto().trim()); if(lst.isEmpty()) insertar(obj); else actualizar(obj); } public List<Concepto_cuenta> ListarConsumidor(Dordenliquidaciongasto obj)throws Exception { if (obj != null) { List<Concepto_cuenta> lst = listar("LTRIM(RTRIM(t0.IDEMPRESA)) =? ", obj.getIdempresa().trim()); if(lst.isEmpty()){ return null; }else return lst; } return null; } public Boolean insert(Concepto_cuenta concepto_cuenta) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ContentValues initialValues = new ContentValues(); initialValues.put("IDEMPRESA",concepto_cuenta.getIdempresa()); initialValues.put("IDCONCEPTO",concepto_cuenta.getIdconcepto()); initialValues.put("IDCUENTA",concepto_cuenta.getIdcuenta()); initialValues.put("DESCRIPCION",concepto_cuenta.getDescripcion()); initialValues.put("REGISTRAR_EN",concepto_cuenta.getRegistrar_en()); initialValues.put("ESTADO",concepto_cuenta.getEstado()); initialValues.put("SINCRONIZA",concepto_cuenta.getSincroniza()); initialValues.put("FECHACREACION",dateFormat.format(concepto_cuenta.getFechacreacion() ) ); resultado = mDb.insert("CONCEPTO_CUENTA",null,initialValues)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } public Boolean update(Concepto_cuenta concepto_cuenta,String where) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ContentValues initialValues = new ContentValues(); initialValues.put("IDEMPRESA",concepto_cuenta.getIdempresa()) ; initialValues.put("IDCONCEPTO",concepto_cuenta.getIdconcepto()) ; initialValues.put("IDCUENTA",concepto_cuenta.getIdcuenta()) ; initialValues.put("DESCRIPCION",concepto_cuenta.getDescripcion()) ; initialValues.put("REGISTRAR_EN",concepto_cuenta.getRegistrar_en()) ; initialValues.put("ESTADO",concepto_cuenta.getEstado()) ; initialValues.put("SINCRONIZA",concepto_cuenta.getSincroniza()) ; initialValues.put("FECHACREACION",dateFormat.format(concepto_cuenta.getFechacreacion() ) ) ; resultado = mDb.update("CONCEPTO_CUENTA",initialValues,where,null)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public Boolean delete(String where) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ resultado = mDb.delete("CONCEPTO_CUENTA",where,null)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } public ArrayList<Concepto_cuenta> listar(String where,String order,Integer limit) { if(limit == null){ limit =0; } ArrayList<Concepto_cuenta> lista = new ArrayList<Concepto_cuenta>(); SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ Cursor cur = mDb.query("CONCEPTO_CUENTA", new String[] { "IDEMPRESA" , "IDCONCEPTO" , "IDCUENTA" , "DESCRIPCION" , "REGISTRAR_EN" , "ESTADO" , "SINCRONIZA" , "FECHACREACION" }, where, null, null, null, order); if (cur!=null){ cur.moveToFirst(); int i=0; while (cur.isAfterLast() == false) { int j=0; Concepto_cuenta concepto_cuenta = new Concepto_cuenta() ; concepto_cuenta.setIdempresa(cur.getString(j++)); concepto_cuenta.setIdconcepto(cur.getString(j++)); concepto_cuenta.setIdcuenta(cur.getString(j++)); concepto_cuenta.setDescripcion(cur.getString(j++)); concepto_cuenta.setRegistrar_en(cur.getString(j++)); concepto_cuenta.setEstado(cur.getDouble(j++)); concepto_cuenta.setSincroniza(cur.getString(j++)); concepto_cuenta.setFechacreacion(dateFormat.parse(cur.getString(j++)) ); lista.add(concepto_cuenta); i++; if(i == limit){ break; } cur.moveToNext(); } cur.close(); } } catch (Exception e) { }finally { mDb.close(); } return lista; } }
package com.gxtc.huchuan.ui.search; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.support.v7.widget.LinearLayoutManager; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.gxtc.commlibrary.base.BaseRecyclerAdapter; import com.gxtc.commlibrary.helper.ImageHelper; import com.gxtc.commlibrary.recyclerview.base.ItemViewDelegate; import com.gxtc.commlibrary.recyclerview.base.ViewHolder; import com.gxtc.commlibrary.utils.GotoUtil; import com.gxtc.huchuan.R; import com.gxtc.huchuan.adapter.CircleDynamicAdapter; import com.gxtc.huchuan.bean.CircleHomeBean; import com.gxtc.huchuan.bean.SearchBean; import com.gxtc.huchuan.ui.circle.home.CircleWebActivityv2; import com.gxtc.huchuan.ui.live.search.LiveSearchMoreActivity; import com.gxtc.huchuan.ui.mine.personalhomepage.personalinfo.PersonalInfoActivity; import java.util.HashMap; import java.util.List; /** * Created by Administrator on 2017/4/4. */ public class FriendSearchItemView implements ItemViewDelegate<SearchBean> { private static final String TAG = "FriendSearchItemView"; private final Activity mActivity; private static final int CIRCLE_WEB_REQUEST = 1 << 3; public FriendSearchItemView(Activity activity) { mActivity = activity; } @Override public int getItemViewLayoutId() { return R.layout.item_livesearch; } @Override public boolean isForViewType(SearchBean o, int position) { return "7".equals(o.getType()); } @Override public void convert(final ViewHolder holder, final SearchBean o, int position) { List<CircleHomeBean> bean = o.getDatas(); MyrecyclerViewAdapter myrecyclerViewAdapter = null; if (holder.getDataTag() == null) { android.support.v7.widget.RecyclerView recyclerView = holder.getView( R.id.rc_recyclerview); myrecyclerViewAdapter = new MyrecyclerViewAdapter(holder.getConvertView().getContext(), bean, R.layout.item_search_friend); holder.setDataTag(myrecyclerViewAdapter); recyclerView.setLayoutManager( new LinearLayoutManager(holder.getConvertView().getContext(), LinearLayoutManager.VERTICAL, false)); recyclerView.setHasFixedSize(true); recyclerView.setNestedScrollingEnabled(false); myrecyclerViewAdapter.setOnReItemOnClickListener( new BaseRecyclerAdapter.OnReItemOnClickListener() { @Override public void onItemClick(View v, int position) { CircleHomeBean circleBean = ((MyrecyclerViewAdapter) holder.getDataTag()).getList().get( position); Intent intent = new Intent(mActivity, CircleWebActivityv2.class); intent.putExtra("data", circleBean); mActivity. startActivityForResult(intent, CIRCLE_WEB_REQUEST); } }); recyclerView.setAdapter((MyrecyclerViewAdapter) holder.getDataTag()); holder.setText(R.id.tv_search_type_name, "朋友圈动态"); holder.getView(R.id.tv_search_more).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HashMap<String, String> map = new HashMap<>(); map.put("type", "7"); map.put("searchKey", o.getSearchKey()); GotoUtil.goToActivityWithData(mActivity, LiveSearchMoreActivity.class, map); } }); myrecyclerViewAdapter.setOnShareAndLikeItemListener( new CircleDynamicAdapter.OnShareAndLikeItemListener() { @Override public void goToCircleHome(CircleHomeBean bean) { PersonalInfoActivity.startActivity(mActivity, bean.getUserCode()); } @Override public void notifyRecyclerView(String userCode) { } @Override public void onShield(int position, CircleHomeBean bean, View view) { } @Override public void shareItem(int position, CircleHomeBean bean) { } }); } else { myrecyclerViewAdapter = (MyrecyclerViewAdapter) holder.getDataTag(); myrecyclerViewAdapter.changeDatas(bean); } } private static class MyrecyclerViewAdapter extends BaseRecyclerAdapter<CircleHomeBean> { private CircleDynamicAdapter.OnShareAndLikeItemListener listener; public MyrecyclerViewAdapter(Context context, List<CircleHomeBean> list, int itemLayoutId) { super(context, list, itemLayoutId); } @Override public void bindData(ViewHolder holder, final int position, final CircleHomeBean bean) { holder.setText(R.id.tv_circle_home_name, bean.getUserName()); holder.getView(R.id.tv_circle_home_three_content).setVisibility( TextUtils.isEmpty(bean.getContent()) ? View.GONE : View.VISIBLE); ImageHelper.loadImage(holder.getItemView().getContext(), holder.getImageView(R.id.iv_circle_home_img), bean.getUserPic()); holder.getView(R.id.iv_circle_home_img).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.goToCircleHome(bean); } }); final TextView content = holder.getViewV2(R.id.tv_circle_home_three_content); content.setText(bean.getContent()); } public interface OnShareAndLikeItemListener { // void onLike(View view, int isLike, int position, CircleHomeBean bean); void goToCircleHome(CircleHomeBean bean); } public void setOnShareAndLikeItemListener( CircleDynamicAdapter.OnShareAndLikeItemListener itemShare) { this.listener = itemShare; } } }
package com.darwinsys.aidldemo.server; import androidx.appcompat.app.AppCompatActivity; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import com.darwinsys.aidldemo.Expense; public class ServiceActivity extends AppCompatActivity { final static String TAG = "ServiceActivity"; ListView listView; ArrayAdapter listViewAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ExpenseListModel expenseListModel = ExpenseListModel.INSTANCE; listView = findViewById(R.id.myList); listViewAdapter = new ArrayAdapter<Expense>(this, android.R.layout.simple_list_item_1, expenseListModel.getExpenses()); listView.setAdapter(listViewAdapter); LocalBroadcastManager.getInstance(this).registerReceiver(updater, new IntentFilter(ExpenseListModel.ACTION_EXPENSE_ADDED)); Log.d(TAG, "Registered Receiver " + updater); } private BroadcastReceiver updater = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int id = intent.getIntExtra("id", -1); Log.d(TAG, "BroadcastReceiver got new expense item " + id); listViewAdapter.notifyDataSetChanged(); } }; @Override protected void onDestroy() { // Stop receiving notifications super.onDestroy(); unregisterReceiver(updater); } }
package pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; public class testmeappHome { @FindBy(how=How.PARTIAL_LINK_TEXT,using="SignUp") public static WebElement signup; @FindBy(how=How.PARTIAL_LINK_TEXT,using="SignIn") public static WebElement signin; }
/** * This class is generated by jOOQ */ package com.gogo.schema.tables; import com.gogo.schema.Bb; import com.gogo.schema.Keys; import com.gogo.schema.tables.records.BbOrderRecord; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.5" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class BbOrder extends TableImpl<BbOrderRecord> { private static final long serialVersionUID = -475565654; /** * The reference instance of <code>bb.bb_order</code> */ public static final BbOrder BB_ORDER = new BbOrder(); /** * The class holding records for this type */ @Override public Class<BbOrderRecord> getRecordType() { return BbOrderRecord.class; } /** * The column <code>bb.bb_order.order_no</code>. */ public final TableField<BbOrderRecord, Long> ORDER_NO = createField("order_no", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** * The column <code>bb.bb_order.status</code>. */ public final TableField<BbOrderRecord, Byte> STATUS = createField("status", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, ""); /** * The column <code>bb.bb_order.quantity</code>. */ public final TableField<BbOrderRecord, Integer> QUANTITY = createField("quantity", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>bb.bb_order.total_amount</code>. */ public final TableField<BbOrderRecord, BigDecimal> TOTAL_AMOUNT = createField("total_amount", org.jooq.impl.SQLDataType.DECIMAL.precision(10, 2).nullable(false), this, ""); /** * The column <code>bb.bb_order.pay_type</code>. 1-deliveryCash */ public final TableField<BbOrderRecord, Byte> PAY_TYPE = createField("pay_type", org.jooq.impl.SQLDataType.TINYINT, this, "1-deliveryCash"); /** * The column <code>bb.bb_order.description</code>. */ public final TableField<BbOrderRecord, String> DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.VARCHAR.length(1024), this, ""); /** * The column <code>bb.bb_order.create_time</code>. */ public final TableField<BbOrderRecord, Long> CREATE_TIME = createField("create_time", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** * The column <code>bb.bb_order.update_time</code>. */ public final TableField<BbOrderRecord, Long> UPDATE_TIME = createField("update_time", org.jooq.impl.SQLDataType.BIGINT, this, ""); /** * The column <code>bb.bb_order.delete_flag</code>. 0-NO,1-YES */ public final TableField<BbOrderRecord, Byte> DELETE_FLAG = createField("delete_flag", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, "0-NO,1-YES"); /** * The column <code>bb.bb_order.delete_time</code>. */ public final TableField<BbOrderRecord, Long> DELETE_TIME = createField("delete_time", org.jooq.impl.SQLDataType.BIGINT, this, ""); /** * Create a <code>bb.bb_order</code> table reference */ public BbOrder() { this("bb_order", null); } /** * Create an aliased <code>bb.bb_order</code> table reference */ public BbOrder(String alias) { this(alias, BB_ORDER); } private BbOrder(String alias, Table<BbOrderRecord> aliased) { this(alias, aliased, null); } private BbOrder(String alias, Table<BbOrderRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return Bb.BB; } /** * {@inheritDoc} */ @Override public UniqueKey<BbOrderRecord> getPrimaryKey() { return Keys.KEY_BB_ORDER_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<BbOrderRecord>> getKeys() { return Arrays.<UniqueKey<BbOrderRecord>>asList(Keys.KEY_BB_ORDER_PRIMARY); } /** * {@inheritDoc} */ @Override public BbOrder as(String alias) { return new BbOrder(alias, this); } /** * Rename this table */ public BbOrder rename(String name) { return new BbOrder(name, null); } }
package com.coincoinche; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CoincoincheApplication { public static void main(String[] args) { SpringApplication.run(CoincoincheApplication.class, args); } }
package com.holodec.todo.action; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.holodec.models.util.HibernateListener; import com.holodec.todo.model.ToDo; import com.opensymphony.xwork2.ActionSupport; public class ToDoAddAction extends ActionSupport { private String newDo; public String execute() { SessionFactory factory = HibernateListener.getFactory(); Session session = factory.openSession(); session.beginTransaction(); session.save(new ToDo(getNewDo())); session.getTransaction().commit(); return SUCCESS; } public void validate() { if ("".equals(getNewDo())) { addActionError("can't use empty string!"); } else { addActionMessage(getNewDo()+" is added"); } } public String getNewDo() { return newDo; } public void setNewDo(String newDo) { this.newDo = newDo; } }
package fr.skytasul.quests.utils.logger; import java.util.concurrent.CompletionException; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.command.CommandSender; import fr.skytasul.quests.utils.Lang; public class LoggerExpanded { private Logger logger; public LoggerExpanded(Logger logger) { this.logger = logger; } public void info(String msg) { logger.info(msg); } public void warning(String msg) { logger.log(Level.WARNING, msg); } public void warning(String msg, Throwable throwable) { logger.log(Level.WARNING, msg, throwable); } public void severe(String msg) { logger.log(Level.SEVERE, msg); } public void severe(String msg, Throwable throwable) { logger.log(Level.SEVERE, msg, throwable); } public <T> BiConsumer<T, Throwable> logError(Consumer<T> consumer, String friendlyErrorMessage, CommandSender sender) { return (object, ex) -> { if (ex == null) { if (consumer != null) consumer.accept(object); } else { if (ex instanceof CompletionException) { CompletionException exCompl = (CompletionException) ex; if (exCompl.getCause() != null) ex = exCompl.getCause(); } if (sender != null) Lang.ERROR_OCCURED.send(sender, friendlyErrorMessage); severe(friendlyErrorMessage, ex); } }; } public <T> BiConsumer<T, Throwable> logError(String friendlyErrorMessage, CommandSender sender) { return logError(null, friendlyErrorMessage, sender); } public <T> BiConsumer<T, Throwable> logError(String friendlyErrorMessage) { return logError(null, friendlyErrorMessage, null); } public <T> BiConsumer<T, Throwable> logError() { return logError(null, null, null); } }
package cap5exercices.example1; import java.util.Scanner; public class OwnRandomNumberGame { public static void main(String[] args) { boolean end = false; exit: do { Scanner input = new Scanner(System.in); int resp; int tries = 0; boolean guess = false; Double d = Math.random();//gera numerps de 0 a 1 int unknownNumber = (int)(2*d);//convertemos para passar a gerar numeros de 0 a 2 while (guess == false) { System.out.println("Qual é o número? De [0-100] e [-1] para desistir do jogo"); resp = input.nextInt(); if (resp == -1) { System.out.println("Desistiu do jogo"); break exit; } if (resp == unknownNumber) { System.out.println("Parabéns conseguiu acertar!"); guess = true; } else { if (resp > unknownNumber){ System.out.println(resp + "? Não, o número desconhecido é menor"); System.out.println("O numero desconhecido corresponde a " + unknownNumber); } else if (resp < unknownNumber) { System.out.println(resp + "? Não, o número desconhecido é maior"); System.out.println("O numero desconhecido corresponde a " + unknownNumber); } } } System.out.println("Parabéns! Acertou em " + tries + " tentativas" ); boolean repeat; String respRepiticao; do { System.out.println("Quer jogar outra vez?"); respRepiticao = input.next(); switch (respRepiticao) { case "s": case "S": System.out.println("Vamos jogar outra vez!"); repeat = false; break; case "n": case "N": System.out.println("Ate a proxima...."); repeat = false; break; default: System.out.println("Resposta inválida"); repeat = true; break; } } while (repeat == true); } while (end == true); } }
package com.example.agent; import javassist.ClassClassPath; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.security.ProtectionDomain; import java.util.Objects; /** * @author youthlin.chen * @date 2020-01-13 11:06 */ public class AgentTransformer implements ClassFileTransformer { private static final Logger LOGGER = LoggerFactory.getLogger(AgentTransformer.class); public static final String TARGET_CLASS_NAME_SLASH = "com/youthlin/example/boot/App"; public static final String TARGET_CLASS_NAME_DOT = "com.youthlin.example.boot.App"; @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classFileBuffer) throws IllegalClassFormatException { if (Objects.equals(TARGET_CLASS_NAME_SLASH, className)) { className = className.replace("/", "."); LOGGER.info("transform... {}", className); try { ClassPool pool = ClassPool.getDefault(); if (classBeingRedefined != null) { // https://www.jianshu.com/p/43424242846b pool.insertClassPath(new ClassClassPath(classBeingRedefined)); } CtClass ctClass = pool.get(className); CtMethod method = ctClass.getDeclaredMethod("sayHello", new CtClass[]{pool.get("java.lang.String")}); // https://www.jianshu.com/p/1e2d970e3661 method.addLocalVariable("$_start", CtClass.longType); method.insertBefore("$_start = System.currentTimeMillis();"); method.insertAfter("System.out.println(\"cost:\"+(System.currentTimeMillis()-$_start));"); byte[] bytes = ctClass.toBytecode(); ctClass.detach(); Path path = Path.of("App.class"); LOGGER.info("Write to {}", path.toAbsolutePath()); Files.write(path, bytes, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); return bytes; } catch (Throwable e) { LOGGER.warn("error", e); } } return null; } }
package com.example.fontext; import java.io.BufferedInputStream; import java.io.InputStream; import java.util.List; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.provider.ContactsContract; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; class ViewHolder{ TextView text; ImageView icon; } /** * Custom adapter to convert list of SMS conversation into a listview. * The SMS messages are stored as SmsConversation objects (another custom class). * @author Ben Kaiser */ @SuppressWarnings("rawtypes") public class SmsConversationListAdapter extends ArrayAdapter{ private LayoutInflater inflater; private Context context; @SuppressWarnings("unchecked") public SmsConversationListAdapter(Context ctx, int resourceId, List objects) { super(ctx, resourceId, objects); inflater = LayoutInflater.from( ctx ); context=ctx; } @Override public View getView (int position, View convertView, ViewGroup parent) { //Extract the conversation to display SmsConversation convo = (SmsConversation) getItem(position); //Initialize viewholder ViewHolder holder; //Apply layout (with view recycling) if (convertView == null){ convertView = inflater.inflate(R.layout.smsconversationlistview_item_row, null); holder = new ViewHolder(); holder.text = (TextView) convertView.findViewById(R.id.lblSnippet); holder.icon = (ImageView) convertView.findViewById(R.id.imgContactPhoto); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } //Set message to text view holder.text.setText(convo.getDisplayMsg()); //Set contact icon to image view long contactId = SmsMessageListAdapter.fetchContactId(convo.getContactNumber(), context); Uri uriContact = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactId)); InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),uriContact); BufferedInputStream buf = new BufferedInputStream(photo_stream); Bitmap my_btmp = BitmapFactory.decodeStream(buf); holder.icon.setImageBitmap(my_btmp); return convertView; } }
package org.androidtown.lab31; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); registerForContextMenu(button); } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Button Menu"); menu.add(0, 0, 0, "Red"); menu.add(0, 1, 1, "Green"); menu.add(0, 2, 2, "Blue"); } public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case 0: button.setTextColor(Color.RED); return true; case 1: button.setTextColor(Color.GREEN); return true; case 2: button.setTextColor(Color.BLUE); return true; } return false; } }
package com.how2java.tmall.util; public class PortUtil { }
/** * @author zzs * @create_date 2019.8.1 * @description 教师相关业务服务接口 **/ package com.app.service; import java.math.BigDecimal; import java.util.List; import java.util.Map; import com.code.model.Class; import com.code.model.Contest; import com.code.model.OnePaper; import com.code.model.OneSimproblem; import com.code.model.Response; import com.code.model.User; public interface TeacherService { /** * @author zzs * @param contest:Contest实体 * @param class:班级名称 * @description 添加一场考试 * @return 状态响应 */ public Response addContest(Contest contest,String className); /** * @author zzs * @param user:用户实例 * @description 查询老师出的所有卷子 * @return 状态响应 */ public Response selAllpaper(User user); /** * @author zzs * @param newpaper:OnePaper实例 * @param user:用户实例 * @param oneSimps:List<OneSimproblem>实例 * @description 添加新的试卷 * @return 状态响应 */ public Response addNewpaper(OnePaper newpaper,User user,List<OneSimproblem> oneSimps,String basePath); /** * @author zzs * @param user:用户实例 * @description 教师查询所有考试Status * @return 状态响应 */ public Response selContestStatus(User user); /** * 查询属于某个教师的所有contest对象 * @param 教师 * @return 属于同个教师的所有contest */ public Response selAllContest(User user); /** * 查询计算所有班级某场考试的平均分 * @param cla 具体班级 * @param contest 具体考试 * @return */ public Response selClassAverageScore(User user,Class cla,Contest contest); /** * 查询计算所有班级某场考试的最高分分 * @param cla 具体班级 * @param contest 具体考试 * @return */ public Response selClassHighestScore(User user,Class cla,Contest contest); /** * 查询计算所有班级某场考试的最低分 * @param cla 具体班级 * @param contest 具体考试 * @return */ public Response selClasslowestScore(User user,Class cla,Contest contest); /** * 导出年级成绩表 * @param user 具体老师 * @param contest 具体考试 * @return 导出结果 */ public Response exportGradeScoreExcel(User user,Contest contest); /** * 查询全级学生分数 * @param user * @param contest * @return 成绩实体Map对象集合 */ public List<Map<String,Object>> selGradeScore(User user,Contest contest); /** * 根据搜索条件模糊查询出学生成绩表 * @param 1、班级名称 * @param 2、学生学号 * @param 3、学生名字 * @param 4、考试名称 * @return 成绩实体Map对象集合 */ public List<Map<String,Object>> selStuScore(String className,String stuId,String stuName,String contestName,String pageSize,String pageNumber); /** * 查询出所有学生成绩表 * @return 成绩实体Map对象集合 */ public List<Map<String,Object>> selAllStuScore(); /** * 根据搜索条件模糊查询出学生成绩表 * @param cstatusid: 所更新成绩对应的表的主键id * @param score: 用户重新更新的成绩 * @return 更新操作返回的状态 */ public int updateScore(String cStatusId,String score); /** * 查询所有的班级对象 * @return 所有的班级对象 */ public List<Map<String,Object>> selAllClassObj(); /** * 查询所有的考试对象 * @return 所有的考试对象 */ public List<Map<String,Object>> selAllContestObj(); /** * 查询所有的班级的所有考试的平均分 * @return 所有对象 */ public List<Map<String,Object>> selClassContestAVG(List className,List contestName); /** * 查询通用题库列表 * @return 所有对象 */ public List<Map<String,Object>> selSimproblemList(int simCourseId,String simPaperTitle,int simType,String pageSize,String pageNumberr); /** * 删除单条simproblem * @param simId * @return */ public int delSimproblemById(int simId); /** * 删除多条simproblem * @param ids * @return */ public int delBatchSimproblemByIds(List<String> ids); }
package src; public class Bicicleta implements iMusicable{ private String marca; private String color; protected int velocidad=0; protected int acelerar; protected int freno; public Bicicleta(String marca, String color, int acelerar, int freno) { this.marca=marca; this.color=color; this.acelerar=acelerar; this.freno=freno; } @Override public void iniciarReproduccion(){ System.out.println("Reproduciendo música"); } @Override public void detenerReproduccion(){ System.out.println("Detener música"); } }
package org.hnrw.chin.integrators; import org.dom4j.Element; import org.dom4j.Document; import org.dom4j.io.SAXReader; import be.mxs.common.util.db.MedwanQuery; import java.net.URL; import java.util.Iterator; import java.util.Date; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.text.SimpleDateFormat; /** * Created by IntelliJ IDEA. * User: Frank * Date: 23-mei-2008 * Time: 22:51:22 * To change this template use File | Settings | File Templates. */ public abstract class Integrator { public abstract boolean integrate(Element message); static public boolean readMessage(String filename){ boolean bSuccess=false; String sDoc = MedwanQuery.getInstance().getConfigString("templateSource") + "healthnet.xml"; SAXReader reader = new SAXReader(false); Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ Document hnConfig = reader.read(new URL(sDoc)); Element root=hnConfig.getRootElement(); Element integrator = root.element("integrator"); Document msg = reader.read((integrator.attributeValue("directory","c:/hn/received")+"/"+filename).replaceAll("//","/")); Element message = msg.getRootElement(); Iterator classes = integrator.elementIterator("class"); while(classes.hasNext()){ Element cls = (Element)classes.next(); if(cls.attributeValue("id").equals(message.attributeValue("type"))){ Integrator i = (Integrator)Class.forName(cls.attributeValue("name")).newInstance(); if(i.integrate(message)){ String sQuery="update HealthNetIntegratedMessages set integrationDateTime=?,creationDateTime=? where hn_filename=?"; PreparedStatement ps = oc_conn.prepareStatement(sQuery); ps.setTimestamp(1,new Timestamp(new Date().getTime())); ps.setTimestamp(2,new Timestamp(new SimpleDateFormat("yyyyMMddHHmmssSSS").parse(message.attributeValue("created")).getTime())); ps.setString(3,filename); ps.execute(); ps.close(); } } } } catch(Exception e){ e.printStackTrace(); } try { oc_conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bSuccess; } Timestamp makeTimestamp(String s){ Timestamp d = null; try{ d=new Timestamp(new SimpleDateFormat("yyyyMMddHHmmssSSS").parse(s).getTime()); } catch(Exception e){ } return d; } }
package com.eshop.model.service; import java.util.List; import com.eshop.model.dao.DBException; import com.eshop.model.dao.DaoFactory; import com.eshop.model.dao.OrdersDao; import com.eshop.model.entity.Order; public class OrdersService { DaoFactory daoFactory = DaoFactory.getInstance(); public void createOrder (Order o) throws DBException { try (OrdersDao dao = daoFactory.createOrdersDao()) { dao.create(o); } } public Order getOrder (long id) throws DBException { try (OrdersDao dao = daoFactory.createOrdersDao()) { Order o = dao.findById(id); return o; } } public List <Order> getOrders () throws DBException { try (OrdersDao dao = daoFactory.createOrdersDao()) { return dao.findAll(); } } public void updateOrder (Order o) throws DBException { try (OrdersDao dao = daoFactory.createOrdersDao()) { dao.update(o); } } public void deleteOrder (Order o) throws DBException { try (OrdersDao dao = daoFactory.createOrdersDao()) { dao.delete(o); } } }
package com.rednovo.ace.core.session; import android.text.TextUtils; import com.alibaba.fastjson.JSONObject; import com.rednovo.ace.common.Globle; import com.rednovo.ace.common.KeyGenerator; import com.rednovo.ace.communication.client.ClientSession; import com.rednovo.ace.data.cell.MsgLog; import com.rednovo.ace.data.events.ReciveGiftInfo; import com.rednovo.ace.entity.Message; import com.rednovo.ace.entity.Summary; import com.rednovo.libs.ui.base.BasicData; import de.greenrobot.event.EventBus; /** * Created by lizhen on 16/3/11. */ public class SendUtils { /** * 发送私聊文本 * * @param sendId * @param recvId * @param txtMSG */ private void sendPrivateText(String sendId, String recvId, String txtMSG) { sendChat(Globle.TXT_MSG, Globle.PRIVATE, sendId, recvId, "", txtMSG); } /** * 发送群聊文本 * * @param sendId * @param recvId 群组聊天可以recvId不用传入,也可以传入GroupID * @param showId * @param txtMSG 文本 */ private static void sendGroupText(String sendId, String recvId, String showId, String txtMSG) { sendChat(Globle.TXT_MSG, Globle.GROUP, sendId, recvId, showId, txtMSG); } /** * 发送私聊语音 * * @param sendId 发送者ID * @param recvId 接受者ID * @param fileName 语音文件路径 */ private static void sendPrivateVoice(String sendId, String recvId, String fileName, String duration) { sendVoice(Globle.MEDIA_MSG_AUDIO, Globle.PRIVATE, sendId, recvId, "", fileName, duration); } /** * 发送群聊语音 * * @param sendId * @param recvId 群组聊天可以recvId不用传入,也可以传入GroupID * @param groupId * @param fileName */ private static void sendGroupVoice(String sendId, String recvId, String groupId, String fileName, String duration) { sendVoice(Globle.MEDIA_MSG_AUDIO, Globle.GROUP, sendId, recvId, groupId, fileName, duration); } /** * 发送私聊图片 * * @param sendId * @param recvId * @param fileName * @author zhen.Li * @since 2015-5-20下午6:57:17 */ private static void sendPrivatePic(String sendId, String recvId, String fileName) { sendPictrue(Globle.MEDIA_MSG_PIC, Globle.PRIVATE, sendId, recvId, "", fileName); } /** * 发送群组图片 * * @param sendId * @param recvId * @param groupId * @param fileName * @author zhen.Li * @since 2015-5-20下午6:57:26 */ private static void sendGroupPic(String sendId, String recvId, String groupId, String fileName) { sendPictrue(Globle.MEDIA_MSG_PIC, Globle.GROUP, sendId, recvId, groupId, fileName); } /** * 发送图片 * * @param msgType * @param chatMode * @param sendId * @param recvId * @param showId * @param fileName * @author zhen.Li * @since 2015-5-20下午6:51:46 */ private static void sendPictrue(String msgType, String chatMode, String sendId, String recvId, String showId, String fileName) { Message msg = new Message(); Summary sumy = new Summary(); sumy.setRequestKey(Globle.KEY_SEND_MSG_STATUS); sumy.setChatMode(chatMode); sumy.setInteractMode(Globle.REQUEST); sumy.setMsgId(KeyGenerator.createUniqueId()); sumy.setMsgType(msgType); sumy.setReceiverId(recvId); sumy.setSenderId(sendId); sumy.setFileName(fileName); if (!TextUtils.isEmpty(showId)) { sumy.setShowId(showId); } msg.setSumy(sumy); ClientSession.getInstance().sendMessage(msg); } /** * @param msgType 消息类型 * @param chatMode 聊天模式 * @param sendId 发送者id * @param recvId 接受者id * @param groupId 群组id * @param fileName 文件路径 */ private static void sendVoice(String msgType, String chatMode, String sendId, String recvId, String groupId, String fileName, String duration) { Message msg = new Message(); Summary sumy = new Summary(); sumy.setRequestKey(Globle.KEY_SEND_MSG_STATUS); sumy.setChatMode(chatMode); sumy.setInteractMode(Globle.REQUEST); sumy.setMsgId(KeyGenerator.createUniqueId()); sumy.setMsgType(msgType); sumy.setReceiverId(recvId); sumy.setSenderId(sendId); sumy.setFileName(fileName); sumy.setDuration(TextUtils.isEmpty(duration) ? "0" : duration); if (!TextUtils.isEmpty(groupId)) { sumy.setShowId(groupId); } msg.setSumy(sumy); ClientSession.getInstance().sendMessage(msg); } /** * @param chatMode 私聊,还是群聊,目前封装在ChatMode类中 * @param msgType 消息类型,Globle定义的常量类型 * @param sendId 发送者ID * @param recvId 接收者id * @param showId 群组ID * @param txtMSG 消息文本 */ private static void sendChat(String msgType, String chatMode, String sendId, String recvId, String showId, String txtMSG) { Message msg = new Message(); Summary sumy = new Summary(); sumy.setRequestKey(Globle.KEY_SEND_MSG_STATUS); sumy.setChatMode(chatMode); sumy.setInteractMode(Globle.REQUEST); sumy.setMsgId(KeyGenerator.createUniqueId()); sumy.setMsgType(msgType); sumy.setReceiverId(recvId); sumy.setSenderId(sendId); if (!TextUtils.isEmpty(showId)) { sumy.setShowId(showId); } msg.setSumy(sumy); JSONObject obj = new JSONObject(); obj.put("basicData", BasicData.formatJson()); obj.put("senderId", sendId); obj.put("showId", showId); obj.put("receiverId", recvId); obj.put("chatMode", chatMode); obj.put("txt", txtMSG); msg.setBody(obj); ClientSession.getInstance().sendMessage(msg); } /** * 发送消息 * * @param msg */ public static void sendMessage(MsgLog msg) { if (msg != null) { // int chatMode = msg.chatMode; // if (chatMode == MsgLog.CHAT_MODE_PRIVATE) { // // if (msg.isText()) { // sendPrivateText(msg.sendNumber, msg.receiveNumber, msg.msgContent); // } // if (msg.isVoice()) { // sendPrivateVoice(msg.sendNumber, msg.receiveNumber, msg.msgContent, String.valueOf(msg.msgDuration)); // } // if (msg.isPic()) { // sendPrivatePic(msg.sendNumber, msg.receiveNumber, msg.msgContent); // } // } else { // if (msg.isText()) { sendGroupText(msg.sendNumber, msg.receiveNumber, msg.showId, msg.msgContent); //} // if (msg.isVoice()) { // sendGroupVoice(msg.sendNumber, msg.receiveNumber, msg.receiveNumber, msg.msgContent, String.valueOf(msg.msgDuration)); // } // if (msg.isPic()) { // sendGroupPic(msg.sendNumber, msg.receiveNumber, msg.receiveNumber, msg.msgContent); // } // } } } /** * 进入房间 */ public static void enterRoom(String userId, String showId) { Message msg = new Message(); Summary sumy = new Summary(); sumy.setRequestKey(Globle.KEY_ENTER_ROOM); sumy.setChatMode(Globle.GROUP); sumy.setInteractMode(Globle.REQUEST); sumy.setMsgId(KeyGenerator.createUniqueId()); sumy.setMsgType(Globle.TXT_MSG); if (TextUtils.isEmpty(userId)) { sumy.setSenderId("-1"); } else { sumy.setSenderId(userId); } msg.setSumy(sumy); JSONObject json = new JSONObject(); json.put("basicData", BasicData.formatJson()); json.put("userId", userId); json.put("showId", showId); msg.setBody(json); ClientSession.getInstance().sendMessage(msg); } /** * 退出房间 * * @param userId * @param showId */ public static void exitRoom(String userId, String showId) { Message msg = new Message(); Summary sumy = new Summary(); sumy.setRequestKey(Globle.KEY_EXIT_ROOM); sumy.setChatMode(Globle.GROUP); sumy.setInteractMode(Globle.REQUEST); sumy.setMsgId(KeyGenerator.createUniqueId()); sumy.setMsgType(Globle.TXT_MSG); if (TextUtils.isEmpty(userId)) { sumy.setSenderId("-1"); } else { sumy.setSenderId(userId); } msg.setSumy(sumy); JSONObject json = new JSONObject(); json.put("basicData", BasicData.formatJson()); json.put("userId", userId); json.put("showId", showId); msg.setBody(json); ClientSession.getInstance().sendMessage(msg); } /** * 踢人 * * @param starId * @param userId * @param showId */ public static void kickOut(String starId, String userId, String showId) { Message msg = new Message(); Summary sumy = new Summary(); sumy.setRequestKey(Globle.KEY_KICK_OUT); sumy.setChatMode(Globle.GROUP); sumy.setInteractMode(Globle.REQUEST); sumy.setMsgId(KeyGenerator.createUniqueId()); sumy.setMsgType(Globle.TXT_MSG); if (TextUtils.isEmpty(userId)) { sumy.setSenderId("-1"); } else { sumy.setSenderId(userId); } msg.setSumy(sumy); JSONObject json = new JSONObject(); json.put("basicData", BasicData.formatJson()); json.put("starId", starId); json.put("userId", userId); json.put("showId", showId); msg.setBody(json); ClientSession.getInstance().sendMessage(msg); } /** * 禁言 * @param starId * @param userId * @param showId */ public static void shutup(String starId, String userId, String showId) { Message msg = new Message(); Summary sumy = new Summary(); sumy.setRequestKey(Globle.KEY_SHUTUP); sumy.setChatMode(Globle.GROUP); sumy.setInteractMode(Globle.REQUEST); sumy.setMsgId(KeyGenerator.createUniqueId()); sumy.setMsgType(Globle.TXT_MSG); if (TextUtils.isEmpty(starId)) { sumy.setSenderId("-1"); } else { sumy.setSenderId(starId); } msg.setSumy(sumy); JSONObject json = new JSONObject(); json.put("basicData", BasicData.formatJson()); json.put("starId", starId); json.put("userId", userId); json.put("showId", showId); msg.setBody(json); ClientSession.getInstance().sendMessage(msg); } /** * 送礼物 * * @param senderId * @param receiverId * @param showId * @param giftId * @param cnt */ public static void sendGif(String senderId, String receiverId, String showId, String giftId, String cnt) { Message msg = new Message(); Summary sumy = new Summary(); sumy.setRequestKey(Globle.KEY_SEND_GIF); sumy.setChatMode(Globle.GROUP); sumy.setInteractMode(Globle.REQUEST); sumy.setMsgId(KeyGenerator.createUniqueId()); sumy.setMsgType(Globle.TXT_MSG); if (TextUtils.isEmpty(senderId)) { sumy.setSenderId("-1"); } else { sumy.setSenderId(senderId); } msg.setSumy(sumy); JSONObject json = new JSONObject(); json.put("basicData", BasicData.formatJson()); json.put("senderId", senderId); json.put("receiverId", receiverId); json.put("showId", showId); json.put("giftId", giftId); json.put("cnt", cnt); msg.setBody(json); ClientSession.getInstance().sendMessage(msg); } /** * 发送点赞 * * @param showId * @param userId * @param cnt */ public static void sendParise(String showId, String userId, String cnt) { Message msg = new Message(); Summary sumy = new Summary(); sumy.setRequestKey(Globle.KEY_SEND_PARISE); sumy.setChatMode(Globle.GROUP); sumy.setInteractMode(Globle.REQUEST); sumy.setMsgId(KeyGenerator.createUniqueId()); if (TextUtils.isEmpty(userId)) { sumy.setSenderId("-1"); } else { sumy.setSenderId(userId); } sumy.setMsgType(Globle.TXT_MSG); msg.setSumy(sumy); JSONObject json = new JSONObject(); json.put("basicData", BasicData.formatJson()); json.put("showId", showId); json.put("userId", userId); json.put("cnt", cnt); msg.setBody(json); ClientSession.getInstance().sendMessage(msg); } }
package com.example.a0924; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.wifi.p2p.WifiP2pManager; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.RadioButton; import android.widget.Spinner; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button b1,b2; RadioButton r1,r2; TextView ta; EditText ed1,ed2; Spinner sp; ListView li; String s1[]={"1학년","3학년","5학년"}; String s2[]={"상","중","하"}; //가져올 값 String v;//level int num,result;//grade @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Spinner_choose the grade sp = (Spinner) findViewById(R.id.sp); ArrayAdapter<String> ad1=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,s1); sp.setAdapter(ad1); sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if(i==0) num=10; //1 else if(i==1) num=20; //3 else num=30; //5 } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); //ListView choose the level li = (ListView) findViewById(R.id.li); ArrayAdapter<String> ad2= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,s2); li.setAdapter(ad2); li.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if(i==0) v="상:"; else if(i==1) v="중:"; else v="하"; } }); b1=(Button)findViewById(R.id.b1); b1.setOnClickListener(new Op()); ed1=(EditText)findViewById(R.id.ed1); ed2=(EditText)findViewById(R.id.ed2); ta=(TextView)findViewById(R.id.ta); r1=(RadioButton)findViewById(R.id.r1); r2=(RadioButton)findViewById(R.id.r2); b2=(Button)findViewById(R.id.b2); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String s=ed2.getText().toString().trim(); int is=Integer.parseInt(s); String n=ed1.getText().toString(); String r; if(result==is) r=n+"정답"; else r=n+"오답"; Intent it=new Intent(getApplication(),sub.class); it.putExtra("toss",r); startActivity(it); } }); }//onCreate class Op implements View.OnClickListener{ @Override public void onClick(View view) { if(r1.isChecked()){ int n1=(int)(Math.random()*num+1); int n2=(int)(Math.random()*num+1); result=n1+n2; ta.setText(v+n1+"+"+n2); }else{ int n1=(int)(Math.random()*num+1); int n2=(int)(Math.random()*num+1); result=n1*n2; ta.setText(v+n1+"*"+n2); }//else //ta print }//onClick }//Op }//class
package com.trump.auction.web.controller; import com.trump.auction.cust.api.NotificationDeviceStubService; import com.trump.auction.cust.enums.NotificationDeviceTypeEnum; import com.trump.auction.cust.model.NotificationDeviceModel; import com.trump.auction.web.service.NotificationDeviceService; import com.trump.auction.web.util.HandleResult; import com.trump.auction.web.util.JsonView; import com.trump.auction.web.util.SpringUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Author: zhanping */ @Controller @RequestMapping(value = "notiDevice/") public class NotificationDeviceController extends BaseController{ @Autowired private NotificationDeviceService notificationDeviceService; @RequestMapping("save") public void save(HttpServletRequest request, HttpServletResponse response,NotificationDeviceModel obj) { String deviceId = request.getHeader("deviceId"); if (StringUtils.isNotBlank(deviceId)) { obj.setDeviceId(deviceId); } String clientType = request.getHeader("clientType"); if (StringUtils.isNotBlank(clientType)) { NotificationDeviceTypeEnum[] values = NotificationDeviceTypeEnum.values(); for (NotificationDeviceTypeEnum type:values){ if (clientType.equals(type.getName())){ obj.setDeviceType(type.getType()); break; } } } String userId = getUserIdFromRedis(request); if (StringUtils.isNotBlank(userId)) { obj.setUserId(Integer.valueOf(userId)); } HandleResult result = notificationDeviceService.save(obj); SpringUtils.renderJson(response, JsonView.build(result.getCode(),result.getMsg(), result.getData())); } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class Driver { public static void main(String[] args) throws IOException { double start, end; Maze fiveMaze = readMazeIn("5x5maze.txt"); //Load Mazes Maze sevenMaze = readMazeIn("7x7maze.txt"); Maze eightMaze = readMazeIn("8x8maze.txt"); Maze nineMaze = readMazeIn("9x9maze.txt"); Maze tenMaze = readMazeIn("10x10maze.txt"); Maze twelveMaze = readMazeIn("12x12maze.txt"); // Maze fourteenMaze = readMazeIn("14x14maze.txt"); // fiveMaze.printColorBaseNodes(); //Prints to the console with color System.out.println(); //fiveMaze.dumbSolve(); // fiveMaze.solveMaze(); System.out.println("Initial Maze"); fiveMaze.printColorMaze(); start = System.currentTimeMillis(); new SimpleSolver(fiveMaze); end = System.currentTimeMillis(); System.out.println("Final 5x5 Maze"); fiveMaze.printColorMaze(); System.out.println("Time to solve is " + (end - start) + "ms."); //sevenMaze.printColorBaseNodes(); sevenMaze.printColorMaze(); start = System.currentTimeMillis(); new SimpleSolver((sevenMaze)); end = System.currentTimeMillis(); System.out.println("Final 7x7 Maze"); sevenMaze.printColorMaze(); System.out.println("Time to solve is " + (end - start) + "ms."); // eightMaze.printColorMaze(); start = System.currentTimeMillis(); new SimpleSolver(eightMaze); end = System.currentTimeMillis(); System.out.println("Final 8x8 Maze"); eightMaze.printColorMaze(); System.out.println("Time to solve is " + (end - start) + "ms."); // nineMaze.printColorMaze(); // new SimpleSolver(nineMaze); // System.out.println("Final 9x9 Maze"); // nineMaze.printColorMaze(); // // tenMaze.printColorMaze(); // new SimpleSolver(tenMaze); // System.out.println("Final 10x10 Maze"); // tenMaze.printColorMaze(); //// // twelveMaze.printColorMaze(); // new SimpleSolver(twelveMaze); // System.out.println("Final 12x12 Maze"); // twelveMaze.printColorMaze(); // // fourteenMaze.printColorBaseNodes(); // fourteenMaze.printColorMaze(); System.out.println("Program Done"); } private static Maze readMazeIn(String mazeName) throws IOException { //creates a 2 dimensional character array ArrayList<String> maze = new ArrayList<>(); // that holds the maze try (BufferedReader br = new BufferedReader(new FileReader(mazeName))) { String line = br.readLine(); while (line != null) { maze.add(line); line = br.readLine(); } } char[][] newMaze = new char[maze.size()][maze.get(0).length()]; for (int i = 0; i < maze.size(); i++) { newMaze[i] = maze.get(i).toCharArray(); } return new Maze(newMaze); } }
package lxy.liying.circletodo.db; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; import lxy.liying.circletodo.app.App; import lxy.liying.circletodo.domain.DateEvent; import lxy.liying.circletodo.utils.Constants; import lxy.liying.circletodo.utils.StringUtils; /** * ======================================================= * 版权:©Copyright LiYing 2015-2016. All rights reserved. * 作者:liying * 日期:2016/7/24 13:07 * 版本:1.0 * 描述:数据库操作层——操作表 date_event * 备注: * ======================================================= */ public class DateEventService { private DatabaseHelper dbHelper; private String[] columns = {DateEvent.D_ID, DateEvent.UID, DateEvent.E_DATE, DateEvent.COLOR_ID}; /** * 升序 */ public static final String ORDER_ASC = "ASC"; /** * 降序 */ public static final String ORDER_DESC = "DESC"; /** * 构造方法 * * @param context */ public DateEventService(Context context) { dbHelper = new DatabaseHelper(context); } /** * 添加日期标记到数据库中 <br/> * d_id为时间戳,调用者不需要传入 <br/> * 日期将被格式化为“yyyy-MM-dd”格式 <br/> * * @param de */ public void addDateEvent(DateEvent de) { SQLiteDatabase db = this.dbHelper.getWritableDatabase(); String sql = "INSERT INTO " + DBInfo.Table.TB_DATE_EVENT + " VALUES (" + System.currentTimeMillis() + ",'" + App.CURRENT_UID + "','" + StringUtils.formatDate(de.getE_date()) + "', " + de.getColor_id() + ");"; db.execSQL(sql); // System.out.println("addDateEvent:" + sql); db.close(); } /** * 根据日期获得colorId * * @param date * @return */ public List<Integer> getColorId(String date) { date = StringUtils.formatDate(date); SQLiteDatabase db = this.dbHelper.getReadableDatabase(); Cursor cursor = db.query(DBInfo.Table.TB_DATE_EVENT, columns, DateEvent.E_DATE + "=? AND " + DateEvent.UID + "=?", new String[]{date, App.CURRENT_UID}, null, null, null); List<Integer> colorIds = new ArrayList<>(Constants.DAY_MAX_MARK_NUM); if (cursor.getCount() > 0) { while (cursor.moveToNext()) { int colorId = cursor.getInt(cursor.getColumnIndex(DateEvent.COLOR_ID)); colorIds.add(colorId); } cursor.close(); } db.close(); return colorIds; } /** * 删除指定的标记 * * @param date 日期 * @param colorId ColorId */ public void removeMark(String date, int colorId) { date = StringUtils.formatDate(date); SQLiteDatabase db = this.dbHelper.getWritableDatabase(); String sql = "DELETE FROM " + DBInfo.Table.TB_DATE_EVENT + " WHERE " + DateEvent.UID + " = '" + App.CURRENT_UID + "' AND " + DateEvent.E_DATE + " = '" + date + "' AND " + DateEvent.COLOR_ID + " = " + colorId; db.execSQL(sql); // System.out.println("removeMark:" + sql); db.close(); } /** * 删除指定日期的标记 * * @param date 日期 */ public void removeMarksOfDate(String date) { date = StringUtils.formatDate(date); SQLiteDatabase db = this.dbHelper.getWritableDatabase(); String sql = "DELETE FROM " + DBInfo.Table.TB_DATE_EVENT + " WHERE " + DateEvent.UID + " = '" + App.CURRENT_UID + "' AND " + DateEvent.E_DATE + " = '" + date + "'"; db.execSQL(sql); // System.out.println("removeMarksOfDate:" + sql); db.close(); } /** * 删除指定的标记 * * @param d_id 添加标记时的时间戳 */ public void removeMark(long d_id) { SQLiteDatabase db = this.dbHelper.getWritableDatabase(); String sql = "DELETE FROM " + DBInfo.Table.TB_DATE_EVENT + " WHERE " + DateEvent.UID + " = '" + App.CURRENT_UID + "' AND " + DateEvent.D_ID + " = " + d_id; db.execSQL(sql); // System.out.println("removeMark:" + sql); db.close(); } /** * 删除所有该颜色的标记 * * @param colorId */ public void removeMarks(int colorId) { SQLiteDatabase db = this.dbHelper.getWritableDatabase(); String sql = "DELETE FROM " + DBInfo.Table.TB_DATE_EVENT + " WHERE " + DateEvent.UID + " = '" + App.CURRENT_UID + "' AND " + DateEvent.COLOR_ID + " = " + colorId; // System.out.println("removeMarks:" + sql); db.execSQL(sql); db.close(); } /** * 统计该颜色的标记数目 * * @param colorId */ public int marksCount(int colorId) { SQLiteDatabase db = this.dbHelper.getReadableDatabase(); Cursor cursor = db.query(DBInfo.Table.TB_DATE_EVENT, columns, DateEvent.UID + "=? AND " + DateEvent.COLOR_ID + "=? ", new String[]{App.CURRENT_UID, String.valueOf(colorId)}, null, null, null); int count = cursor.getCount(); cursor.close(); db.close(); return count; } /** * 删除该用户所有的标记 <br/> * 此方法删除数据时无法获取进度,暂时不用 <br/> */ public void removeMarks() { SQLiteDatabase db = this.dbHelper.getWritableDatabase(); String sql = "DELETE FROM " + DBInfo.Table.TB_DATE_EVENT + " WHERE " + DateEvent.UID + " = '" + App.CURRENT_UID + "'"; // System.out.println("removeMarks:" + sql); db.execSQL(sql); db.close(); } /** * 得到该用户所有日期标记 <br/> * * @param order 指定排序(可取值:"ASC":按日期从小到大排序;"DESC":按日期从大到小排序) * @return */ public List<DateEvent> findAllDateEvent(String order) { SQLiteDatabase db = this.dbHelper.getReadableDatabase(); List<DateEvent> lists = null; Cursor cursor = db.query(DBInfo.Table.TB_DATE_EVENT, columns, DateEvent.UID + "=?", new String[]{App.CURRENT_UID}, null, null, DateEvent.E_DATE + " " + order); if (cursor.getCount() > 0) { lists = new ArrayList<>(cursor.getCount()); DateEvent dateEvent = null; while (cursor.moveToNext()) { dateEvent = new DateEvent(); long d_id = cursor.getLong(cursor.getColumnIndex(DateEvent.D_ID)); String e_date = cursor.getString(cursor.getColumnIndex(DateEvent.E_DATE)); int color_id = cursor.getInt(cursor.getColumnIndex(DateEvent.COLOR_ID)); dateEvent.setD_id(d_id); dateEvent.setE_date(e_date); dateEvent.setColor_id(color_id); lists.add(dateEvent); } cursor.close(); } db.close(); return lists; } /** * 统计该用户所有标记的数目 * * @return */ public int getMarkCount() { SQLiteDatabase db = this.dbHelper.getReadableDatabase(); Cursor cursor = db.query(DBInfo.Table.TB_DATE_EVENT, columns, DateEvent.UID + "=?", new String[]{App.CURRENT_UID}, null, null, null); int count = cursor.getCount(); cursor.close(); db.close(); return count; } /** * 更新ColorId * * @param oldColorId * @param newColorId */ public void updateColorId(int oldColorId, int newColorId) { SQLiteDatabase db = this.dbHelper.getReadableDatabase(); String sql = "UPDATE " + DBInfo.Table.TB_DATE_EVENT + " SET " + DateEvent.COLOR_ID + "=" + newColorId + " WHERE " + DateEvent.UID + " = '" + App.CURRENT_UID + "' AND " + DateEvent.COLOR_ID + "=" + oldColorId; db.execSQL(sql); // System.out.println("updateEvent: " + sql); db.close(); } }
package containers; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Scanner; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.rapplebob.ArmsAndArmorChampions.State; public class Menuholder extends Content{ public Menuholder(String name, int x, int y) { super(x, y, ContentType.MENUHOLDER); NAME = name; } public ArrayList<Menu> menus = new ArrayList<Menu>(); public int activeMenu = 0; public State gameState = State.DEFAULT; public String NAME = ""; public void openMenuByID(String ID){ for(int i = 0; i < menus.size(); i++){ if(menus.get(i).ID.equals(ID)){ activeMenu = i; break; } } //soutMenu(getActiveMenu()); } public void soutMenu(Menu m){ //In case of disaster: sout the menu to console. m.sout(); } public void update(){ for(int i = 0; i < menus.size(); i++){ menus.get(i).update(); } } public void loadMenusFromFolder(String path){ try{ //Rensa menyer menus.clear(); //Öppna mappen String index = Gdx.files.internal(path + "INDEX.txt").readString(); ArrayList<String> files = new ArrayList<String>(); while(index.contains(":")){ files.add(index.substring(1, index.indexOf(";"))); index = index.substring(index.indexOf(";") + 1); } //Loopa igenom filer Scanner reader; if(files.size() > 0){ for(int i = 0; i < files.size(); i++){ FileHandle file = Gdx.files.internal(path + files.get(i)); if(file.extension().equals("txt")){ String s = file.readString(); Menu m = Menu.parseMenu(s); menus.add(m); }else{ System.out.println("Non-txt in index of menus"); } } }else{ System.out.println("NO MENUS TO LOAD"); } }catch(Exception ex){ ex.printStackTrace(); } } public Menu getActiveMenu(){ return menus.get(activeMenu); } @Override public void mouseMoved(Rectangle mouse, int cx, int cy) { } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author Gen Xander */ public class UserModel { String id_user, nama_user, username, password, level; public String getId_user() { return id_user; } public void setId_user(String id_user) { this.id_user = id_user; } public String getNama_user() { return nama_user; } public void setNama_user(String nama_user) { this.nama_user = nama_user; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } Koneksi db = null; public UserModel(){ db = new Koneksi(); } public List tampil(){ List<UserModel> data = new ArrayList<>(); ResultSet rs = null; try { String sql = "select * from user"; rs = db.ambilData(sql); while(rs.next()){ UserModel um = new UserModel(); um.setId_user(rs.getString("id_user")); um.setNama_user(rs.getString("nama_user")); um.setUsername(rs.getString("username")); um.setPassword(rs.getString("password")); um.setLevel(rs.getString("level")); data.add(um); } db.tutupKoneksi(rs); } catch (Exception e) { JOptionPane.showMessageDialog(null,"Salah tampil" +e); } return data; } public List cariLogin(String username,String password){ List<UserModel> data = new ArrayList<>(); ResultSet rs = null; try { String sql = "select username,password,level from user where username='"+username+"' and password='"+password+"'"; rs = db.ambilData(sql); while(rs.next()){ UserModel um = new UserModel(); um.setUsername(rs.getString("username")); um.setPassword(rs.getString("password")); um.setLevel(rs.getString("level")); data.add(um); } db.tutupKoneksi(rs); } catch (Exception e) { JOptionPane.showMessageDialog(null,"Salah tampil" +e); } return data; } }
package net.tecgurus.persistence.dao; import java.util.List; import net.tecgurus.entities.Banco; import net.tecgurus.entities.Cliente; public interface ClienteDAO { List<Cliente> findAll(); List<Cliente> findMatches(String name, String aP, String aM); List<Cliente> findMatches2(String name, String aP, String aM); List<Cliente> findMatches3(String name, String aP, String aM); List<Cliente> findMatches(int lowRange, int maxRange); List<Cliente> findFromBanco(int idBanco); List<Cliente> findFromBanco(String bancoNombre); List<Cliente> findFromBanco(Banco banco); List<Cliente> findAllByCriteria(); List<Cliente> findMatchesFromCriteria(String name, String aP, String aM); List<Cliente> findMatchesFromCriteria(int lowRange, int maxRange); List<Cliente> findFromBancoCriteria(int idBanco); List<Cliente> findFromBancoCriteria(String bancoNombre); }
package br.com.julianocelestino.domain; import br.com.julianocelestino.persistence.NodeJsonType; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity @TypeDefs( {@TypeDef( name= "NodeJsonType", typeClass = NodeJsonType.class)}) public class Territory { @Id @GeneratedValue(generator = "territory") @GenericGenerator(name = "territory", strategy = "increment") private long id; @Column private String name; @Column @Type(type = "NodeJsonType") private Node startArea; @Column @Type(type = "NodeJsonType") private Node endArea; @Column @ElementCollection(targetClass=Node.class,fetch=FetchType.EAGER) private List<Node> paintedSquares; public boolean belongs(Node square) { return ((square.getX() > startArea.getX() && square.getY() > startArea.getY()) && (square.getX() < endArea.getX() && square.getY() < endArea.getY())); } public List<Node> paintedSquares() { return paintedSquares; } public void paint (Node squareToPain) throws InvalidPaintAreaException { if (paintedSquares == null) { paintedSquares = new ArrayList<Node>(); } if (!paintedSquares.contains(squareToPain)) { if (squareToPain.getY() - squareToPain.getX() != 1) { throw new InvalidPaintAreaException(); } paintedSquares.add(squareToPain); squareToPain.painted(true); } } public long paintedArea() { if (paintedSquares == null) { return 0; } else { return paintedSquares.size(); } } public boolean isSameArea(Territory other) { return (startArea.equals(other.getStartArea()) && endArea.equals(other.getEndArea())); } public long proportionalPaintedArea() { return ((Float) ((new Float(paintedArea()) / new Float(area())) * 100)).longValue(); } public long area() { return startArea.area() + endArea.area(); } public Territory(String name, Node startArea, Node endArea) { this.name = name; this.startArea = startArea; this.endArea = endArea; } public Territory() {} public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Node getStartArea() { return startArea; } public void setStartArea(Node startArea) { this.startArea = startArea; } public Node getEndArea() { return endArea; } public void setEndArea(Node endArea) { this.endArea = endArea; } }
package com.demo.tutorial; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; import org.springframework.data.redis.core.ReactiveRedisOperations; import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.StringRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @Configuration public class TutorialConfiguration { @Bean ReactiveRedisOperations<String, Tutorial> redisTutorialOperations(ReactiveRedisConnectionFactory factory) { Jackson2JsonRedisSerializer<Tutorial> serializer = new Jackson2JsonRedisSerializer<>(Tutorial.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // Solve the problem that jackson2 cannot deserialize LocalDateTime om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); om.registerModule(new JavaTimeModule()); om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); serializer.setObjectMapper(om); RedisSerializationContext.RedisSerializationContextBuilder<String, Tutorial> builder = RedisSerializationContext .newSerializationContext(new StringRedisSerializer()); RedisSerializationContext<String, Tutorial> context = builder.value(serializer).build(); return new ReactiveRedisTemplate<>(factory, context); } }
/* * 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 Adapter; /** * * @author ifpb */ public class ClasseExistente { String pinoFase; String pinoNeutro; String pinoTerra; boolean energia = false; public boolean metodoUtil(String pinoFase, String pinoNeutro, String pinoTerra) { this.pinoFase = pinoFase; this.pinoNeutro = pinoNeutro; this.pinoTerra = pinoTerra; this.energia = true; return energia; } }
package com.example.sosso.newsapplication.database; import com.example.sosso.newsapplication.database.DAOs.ArticleDAO; import com.example.sosso.newsapplication.models.Article; import androidx.room.Database; import androidx.room.RoomDatabase; @Database(entities = {Article.class}, version = 1) public abstract class ArticleDatabase extends RoomDatabase { public abstract ArticleDAO articleDAO(); }
package gateway.persist; import domain.TeacherEntity; import java.util.ArrayList; import java.util.List; public class TeacherDBGatewayStub implements TeacherDBGateway { public List<TeacherEntity> persistTeacherInvocations = new ArrayList<>(); @Override public void persist(TeacherEntity teacher) { persistTeacherInvocations.add(teacher); } }
/* * Copyright (c) TIKI Inc. * MIT license. See LICENSE file in root directory. */ package com.mytiki.blockchain.features.latest.block; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; public interface BlockRepository extends JpaRepository<BlockDO, Long> { Optional<BlockDO> findByHash(String hash); List<BlockDO> findAllByAddress(String address); }
package common; import java.awt.BorderLayout; import java.time.LocalDate; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.WindowConstants; import datepicker.JDatePicker; public class DatePickerDialog extends JOptionPane { /** * */ private static final long serialVersionUID = -3511960440606047358L; public static LocalDate getDate(final JFrame p_frame) { final JOptionPane optionPane = new DatePickerDialog(); final JDialog dialog = new JDialog(p_frame, Messages.getString("DatePickerDialog.0"), true); //$NON-NLS-1$ dialog.setContentPane(optionPane); dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); optionPane.addPropertyChangeListener(e -> { final String prop = e.getPropertyName(); if (dialog.isVisible() && e.getSource() == optionPane && prop.equals(JOptionPane.VALUE_PROPERTY)) { // If you were going to check something // before closing the window, you'd do // it here. dialog.setVisible(false); } }); dialog.pack(); dialog.setVisible(true); return (LocalDate) optionPane.getValue(); } public static void main(final String[] p_args) { System.out.println(getDate(new JFrame())); } private final JDatePicker m_picker; public DatePickerDialog() { super( Messages.getString("DatePickerDialog.1"), //$NON-NLS-1$ JOptionPane.QUESTION_MESSAGE, JOptionPane.DEFAULT_OPTION, null,null, null); setSize(500, 500); setLayout(new BorderLayout()); final JPanel jPanel = new JPanel(); m_picker = new JDatePicker(); m_picker.setTextEditable(true); m_picker.setShowYearButtons(true); jPanel.add(m_picker); final JPanel centerPanel = new JPanel(); centerPanel.setLayout(new BorderLayout()); centerPanel.add(jPanel, BorderLayout.WEST); final JPanel southPanel = new JPanel(); final JButton selectButton = new JButton(Messages.getString("DatePickerDialog.2")); //$NON-NLS-1$ selectButton.addActionListener(p_arg0 -> setValue(PMMainController.getDateObject(m_picker.getModel()))); southPanel.add(selectButton); add(centerPanel, BorderLayout.CENTER); add(southPanel, BorderLayout.SOUTH); } }
package com.feng.RandomAccessFileTest; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class test2 { @Test public void test() throws IOException { RandomAccessFile f = new RandomAccessFile("randomAccessFile2.txt","rw"); f.write(("今天是2021-06-11 10:53 晴 星期五").getBytes()); f.close(); } @Test public void test2() throws IOException { RandomAccessFile f = new RandomAccessFile("randomAccessFile2.txt","rw"); f.write(("明天").getBytes()); f.close(); } @Test//调用seek方法,指定插入位置 public void test3() throws IOException { RandomAccessFile f = new RandomAccessFile("randomAccessFile2.txt","rw"); f.seek(2); f.write(("明天").getBytes()); f.close(); } @Test//在中间添加 public void test4(){ RandomAccessFile file = null; try { file = new RandomAccessFile("randomAccessFile3.txt","rw"); file.seek(3); //指针指向3这个位置,保存后面的值到StringBuilder; StringBuilder builder = new StringBuilder((int) new File("randomAccessFile3.txt").length()); byte[] bytes = new byte[1024]; int len; while((len=file.read(bytes))!=-1){ builder.append(new String(bytes,0,len)); } file.seek(3);//刚刚保存文件到builder的时候把指针指向到了末尾了,重新指向3开始添加 file.write("123".getBytes()); //现在指针就是在添加好的值的末尾 file.write(builder.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (file != null) { try { file.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
package com.corejava.multithreading; //Custom Thread public class MultiThreadingDemo extends Thread { @Override public void run() { System.out.println("Thread:"+Thread.currentThread().getName()); System.out.println("MultiThreadingDemo:run()"); for(int i=1;i<=5;i++) { try { // Making main thread in sleeping state for 5 sec(5000 ms) Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } System.out.println(i); } } }
package com.neu.cloudwebapp.file; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.util.HashMap; import java.util.Optional; import java.util.UUID; @Service public class FileService { // private static final AmazonS3 s3 = AmazonS3ClientBuilder.standard() // .withRegion(Regions.US_EAST_1) // .build(); private AmazonS3 s3; @Autowired private FileRepository fileRepository; public HashMap<String, Object> getFileData(UUID uuid) { try { HashMap<String, Object> obj = new HashMap<>(); Optional<File> f = fileRepository.findById(uuid); obj.put("file_id", f.get().getFile_id().toString()); obj.put("s3_object_name", f.get().getS3_object_name()); obj.put("file_name", f.get().getFileName()); obj.put("created_date", f.get().getCreated_date()); return obj; } catch(Exception ex){ System.out.println(ex); return null; } } @Value("${BUCKET_NAME:#{null}}") private String bucket_name; public ObjectMetadata saveFileS3(UUID id, MultipartFile file) throws Exception{ S3Object fullObject = null; try { s3 = new AmazonS3Client(); String fileNewName = id + "-" + file.getOriginalFilename(); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentType(file.getContentType()); PutObjectRequest obj = new PutObjectRequest(bucket_name, fileNewName, file.getInputStream(), objectMetadata).withCannedAcl(CannedAccessControlList.Private); s3.putObject(obj); fullObject = s3.getObject(new GetObjectRequest(bucket_name, obj.getKey())); } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); } return fullObject.getObjectMetadata(); } public void deleteFileS3(String s3_object_name) throws Exception{ try { s3 = new AmazonS3Client(); s3.deleteObject(new DeleteObjectRequest(bucket_name, s3_object_name)); } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); } } }
package org.sansorm.sqlite; import org.junit.AfterClass; import org.junit.Test; import org.sansorm.TestUtils; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.sansorm.OrmElf; import com.zaxxer.sansorm.SansOrm; import com.zaxxer.sansorm.SqlClosure; import com.zaxxer.sansorm.SqlClosureElf; import com.zaxxer.sansorm.internal.Introspected; import com.zaxxer.sansorm.internal.Introspector; public class QueryTestSQLite { public static Closeable prepareSQLiteDatasource(File db) { HikariDataSource hds = TestUtils.makeSQLiteDataSource(db); SansOrm.initializeTxNone(hds); SqlClosureElf.executeUpdate("CREATE TABLE IF NOT EXISTS TargetClassSQL (" + "id integer PRIMARY KEY AUTOINCREMENT," + "string text NOT NULL," + "timestamp INTEGER" + ')'); return hds; // to close it properly } @AfterClass public static void tearDown() { SansOrm.deinitialize(); } @Test public void shouldPerformCRUD() throws IOException { Introspected is = Introspector.getIntrospected(TargetClassSQL.class); assertThat(is.hasGeneratedId()).isTrue().as("test is meaningful only if class has generated id"); assertThat(is.getIdColumnNames()).isEqualTo(new String[]{"id"}); try (Closeable ignored = prepareSQLiteDatasource(null)) { TargetClassSQL original = new TargetClassSQL("Hi", new Date(0)); assertThat(original.getId()).isNull(); TargetClassSQL inserted = SqlClosureElf.insertObject(original); assertThat(inserted).isSameAs(original).as("insertObject() sets generated id"); Integer idAfterInsert = inserted.getId(); assertThat(idAfterInsert).isNotNull(); List<TargetClassSQL> selectedAll = SqlClosureElf.listFromClause(TargetClassSQL.class, null); assertThat(selectedAll).isNotEmpty(); TargetClassSQL selected = SqlClosureElf.objectFromClause(TargetClassSQL.class, "string = ?", "Hi"); assertThat(selected.getId()).isEqualTo(idAfterInsert); assertThat(selected.getString()).isEqualTo("Hi"); assertThat(selected.getTimestamp().getTime()).isEqualTo(0); selected.setString("Hi edited"); TargetClassSQL updated = SqlClosureElf.updateObject(selected); assertThat(updated).isSameAs(selected).as("updateObject() only set generated id if it was missing"); assertThat(updated.getId()).isEqualTo(idAfterInsert); } } @Test public void shouldPerformCRUDAfterReconnect() throws IOException { Introspected is = Introspector.getIntrospected(TargetClassSQL.class); assertThat(is.hasGeneratedId()).isTrue().as("test is meaningful only if class has generated id"); assertThat(is.getIdColumnNames()).isEqualTo(new String[]{"id"}); File path = File.createTempFile("sansorm", ".db"); path.deleteOnExit(); Integer idAfterInsert; try (Closeable ignored = prepareSQLiteDatasource(path)) { TargetClassSQL original = new TargetClassSQL("Hi", new Date(0)); assertThat(original.getId()).isNull(); TargetClassSQL inserted = SqlClosureElf.insertObject(original); assertThat(inserted).isSameAs(original).as("insertObject() sets generated id"); idAfterInsert = inserted.getId(); assertThat(idAfterInsert).isNotNull(); } // reopen database, it is important for this test // then select previously inserted object and try to edit it try (Closeable ignored = prepareSQLiteDatasource(path)) { TargetClassSQL selected = SqlClosureElf.objectFromClause(TargetClassSQL.class, "string = ?", "Hi"); assertThat(selected.getId()).isEqualTo(idAfterInsert); assertThat(selected.getString()).isEqualTo("Hi"); assertThat(selected.getTimestamp().getTime()).isEqualTo(0L); selected.setString("Hi edited"); TargetClassSQL updated = SqlClosureElf.updateObject(selected); assertThat(updated).isSameAs(selected).as("updateObject() only set generated id if it was missing"); assertThat(updated.getId()).isEqualTo(idAfterInsert); } } @Test public void testInsertListNotBatched2() throws IOException { // given int count = 5; Set<TargetClassSQL> toInsert = IntStream.range(0, count).boxed() .map(i -> new TargetClassSQL(String.valueOf(i), new Date(i))) .collect(Collectors.toSet()); // when try (Closeable ignored = prepareSQLiteDatasource(null)) { SqlClosure.sqlExecute(c -> { OrmElf.insertListNotBatched(c, toInsert); return null; }); } // then Set<Integer> generatedIds = toInsert.stream().map(TargetClassSQL::getId).collect(Collectors.toSet()); assertThat(generatedIds).doesNotContain(0).as("Generated ids should be filled for passed objects"); assertThat(generatedIds).hasSize(count).as("Generated ids should be unique"); } @Test public void testInsertListBatched() throws IOException { // given int count = 5; String u = UUID.randomUUID().toString(); Set<TargetClassSQL> toInsert = IntStream.range(0, count).boxed() .map(i -> new TargetClassSQL(u + String.valueOf(i), new Date(i))) .collect(Collectors.toSet()); // when try (Closeable ignored = prepareSQLiteDatasource(null)) { SqlClosure.sqlExecute(c -> { OrmElf.insertListBatched(c, toInsert); return null; }); List<TargetClassSQL> inserted = SqlClosureElf.listFromClause( TargetClassSQL.class, "string in " + SqlClosureElf.getInClausePlaceholdersForCount(count), IntStream.range(0, count).boxed().map(i -> u + String.valueOf(i)).collect(Collectors.toList()).toArray(new Object[]{})); // then Set<Integer> generatedIds = inserted.stream().map(TargetClassSQL::getId).collect(Collectors.toSet()); assertThat(generatedIds).doesNotContain(0).as("Generated ids should be filled for passed objects"); assertThat(generatedIds).hasSize(count).as("Generated ids should be unique"); } } }
/* * Created on Mar 14, 2007 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.citibank.ods.modules.product.prodriskcatprvt.functionality.valueobject; import com.citibank.ods.entity.pl.TplProdRiskCatPrvtEntity; /** * @author leonardo.nakada * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ProdRiskCatPrvtDetailFncVO extends BaseProdRiskCatPrvtDetailFncVO { public ProdRiskCatPrvtDetailFncVO(){ m_baseTplProdRiskCatPrvtEntity = new TplProdRiskCatPrvtEntity(); } }
// File : MatrixCellTest.java // PIC : Nur Latifah Ulfah - 13514015 import org.junit.*; import static org.junit.Assert.*; /** * * @author Nur Latifah Ulfah - 13514015 */ public class MatrixCellTest { @Test public void test_setCell() { System.out.println("Test setCell"); MatrixCell m = new MatrixCell(5,5); Cell c = new Cell(0,0,'c'); m.setCell(c,0,0); assertTrue(m.getCell(0,0).render()=='c'); } @Test public void test_getNBrs() { System.out.println("Test getNBrs"); MatrixCell m = new MatrixCell(5,4); assertTrue(m.getNBrs()==5); } @Test public void test_getNKol() { System.out.println("Test getNKol"); MatrixCell m = new MatrixCell(5,4); assertTrue(m.getNKol()==4); } }
package org.dbdoclet.test.sample; import java.io.Serializable; public interface Realisable extends Thinkable { public void realise(String what) throws Exception; }
package Chess; import java.util.ArrayList; import java.util.List; public class Game { Player p1, p2; Board board; List<Move> moves; boolean playerOne; Game(String player1, String player2) { p1 = new Player(1, player1); p2 = new Player(2, player2); board = new Board(); moves = new ArrayList<>(); playerOne = true; } public String playerTurn() { return playerOne ? p1.getName() : p2.getName(); } public void makeMove(int sr, int sc, int er, int ec) { } }
// https://leetcode.com/problems/rotate-list/ // #linked-list #two-pointer /** * Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode() {} * ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; * this.next = next; } } */ class Solution { public ListNode rotateRight(ListNode head, int k) { if (head == null) { return head; } int len = 0; ListNode tmp = head; while (tmp != null) { len += 1; tmp = tmp.next; } int left_len = len - (k % len); ListNode left_tail = head; while (left_len > 1) { left_tail = left_tail.next; left_len -= 1; } ListNode new_head = left_tail.next; left_tail.next = null; ListNode right_tail = new_head; if (right_tail != null) { while (right_tail.next != null) { right_tail = right_tail.next; } right_tail.next = head; } else { new_head = head; } return new_head; } }
package com.zhicai.byteera.activity.community.dynamic.view; import android.content.Context; import android.view.LayoutInflater; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.zhicai.byteera.MyApp; import com.zhicai.byteera.R; import com.zhicai.byteera.activity.community.dynamic.interfaceview.UserHomeProductItemIV; import com.zhicai.byteera.activity.community.dynamic.presenter.UserHomeActivityPre; import com.zhicai.byteera.activity.product.entity.ProductEntity; /** Created by bing on 2015/6/2. */ public class UserHomeProductItem extends FrameLayout implements UserHomeProductItemIV { private ImageView ivHead; private TextView tvTitle; private TextView tvIncome; private TextView tvIncomeDetail; public UserHomeProductItem(Context context) { super(context); initView(); } private void initView() { LayoutInflater.from(getContext()).inflate(R.layout.product_item, this, true); ivHead = (ImageView) findViewById(R.id.iv_head); tvTitle = (TextView) findViewById(R.id.tv_title); tvIncome = (TextView) findViewById(R.id.tv_income); tvIncomeDetail = (TextView) findViewById(R.id.tv_income_detail); } public void refreshView(int position, final ProductEntity productEntity, UserHomeActivityPre userHomeActivityPre) { userHomeActivityPre.addUserHomeProductIV(this, position); if (productEntity != null) { ImageLoader.getInstance().displayImage(productEntity.getSmallImage(), ivHead); tvTitle.setText(productEntity.getProductTitle()); tvIncome.setText(String.format("年化收益%.1f", productEntity.getProductIncome()*100.0) + "%"); tvIncomeDetail.setText(String.format("融资金额%.1f万 期限%d个月", productEntity.getProductCoin()/10000.0, productEntity.getProductLimit()/30)); } } }
package com.ece492T5.smartlamp; import android.graphics.Color; import com.ece492T5.smartGesture;.models.Mood; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Unit Test for Lamp Class */ public class LampTest { private Lamp Lamp; @Before public void setUp(){ lamp = new Lamp("user1"); } @Test public void testMood(){ Lamp testLamp = new Lamp("test1"); assertSame(testMood.getUser(),"test1"); } @Test public void testGetMood(){ assertSame("test1", mood.getUser()); } @Test public void testON(){ lamp.turnON(); assertSame("ON", mood.getStatus()); } @Test public void testOFF(){ lamp.turnOff(); assertSame("OFF", mood.getStatus()); } @Test public void testSetColor(){ lamp.setColor(Color.GREEN); } @Test public void testGetColor(){ lamp.setColor(Color.GREEN); assertEquals(lamp.getColor(), Color.GREEN); } }
package com.gsccs.sme.plat.svg.model; import java.util.Calendar; public class GclassT { private Long id; private Long parid; private String title; private String logo; private String templet; private String url; private String status; private Integer clicknum; private String pagemark; private Integer indexnum; private String metaTitle; private String metaKeywords; private String metaDescr; public Long getId() { return id; } public Long getParid() { return parid; } public void setParid(Long parid) { this.parid = parid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } public String getTemplet() { return templet; } public void setTemplet(String templet) { this.templet = templet; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getClicknum() { return clicknum; } public void setClicknum(Integer clicknum) { this.clicknum = clicknum; } public String getPagemark() { return pagemark; } public void setPagemark(String pagemark) { this.pagemark = pagemark; } public Integer getIndexnum() { return indexnum; } public void setIndexnum(Integer indexnum) { this.indexnum = indexnum; } public String getMetaTitle() { return metaTitle; } public void setMetaTitle(String metaTitle) { this.metaTitle = metaTitle; } public String getMetaKeywords() { return metaKeywords; } public void setMetaKeywords(String metaKeywords) { this.metaKeywords = metaKeywords; } public String getMetaDescr() { return metaDescr; } public void setMetaDescr(String metaDescr) { this.metaDescr = metaDescr; } public void setId(Long id) { this.id = id; } }
package com.wipro.exceptionhandling; import java.util.Scanner; public class Ex1 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan=new Scanner(System.in); int n=0,ind=0; int a[]=null; try { System.out.println("Enter the number of elements in the array"); n=Integer.parseInt(scan.nextLine()); a=new int[n]; System.out.println("Enter the elements in the array"); for(int i=0;i<n;i++) a[i]=Integer.parseInt(scan.nextLine()); System.out.println("Enter the index of the array element you want to access"); ind=Integer.parseInt(scan.nextLine()); System.out.println("The array element at index "+ind+" = "+a[ind]); System.out.println("The array element successfully accessed"); } catch(Exception e) { System.out.println(e); } finally { scan.close(); } } }
package com.scut.service.impl; import com.scut.dao.BookImageDAO; import com.scut.entity.BookImage; import com.scut.service.BookImageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class BookImageServiceImpl implements BookImageService{ @Autowired private BookImageDAO bookImageDAO; @Override public BookImage getByBookId(int bid) { return bookImageDAO.getByBookId(bid); } @Override public void add(BookImage bookImage) { bookImageDAO.add(bookImage); } @Override public void update(BookImage bookImage) { bookImageDAO.update(bookImage); } @Override public void deleteByBookId(int bid) { bookImageDAO.deleteByBookId(bid); } }
/** */ package iso20022.impl; import org.eclipse.emf.ecore.EClass; import iso20022.IndustryMessageSet; import iso20022.Iso20022Package; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Industry Message Set</b></em>'. * <!-- end-user-doc --> * * @generated */ public class IndustryMessageSetImpl extends TopLevelCatalogueEntryImpl implements IndustryMessageSet { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IndustryMessageSetImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Iso20022Package.eINSTANCE.getIndustryMessageSet(); } } //IndustryMessageSetImpl
/** * @Description: TODO * @author weifu.du * @date Nov 12, 2013 * @version V1.0 */ package com.datayes.textmining.Utils; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * @author weifu * */ @SuppressWarnings("serial") public class Label implements Serializable { public int labelID; public String lableName; /** * @param lableName */ public Label(String lableName) { this.lableName = lableName; this.labelID = -1; } public Label(int labelID, String lableName) { this.labelID = labelID; this.lableName = lableName; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((lableName == null) ? 0 : lableName.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Label)) { return false; } Label other = (Label) obj; if (lableName == null) { if (other.lableName != null) { return false; } } else if (!lableName.equals(other.lableName)) { return false; } return true; } }
package br.com.moryta.myfirstapp.pets; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import br.com.moryta.myfirstapp.R; import br.com.moryta.myfirstapp.SimpleItemTouchHelperAdapter; import br.com.moryta.myfirstapp.model.Pet; import br.com.moryta.myfirstapp.utils.DateUtil; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by moryta on 17/08/2017. */ public class PetsAdapter extends RecyclerView.Adapter<PetsAdapter.PetViewHolder> implements SimpleItemTouchHelperAdapter { private List<Pet> petList; public PetsAdapter(List<Pet> petList) { this.petList = petList; } @Override public PetViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View petLayout = layoutInflater.inflate(R.layout.row_pet, parent, false); return new PetViewHolder(petLayout); } @Override public void onBindViewHolder(PetViewHolder holder, int position) { Pet pet = this.petList.get(position); String age; try { age = String.valueOf(DateUtil.getAge(pet.getBirthDate())); } catch (Exception e) { age = "?"; } holder.tvPetName.setText(pet.getName()); holder.tvPetBreed.setText(pet.getBreed()); holder.tvPetAge.setText(age); // Set image by pet type switch (pet.getType()) { case DOG: holder.ivPetPhoto.setImageResource(R.drawable.default_dog_photo); break; case CAT: holder.ivPetPhoto.setImageResource(R.drawable.default_cat_photo); break; default: holder.ivPetPhoto.setImageResource(R.mipmap.ic_launcher_round); } } @Override public int getItemCount() { return this.petList.size(); } public void update(List<Pet> petList) { this.petList = petList; notifyDataSetChanged(); } @Override public boolean onItemMoved(int fromPosition, int toPosition) { return false; } @Override public Pet onItemSwiped(int position) { Pet removedPet = this.petList.remove(position); notifyDataSetChanged(); return removedPet; } public class PetViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.ivPetPhoto) ImageView ivPetPhoto; @BindView(R.id.tvPetName) TextView tvPetName; @BindView(R.id.tvPetBreed) TextView tvPetBreed; @BindView(R.id.tvPetAge) TextView tvPetAge; public PetViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
package xpadro.spring.security.web; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class AppController { @RequestMapping(value = "/home", method = RequestMethod.GET) public ModelAndView secured() { ModelAndView mav = new ModelAndView("home"); mav.getModelMap().addAttribute("message", "Hello user!"); return mav; } @RequestMapping(value = "/admin", method = RequestMethod.GET) public ModelAndView admin() { ModelAndView mav = new ModelAndView("admin"); mav.getModelMap().addAttribute("message", "Hello admin!"); return mav; } }
package com.example.testswagger.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.springframework.stereotype.Component; import java.io.Serializable; @Component @ApiModel("用户类") public class User implements Serializable { @ApiModelProperty("用户名") //@JsonProperty("user_name") String username; @ApiModelProperty("用户密码") //@JsonProperty("pass_word") String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString(){ return username+" "+password; } }
package it.bibliotecaweb.servlet.utente; import java.io.IOException; import java.util.HashSet; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import it.bibliotecaweb.model.Ruolo; import it.bibliotecaweb.model.StatoUtente; import it.bibliotecaweb.model.Utente; import it.bibliotecaweb.service.MyServiceFactory; /** * Servlet implementation class ExecuteInsertUtenteServlet */ @WebServlet("/ExecuteInsertUtenteServlet") public class ExecuteInsertUtenteServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ExecuteInsertUtenteServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String nome = request.getParameter("nome"); String cognome = request.getParameter("cognome"); String username = request.getParameter("username"); String password = request.getParameter("password"); String[] stringRuolo = request.getParameterValues("idRuolo"); try { if (nome == null || cognome == null || username == null || password == null || stringRuolo == null || nome.equals("") || cognome.equals("") || username.equals("") || password.equals("") || stringRuolo.length == 0) { request.setAttribute("nome", nome); request.setAttribute("cognome", cognome); request.setAttribute("username", username); request.setAttribute("password", password); Set<Ruolo> ruoli = new HashSet<>(); if (stringRuolo != null && stringRuolo.length > 0) { for (String s : stringRuolo) { int id = Integer.parseInt(s); Ruolo ruolo = MyServiceFactory.getRuoloServiceInstance().findById(id); ruoli.add(ruolo); } request.setAttribute("ruoli", ruoli); } request.setAttribute("errore", MyServiceFactory.getUtenteServiceInstance().validate(request)); request.getRequestDispatcher("PrepareInsertUtenteServlet").forward(request, response); return; } else { for (Utente u : MyServiceFactory.getUtenteServiceInstance().list()) { if (u.getUsername().equals(username)) { request.setAttribute("nome", nome); request.setAttribute("cognome", cognome); request.setAttribute("username", username); request.setAttribute("password", password); Set<Ruolo> ruoli = new HashSet<>(); if (stringRuolo != null && stringRuolo.length > 0) { for (String s : stringRuolo) { int id = Integer.parseInt(s); Ruolo ruolo = MyServiceFactory.getRuoloServiceInstance().findById(id); ruoli.add(ruolo); } request.setAttribute("ruoli", ruoli); } request.setAttribute("errore", "Questo username è gia stato utilizzato!"); request.getRequestDispatcher("PrepareInsertUtenteServlet").forward(request, response); return; } } Set<Ruolo> ruoli = new HashSet<>(); for (String s : stringRuolo) { int id = Integer.parseInt(s); Ruolo ruolo = MyServiceFactory.getRuoloServiceInstance().findById(id); ruoli.add(ruolo); } Utente utente = new Utente(nome, cognome, username, password, ruoli); utente.setStato(StatoUtente.ATTIVO); MyServiceFactory.getUtenteServiceInstance().insert(utente); request.setAttribute("effettuato", "Operazione effettuata con successo!"); request.getRequestDispatcher("ListaUtentiServlet").forward(request, response); } } catch (Exception e) { e.printStackTrace(); } } }
package com.github.web.servlet; /** * 个人主页 * * @autor lzy */ import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.domain.User; import com.github.domain.follow; import com.github.domain.simpletext; import com.github.service.TextService; import com.github.service.UserService; import com.github.service.impl.TextServiceImpl; import com.github.service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; @WebServlet("/usercenter") public class UserCenter extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); Map<String, Object> map = new HashMap<String, Object>(); TextServiceImpl textService = new TextServiceImpl(); UserService userService = new UserServiceImpl(); //获取session数据 HttpSession session = request.getSession(); User user = (User) session.getAttribute("usermsg"); User auser = null; if (user != null) { System.out.println("个人中心session 的 userid : " + user.getUserid()); auser = userService.getUserByUserID(user.getUserid()); session.setAttribute("usermsg", auser); } //接收userid String auserid = (String) session.getAttribute("auserid"); List<simpletext> listArtical = textService.getsimpleTextByUserID(auserid); List<simpletext> listCollection = textService.getcollectionByUserID(auserid); //查询user信息 System.out.println("个人中心 接收的 userid"+auserid); User userByUserID = userService.getUserByUserID(auserid); System.out.println("通过个人中心接受的userid查询到的user对象是:" + userByUserID); //用于传递list集合,将list集合再放入一个json中传给前端 String isself = ""; String isfollow = "false"; //获取follownum int follownum = userService.countFollowedNumByUserId(auserid); if (user != null) { if (auserid.equals(user.getUserid())) { //判断是否为自己的主页 isself = "true"; map.put("user", auser); } else { //判断是否为他人主页 isself = "false"; // 根据userid查询数据 map.put("user", userByUserID); //判断关注情况 follow follow = new follow(); follow.setUserid(user.getUserid()); follow.setFollowed(auserid); if (userService.isFollow(follow)) isfollow = "true"; else isfollow = "false"; } //传递list集合 map.put("listArticle", listArtical); map.put("listCollection", listCollection); map.put("isself", isself); map.put("isfollow", isfollow); map.put("follownum", follownum); map.put("username", auser.getUsername()); map.put("userid", auser.getUserid()); map.put("imageid", auser.getImageid()); String s = JSON.toJSONString(map); System.out.println(s); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getWriter(), map); //session.removeAttribute("auserid"); } else { // response.setContentType("text/html;charset=utf-8"); // PrintWriter out = response.getWriter(); // out.print("<script language='javascript'>alert('登录已失效请重新登陆');window.location.href='http://172.20.151.117:8066/Music_forum/login-regist-writeText/enter.html';</script>"); isself = "false"; map.put("isself", isself); map.put("isfollow", isfollow); map.put("listArticle", listArtical); map.put("listCollection", listCollection); map.put("follownum", follownum); map.put("user", userByUserID); String s = JSON.toJSONString(map); System.out.println(s); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getWriter(), map); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
package com.lzm.KnittingHelp.model; public interface Section { int getId(); String getTitle(); String getContent(); int getPatternId(); int getOrder(); int getActivePartId(); }
package algoritmos.lista_exerc2; import java.util.Scanner; public class Exerc10 { public static void main(String[] args) { int valor1, valor2, valor3; Scanner abobrinha = new Scanner(System.in); System.out.print("Favor inserir o primeiro valor: "); valor1 = abobrinha.nextInt(); System.out.print("Favor inserir o segundo valor: "); valor2 = abobrinha.nextInt(); System.out.print("Favor inserir o terceiro valor: "); valor3 = abobrinha.nextInt(); if (valor1 != valor2 && valor2 != valor3 && valor1 != valor3) { if (valor1 < valor2 && valor1 < valor3) { if (valor2 < valor3) { System.out.printf("\nMenor valor: %d.\nMaior valor: %d.", valor1, valor3); } else { System.out.printf("\nMenor valor: %d.\nMaior valor: %d.", valor1, valor2); } } else if (valor2 < valor3) { if (valor1 < valor3) { System.out.printf("\nMenor valor: %d.\nMaior valor: %d.", valor2, valor3); } else { System.out.printf("\nMenor valor: %d.\nMaior valor: %d.", valor2, valor1); } } else { if (valor1 < valor2) { System.out.printf("\nMenor valor: %d.\nMaior valor: %d.", valor3, valor2); } else { System.out.printf("\nMenor valor: %d.\nMaior valor: %d.", valor3, valor1); } } } else { System.out.println("\nOs valores precisam ser diferentes entre si."); } abobrinha.close(); } }
package com.driva.drivaapi.service; import com.driva.drivaapi.mapper.dto.InstructorDTO; import com.driva.drivaapi.model.user.Instructor; import java.util.List; public interface InstructorService { List<InstructorDTO> findAll(); InstructorDTO find(Long id); Instructor findEntity(Long id); Instructor save(InstructorDTO instructor); InstructorDTO update(Long id, InstructorDTO instructor); void delete(Long id); Boolean doesEmailExist(String email); }
public class TesteSistema { public static void main(String[] args) { //Cria o gerente e seta a senha. Gerente g = new Gerente(); g.setSenha(2222); //Cria o Sistema e autentica o gerenete acima. SistemaInterno si = new SistemaInterno(); si.autentica(g); } }
package lotto; import java.util.Random; public class Lottomaschine { public int[] auswahl = new int[6]; public void ziehung() { int x = 0; int i = 0; boolean check = true; while (i < 6) { x = zug(); check = check(x, auswahl, i); if (check) { auswahl[i] = x; i++; } } } public boolean check(int x, int[] auswahl, int i) { for (int ele : auswahl) { if (ele == x) { return false; } } return true; } public int zug() { Random ziehung = new Random(); return ziehung.nextInt(49 + 1); } public void getAuswahl() { for (int zahlen : auswahl) { System.out.println(zahlen); } } public int zahl1() { return auswahl[0]; } public int zahl2() { return auswahl[1]; } public int zahl3() { return auswahl[2]; } public int zahl4() { return auswahl[3]; } public int zahl5() { return auswahl[4]; } public int zahl6() { return auswahl[5]; } }
package br.com.fiap.bo; import java.util.Date; import java.util.List; import br.com.fiap.beans.Acao; import br.com.fiap.dao.AcaoDAO; /** * Classe com as regras de negócio da Ação * @since 1.0 * @version 2.0 * @author @author Lucas 74795, Mateus 74793, Gustavo 74816, Estevão 74803 * */ public class AcaoBO { /** * Método de gravação da ação. A data de inicio não pode ser superior a data de término, e a descrição não pode ser superior a 120 caracteres * @author Lucas 74795, Mateus 74793, Gustavo 74816, Estevão 74803 * @param a * @return true ou false - se as regras forem atendidas e a inserção ocorrer (true), caso contrário (false) * @throws Exception */ @SuppressWarnings("deprecation") public boolean gravarAcao(Acao a) throws Exception{ new AcaoDAO().add(a); return true; } /** * Busca todas as ações. Nenhuma regra de negócio adicional * @author Lucas 74795, Mateus 74793, Gustavo 74816, Estevão 74803 * @return lstAcao * @throws Exception */ public List<Acao> buscarAcao() throws Exception{ return new AcaoDAO().find(); } /** * Busca a quantidade de usuários que estão participandod e pelo menos uma ação no site. * @author Lucas 74795, Mateus 74793, Gustavo 74816, Estevão 74803 * @return * @throws Exception */ public int buscarQuantidadeParticipantes() throws Exception{ return new AcaoDAO().findQtPessoas(); } /** * Atualiza uma ação, caso as modificações atendam as mesmas condiçoes de gravação: data de inicio menor que data de termino, e descrição de até 120 caracteres * @author Lucas 74795, Mateus 74793, Gustavo 74816, Estevão 74803 * @param a * @return * @throws Exception */ @SuppressWarnings("deprecation") public boolean atualizarAcao(Acao a) throws Exception{ new AcaoDAO().atualizar(a); return true; } /** * Exclui uma determinada ação com seu código. * @author Lucas 74795, Mateus 74793, Gustavo 74816, Estevão 74803 * @param a * @throws Exception */ public void excluirAcao(Acao a) throws Exception{ new AcaoDAO().excluir(a); } public Acao buscarAcaoId(int id) throws Exception{ return new AcaoDAO().findById(id); } }
package com.drugstore.pdp.product.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ProductController { @RequestMapping("/sale") public String daliySaleInvoice(){ return "sales/sale"; } }
package com.examples.io.linkedlists; public class ReverseALinkedList { public static void main(String[] args) { Node node = new Node(1); node.next = new Node(2); node.next.next = new Node(3); node.next.next.next = new Node(4); node.next.next.next.next = new Node(5); node.printNode(node); ReverseALinkedList reverseALinkedList = new ReverseALinkedList(); Node reversedNode = reverseALinkedList.reverseALinkedList(node); System.out.println(); node.printNode(reversedNode); } public Node reverseALinkedList(Node current) { Node prev = null; while(current!=null) { Node next = current.next; current.next = prev; prev=current; current = next; } return prev; } }
package com.joda.tentatime; import android.app.Activity; import android.app.ListActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.List; /** * Created by daniel on 8/7/13. * * @author Daniel Kristoffersson * * Copyright (c) Joseph Hejderup & Daniel Kristoffersson, All rights reserved. * See License.txt in the project root for license information. */ public class Result extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); Bundle b = getIntent().getExtras(); ExamResult mExam = (ExamResult) b.getSerializable("key"); setupWidgets(mExam); } private void setupWidgets(ExamResult exam){ TextView name = (TextView) findViewById(R.id.examName); if (name == null) { Log.w("", "TextView is null"); } name.append(exam.getName().trim()); TextView code = (TextView) findViewById(R.id.examCode); if (code == null) { Log.w("", "TextView is null"); } code.append(exam.getCode()); TextView date = (TextView) findViewById(R.id.examDate); if (date == null) { Log.w("", "TextView is null"); } date.append(exam.getExamDate()); TextView time = (TextView) findViewById(R.id.examTime); if (time == null) { Log.w("", "TextView is null"); } time.append(exam.getBeginsAt()); TextView description = (TextView) findViewById(R.id.examDescription); if (description == null) { Log.w("", "TextView is null"); } description.append(exam.getExamDate()); } }
package me.kpali.wolfflow.core.event; import me.kpali.wolfflow.core.cluster.IClusterController; import me.kpali.wolfflow.core.config.ClusterConfig; import me.kpali.wolfflow.core.exception.TaskLogException; import me.kpali.wolfflow.core.exception.TryLockException; import me.kpali.wolfflow.core.logger.ITaskLogger; import me.kpali.wolfflow.core.model.*; import me.kpali.wolfflow.core.util.context.TaskContextWrapper; import me.kpali.wolfflow.core.util.context.TaskFlowContextWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; import java.util.Date; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; /** * 任务状态事件发布器 * * @author kpali */ @Component public class TaskStatusEventPublisher { @Autowired private ApplicationEventPublisher eventPublisher; @Autowired private ClusterConfig clusterConfig; @Autowired private IClusterController clusterController; @Autowired private ITaskLogger taskLogger; /** * 发布任务状态变更事件 * * @param task * @param taskFlowId * @param context * @param status * @param message * @param record */ public void publishEvent(Task task, Long taskFlowId, ConcurrentHashMap<String, Object> context, String status, String message, boolean record) throws TryLockException, TaskLogException { TaskFlowContextWrapper taskFlowContextWrapper = new TaskFlowContextWrapper(context); TaskContextWrapper taskContextWrapper = taskFlowContextWrapper.getTaskContextWrapper(task.getId().toString()); TaskStatus taskStatus = new TaskStatus(); taskStatus.setTask(task); taskStatus.setTaskFlowId(taskFlowId); taskStatus.setContext(taskContextWrapper.getContext()); taskStatus.setStatus(status); taskStatus.setMessage(message); if (record) { String taskLogLock = ClusterConstants.getTaskLogLock(task.getId()); boolean locked = false; try { locked = this.clusterController.tryLock( taskLogLock, clusterConfig.getTaskLogLockWaitTime(), clusterConfig.getTaskLogLockLeaseTime(), TimeUnit.SECONDS); if (!locked) { throw new TryLockException("Acquire the task log lock failed!"); } Long taskFlowLogId = taskFlowContextWrapper.getValue(TaskFlowContextKey.LOG_ID, Long.class); boolean isRollback = taskFlowContextWrapper.getValue(TaskFlowContextKey.IS_ROLLBACK, Boolean.class); Long taskLogId = taskContextWrapper.getValue(TaskContextKey.TASK_LOG_ID, Long.class); String logFileId = taskContextWrapper.getValue(TaskContextKey.TASK_LOG_FILE_ID, String.class); TaskLog taskLog = this.taskLogger.get(taskFlowLogId, task.getId()); boolean isNewLog = false; Date now = new Date(); if (taskLog == null) { isNewLog = true; taskLog = new TaskLog(); taskLog.setCreationTime(now); } taskLog.setLogId(taskLogId); taskLog.setTaskId(task.getId()); taskLog.setTask(task); taskLog.setTaskFlowLogId(taskFlowLogId); taskLog.setTaskFlowId(taskFlowId); taskLog.setContext(taskContextWrapper.getContext()); taskLog.setStatus(status); taskLog.setMessage(message); taskLog.setLogFileId(logFileId); taskLog.setRollback(isRollback); taskLog.setUpdateTime(now); if (isNewLog) { this.taskLogger.add(taskLog); } else { this.taskLogger.update(taskLog); } } finally { if (locked) { this.clusterController.unlock(taskLogLock); } } } TaskStatusChangeEvent taskStatusChangeEvent = new TaskStatusChangeEvent(this, taskStatus); this.eventPublisher.publishEvent(taskStatusChangeEvent); } }
import static org.junit.Assert.assertEquals; import controller.Sharpen; import image.Image; import image.Pixel; import java.util.ArrayList; import java.util.List; import model.MultiLayerImageProcessingModel; import model.SimpleMultiLayerImageProcessingModel; import org.junit.Test; /** * Test class for the sharpen command. */ public class SharpenTest { // test go @Test public void testGo() { MultiLayerImageProcessingModel model = new SimpleMultiLayerImageProcessingModel(); model.createLayer("First"); model.makeCheckerBoard(3); new Sharpen().run(model); Image im = model.exportImage(); List<List<Pixel>> expectedPixels = new ArrayList<>(); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.get(0).add(new Pixel(64, 64, 64)); expectedPixels.get(0).add(new Pixel(255, 255, 255)); expectedPixels.get(0).add(new Pixel(64, 64, 64)); expectedPixels.get(1).add(new Pixel(255, 255, 255)); expectedPixels.get(1).add(new Pixel(255, 255, 255)); expectedPixels.get(1).add(new Pixel(255, 255, 255)); expectedPixels.get(2).add(new Pixel(64, 64, 64)); expectedPixels.get(2).add(new Pixel(255, 255, 255)); expectedPixels.get(2).add(new Pixel(64, 64, 64)); Image expectedImage = new Image(expectedPixels, 3, 3); assertEquals(im, expectedImage); } }
/* Compare two linked lists A and B Return 1 if they are identical and 0 if they are not. Node is defined as class Node { int data; Node next; } */ int CompareLists(Node headA, Node headB) { // This is a "method-only" submission. // You only need to complete this method Node temp1 = headA, temp2 = headB; if(temp1 == null && temp2 == null) return 1; else if(temp1 == null && temp2!=null) return 0; else if(temp1!=null && temp2 == null) return 0; else { int length1 = 0, length2 = 0; while(temp1!=null) { length1++; temp1 = temp1.next; } while(temp2!=null) { length2++; temp2 = temp2.next; } if(length1!=length2) return 0; else { temp1 = headA; temp2 = headB; while(temp1!=null) { if(temp1.data!=temp2.data) return 0; temp1 = temp1.next; temp2 = temp2.next; } return 1; } } }
/* * Welcome to use the TableGo Tools. * * http://vipbooks.iteye.com * http://blog.csdn.net/vipbooks * http://www.cnblogs.com/vipbooks * * Author:bianj * Email:edinsker@163.com * Version:5.8.0 */ package com.lenovohit.hwe.org.model; import java.util.Set; import java.util.TreeSet; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; import com.lenovohit.hwe.base.model.AuditableModel; /** * HWE_MENU * * @author zyus * @version 1.0.0 2017-12-14 */ @Entity @Table(name = "HWE_MENU") public class Menu extends AuditableModel implements java.io.Serializable { /** 版本号 */ private static final long serialVersionUID = -2829128170738844422L; /** code */ private String code; /** name */ private String name; /** name */ private String alias; /** type */ private String type; /** descp */ private String descp; /** icon */ private String icon; /** uri */ private String uri; /** sorter */ private Integer sorter; /** status */ private String status; private Menu parent; private Set<Menu> children; /** * 获取code * * @return code */ @Column(name = "CODE", nullable = true, length = 25) public String getCode() { return this.code; } /** * 设置code * * @param code */ public void setCode(String code) { this.code = code; } /** * 获取name * * @return name */ @Column(name = "NAME", nullable = true, length = 50) public String getName() { return this.name; } /** * 设置name * * @param name */ public void setName(String name) { this.name = name; } /** * 获取name * * @return name */ @Column(name = "Alias", nullable = true, length = 50) public String getAlias() { return this.alias; } /** * 设置name * * @param name */ public void setAlias(String alias) { this.alias = alias; } /** * 获取type * * @return type */ @Column(name = "TYPE", nullable = true, length = 1) public String getType() { return this.type; } /** * 设置type * * @param type */ public void setType(String type) { this.type = type; } /** * 获取descp * * @return descp */ @Column(name = "DESCP", nullable = true, length = 255) public String getDescp() { return this.descp; } /** * 设置descp * * @param descp */ public void setDescp(String descp) { this.descp = descp; } /** * 获取icon * * @return icon */ @Column(name = "ICON", nullable = true, length = 255) public String getIcon() { return this.icon; } /** * 设置icon * * @param icon */ public void setIcon(String icon) { this.icon = icon; } /** * 获取uri * * @return uri */ @Column(name = "URI", nullable = true, length = 255) public String getUri() { return this.uri; } /** * 设置uri * * @param uri */ public void setUri(String uri) { this.uri = uri; } /** * 获取sorter * * @return sorter */ @Column(name = "SORTER", nullable = true, length = 10) public Integer getSorter() { return this.sorter; } /** * 设置sorter * * @param sorter */ public void setSorter(Integer sorter) { this.sorter = sorter; } /** * 获取status * * @return status */ @Column(name = "STATUS", nullable = true, length = 1) public String getStatus() { return this.status; } /** * 设置status * * @param status */ public void setStatus(String status) { this.status = status; } @ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, optional = true) @JoinColumn(name = "PARENT_ID", nullable = true) @NotFound(action=NotFoundAction.IGNORE) public Menu getParent() { return parent; } public void setParent(Menu parent) { this.parent = parent; } @Transient public Set<Menu> getChildren() { if(null == children){ children = new TreeSet<Menu>(); } return children; } public void setChildren(Set<Menu> children) { this.children = children; } }
package br.com.ShoolDrive.view; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; @Controller @Secured("ROLE_PROFESSOR") public class PrincipalProfessorView { public PrincipalProfessorView() { } }
package com.company.exercise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <h1>Table</h1> * Table Class - contains the attributes of the table * <p> * responsible for containing the data about the table for the game * </p> * * @author aafonya * @since 2017-05 */ public class Table { private static final Logger logger = LoggerFactory.getLogger(Table.class); private int size; private int level; /** * Getter of the variable numbers(which contains the elements of the table) * * @return the numbers in the table */ public int[][] getNumbers() { return numbers; } /** * Contains the elements of the table */ private int[][] numbers = {{0,1,0},{0,0,1},{1,0,0}}; /** * Looking for an element of the table by the id shown on the button * * @param id id of the button * @return value of the element in the table */ public String findById(int id){ int i = id / numbers.length; int j = id % numbers.length; int result = numbers[i][j]; if (result == 1) { return "*"; } return String.valueOf(numbers[i][j]); } /** * Getter of the height of the table * * @return int - value of height */ public int getHeight() { logger.info("Height" + numbers.length); return numbers.length; } /** * Getter of the width of the table * * @return int - value of width */ public int getWidth(){ logger.info("Width" + numbers[0].length); return numbers[0].length; } public Table () { } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } }
/* * Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms. */ package com.yahoo.cubed.dao; import com.yahoo.cubed.model.Field; import java.util.List; import org.hibernate.Session; /** * Field data access object. */ public interface FieldDAO extends AbstractAssociationDAO<Field> { /** * Fetch all the fields, two fetch modes: eager and lazy. * @param session open session * @param mode eager or lazy * @return a list of pipelines */ public List<Field> fetchAll(Session session, FetchMode mode); /** * Fetch all the fields according to the schemaId. * @param session open session * @param schemaName schema name * @return a list of fields */ public List<Field> fetchBySchemaName(Session session, String schemaName); /** * Fetch the field according to the composite key. * @param session open session * @param schemaName schema name * @param fieldId field id * @return field */ public Field fetchByCompositeKey(Session session, String schemaName, long fieldId); /** * Fetch the field according to the schema name and field name. * @param session open session * @param schemaName schema name * @param fieldName field name * @return field */ public Field fetchBySchemaNameFieldName(Session session, String schemaName, String fieldName); }
package egovframework.com.file.controller; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.channels.FileChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import net.sf.jazzlib.ZipEntry; import net.sf.jazzlib.ZipFile; import net.sf.jazzlib.ZipInputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jdom.Document; import org.jdom.Element; import org.jdom.Namespace; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.springframework.stereotype.Controller; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import egovframework.com.cmm.service.EgovFileMngUtil; import egovframework.com.cmm.service.EgovProperties; import egovframework.com.cmm.service.Globals; import egovframework.com.lcms.inn.controller.innoDSFileUploadController; import egovframework.com.utl.fcc.service.EgovStringUtil; /** * * @author * @since * @version 1.0 * @see * * <pre> * * </pre> */ @Controller public class FileController { /** log */ protected static final Log log = LogFactory.getLog(innoDSFileUploadController.class); static String chararray="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; static Random random=new Random(System.currentTimeMillis()); ArrayList _fileList = new ArrayList(); Namespace na1 = Namespace.getNamespace("adlcp", "http://www.adlnet.org/xsd/adlcp_v1p3"); Namespace na2 = Namespace.getNamespace("adlseq", "http://www.adlnet.org/xsd/adlseq_v1p3"); Namespace na3 = Namespace.getNamespace("adlnav", "http://www.adlnet.org/xsd/adlnav_v1p3"); Namespace na4 = Namespace.getNamespace("imsss", "http://www.imsglobal.org/xsd/imsss"); Namespace na5 = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); public String fileUnZip2(String strSavePath, String strSavePath2, String saveFile) throws Exception{ String imsPath = ""; try{ ZipFile zipFile = new ZipFile(strSavePath+"/"+saveFile); File zFile = new File(strSavePath+"/"+saveFile); for(Enumeration zipEntries = zipFile.entries(); zipEntries.hasMoreElements();){ ZipEntry entry = (ZipEntry)zipEntries.nextElement(); String name = entry.getName(); name = new String(name.getBytes("latin1"),"euc-kr"); name = name.replaceAll("\\\\","/"); InputStream zis = null; FileOutputStream fos = null; File uncompressedFile_dir = null; File uncompressedFile = null; if(!entry.isDirectory()) { zis = zipFile.getInputStream(entry); if(name.split("/").length > 1){ uncompressedFile_dir = new File(strSavePath2+"/"+name.substring(0,name.lastIndexOf("/"))); uncompressedFile_dir.mkdirs(); } String temp_file = strSavePath2+File.separator+name; uncompressedFile = new File(temp_file); if(!uncompressedFile.isDirectory()){ fos = new FileOutputStream(uncompressedFile); byte buffer[] = new byte[4096]; int read = 0; for(read = zis.read(buffer); read >= 0; read = zis.read(buffer)) fos.write(buffer, 0, read); fos.close(); zis.close(); } } } zipFile.close(); zFile.delete(); }catch (IOException ioe) { // 폴더 삭제 this.deleteDirector(strSavePath); ioe.printStackTrace(); } return imsPath; } public ArrayList fileUnZip(String strSavePath, String saveFile) throws Exception{ ArrayList imsPath = new ArrayList(); try{ String inputPath = strSavePath; new File(inputPath).mkdirs(); //imsPath = inputPath; ZipFile zipFile = new ZipFile(strSavePath+"/"+saveFile); File zFile = new File(strSavePath+"/"+saveFile); for(Enumeration zipEntries = zipFile.entries(); zipEntries.hasMoreElements();){ ZipEntry entry = (ZipEntry)zipEntries.nextElement(); String name = entry.getName(); name = new String(name.getBytes("latin1"),"euc-kr"); name = name.replaceAll("\\\\","/"); InputStream zis = null; FileOutputStream fos = null; File uncompressedFile_dir = null; File uncompressedFile = null; if(!entry.isDirectory()) { zis = zipFile.getInputStream(entry); if(name.split("/").length > 1){ uncompressedFile_dir = new File(inputPath+"/"+name.substring(0,name.lastIndexOf("/"))); uncompressedFile_dir.mkdirs(); imsPath.add(inputPath+"/"+name.substring(0,name.lastIndexOf("/"))); } String temp_file = inputPath+File.separator+name; uncompressedFile = new File(temp_file); if(!uncompressedFile.isDirectory()){ fos = new FileOutputStream(uncompressedFile); byte buffer[] = new byte[4096]; int read = 0; for(read = zis.read(buffer); read >= 0; read = zis.read(buffer)) fos.write(buffer, 0, read); fos.close(); zis.close(); } } if( name.endsWith("imsmanifest.xml")){ String path = inputPath+File.separator+name; Document doc = readManifestFile(path); File file = new File(path); String encoding = "UTF-8"; convertEncoding(file, encoding); saveManifestFile(doc, path); } } zipFile.close(); zFile.delete(); }catch (IOException ioe) { // 폴더 삭제 this.deleteDirector(strSavePath); ioe.printStackTrace(); } return imsPath; } /** * 컨텐츠 업로드 후 imsmanifest.xml파일만 압축해제 * @param strSavePath * @param saveFile * @return * @throws Exception */ public ArrayList manifestUnZip(String strSavePath, String saveFile) throws Exception{ ArrayList imsPath = new ArrayList(); try{ File zp = null; ZipInputStream in = null; FileOutputStream output = null; in = new ZipInputStream(new FileInputStream(strSavePath+"/"+saveFile)); zp = new File(strSavePath+"/"+saveFile); ZipEntry entry = null; // input stream내의 압축된 파일들을 하나씩 읽어들임. String mkDirNm = ""; while((entry = in.getNextEntry()) != null){ // zip 파일의 구조와 동일하게 가기위해 로컬의 디렉토리 구조를 만듬. String entryName = entry.getName(); if( entryName.endsWith("imsmanifest.xml") ){ if( !new File(strSavePath+"/tmp").isDirectory() ){ new File(strSavePath+"/tmp").mkdirs(); } mkDirNm = entryName.replace("imsmanifest.xml", ""); new File(strSavePath +"/tmp/"+ mkDirNm).mkdirs(); imsPath.add(strSavePath+"/tmp/"+ mkDirNm); // 해제할 각각 파일의 output stream을 생성 output = new FileOutputStream(strSavePath +"/tmp/"+ entryName); int bytes_read; byte buf[] = new byte[1024]; while((bytes_read = in.read(buf)) != -1){ output.write(buf, 0, bytes_read); } // 하나의 파일이 압축해제됨 output.close(); String path = strSavePath +"/tmp/"+ entryName; Document doc = readManifestFile(path); File file = new File(path); String encoding = "UTF-8"; convertEncoding(file, encoding); saveManifestFile(doc, path); } } in.close(); }catch(Exception ex){ imsPath = null; log.info("manifestUnZip Exception"); log.info("exception : "+ex); } return imsPath; } public static void convertEncoding(File file, String encoding) throws Exception{ try{ BufferedReader in = new BufferedReader(new FileReader(file)); String read = null; List list = new ArrayList(); while( (read = in.readLine()) != null ){ list.add(read); } in.close(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding)); for( int i=0; i<list.size(); i++ ){ out.write((String)list.get(i)); out.newLine(); } out.close(); }catch(IOException e){ e.printStackTrace(); throw e; } } /** * description: manifestfile read. * @return Document * @throws Exception */ public Document readManifestFile(String filename) { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(new File(filename)); return doc; } catch (Exception e) { return null; } } /** * 특정파일 삭제 * @param path * @param withName * @return * @throws Exception */ public boolean deleteZipFile(String path, String withName) throws Exception{ boolean result = true; try{ File dir = new File(path); String[] list = dir.list(); for( int i=0; i<list.length; i++ ){ if( list[i].endsWith(withName) ){ new File(path+"/"+list[i]).delete(); } } }catch(Exception ex){ result = false; log.info("deleteZipFile Exception"); log.info("exception : "+ex); } return result; } /** * 하위디렉토리 전체 삭제 * @param deletePath * @return * @throws Exception */ public boolean deleteDirector(String deletePath) throws Exception{ boolean result = true; try{ File dir = new File(deletePath); String[] list = dir.list(); File file; for( int i=0; i<list.length; i++ ){ file = new File(deletePath+File.separator+list[i] ); if( file.isDirectory() ){ deleteDirector(file.getPath()+File.separator ); }else{ file.delete(); } } dir.delete(); }catch(Exception ex){ result = false; log.info("deleteDirector Exception"); log.info("exception : "+ex); } return result; } /** * 하위디렉토리 전체 삭제 * @param deletePath * @return * @throws Exception */ public boolean deleteDirector2(String deletePath) throws Exception{ boolean result = true; try{ File dir = new File(deletePath); String[] list = dir.list(); File file; for( int i=0; i<list.length; i++ ){ file = new File(deletePath+File.separator+list[i] ); if( list[i].toUpperCase().endsWith(".XLS") ){ file.delete(); } } dir.delete(); }catch(Exception ex){ result = false; log.info("deleteDirector Exception"); log.info("exception : "+ex); } return result; } /** * 차시폴더생성의 랜점키생성 * @param len * @return */ public static String getRandomKey(int len){ String ret=""; for(int i=0;i<len;i++){ ret+=chararray.charAt(random.nextInt(chararray.length())); } return ret; } /** * transferTo() 사용한 파일 복사후 원래파일삭제[이게 젤루 빠름] * @param oldfile 원래파일명[폴더포함] * @param targetfile 새파일명[폴더포함] * @throws Exception */ public static void moveDirs(File oldfile, File targetfile) throws Exception{ if(oldfile.isDirectory()){ if(!targetfile.exists()){ targetfile.mkdirs(); } String[] children = oldfile.list(); for(int i = 0; i < children.length; i++){ moveTransfer(new File(oldfile, children[i]),new File(targetfile, children[i])); } }else{ oldfile.renameTo(targetfile); } oldfile.delete(); } /** * transferTo() 사용한 파일 복사후 원래파일삭제[이게 젤루 빠름] * @param oldfile 원래파일명[폴더포함] * @param targetfile 새파일명[폴더포함] * @throws Exception */ public static void moveTransfer(File oldfile, File targetfile) throws Exception{ if(oldfile.isDirectory()){ if(!targetfile.exists()){ targetfile.mkdirs(); } String[] children = oldfile.list(); for(int i = 0; i < children.length; i++){ moveTransfer(new File(oldfile, children[i]),new File(targetfile, children[i])); } }else{ FileInputStream f_in=new FileInputStream(oldfile); FileOutputStream f_out=new FileOutputStream(targetfile); try{ byte[] buffer=new byte[1024]; int len=f_in.read(buffer); while(len>0){ f_out.write(buffer, 0, len); len=f_in.read(buffer); } f_out.flush(); }finally{ f_out.close(); f_in.close(); } } oldfile.delete(); } /** * description: pif size 조회. * @return int retval * @throws Exception */ public static int getScoSize(String path){ int retval = 0; FileController futil = new FileController(); ArrayList files = futil.scanDir(path,true); for(int i = 0; i < files.size(); i++){ File f = new File(files.get(i).toString()); //KB로 계산시 나머지가 있으면 +1KB해줌. if(f.length() % 1024 != 0){ retval += f.length()/1024 +1; }else{ retval += f.length()/1024; } } return retval; } /** * 파일의 목록을 리턴 * @param dir * @param checksubdir * @return */ public ArrayList scanDir(String dir, boolean checksubdir){ File file = new File(dir); if(file.exists()){ for(int i = 0; i < file.list().length; i++){ File tmpfile = new File(dir+File.separator+file.list()[i]); if(tmpfile.isDirectory() && checksubdir){ this.scanDir(dir+File.separator+file.list()[i], checksubdir); }else{ this._fileList.add(tmpfile); } } } return _fileList; } public void makeManifest(String savePath){ try{ Document main = null; Element root = new Element("manifest"); root.setAttribute("identifier", getUniqueID()); root.setAttribute("version", "2.0"); root.addNamespaceDeclaration(na1); root.addNamespaceDeclaration(na2); root.addNamespaceDeclaration(na3); root.addNamespaceDeclaration(na4); root.setAttribute("schemaLocation", "http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd " + "http://www.adlnet.org/xsd/adlcp_v1p3 adlcp_v1p3.xsd " + "http://www.adlnet.org/xsd/adlseq_v1p3 adlseq_v1p3.xsd " + "http://www.adlnet.org/xsd/adlnav_v1p3 adlnav_v1p3.xsd " + "http://www.imsglobal.org/xsd/imsss imsss_v1p0.xsd", na5); // metadata Element구성 Element el1 = new Element("metadata"); Element el1_1 = new Element("schema"); Element el1_2 = new Element("schemaversion"); el1_1.setText("LCMS KEM"); el1_2.setText("KEM 2.0"); el1.addContent(el1_1); el1.addContent(el1_2); // organization구성 Element el2 = new Element("organizations"); el2.setAttribute("default", getUniqueID()); Element el2_1 = new Element("organization"); el2_1.setAttribute("identifier", el2.getAttributeValue("default")); Element title = new Element("title"); title.setText("신규차시"); el2_1.addContent(title); el2.addContent(el2_1); // resource구성 Element el3 = new Element("resources"); root.addContent(el1); root.addContent(el2); root.addContent(el3); main = new Document(); main.setRootElement(root); saveManifestFile(main, savePath + "/imsmanifest.xml"); }catch(Exception ex){ ex.printStackTrace(); } } public boolean saveManifestFile(Document doc, String fileName){ OutputStream manifestOut = null; String dir = ""; boolean flag = false; try{ manifestOut = new FileOutputStream(fileName.trim(), false); }catch( FileNotFoundException e ){ String filedir[] = fileName.split("/"); for( int i=1; i<filedir.length-1; i++ ){ dir += "/" + filedir[i].trim(); new File(filedir[0].trim() + "/" + dir).mkdirs(); } try{ manifestOut = new FileOutputStream(fileName.trim(), false); }catch( FileNotFoundException e1 ){ e1.printStackTrace(); return false; } } XMLOutputter outputter = new XMLOutputter(); Format f = outputter.getFormat(); try{ f.setEncoding("utf-8"); f.setLineSeparator("\r\n"); f.setIndent(" "); outputter.setFormat(f); outputter.output(doc, manifestOut); manifestOut.flush(); manifestOut.close(); flag = true; }catch(IOException e){ e.printStackTrace(); return false; } return flag; } public String getUniqueID(){ String key = "Edu-"; key += String.valueOf(UUID.randomUUID()); return key; } /** * 엑셀파일 내용 반환 * @param savePath * @return * @throws Exception */ public List getExcelDataList(String savePath) throws Exception{ ArrayList list = new ArrayList(); String fileName = ""; if(savePath.endsWith(".xls")) { System.out.println("########## xls 확장자 ##############"); fileName = savePath; } else { String content[] = (new File(savePath)).list(); for( int i=0; i<content.length; i++ ){ if( content[i].endsWith(".xls") ){ fileName = savePath+"/"+content[i]; } } } log.info("# Xls read fileName : " + fileName); if( fileName.equals("") ){ return null; } Workbook workbook = Workbook.getWorkbook(new File(fileName)); Sheet sheet = workbook.getSheet(0); int row = sheet.getRows(); Map inputMap; String oldKey = ""; int merge = 0; for( int i=0; i<row; i++ ){ inputMap = new HashMap<String, Object>(); Cell cell[] = sheet.getRow(i); for( int j=0; j<cell.length; j++ ){ inputMap.put("parameter"+j, cell[j].getContents()); log.info(i + "-" + j +")" + cell[j].getContents()); } if( !oldKey.equals(cell[0].getContents()) ){ merge = 0; oldKey = cell[0].getContents(); for( int idx=0; idx<row; idx++ ){ Cell cell2[] = sheet.getRow(idx); if( cell2[0].getContents().equals(oldKey) ){ merge++; } } } inputMap.put("merge", merge); list.add(inputMap); } return list; } /** * 중공교 컨텐츠 구조에 맞게 docs생성 * @param path * @param fileName * @return * @throws Exception */ public String checkCotiFile(String path, String fileName) throws Exception{ try{ ZipFile zipFile = new ZipFile(path+"/"+fileName); boolean check = false; for(Enumeration zipEntries = zipFile.entries(); zipEntries.hasMoreElements();){ ZipEntry entry = (ZipEntry)zipEntries.nextElement(); if( "docs".equals(entry.getName()) ){ check = true; } } if( !check ){ path = path+"/docs"; new File(path).mkdirs(); } zipFile.close(); }catch (IOException ioe) { ioe.printStackTrace(); } return path; } public String copyContentFile(String crsCode, String scoFolder, String baseDir, String strSavePath, String imspath, String inputPath) throws Exception{ String path = Globals.CONTNET_REAL_PATH; try{ File targetfile = new File(inputPath+"/"+scoFolder); targetfile.mkdirs(); File copyfile = new File(path+baseDir); if(copyfile.isDirectory()){ if(!targetfile.exists()){ targetfile.mkdirs(); } String[] children = copyfile.list(); for(int i = 0; i < children.length; i++){ moveCopy(new File(copyfile, children[i]),new File(targetfile, children[i])); } }else{ copyfile.renameTo(targetfile); } }catch(Exception ex){ ex.printStackTrace(); } return inputPath; } /** * transferTo() 사용한 파일 복사후 원래파일삭제[이게 젤루 빠름] * @param oldfile 원래파일명[폴더포함] * @param targetfile 새파일명[폴더포함] * @throws Exception */ public static void moveCopy(File oldfile, File targetfile) throws Exception{ if(oldfile.isDirectory()){ if(!targetfile.exists()){ targetfile.mkdirs(); } String[] children = oldfile.list(); for(int i = 0; i < children.length; i++){ moveCopy(new File(oldfile, children[i]),new File(targetfile, children[i])); } }else{ FileInputStream f_in=new FileInputStream(oldfile); FileOutputStream f_out=new FileOutputStream(targetfile); try{ byte[] buffer=new byte[1024]; int len=f_in.read(buffer); while(len>0){ f_out.write(buffer, 0, len); len=f_in.read(buffer); } f_out.flush(); }finally{ f_out.close(); f_in.close(); } } } public static void uploadFile(HttpServletRequest request, Map<String, Object> commandMap) throws Exception{ MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request; Iterator fileIter = mptRequest.getFileNames(); String dir = (String)commandMap.get("p_upload_dir"); if( commandMap.get("p_upload_dir") == null || ((String)commandMap.get("p_upload_dir")).equals("") ){ dir = "bulletin"; } String strSavePath = EgovProperties.getProperty("Globals.defaultDP")+dir+"/"; if( commandMap.get("p_filedel") != null ){ String fileName = (String)commandMap.get("p_savefile"); new File(strSavePath+fileName).delete(); } Map result = new HashMap(); while (fileIter.hasNext()) { MultipartFile mFile = mptRequest.getFile((String)fileIter.next()); if (mFile.getSize() > 0) { commandMap.putAll(EgovFileMngUtil.uploadContentFile(mFile, strSavePath)); } } } public static void uploadMultiFile(HttpServletRequest request, Map<String, Object> commandMap) throws Exception{ MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request; Iterator fileIter = mptRequest.getFileNames(); String dir = "bulletin"; if( commandMap.get("p_upload_dir") != null || !((String)commandMap.get("p_upload_dir")).equals("") ){ dir = (String)commandMap.get("p_upload_dir"); } String strSavePath = EgovProperties.getProperty("Globals.defaultDP")+dir+"/"; if( commandMap.get("p_filedel") != null ){ String[] idx = EgovStringUtil.getStringSequence(commandMap, "p_filedel"); for(int i=0; i<idx.length; i++ ){ String fileName = (String)commandMap.get("p_savefile"+idx[i]); new File(strSavePath+fileName).delete(); } } ArrayList result = new ArrayList(); while (fileIter.hasNext()) { MultipartFile mFile = mptRequest.getFile((String)fileIter.next()); if (mFile.getSize() > 0) { result.add(EgovFileMngUtil.uploadContentFile(mFile, strSavePath)); } } commandMap.put("multiFiles", result); } public static int deleteFiles(Map<String, Object> commandMap) throws Exception{ String dir = "bulletin"; int isOk = 1; try{ if( commandMap.get("p_upload_dir") != null || !((String)commandMap.get("p_upload_dir")).equals("") ){ dir = (String)commandMap.get("p_upload_dir"); } String strSavePath = EgovProperties.getProperty("Globals.defaultDP")+dir+"/"; if( commandMap.get("p_savefile") != null ){ String[] fileName = EgovStringUtil.getStringSequence(commandMap, "p_savefile"); for(int i=0; i<fileName.length; i++ ){ new File(strSavePath+fileName[i]).delete(); } } }catch(Exception ex){ isOk = 0; } return isOk; } }
package com.whl.netsongdata; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class SearchUtil { private String keySearchUrl; /** * 存放音乐或者是专辑,或是艺人的列表 */ private List<Music> mList; /** * 获取音乐或者是专辑,或是艺人的列表 * @return */ public List<Music> getmList() { return mList; } /** * 默认的最外层的类 */ private String clazz="track_list"; /** * 搜索关键字地址(全部) */ public static final String KEY_SEARCH_URL_ALL="http://www.xiami.com/search"; /** * 搜索关键字地址(歌曲) */ public static final String KEY_SEARCH_URL_MUSIC="http://www.xiami.com/search/song"; /** * 搜索关键字地址(歌词) */ public static final String KEY_SEARCH_URL_SONG_LYRIC="http://www.xiami.com/search/song-lyric"; /** * 搜索关键字地址(艺人) */ public static final String KEY_SEARCH_URL_ARTIST="http://www.xiami.com/search/artist"; /** * 歌曲id接口 */ public static final String ID_SEARCH_URL="http://www.xiami.com/song/playlist/id/"; /** * 搜索入口 * @param index(1:全部搜索,2:根据歌曲名字搜索,3.根据歌词搜索,4:搜索艺人) * @param key(搜索关键字) * @param page(页数,全部搜索的时候只有一页) * @throws CommonException */ public void entrance(int index,String key,int page) throws CommonException{ switch(index){ default://全部搜索 keySearchUrl=KEY_SEARCH_URL_ALL+"/page/"+page+"?key="+key; break; case 1://全部搜索 keySearchUrl=KEY_SEARCH_URL_ALL+"/page/"+page+"?key="+key; break; case 2://根据歌曲名字搜索 keySearchUrl=KEY_SEARCH_URL_MUSIC+"/page/"+page+"?key="+key; break; case 3://根据歌词搜索 keySearchUrl=KEY_SEARCH_URL_SONG_LYRIC+"/page/"+page+"?key="+key; clazz="all_LRC"; break; case 4://搜索艺人 keySearchUrl=KEY_SEARCH_URL_ARTIST+"/page/"+page+"?key="+key; break; } if(index==4){ mList=getArtistList(keySearchUrl); }else{ mList = getMusicList(keySearchUrl); } } /** * 获取艺人相关列表 * @param keySearchUrl * @return */ private List<Music> getArtistList(String keySearchUrl) { List<Music> musicList=new ArrayList<Music>(); String html=null; try { html=getHtml(keySearchUrl); } catch (CommonException e) { // TODO Auto-generated catch block e.printStackTrace(); } Document doc = Jsoup.parse(html); Elements elements = doc.getElementsByClass("artistBlock_list"); if(elements!=null&&elements.size()>0){ Elements all = elements.get(0).getElementsByClass("artist_item100_block"); if(all!=null&&all.size()>0){ for (Element element : all) { Music music=new Music(); music.setBigAlumUrl(element.getElementsByTag("img").attr("src")); music.setPath(element.getElementsByClass("artist100").attr("href")); music.setAirtistName(element.getElementsByClass("title").attr("title")); musicList.add(music); } } } return musicList; } /** * 获取网页html * @param urlString * @return * @throws CommonException */ public String getHtml(String urlString) throws CommonException{ StringBuffer sb=new StringBuffer(); try { URL url=new URL(urlString); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(30000); conn.setDoInput(true); conn.setDoOutput(true); if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){ InputStream is=conn.getInputStream(); int len=0; byte[] buf= new byte[1024]; while((len=is.read(buf))!=-1){ sb.append(new String(buf,0,len,"UTF-8")); } is.close(); }else{ throw new CommonException("访问网络失败!"); } } catch (Exception e) { e.printStackTrace(); throw new CommonException("访问网络失败!"); } return sb.toString(); } /** * 抓取歌曲id * @param input */ public List<String> getIds(String url){ List<String> allIds=new ArrayList<String>(); String html=null; try { html= getHtml(url); } catch (CommonException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Document document=null; if(!StringUtil.isEmpty(html)){ document=Jsoup.parse(html); Elements elements = document.getElementsByClass(clazz); if(elements!=null&&elements.size()>0){ Elements all = elements.get(0).getElementsByClass("chkbox"); if(all!=null&&all.size()>0){ for (Element element : all) { String id=element.select("input").attr("value"); if(!StringUtil.isEmpty(id)){ allIds.add(id); } } } } } return allIds; } /** * 通过ids获取music数据列表 * @param ids * @return */ public List<Music> getMusicList(String url){ List<String> ids = getIds(url); List<Music> musicList=new ArrayList<Music>(); if(ids!=null&&ids.size()>0){ for (String id : ids) { String postUrl=ID_SEARCH_URL+id; String html =null; try { html = getHtml(postUrl); } catch (CommonException e) { // TODO Auto-generated catch block e.printStackTrace(); } Document doc=Jsoup.parse(html); Elements elements = doc.select("trackList"); if(elements!=null&&elements.size()>0){ for (Element element : elements) { Music music=new Music(); music.setMusicId(id); music.setMusicName(element.select("songName").text()); music.setAirtistName(element.select("artist").text()); music.setSmallAlumUrl(element.select("pic").text()); music.setBigAlumUrl(element.select("album_pic").text()); music.setLrcUrl(element.select("lyric").text()); music.setAlbumName(element.select("album_name").text()); music.setPath(StringUtil.decodeMusicUrl(element.select("location").text())); musicList.add(music); } } } } return musicList; } /** * 解析歌名 * * @return */ private String getSubString(String name) { int start = name.indexOf("[", 3) + 1; int end = name.indexOf("]"); return name.substring(start, end); } }
package Dao; import java.sql.SQLException; import java.util.List; import entity.Ticket; import entity.User; public interface TickeDao { /** * 添加 * @param ticket * @return * @throws Exception */ boolean add(String station_arrival,String station_depart,String depart_date,String depart_time,int ticket_number,String seattypeid, String tickettypeid,int tickets_left,String fares,String ticket_office) throws Exception; /** * 修改 * @param ticket * @return * @throws SQLException */ boolean update(Ticket ticket) throws SQLException; /** * 删除 * @param ticketid * @return * @throws SQLException */ void delete(int ticketid) throws SQLException; /** * 通过Id查找 一条记录 * @param ticketid * @return * @throws SQLException */ List<Ticket> QueryById(int ticketid) throws SQLException; /** * 查找全部记录 * @return * @throws SQLException */ List<Ticket> queryAll() throws SQLException; List<Ticket> quetida(String station_arrival,String station_depart,String depart_date) throws SQLException; int fares(int ticketid) throws SQLException; }
package org.sayesaman.app3; import android.app.Activity; 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.TextView; import org.sayesaman.R; import org.sayesaman.database.model.GoodsGroup; import java.util.ArrayList; /** * Created by meysami on 8/20/13. */ public class ListViewAdapter extends BaseAdapter { private Activity activity; private static LayoutInflater inflater = null; private ArrayList<GoodsGroup> data; public ListViewAdapter(MyActivity1 a, ArrayList<GoodsGroup> d) { activity = a; data = d; inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return data.size(); } @Override public Object getItem(int i) { return data.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int position, View convertView, ViewGroup parent) { View vi = convertView; if (convertView == null) vi = inflater.inflate(R.layout.app3_row_list, null); TextView goodsGroupName = (TextView) vi.findViewById(R.id.goodsGroupName); TextView goodsGroupQty = (TextView) vi.findViewById(R.id.goodsQtyActive); ImageView goodsGroupImage = (ImageView) vi.findViewById(R.id.goodsGroupImage); GoodsGroup group = data.get(position); goodsGroupName.setText(group.getName()); goodsGroupImage.setImageResource(R.drawable.app2_btn02); return vi; } }
package com.beike.common.interceptor.trx; import java.io.Serializable; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.beike.interceptors.BaseBeikeInterceptor; import com.beike.util.cache.cachedriver.service.MemCacheService; import com.beike.util.cache.cachedriver.service.impl.MemCacheServiceImpl; /** * @Title: DenyDuplicateFormSubmitInterceptor.java * @Package com.beike.common.interceptor.trx * @Description: * @date Jun 14, 2011 10:51:05 PM * @author wh.cheng * @version v1.0 */ public class DenyDuplicateFormSubmitInterceptor extends BaseBeikeInterceptor { private static Log logger=LogFactory.getLog(DenyDuplicateFormSubmitInterceptor.class); private static final String UUID_TOKEN_KEY_NAME = "UUID_TOKEN_KEY"; private static final String REPEAT_SUBMIT = "REPEAT_SUBMIT"; private MemCacheService memCacheService = MemCacheServiceImpl.getInstance(); public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { boolean pathFlag=super.preHandle(request, response, handler); boolean flag = true; if(pathFlag){ String token = request.getParameter(UUID_TOKEN_KEY_NAME); // if (token == null) { // 赋一个令牌 // String UuidTokenKey = StringUtils.createUUID(); // /memCacheService.set(UuidTokenKey, new Object(),1800);// 配对Token // 往客户端发送Token // request.setAttribute(UUID_TOKEN_KEY_NAME, UuidTokenKey); // } else { String tokenResult = (String) memCacheService.get(token); if (tokenResult != null && !"".equals(tokenResult)) { // 销毁TOKEN logger.info("+++++First Submit , Token is :"+token+"+++++++++"); memCacheService.remove(token); } else { //flag = false; logger.info("++++++repeat Submit , Token is :"+token+"+++++++++"); request.setAttribute(REPEAT_SUBMIT, "true"); //throw new Exception("表单重复提交或过期,令牌[" + token + "]"); } } return flag; } @Override protected Serializable createLog(Map<String, String> map, HttpServletRequest request) { // TODO Auto-generated method stub return null; } }
package OOP.EX10_INTERFACES_AND_ABSTRACTION.E05_Тelephony; public interface Browsable { String browse(); }
package com.emmanuj.todoo.db; /** * Created by emmanuj on 11/12/15. */ public class DBTableField { private String name; private String type; private String properties; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getProperties() { return properties; } public void setProperties(String properties) { this.properties = properties; } }
package com.youthlin.demo.ioc.dao; import com.youthlin.demo.ioc.po.User; import java.util.List; /** * 创建: youthlin.chen * 时间: 2017-08-11 15:15. */ public interface IUserDao { void save(User user); List<User> list(); }
package com.huffmancoding.pelotonia.funds; import java.math.BigDecimal; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; /** * This is a column in the roster file that has a header title an values for each team member * * @author khuffman */ public class SpreadsheetColumn { /** the header name of the column. */ private final String name; /** the index of this header in the spreadsheet. */ private int index = -1; /** * Constructor. * * @param name the title to match against the roster file cell value */ public SpreadsheetColumn(String name) { this.name = name; } /** * Return the header name of this column. * * @return the header name of this column */ public String getName() { return name; } /** * Whether this cell contains the name of this column. * * @param cell the cell to look at * @return true if this the cell that matches the name of this column */ public boolean isHeaderCell(Cell cell) { if (cell != null && cell.getCellType() == Cell.CELL_TYPE_STRING) { String cellValue = cell.getStringCellValue(); if (cellValue.equalsIgnoreCase(name)) { index = cell.getColumnIndex(); return true; } } return false; } /** * Verifies that a column has been found in the spreadsheet * * @throws InvalidFormatException thrown if the column is missing but required, if optional it is only logged */ public void checkHeaderFound() throws InvalidFormatException { if (! isHeaderFound()) { throw new InvalidFormatException("Header row does not contain column \"" + name + "\""); } } /** * Returns true if an earlier call to {@link #isHeaderCell(Cell)} returned true. * * @return true if the header is present in the spreadsheet */ public boolean isHeaderFound() { return index >= 0; } /** * Return a string value for a row and column in the spreadsheet. * * @param row to read from * @return the value at that row and column * @throws InvalidFormatException if the cell does not contain a valid string value */ public String getRowString(Row row) throws InvalidFormatException { Cell cell = row.getCell(index); if (cell == null || cell.getColumnIndex() != index) { return null; } int cellType = cell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); case Cell.CELL_TYPE_NUMERIC: return new BigDecimal(cell.getNumericCellValue()).toPlainString(); default: return null; } } /** * Return a BigDecimal value for a row and column in the spreadsheet. * * @param row to read from * @return the value at that row and column * @throws InvalidFormatException if the cell does not contain a valid BigDecimal value */ public BigDecimal getRowBigDecimal(Row row) throws InvalidFormatException { Cell cell = row.getCell(index); if (cell == null || cell.getColumnIndex() != index) { throw new InvalidFormatException("No cell at column: " + index); } int cellType = cell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_NUMERIC: return new BigDecimal(cell.getNumericCellValue()); case Cell.CELL_TYPE_STRING: String stringCellValue = cell.getStringCellValue(); if (stringCellValue.charAt(0) == '$') { stringCellValue = stringCellValue.substring(1); int dot = stringCellValue.indexOf('.'); if (dot >= 0 && stringCellValue.length() > dot + 3) { stringCellValue = stringCellValue.substring(0, dot + 3); } } return new BigDecimal(stringCellValue); default: return BigDecimal.ZERO; } } }
package com.cheese.radio.ui.home.page.banner; import com.binding.model.layout.rotate.PagerRotateListener; import com.binding.model.layout.rotate.TimeEntity; import com.binding.model.model.inter.Inflate; import com.binding.model.model.inter.Parse; import java.util.ArrayList; import java.util.List; /** * @param <E> model is the view page Model */ public class PagerEntity<E extends Parse> implements TimeEntity{ private int totalTime; private int time = 0; private int index = 0; private int lastIndex = 0; private int loop = -1; private int count = 0; private List<E> list = new ArrayList<>(); private Inflate inflate; private List<PagerRotateListener<E>> pagerRotateListeners = new ArrayList<>(); public PagerEntity(List<? extends E> list, Inflate inflate) { this(3, list,inflate ); } public PagerEntity(int totalTime, List<? extends E> list, Inflate inflate) { this.inflate = inflate; this.totalTime = totalTime; if (list != null) { this.list.clear(); this.list.addAll(list); this.index = list.size() - 1; count = list.size(); } } public Inflate getModel() { return inflate; } public void setCount(int count) { this.count = count; } public void setLoop(int loop) { this.loop = loop; } public int getCheckIndex(E model) { return list.indexOf(model); } public PagerEntity<E> addRotateListener(PagerRotateListener<E> listener) { pagerRotateListeners.add(listener); return this; } @Override public void getTurn() { if (totalTime == getTime()) { E model = getType(); if (model != null) if (loop == -1 || --loop > 0) { for (PagerRotateListener<E> pagerRotateListener : pagerRotateListeners) pagerRotateListener.nextRotate(model); } } } private int getCheckIndex() { lastIndex = index; return index = index == count - 1 ? 0 : ++index; } public int getLastIndex() { return lastIndex; } public void setIndex(int index) { lastIndex = this.index; this.index = index; } public int getIndex() { return index; } public E getType() { if (count != 0) return list.get(getCheckIndex() % count); return null; } public void setTotalTime(int totalTime) { this.totalTime = totalTime; } public int getTotalTime() { return totalTime; } public int getTime() { return time = time == 0 ? totalTime : --time; } public List<E> getList() { return list; } public void setList(List<E> list) { this.list.clear(); this.list.addAll(list); count = list.size(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PagerEntity<?> that = (PagerEntity<?>) o; return inflate.equals(that.inflate); } @Override public int hashCode() { return inflate.hashCode(); } }
package com.lsjr.zizisteward.mvp.recycle; import android.support.annotation.IntDef; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by admin on 2017/5/22. */ public class RecycleBean { public static final int TYPE_1=0X11; public static final int TYPE_2=0X22; public static final int TYPE_3=0X33; public static final int TYPE_4=0X44; private int type; private Map<Integer,List<RecycleDeatil>> recycleTypes; public Map<Integer, List<RecycleDeatil>> getRecycleTypes() { return recycleTypes; } public void setRecycleTypes(Map<Integer, List<RecycleDeatil>> recycleTypes) { this.recycleTypes = recycleTypes; } @IntDef({TYPE_1, TYPE_2, TYPE_3, TYPE_4}) public @interface EmType { } public int getType() { return type; } public void setType(@EmType int type) { this.type = type; } static class RecycleDeatil{ private String title; private String imgUrl; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } } }
package pkgcpmain; /** * This class is on the classpath, i.e. in the unnamed module. */ /** * This class cannot be compiled in Eclipse because of missing dependencies, might be an Eclipse problem * as cpmain cannot access modb. */ public class Main { public static void main(String[] args) { System.out.println("We are calling various classes from " + Main.class + " (which is on the classpath, i.e. in the unnamed module)"); // ---------------------------------------------------------------------------------------------------------------------------------- // We access a class on the module path, in module modb - class's package is exported, should work System.out.println("\n1. Classpath code calling code in an explicit module on the module path"); System.out.println("a. ... calling an exported class B which is in module modb: " + new pkgb.BFromModule().doIt()); // ---------------------------------------------------------------------------------------------------------------------------------- // We access a class on the module path, in module modb - class's package is not exported, results in an java.lang.IllegalAccessError try { System.out.println("b. ... calling an internal, non-exported class which is in module modb - " + "results in a java.lang.IllegalAccessError:"); System.out.println(new pkgbinternal.BFromModuleButInternal().doIt()); } catch (Throwable ex) { ex.printStackTrace(System.err); // we expect a java.lang.IllegalAccessError } // ---------------------------------------------------------------------------------------------------------------------------------- // We access a class which is only on the classpath, should always work System.out.println("\n2. Classpath code calling a class which is also on the classpath"); System.out.println("... calling BFromClasspath which is on the classpath: " + new pkgboncp.BFromClasspath().doIt()); // ---------------------------------------------------------------------------------------------------------------------------------- // We access a class which is on the classpath and whose package is also in modb, results in a java.lang.ClassNotFoundException try { System.out.println("\n3. Classpath code calling a class which is on the classpath, " + "but whose package name is 'covered' by a package in a module on the module path - " + "results in a java.lang.ClassNotFoundException"); // We access a class which is on the classpath - will not work, but only because the package name "pkgb" is covered by the same class in the same package in modb pkgb.BFromClasspath myB4 = new pkgb.BFromClasspath(); System.out.println("ERROR: Calling BFromClasspath whose package is both on the module path and on the classpath - SHOULD NOT WORK: " + myB4.doIt()); } catch (Throwable ex) { ex.printStackTrace(System.err); // we expect a java.lang.ClassNotFoundException } // ---------------------------------------------------------------------------------------------------------------------------------- // We access a class which is both on the classpath and in modb, will use the class in modb System.out.println("\n4. Classpath code calling a class which is both on the classpath and in a module on the module path - will use the latter from module modb:"); // We access a class which is on the classpath - will not work, but only because the package name "pkgb" is covered by the same class in the same package in modb System.out.println("... calling B which is both on the module path and on the classpath: " + new pkgb.B().doIt()); } }
/* * 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.pmm.sdgc.converter; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import javax.persistence.AttributeConverter; import javax.persistence.Converter; /** * * @author acg */ @Converter(autoApply = true) public class LocalTimeConverter implements AttributeConverter<LocalTime, String> { @Override public String convertToDatabaseColumn(LocalTime localTime) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); try { String strTime = localTime.format(formatter); return strTime; } catch (Exception e) { return null; } } @Override public LocalTime convertToEntityAttribute(String strTime) { if (strTime == null) { return null; } if (strTime.isEmpty()) { return null; } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); LocalTime localTime = null; try { localTime = LocalTime.parse(strTime.trim(), formatter); return localTime; } catch (Exception e) { return null; } } }
package com.xeland.project; import java.util.Locale; public interface ClassNa { ClassTh getDisplayName(); default String getDisplayName(final Locale locale) { return ""; } }
package com.company.iba.ialeditor.model; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.model.ModelWrapper; import java.util.HashMap; import java.util.Map; /** * <p> * This class is a wrapper for {@link Dictionary}. * </p> * * @author Brian Wing Shun Chan * @see Dictionary * @generated */ public class DictionaryWrapper implements Dictionary, ModelWrapper<Dictionary> { private Dictionary _dictionary; public DictionaryWrapper(Dictionary dictionary) { _dictionary = dictionary; } @Override public Class<?> getModelClass() { return Dictionary.class; } @Override public String getModelClassName() { return Dictionary.class.getName(); } @Override public Map<String, Object> getModelAttributes() { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("dictionaryId", getDictionaryId()); attributes.put("termId", getTermId()); attributes.put("langId", getLangId()); attributes.put("translation", getTranslation()); return attributes; } @Override public void setModelAttributes(Map<String, Object> attributes) { Long dictionaryId = (Long) attributes.get("dictionaryId"); if (dictionaryId != null) { setDictionaryId(dictionaryId); } Long termId = (Long) attributes.get("termId"); if (termId != null) { setTermId(termId); } Long langId = (Long) attributes.get("langId"); if (langId != null) { setLangId(langId); } String translation = (String) attributes.get("translation"); if (translation != null) { setTranslation(translation); } } /** * Returns the primary key of this dictionary. * * @return the primary key of this dictionary */ @Override public long getPrimaryKey() { return _dictionary.getPrimaryKey(); } /** * Sets the primary key of this dictionary. * * @param primaryKey the primary key of this dictionary */ @Override public void setPrimaryKey(long primaryKey) { _dictionary.setPrimaryKey(primaryKey); } /** * Returns the dictionary ID of this dictionary. * * @return the dictionary ID of this dictionary */ @Override public long getDictionaryId() { return _dictionary.getDictionaryId(); } /** * Sets the dictionary ID of this dictionary. * * @param dictionaryId the dictionary ID of this dictionary */ @Override public void setDictionaryId(long dictionaryId) { _dictionary.setDictionaryId(dictionaryId); } /** * Returns the term ID of this dictionary. * * @return the term ID of this dictionary */ @Override public long getTermId() { return _dictionary.getTermId(); } /** * Sets the term ID of this dictionary. * * @param termId the term ID of this dictionary */ @Override public void setTermId(long termId) { _dictionary.setTermId(termId); } /** * Returns the lang ID of this dictionary. * * @return the lang ID of this dictionary */ @Override public long getLangId() { return _dictionary.getLangId(); } /** * Sets the lang ID of this dictionary. * * @param langId the lang ID of this dictionary */ @Override public void setLangId(long langId) { _dictionary.setLangId(langId); } /** * Returns the translation of this dictionary. * * @return the translation of this dictionary */ @Override public java.lang.String getTranslation() { return _dictionary.getTranslation(); } /** * Sets the translation of this dictionary. * * @param translation the translation of this dictionary */ @Override public void setTranslation(java.lang.String translation) { _dictionary.setTranslation(translation); } @Override public boolean isNew() { return _dictionary.isNew(); } @Override public void setNew(boolean n) { _dictionary.setNew(n); } @Override public boolean isCachedModel() { return _dictionary.isCachedModel(); } @Override public void setCachedModel(boolean cachedModel) { _dictionary.setCachedModel(cachedModel); } @Override public boolean isEscapedModel() { return _dictionary.isEscapedModel(); } @Override public java.io.Serializable getPrimaryKeyObj() { return _dictionary.getPrimaryKeyObj(); } @Override public void setPrimaryKeyObj(java.io.Serializable primaryKeyObj) { _dictionary.setPrimaryKeyObj(primaryKeyObj); } @Override public com.liferay.portlet.expando.model.ExpandoBridge getExpandoBridge() { return _dictionary.getExpandoBridge(); } @Override public void setExpandoBridgeAttributes( com.liferay.portal.model.BaseModel<?> baseModel) { _dictionary.setExpandoBridgeAttributes(baseModel); } @Override public void setExpandoBridgeAttributes( com.liferay.portlet.expando.model.ExpandoBridge expandoBridge) { _dictionary.setExpandoBridgeAttributes(expandoBridge); } @Override public void setExpandoBridgeAttributes( com.liferay.portal.service.ServiceContext serviceContext) { _dictionary.setExpandoBridgeAttributes(serviceContext); } @Override public java.lang.Object clone() { return new DictionaryWrapper((Dictionary) _dictionary.clone()); } @Override public int compareTo(com.company.iba.ialeditor.model.Dictionary dictionary) { return _dictionary.compareTo(dictionary); } @Override public int hashCode() { return _dictionary.hashCode(); } @Override public com.liferay.portal.model.CacheModel<com.company.iba.ialeditor.model.Dictionary> toCacheModel() { return _dictionary.toCacheModel(); } @Override public com.company.iba.ialeditor.model.Dictionary toEscapedModel() { return new DictionaryWrapper(_dictionary.toEscapedModel()); } @Override public com.company.iba.ialeditor.model.Dictionary toUnescapedModel() { return new DictionaryWrapper(_dictionary.toUnescapedModel()); } @Override public java.lang.String toString() { return _dictionary.toString(); } @Override public java.lang.String toXmlString() { return _dictionary.toXmlString(); } @Override public void persist() throws com.liferay.portal.kernel.exception.SystemException { _dictionary.persist(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof DictionaryWrapper)) { return false; } DictionaryWrapper dictionaryWrapper = (DictionaryWrapper) obj; if (Validator.equals(_dictionary, dictionaryWrapper._dictionary)) { return true; } return false; } /** * @deprecated As of 6.1.0, replaced by {@link #getWrappedModel} */ public Dictionary getWrappedDictionary() { return _dictionary; } @Override public Dictionary getWrappedModel() { return _dictionary; } @Override public void resetOriginalValues() { _dictionary.resetOriginalValues(); } }
/** * @(#) Coller.java */ package command; import receiver.Buffer; /** * La commande qui exécute l'action coller() du buffer. */ public class Coller extends Command { public Coller(Buffer buffer) { this.buffer = buffer; } @Override public void execute() { buffer.coller(); } }
package com.example.utils; import com.example.ConfigFileReader; import io.cucumber.java.Scenario; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.concurrent.TimeUnit; public class DriverFactory { protected static WebDriver driver; protected static WebDriverWait waitVar = null; protected static Boolean headlessModeValue = false; ConfigFileReader configFileReader = new ConfigFileReader(); public void setUp(){ switch (configFileReader.getBrowser().toLowerCase()){ case "firefox": System.setProperty("webdriver.gecko.driver", configFileReader.getFirefoxDriverPath()); headlessModeValue = Boolean.parseBoolean(configFileReader.getHeadlessModeValue()); if(headlessModeValue) { FirefoxOptions options = new FirefoxOptions(); options.setHeadless(true); driver = new FirefoxDriver(options); } else { driver = new FirefoxDriver(); } break; case "ie": //Here you can put the code for IE Webdriver if you need multiple options to execute the tests. default: System.setProperty("webdriver.chrome.driver", configFileReader.getChromeDriverPath()); // Initialize new WebDriver session System.out.println("Starting driver..."); headlessModeValue = Boolean.parseBoolean(configFileReader.getHeadlessModeValue()); if(headlessModeValue){ //running with headless mode ChromeOptions optionsForChrome = new ChromeOptions(); optionsForChrome.addArguments("headless"); optionsForChrome.addArguments("window-size=1200x600"); driver = new ChromeDriver(optionsForChrome); } else{ driver = new ChromeDriver(); } } driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(configFileReader.getImplicitlyWait(), TimeUnit.SECONDS); driver.get(configFileReader.getApplicationUrl()); waitVar = new WebDriverWait(driver, 15); } public void tearDown() { driver.close(); } public void takeScreenshot(Scenario scenario){ // Take a screenshot... final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES); // embed it in the report. scenario.attach(screenshot, "image/png", scenario.getName()); } }
package com.example.krishnaghatia.break_no_chain.Controllers; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.krishnaghatia.break_no_chain.Models.Goal; /** * Created by Prachi on 02-04-2015. */ public class DatabaseHelper extends SQLiteOpenHelper { // TODO - Added these data tables method to create goal on parse - Avirek - 5/8/15 private static final String PARSE_CREATE_GOAL_TABLE = "Parse_Create_Goal"; private static final String COLUMN_PARSE_CREATE_GOAL_ID = "Parse_Create_Goal_id"; private static final String COLUMN_PARSE_CREATE_GOAL_NAME = "Parse_Create_Goal_name"; // TODO - Until here - Avirek - 5/8/15 public static String name = "GoalDatabase"; public static int version = 3; private static final String TABLE_GOAL = "GoalTable"; public DatabaseHelper(Context context) { super(context, name, null, version); // TODO Auto-generated constructor stub } public void onCreate(SQLiteDatabase db) { db.execSQL("Create table GoalTable(goal_id integer, user_id text, name text, start_date text, end_date text, notificationTime text, shareBoolean text,count integer, last_marked text, PRIMARY KEY(goal_id, user_id) )"); // TODO - Added this to create table Goal(id retrieved from parse and name of the goal) to create goal on parse - Avirek - 5/8/15 db.execSQL("create table " + PARSE_CREATE_GOAL_TABLE + "(" + COLUMN_PARSE_CREATE_GOAL_ID + " text primary key, " + COLUMN_PARSE_CREATE_GOAL_NAME + " text)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if exists db.execSQL("DROP TABLE IF EXISTS " + TABLE_GOAL); // create tables again onCreate(db); } //public void create_goal(int goal_id, String user_id, String name, String start_date, String end_date,String notificationTime, String shareBoolean ){ public int create_goal(String user_id, String name, String start_date, String end_date,String notificationTime, String shareBoolean ){ SQLiteDatabase dataBase = this.getWritableDatabase(); SQLiteDatabase db = this.getReadableDatabase(); int goal_id = 0; //int go = dataBase.execSQL("select MAX(goal_id) from GoalTable"); //Goal g = new Goal(); // int goal_id = g.getGoalId(); //g.setGoalID(goal_id + 1); Cursor abc = db.rawQuery("Select MAX(goal_id) from GoalTable where user_id =?", new String []{user_id}); abc.moveToFirst(); if (abc.getCount()!= 0) { goal_id = abc.getInt(0); //goal_id=abc.getCount(); goal_id= goal_id + 1; } dataBase.execSQL("Insert into GoalTable values('" + goal_id + "','" +user_id + "','" +name+ "','" +start_date+ "','" // dataBase.execSQL("Insert into GoalTable ((SELECT MAX(goal_id)+1 FROM GoalTable),user_id, name, start_date, end_date, notificationTime, shareBoolean) values('"+user_id + "','" +name+ "','" +start_date+ "','" +end_date+ "','" +notificationTime+ "','" +shareBoolean+ "', '0', '')"); return goal_id; } // TODO - Added this method to create goal on parse - Avirek - 5/8/15 public String parse_create_goal(String goal_id, String name){ SQLiteDatabase dataBase = this.getWritableDatabase(); SQLiteDatabase db = this.getWritableDatabase(); System.out.println("Inside insert Trip functions"); ContentValues cv = new ContentValues(); cv.put(COLUMN_PARSE_CREATE_GOAL_ID, goal_id); cv.put(COLUMN_PARSE_CREATE_GOAL_NAME, name); // return id of new trip db.insert(PARSE_CREATE_GOAL_TABLE, null, cv); System.out.println("Inserted Successfully"); return goal_id; } public Goal display_goal(int goal_id, String user_id){ Goal goal = null; int goalId; String userId; String name; String startDate; String endDate; String notifyTime; String ShareFrds; SQLiteDatabase database = this.getReadableDatabase(); String goalID = String.valueOf(goal_id); Cursor abc = database.rawQuery("Select goal_id,user_id, name,start_date, end_date,notificationTime, shareBoolean from goalTable where user_id=? and goal_id=?", new String []{user_id, goalID}); if (abc.getCount()!= 0) { abc.moveToFirst(); goalId = abc.getInt(0); userId = abc.getString(1); name = abc.getString(2); startDate =abc.getString(3); endDate = abc.getString(4); notifyTime = abc.getString(5); ShareFrds = abc.getString(6); goal = new Goal(goalId,ShareFrds, name,startDate,endDate,notifyTime); // goal = new Goal(name,startDate,endDate,notifyTime,ShareFrds); } return goal; } }
package slimeknights.tconstruct.library.client; import net.minecraft.util.ResourceLocation; import slimeknights.mantle.client.gui.GuiElement; import slimeknights.tconstruct.library.Util; public interface Icons { ResourceLocation ICON = Util.getResource("textures/gui/icons.png"); GuiElement ICON_Anvil = new GuiElement(18 * 3, 0, 18, 18, 256, 256); GuiElement ICON_Pattern = new GuiElement(18 * 0, 18 * 12, 18, 18); GuiElement ICON_Shard = new GuiElement(18 * 1, 18 * 12, 18, 18); GuiElement ICON_Block = new GuiElement(18 * 2, 18 * 12, 18, 18); GuiElement ICON_Pickaxe = new GuiElement(18 * 0, 18 * 13, 18, 18); GuiElement ICON_Dust = new GuiElement(18 * 1, 18 * 13, 18, 18); GuiElement ICON_Lapis = new GuiElement(18 * 2, 18 * 13, 18, 18); GuiElement ICON_Ingot = new GuiElement(18 * 3, 18 * 13, 18, 18); GuiElement ICON_Gem = new GuiElement(18 * 4, 18 * 13, 18, 18); GuiElement ICON_Quartz = new GuiElement(18 * 5, 18 * 13, 18, 18); GuiElement ICON_Button = new GuiElement(180, 216, 18, 18); GuiElement ICON_ButtonHover = new GuiElement(180 + 18 * 2, 216, 18, 18); GuiElement ICON_ButtonPressed = new GuiElement(180 - 18 * 2, 216, 18, 18); GuiElement ICON_PIGGYBACK_1 = new GuiElement(18 * 13, 18 * 0, 18, 18); GuiElement ICON_PIGGYBACK_2 = new GuiElement(18 * 13, 18 * 1, 18, 18); GuiElement ICON_PIGGYBACK_3 = new GuiElement(18 * 13, 18 * 2, 18, 18); }
package io.snice.buffer; import io.snice.buffer.impl.EmptyBuffer; import org.hamcrest.CoreMatchers; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.function.Consumer; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * Base class for all those tests concerning {@link ReadableBuffer}s. * */ public abstract class AbstractReadableBufferTest extends AbstractBufferTest { protected ReadableBuffer createReadableBuffer(final String s) { return (ReadableBuffer)createBuffer(s); } protected ReadableBuffer createReadableBuffer(final byte[] bytes) { return (ReadableBuffer)createBuffer(bytes); } @Test public void testReadUntilWhiteSpace() throws Exception { ensureReadUntilWhiteSpace("hello world", "hello", "world"); ensureReadUntilWhiteSpace("hello\tworld", "hello", "world"); // doesn't matter how many spaces there is, should all be consumed ensureReadUntilWhiteSpace("hello world", "hello", "world"); ensureReadUntilWhiteSpace("hello \t\t world", "hello", "world"); // should only consume up until the first one... // but next read we'll get the final split final ReadableBuffer buf = ensureReadUntilWhiteSpace("hello world again", "hello", "world again"); assertThat(buf.readUntilWhiteSpace().toString(), is("world")); assertThat(buf.toString(), is("again")); } private ReadableBuffer ensureReadUntilWhiteSpace(final String line, final String expected1, final String expected2) { final ReadableBuffer buffer = createReadableBuffer(line); assertThat(buffer.readUntilWhiteSpace().toString(), is(expected1)); assertThat(buffer.toString(), is(expected2)); return buffer; } /** * Make sure that we can read the single-crlf sequence correctly. * * @throws Exception */ @Test public void testReadUntilSingleCRLF() throws Exception { // no CRLF should lead to null... ReadableBuffer buffer = createReadableBuffer("hello"); assertThat(buffer.readUntilSingleCRLF(), is((Buffer)null)); // Only CR should also lead to null buffer = createReadableBuffer("hello\r"); assertThat(buffer.readUntilSingleCRLF(), is((Buffer)null)); // now we have two so that should yield a "hello" buffer back. buffer = createReadableBuffer("hello\r\n"); assertThat(buffer.readUntilSingleCRLF().toString(), is("hello")); // One hello and then a null buffer = createReadableBuffer("hello\r\nworld"); assertThat(buffer.readUntilSingleCRLF().toString(), is("hello")); assertThat(buffer.readUntilSingleCRLF(), is((Buffer)null)); // One hello and then world buffer = createReadableBuffer("hello\r\nworld\r\n"); assertThat(buffer.readUntilSingleCRLF().toString(), is("hello")); assertThat(buffer.readUntilSingleCRLF().toString(), is("world")); // One hello and then an empty buffer buffer = createReadableBuffer("hello\r\n\r\n"); assertThat(buffer.readUntilSingleCRLF().toString(), is("hello")); assertThat(buffer.readUntilSingleCRLF().isEmpty(), is(true)); } /** * Make sure that we can read the double-crlf sequence correctly. * * @throws Exception */ @Test public void testReadUntilDoubleCRLF() throws Exception { ReadableBuffer buffer = createReadableBuffer("hello\r\n\r\nworld"); Buffer hello = buffer.readUntilDoubleCRLF(); assertThat(hello.toString(), is("hello")); assertThat(buffer.toString(), is("world")); // note that the first sequence is missing the last '\n' buffer = createReadableBuffer("hello\r\n\rworld\r\n\r\n"); hello = buffer.readUntilDoubleCRLF(); assertThat(hello.toString(), is("hello\r\n\rworld")); assertThat(buffer.toString(), is("")); // if we only have double crlf we will end up with two empty buffers... buffer = createReadableBuffer("\r\n\r\n"); final Buffer empty = buffer.readUntilDoubleCRLF(); assertThat(empty.isEmpty(), is(true)); // isEmpty for stream backed buffers will never ever return anything but false for isEmpty() // however, has readable bytes do accomplish what we want for this test. assertThat(buffer.hasReadableBytes(), is(false)); // of course, if there are two double-crlf sequences we should still // only read the first one... and reading the next double-crlf should // yield two buffers both with the word "world" in it... buffer = createReadableBuffer("hello\r\n\r\nworld\r\n\r\nworld"); hello = buffer.readUntilDoubleCRLF(); assertThat(hello.toString(), is("hello")); assertThat(buffer.toString(), is("world\r\n\r\nworld")); final Buffer world = buffer.readUntilDoubleCRLF(); assertThat(world.toString(), is("world")); assertThat(buffer.toString(), is("world")); } @Override @Test public void testIndexOf() throws Exception { final ReadableBuffer buffer = createReadableBuffer("hello world ena goa grejor".getBytes()); assertThat(buffer.indexOf(100, (byte) 'h'), is(0)); assertThat(buffer.indexOf(100, (byte) 'e'), is(1)); assertThat(buffer.indexOf(100, (byte) 'l'), is(2)); assertThat(buffer.indexOf(100, (byte) 'o'), is(4)); assertThat(buffer.indexOf(100, (byte) ' '), is(5)); assertThat(buffer.indexOf(100, (byte) 'w'), is(6)); assertThat(buffer.getByte(6), is((byte) 'w')); // indexOf should not affect the reader index so // everything should still be there. assertThat(buffer.toString(), is("hello world ena goa grejor")); // read some byte so now that we try and find 'w' it is actually // not there anymore... assertThat(buffer.readBytes(11).toString(), is("hello world")); assertThat(buffer.indexOf((byte) 'w'), is(-1)); // however, we still have an 'o' around in the visible area // Remember that the index is in relation to the entire buffer // and not where the reader index is. assertThat(buffer.indexOf((byte) 'o'), is(17)); } @Test public void testSliceEmptyBuffer() throws Exception { final Buffer buffer = EmptyBuffer.EMPTY; assertEmptyBuffer(buffer.slice()); assertThat(buffer.slice().toReadableBuffer().hasReadableBytes(), is(false)); final ReadableBuffer buf = Buffers.wrap("a little harder").toReadableBuffer(); buf.readBytes(buf.capacity()); assertEmptyBuffer(buf.slice()); assertThat(buf.slice().toReadableBuffer().hasReadableBytes(), is(false)); } @Test public void testReadUntil2() throws Exception { ReadableBuffer buffer = createReadableBuffer("this is a somewhat long string".getBytes()); Buffer buf = buffer.readUntil(100, (byte) 'a', (byte) 'o'); assertThat(buf.toString(), is("this is ")); buffer = createReadableBuffer("this is a somewhat long string".getBytes()); buf = buffer.readUntil(100, (byte) 'o', (byte) 'a'); assertThat(buf.toString(), is("this is ")); buffer = createReadableBuffer("this is a somewhat long string".getBytes()); buf = buffer.readUntil(100, (byte) 'k', (byte) 'c', (byte) 'o'); assertThat(buf.toString(), is("this is a s")); buffer = createReadableBuffer("this is a somewhat long string".getBytes()); buf = buffer.readUntil(100, (byte) 'k', (byte) 'c', (byte) 'g'); assertThat(buf.toString(), is("this is a somewhat lon")); assertThat(buffer.toString(), is(" string")); // but now we really only want to read a maximum 10 bytes buffer = createReadableBuffer("this is a somewhat long string".getBytes()); try { buf = buffer.readUntil(10, (byte) 'k', (byte) 'c', (byte) 'g'); fail("Expected a ByteNotFoundException"); } catch (final ByteNotFoundException e) { // the buffer should have been left untouched. assertThat(buffer.toString(), is("this is a somewhat long string")); } // also make sure that after slicing the read until stuff // works as expected. buffer = createReadableBuffer("this is a somewhat long string".getBytes()); buffer.readBytes(5); buf = buffer.readUntil((byte) 'i'); assertThat(buf.toString(), is("")); buf = buffer.readUntil((byte) 'e'); assertThat(buf.toString(), is("s a som")); // slice things up and make sure that our readUntil works on slices as well final ReadableBuffer slice = buffer.slice(buffer.getReaderIndex() + 5).toReadableBuffer(); assertThat(slice.toString(), is("what ")); buf = slice.readUntil((byte) 'a'); assertThat(buf.toString(), is("wh")); assertThat(slice.toString(), is("t ")); buf = slice.readUntil((byte) ' '); assertThat(buf.toString(), is("t")); assertThat(slice.toString(), is("")); assertThat(slice.hasReadableBytes(), is(false)); // head back to the buffer which should have been unaffected by our // work on the slice. we should have "what long string" left buf = buffer.readUntil((byte) 'o'); assertThat(buf.toString(), is("what l")); assertThat(buffer.readUntil((byte) 'n').toString(), is("")); assertThat(buffer.readUntil((byte) 'i').toString(), is("g str")); } @Test public void testReadUntil() throws Exception { ReadableBuffer buffer = createReadableBuffer("hello world".getBytes()); final Buffer hello = buffer.readUntil((byte) ' '); assertThat(hello.toString(), is("hello")); // read the next 5 bytes and that should give us the world part final Buffer world = buffer.readBytes(5); assertThat(world.toString(), is("world")); // test to read until 'h' is found, which should yeild nothing // since the character that is found is essentially thrown away buffer = createReadableBuffer("hello world again".getBytes()); final Buffer empty = buffer.readUntil((byte) 'h'); assertThat(empty.toString(), is("")); // then read until 'a' is found final Buffer more = buffer.readUntil((byte) 'a'); assertThat(more.toString(), is("ello world ")); final Buffer gai = buffer.readUntil((byte) 'n'); assertThat(gai.toString(), is("gai")); // and now there should be nothing left try { buffer.readByte(); fail("Expected a IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } // no 'u' in the string, exception expected buffer = createReadableBuffer("nothing will match".getBytes()); try { buffer.readUntil((byte) 'u'); fail("Expected a ByteNotFoundException"); } catch (final ByteNotFoundException e) { // expected } } @Test public void testRead() throws Exception { final ReadableBuffer buffer = createReadableBuffer(RawData.rawEthernetFrame); // read 100 bytes at a time for (int i = 0; i < 5; ++i) { final Buffer hundred = buffer.readBytes(100); assertThat(hundred.capacity(), is(100)); for (int k = 0; k < 100; ++k) { assertThat(hundred.getByte(k), CoreMatchers.is(RawData.rawEthernetFrame[k + i * 100])); } } // there are 547 bytes in the rawEthernetFrame so there should be 47 // left final Buffer theRest = buffer.readBytes(47); assertThat(theRest.capacity(), is(47)); for (int k = 0; k < 47; ++k) { assertThat(theRest.getByte(k), CoreMatchers.is(RawData.rawEthernetFrame[k + 500])); } } /** * Make sure we can read a single line that doesn't contain any new line * characters * * @throws Exception */ @Test public void testReadLineSingleLineNoCRLF() throws Exception { // final String s = "just a regular line, nothing special"; final String s = "hello"; final ReadableBuffer buffer = createReadableBuffer(s.getBytes()); assertThat(buffer.readLine().toString(), is(s)); // no more lines to read assertThat(buffer.readLine(), is((Buffer) null)); } /** * Make sure that we can read line by line * * @throws Exception */ @Test public void testReadLine() throws Exception { int count = 0; final ReadableBuffer buffer = RawData.sipBuffer.toReadableBuffer(); while (buffer.readLine() != null) { ++count; } // this sip buffer contains 19 lines assertThat(count, is(19)); } /** * Contains two lines separated by a single '\n' * * @throws Exception */ @Test public void testReadLines() throws Exception { final String line1 = "this is line 1"; final String line2 = "and this is line 2"; ReadableBuffer buffer = createReadableBuffer((line1 + "\n" + line2).getBytes()); // the first readLine should be equal to line 1 and // the '\n' should have been stripped off assertThat(buffer.readLine().toString(), is(line1)); // and then of course check the second line assertThat(buffer.readLine().toString(), is(line2)); // and then there should be no more assertThat(buffer.readLine(), is((Buffer) null)); // now add only a CR buffer = createReadableBuffer((line1 + "\r" + line2).getBytes()); assertThat(buffer.readLine().toString(), is(line1)); assertThat(buffer.readLine().toString(), is(line2)); assertThat(buffer.readLine(), is((Buffer) null)); // now add CR + LF buffer = createReadableBuffer((line1 + "\r\n" + line2).getBytes()); assertThat(buffer.readLine().toString(), is(line1)); assertThat(buffer.readLine().toString(), is(line2)); assertThat(buffer.readLine(), is((Buffer) null)); // this one is a little trickier. Add LF + CR + LF, which should // result in line1, followed by empty line, followed by line 2 buffer = createReadableBuffer((line1 + "\n\r\n" + line2).getBytes()); assertThat(buffer.readLine().toString(), is(line1)); assertThat(buffer.readLine().toString(), is(new String(new byte[0]))); assertThat(buffer.readLine().toString(), is(line2)); assertThat(buffer.readLine(), is((Buffer) null)); } @Test public void testReadBytes() throws IOException { final ReadableBuffer buffer = createReadableBuffer(allocateByteArray(100)); final ReadableBuffer b1 = buffer.readBytes(10).toReadableBuffer(); // both should have 90 bytes left to read // assertThat(buffer.readableBytes(), is(90)); assertThat(buffer.readByte(), is((byte) 0x0a)); assertThat(buffer.readByte(), is((byte) 0x0b)); assertThat(buffer.readByte(), is((byte) 0x0c)); assertThat(buffer.readByte(), is((byte) 0x0d)); // the next buffer that will be read is the one at index 10 // even though we read some bytes off of the main // buffer, we should still be able to directly access // the bytes assertThat(buffer.getByte(0), is((byte) 0x00)); assertThat(buffer.getByte(5), is((byte) 0x05)); assertThat(buffer.getByte(16), is((byte) 0x10)); assertThat(buffer.getByte(32), is((byte) 0x20)); // and this one should be 10 of course assertThat(b1.getReadableBytes(), is(10)); assertThat(b1.capacity(), is(10)); assertThat(b1.getByte(0), is((byte) 0x00)); assertThat(b1.getByte(1), is((byte) 0x01)); assertThat(b1.getByte(2), is((byte) 0x02)); assertThat(b1.getByte(3), is((byte) 0x03)); assertThat(b1.getByte(4), is((byte) 0x04)); assertThat(b1.getByte(5), is((byte) 0x05)); assertThat(b1.getByte(6), is((byte) 0x06)); assertThat(b1.getByte(7), is((byte) 0x07)); assertThat(b1.getByte(8), is((byte) 0x08)); assertThat(b1.getByte(9), is((byte) 0x09)); // the getByte doesn't move the reader index so we should be able // to read through all the above again assertThat(b1.readByte(), is((byte) 0x00)); assertThat(b1.readByte(), is((byte) 0x01)); assertThat(b1.readByte(), is((byte) 0x02)); assertThat(b1.readByte(), is((byte) 0x03)); assertThat(b1.readByte(), is((byte) 0x04)); assertThat(b1.readByte(), is((byte) 0x05)); assertThat(b1.readByte(), is((byte) 0x06)); assertThat(b1.readByte(), is((byte) 0x07)); assertThat(b1.readByte(), is((byte) 0x08)); assertThat(b1.readByte(), is((byte) 0x09)); } @Test public void testSlice() throws Exception { final ReadableBuffer buffer = createReadableBuffer(allocateByteArray(100)); final ReadableBuffer b1 = buffer.slice(50, 70).toReadableBuffer(); assertThat(b1.capacity(), is(20)); assertThat(b1.readByte(), is((byte) 50)); assertThat(b1.getByte(0), is((byte) 50)); assertThat(b1.readByte(), is((byte) 51)); assertThat(b1.getByte(1), is((byte) 51)); assertThat(b1.getByte(19), is((byte) 69)); try { b1.getByte(20); fail("Expected an IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } try { b1.getByte(21); fail("Expected an IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } // sliceing it again is based on the seconds // buffer's point-of-view final ReadableBuffer b2 = b1.slice(b1.capacity()).toReadableBuffer(); // remember, we already read two bytes above so we should // be at 52 assertThat(b2.readByte(), is((byte) 52)); assertThat(b2.readByte(), is((byte) 53)); // since the b1 buffer already have 2 of its bytes // read, there are 18 bytes left assertThat(b2.capacity(), is(18)); assertThat(b2.getByte(17), is((byte) 69)); try { // the capacity is 18, which means that the last // index is 17, which means that trying to access // 18 should yield in an exception b2.getByte(18); fail("Expected an IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } // grab the entire b2 buffer final ReadableBuffer b3 = b2.slice(0, 18).toReadableBuffer(); assertThat(b3.capacity(), is(18)); assertThat(b3.readByte(), is((byte) 52)); assertThat(b3.getByte(b3.capacity() - 1), is((byte) 69)); } /** * Test to make sure that it is possible to mark the reader index, continue * reading and then reset the buffer and as such, continue from where we * last called marked... * * @throws Exception */ @Test public void testResetAndMarkReaderIndex() throws Exception { final ReadableBuffer buffer = createReadableBuffer(allocateByteArray(100)); // read and "throw away" 10 bytes buffer.readBytes(10); // make sure that the next byte that is being read is 10 assertThat(buffer.readByte(), is((byte) 0x0A)); // reset the buffer and make sure that now, the next // byte being read should be zero again buffer.resetReaderIndex(); assertThat(buffer.readByte(), is((byte) 0x00)); assertThat(buffer.readByte(), is((byte) 0x01)); // mark it and read a head, then check that we are in // the correct spot, reset and check that we are back again buffer.markReaderIndex(); assertThat(buffer.readByte(), is((byte) 0x02)); buffer.readBytes(10); assertThat(buffer.readByte(), is((byte) 0x0D)); buffer.resetReaderIndex(); assertThat(buffer.readByte(), is((byte) 0x02)); // make sure that it works for slices as well final ReadableBuffer slice = buffer.slice(30, 50).toReadableBuffer(); assertThat(slice.readByte(), is((byte) 30)); assertThat(slice.readByte(), is((byte) 31)); slice.resetReaderIndex(); assertThat(slice.readByte(), is((byte) 30)); slice.readBytes(5); slice.markReaderIndex(); assertThat(slice.readByte(), is((byte) 36)); assertThat(slice.readByte(), is((byte) 37)); assertThat(slice.readByte(), is((byte) 38)); slice.resetReaderIndex(); assertThat(slice.readByte(), is((byte) 36)); } @Test public void testReadProgression() { final ReadableBuffer buffer = createBuffer("hello world").toReadableBuffer(); // read the first 5 bytes... assertThat(buffer.readBytes(5).toString(), is("hello")); // which means that what we have left is " world". assertThat(buffer.toString(), is(" world")); // read 5 more bytes, which will consume almost all (not the 'd') assertThat(buffer.readBytes(5).toString(), is(" worl")); // so now we should only have a single 'd' left. assertThat(buffer.toString(), is("d")); // if we reset the reader index we can start over... buffer.setReaderIndex(0); } @Test public void testResetReaderIndex() { final ReadableBuffer buffer = createBuffer("more stuff to write about").toReadableBuffer(); assertThat(buffer.readBytes(10).toString(), is("more stuff")); assertThat(buffer.toString(), is(" to write about")); // rest the reader index... buffer.setReaderIndex(0); assertThat(buffer.readBytes(10).toString(), is("more stuff")); assertThat(buffer.toString(), is(" to write about")); // set to something else... buffer.setReaderIndex(5); assertThat(buffer.readBytes(10).toString(), is("stuff to w")); assertThat(buffer.toString(), is("rite about")); } /** * Make sure that slicing multiple times works since that is a very common * operation. * * @throws Exception */ @Test public void testDoubleSlice() throws Exception { final String str = "This is a fairly long sentance and all together this should be 71 bytes"; final ReadableBuffer buffer = createReadableBuffer(str); buffer.readByte(); final ReadableBuffer b1 = buffer.slice().toReadableBuffer(); assertThat(b1.toString(), is(str.substring(1))); final Buffer b2 = b1.readBytes(20); assertThat(b2.toString(), is(str.subSequence(1, 21))); // now, slice the already sliced b1_1. Since we haven't ready anything // from b1_1Slice just yet we should end up with the exact same thing. final Buffer b2Slice = b2.slice(); assertThat(b2Slice.toString(), is(str.subSequence(1, 21))); final Buffer again = b2Slice.slice(4, 10); assertThat(again.toString(), is("is a f")); } /** * Test the read until on a sliced buffer. * * @throws Exception */ @Test public void testReadUntilFromSlicedBuffer() throws Exception { final ReadableBuffer original = createReadableBuffer("hello world this is going to be a longer one".getBytes()); final ReadableBuffer buffer = original.slice(6, original.capacity()).toReadableBuffer(); final Buffer world = buffer.readUntil((byte) ' '); assertThat(world.toString(), is("world")); final Buffer longer = buffer.readUntil((byte) 'a'); assertThat(longer.toString(), is("this is going to be ")); final Buffer theRest = buffer.readLine(); assertThat(theRest.toString(), is(" longer one")); } @Test public void testReadFromSliced() { final ReadableBuffer buffer = createBuffer("lets test some sliced reading").toReadableBuffer(); final ReadableBuffer slice01 = buffer.readBytes(15).toReadableBuffer(); assertThat(slice01.toString(), is("lets test some ")); assertThat(slice01.readBytes(4).toString(), is("lets")); assertThat(slice01.readBytes(5).toString(), is(" test")); final ReadableBuffer slice02 = buffer.readBytes(8).toReadableBuffer(); assertThat(slice02.toString(), is("sliced r")); assertThat(slice02.setReaderIndex(1).readBytes(3).toString(), is("lic")); assertThat(slice02.readBytes(4).toString(), is("ed r")); ensureUnableToRead(slice02, b -> b.readByte()); // should be at the end so if we try again, we should blow up } /** * Ensure we can't set the reader index to outside the capacity of the buffer */ @Test public void setBadReaderIndex() { final String content = "checking the reader index"; final ReadableBuffer buffer = createBuffer(content).toReadableBuffer(); assertThat(buffer.capacity(), is(content.length())); // set to the very last index is ok though buffer.setReaderIndex(content.length()); assertThat(buffer.hasReadableBytes(), is(false)); ensureUnableToRead(buffer, b -> b.readByte()); ensureUnableToRead(buffer, b -> b.readBytes(2)); ensureUnableToRead(buffer, b -> b.readUnsignedInt()); ensureUnableToSetReaderIndex(buffer, -1); ensureUnableToSetReaderIndex(buffer, content.length() + 1); } @Test public void testWriteToOutputStreamAfterRead() throws Exception { ensureWriteToOutputStream("one two three", 1); ensureWriteToOutputStream("one two three", 3); ensureWriteToOutputStream("a", 1); // off by 1 bugs... } @Test public void testStripEOLSpecialCase() throws Exception { ensureStripEOLSpecialCase("\r", 1); ensureStripEOLSpecialCase("\n", 1); ensureStripEOLSpecialCase("\r\n", 2); } @Test public void testStripEOLReadable() throws Exception { ensureStripEOL("no CRLF in this one", false, false, 5); ensureStripEOL("Just a CR here...\r", true, false, 3); ensureStripEOL("Just a LF in this one...\n", false, true, 5); ensureStripEOL("Alright, got both!\r\n", true, true, 5); ensureStripEOL("Note, this is not readUntilCRLF, this \r\n is strip so we should have the entire thing left", false, false); // and ensure we don't have a +1 off bug resulting, usually, in blowing up // in a spectacular way... ensureStripEOL("", false, false); ensureStripEOL("a", false, false); ensureStripEOL("a\r", true, false); ensureStripEOL("a\n", false, true); ensureStripEOL("a\r\n", true, true); ensureStripEOL("ab", false, false); ensureStripEOL("ab\r", true, false); ensureStripEOL("ab\n", false, true); ensureStripEOL("ab\r\n", true, true); } @Test public void testEqualsHashCodeWithReadable() throws Exception { final ReadableBuffer b1 = createReadableBuffer("hello world"); final ReadableBuffer b2 = createReadableBuffer("hello world"); assertThat(b1, is(b2)); assertThat(b1.hashCode(), is(b2.hashCode())); final ReadableBuffer b3 = createBuffer("hello not world").toReadableBuffer(); assertThat(b1, is(not(b3))); assertThat(b1.hashCode(), is(not(b3.hashCode()))); assertThat(b2, is(not(b3))); // because the way we do equals right now when one of the // buffers has read a head they are no longer equal. // One motivation is because the bytes that have been // consumed actually can be discarded... b2.readByte(); assertThat(b1, is(not(b2))); assertThat(b1.hashCode(), is(not(b2.hashCode()))); // because of this, if we now read a head in both // b1 and b3 and only leave the "world" portion left // then all of a sudden b1 and b3 actually are equal b1.readBytes(6); b3.readBytes(10); assertThat(b1, is(b3)); assertThat(b1.hashCode(), is(b3.hashCode())); final ReadableBuffer a1 = createReadableBuffer("123 world"); final ReadableBuffer a2 = createReadableBuffer("456 world"); assertThat(a1, not(a2)); assertThat(a1.hashCode(), not(a2.hashCode())); final Buffer a1_1 = a1.readBytes(3); final Buffer a2_1 = a2.readBytes(3); assertThat(a1_1, not(a2_1)); assertThat(a1_1.hashCode(), not(a2_1.hashCode())); // now they should be equal final Buffer a1_2 = a1.slice(); final Buffer a2_2 = a2.slice(); assertThat(a1_2, is(a2_2)); assertThat(a1_2.hashCode(), is(a2_2.hashCode())); final Buffer a1_3 = a1.readBytes(5); final Buffer a2_3 = a2.readBytes(5); assertThat(a1_3, is(a2_3)); assertThat(a1_3.hashCode(), is(a2_3.hashCode())); final ReadableBuffer from = createReadableBuffer("From"); final ReadableBuffer fromHeader = createReadableBuffer("some arbitrary crap first then From and then some more shit"); fromHeader.readBytes(31); final Buffer fromAgain = fromHeader.readBytes(4); assertThat(fromAgain.toString(), is("From")); assertThat(fromAgain, is(from)); // TODO: bug - the decision to implement the ReadableBuffer through delegation instead // has come back to bit us... // assertThat(from, is(fromAgain)); } /** * Bug found when parsing a SIP URI. The port wasn't picked up because we * were doing parseToInt without regards to the offset within the buffer * * @throws Exception */ @Test public void testParseAsIntBugWhenParsingSipURI() throws Exception { final ReadableBuffer b = Buffers.wrap("sip:alice@example.com:5099").toReadableBuffer(); assertThat(b.readBytes(4).toString(), is("sip:")); assertThat(b.readBytes(5).toString(), is("alice")); assertThat(b.readByte(), is((byte) '@')); final ReadableBuffer hostPort = b.slice().toReadableBuffer(); assertThat(hostPort.toString(), is("example.com:5099")); assertThat(hostPort.readBytes(11).toString(), is("example.com")); final ReadableBuffer host = hostPort.slice(0, 11).toReadableBuffer(); assertThat(host.toString(), is("example.com")); assertThat(hostPort.readByte(), is((byte) ':')); assertThat(hostPort.parseToInt(), is(5099)); } /** * * @throws Exception */ @Test public void testWrapArraySpecifyingTheWindows() throws Exception { final ReadableBuffer buffer = Buffers.wrap("hello world".getBytes(), 3, 9).toReadableBuffer(); assertThat(buffer.toString(), is("lo wor")); assertThat(buffer.getByte(0), is((byte) 'l')); assertThat(buffer.getByte(1), is((byte) 'o')); assertThat(buffer.readByte(), is((byte) 'l')); assertThat(buffer.readByte(), is((byte) 'o')); assertThat(buffer.getByte(0), is((byte) 'l')); assertThat(buffer.getByte(1), is((byte) 'o')); } /** * * @throws Exception */ @Test public void testClone() throws Exception { final Buffer buffer = Buffers.wrap(allocateByteArray(100)); final Buffer clone = (Buffer)buffer.clone(); assertBuffers(buffer, clone); // make sure that cloning slices are also // correct final Buffer slice = clone.slice(30, 40); assertThat(slice.getByte(0), is((byte) 30)); final Buffer sliceClone = (Buffer)slice.clone(); assertBuffers(sliceClone, slice); } /** * For a readable buffer, when to we do {@link Buffer#toBuffer()} any bytes that have been * consumed by reading past them should not be included in the new of the {@link Buffer} that * is returned. * * @throws Exception */ @Test public void testToBuffer() throws Exception { final ReadableBuffer buffer = createReadableBuffer("hello world"); buffer.readUntilWhiteSpace(); assertThat(buffer.toBuffer().toString(), is("world")); } private static void assertBuffers(final Buffer b1, final Buffer b2) throws Exception { // make sure they are the exact same size and have // the same content etc assertThat(b1.capacity(), is(b2.capacity())); for (int i = 0; i < b1.capacity(); ++i) { assertThat(b1.getByte(i), is(b2.getByte(i))); } } /** * Special case where we expect buffer that's left to be empty. Was easier to separate out * this test case since otherwise the actual unit test became too complicated and too much * code in it. don't want to debug the actual unit test itself! * * @param line * @param read */ protected void ensureStripEOLSpecialCase(final String line, final int read) { final ReadableBuffer buffer = createReadableBuffer(line); buffer.readBytes(read); final Buffer stripped = buffer.stripEOL(); assertThat(stripped.isEmpty(), is(true)); assertThat(stripped.toString(), is("")); } protected void ensureStripEOL(final String line, final boolean cr, final boolean lf, final int read) { final ReadableBuffer buffer = createReadableBuffer(line); buffer.readBytes(read); final Buffer stripped = buffer.stripEOL(); if (cr && lf) { assertThat(buffer.getReadableBytes(), is(stripped.capacity() + 2)); assertThat(stripped.toString(), is(line.substring(read, line.length() - 2))); } else if (cr || lf) { assertThat(buffer.getReadableBytes(), is(stripped.capacity() + 1)); assertThat(stripped.toString(), is(line.substring(read, line.length() - 1))); } else { // neither so should be the exact same. assertThat(buffer, is(stripped)); } } private void ensureWriteToOutputStream(final String data, final int readNoOfBytes) throws IOException { // first make sure that writing the entire data does indeed mean that all that // data is written and that is what we get back as well... final ReadableBuffer b1 = (ReadableBuffer)createBuffer(data); final ByteArrayOutputStream out = new ByteArrayOutputStream(); b1.writeTo(out); assertThat(b1.toString(), is(out.toString())); assertThat(b1.toString(), is(data)); // now to the real test. If you then read from the buffer, the write to OutputStream // should then NOT include the data that was read. if (readNoOfBytes > 0) { final Buffer slice = b1.readBytes(readNoOfBytes); final String expected = data.substring(0, readNoOfBytes); assertThat(slice.toString(), is(expected)); final ByteArrayOutputStream outAgain = new ByteArrayOutputStream(); b1.writeTo(outAgain); final String whatsLeftExpected = data.substring(readNoOfBytes, data.length()); assertThat(b1.toString(), is(outAgain.toString())); assertThat(b1.toString(), is(whatsLeftExpected)); // also then try a slice of the slice... assuming the slice has anything left to read from it. final ReadableBuffer readableSlice = slice.toReadableBuffer(); if (readableSlice.hasReadableBytes()) { readableSlice.readByte(); final ByteArrayOutputStream outAgain2 = new ByteArrayOutputStream(); readableSlice.writeTo(outAgain2); // remember, we are operating on the first slice, which is the // very first part of the original data... final String whatsLeft2 = expected.substring(1); assertThat(readableSlice.toString(), is(outAgain2.toString())); assertThat(readableSlice.toString(), is(whatsLeft2)); } } } /** * Simple helper method to allocate an array of bytes. Each byte in the * array will just be +1 from the previous, making it easy to test the * various operations, such as slice, getByte etc (since you know exactly * what to expect at each index) * * @param length * @return */ protected static byte[] allocateByteArray(final int length) { final byte[] array = new byte[length]; for (int i = 0; i < length; ++i) { array[i] = (byte) i; } return array; } private static void ensureUnableToRead(final ReadableBuffer buffer, final Consumer<ReadableBuffer> fn) { try { fn.accept(buffer); fail("expected to fail here..."); } catch (final IndexOutOfBoundsException e) { // expected... } } private static void ensureUnableToSetReaderIndex(final ReadableBuffer buffer, final int index) { try { buffer.setReaderIndex(index); fail("Expected to blow up"); } catch (final IllegalArgumentException e) { // expected } } /** * Convenience method for making sure that the buffer is indeed empty * * @param buffer */ private static void assertEmptyBuffer(final Buffer buffer) { assertThat(buffer.capacity(), is(0)); assertThat(buffer.isEmpty(), is(true)); } }
package com.trump.auction.back.activity.model; import lombok.Data; import lombok.ToString; import java.util.Date; @Data @ToString public class ActivityShare { private Integer id; private String activityId; private Integer shareEntrance; private String activityName; private Date startTime; private Date endTime; private String activityUrl; private String picUrl; private String title; private String subTitle; private String sharerPoints; private String sharerCoin; private String registerPoints; private String registerCoin; private Date createTime; private Integer status; }