text
stringlengths
10
2.72M
package com.example.pokeapppro.database.entity; import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "pokemon") public class PokemonDB { @PrimaryKey @NonNull @ColumnInfo(name = "pokemonName") private String pokemonName; @ColumnInfo(name = "pokemonImageURL") private String pokemonImageURL; @ColumnInfo(name = "pokemonId") private String pokemonId; @ColumnInfo(name = "pokemonURL") private String pokemonURL; @ColumnInfo(name = "pokemonFavorite") private Boolean pokemonFavorite; @ColumnInfo(name = "pokemonRecent") private Boolean pokemonRecent; public PokemonDB(@NonNull String pokemonName, String pokemonImageURL, String pokemonId, String pokemonURL, Boolean pokemonFavorite, Boolean pokemonRecent) { this.pokemonName = pokemonName; this.pokemonImageURL = pokemonImageURL; this.pokemonId = pokemonId; this.pokemonURL = pokemonURL; this.pokemonFavorite = pokemonFavorite; this.pokemonRecent = pokemonRecent; } @NonNull public String getPokemonName() { return pokemonName; } public void setPokemonName(@NonNull String pokemonName) { this.pokemonName = pokemonName; } public String getPokemonImageURL() { return pokemonImageURL; } public void setPokemonImageURL(String pokemonImageURL) { this.pokemonImageURL = pokemonImageURL; } public String getPokemonId() { return pokemonId; } public void setPokemonId(String pokemonId) { this.pokemonId = pokemonId; } public String getPokemonURL() { return pokemonURL; } public void setPokemonURL(String pokemonURL) { this.pokemonURL = pokemonURL; } public Boolean getPokemonFavorite() { return pokemonFavorite; } public void setPokemonFavorite(Boolean pokemonFavorite) { this.pokemonFavorite = pokemonFavorite; } public Boolean getPokemonRecent() { return pokemonRecent; } public void setPokemonRecent(Boolean pokemonRecent) { this.pokemonRecent = pokemonRecent; } }
package co.khj.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DAO { Connection conn = null; // DB연결된 상태(세션)을 담은 객체 PreparedStatement psmt = null; // SQL 문을 나타내는 객체 ResultSet rs = null; // 쿼리문을 날린것에 대한 반환값을 담을 객체 public DAO() { // TODO Auto-generated constructor stub try { String user = "lee"; String pw = "1234"; String url = "jdbc:oracle:thin:@localhost:1521:xe"; Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection(url, user, pw); } catch (ClassNotFoundException cnfe) { System.out.println("DB 드라이버 로딩 실패 :"+cnfe.toString()); } catch (SQLException sqle) { System.out.println("DB 접속실패 : "+sqle.toString()); } catch (Exception e) { System.out.println("Unkonwn error"); e.printStackTrace(); } } private void close() { // TODO Auto-generated method stub try { if(rs != null) rs.close(); if(psmt != null) psmt.close(); if(conn != null) conn.close(); } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } } //라이브러리 리스트(사진만) 출력 //라이브러리 입력 //라이브러리 출력(단건) 출력 }
package com.oracle.notebookserver.interpreter; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.oracle.notebookserver.model.ProgramingLanguageEnum; @Component public class InterpreterContainer { private Map<String, AbstractInterpreter> interpretersMapPerSessionId = Collections.synchronizedMap(new HashMap<String, AbstractInterpreter>()); @Autowired private InterpreterFactory interpreterFactory; public AbstractInterpreter getInterpreterPerSessionId(ProgramingLanguageEnum programingLanguageEnum,String sessionId) { if(!interpretersMapPerSessionId.containsKey(sessionId)) { interpretersMapPerSessionId.put(sessionId,interpreterFactory.getInterpreter(programingLanguageEnum)); } System.out.println("sessionId " + sessionId); return interpretersMapPerSessionId.get(sessionId); } }
package com.vishaldwivedi.intelliJournal.Adapter; import android.content.Context; 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 android.widget.Toast; import com.vishaldwivedi.intelliJournal.Models.NavigationDrawerItem; import com.vishaldwivedi.intelliJournal.R; import java.util.Collections; import java.util.List; /** * Created by Vishal Dwivedi on 25/03/17. */ public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyVieHolder> { private List<NavigationDrawerItem> mDataList = Collections.EMPTY_LIST; private Context context; private LayoutInflater layoutInflater; public NavigationDrawerAdapter(Context context, List<NavigationDrawerItem> mData) { this.context = context; layoutInflater = LayoutInflater.from(context); this.mDataList = mData; } @Override public MyVieHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = layoutInflater.inflate(R.layout.nav_drawer_list_item,parent, false); MyVieHolder viewHolder = new MyVieHolder(view); return viewHolder; } @Override public void onBindViewHolder(final MyVieHolder holder, int position) { NavigationDrawerItem current = this.mDataList.get(position); holder.imgIcon.setImageResource(current.getImageID()); holder.title.setText(current.getTitle()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, holder.title.getText().toString(), Toast.LENGTH_SHORT).show(); } }); } @Override public int getItemCount() { return this.mDataList.size(); } class MyVieHolder extends RecyclerView.ViewHolder { TextView title; ImageView imgIcon; public MyVieHolder(View itemView){ super(itemView); title = (TextView)itemView.findViewById(R.id.navigation_item_title); imgIcon = (ImageView)itemView.findViewById(R.id.navigation_item_icon); } } }
/* I commenti a ciò che si sta testando sono nelle println così da rendere il risultato su terminale più leggibile. */ public class ShareDocTests { public static void main (String[] args) { ShareDocImpl tester = new ShareDocImpl(); System.out.println("\n1. Test: addUser(String nick, int password).\n Risultato atteso: true, false, false, true, true.\n"); System.out.println(tester.addUser("Giorgio", 123)); System.out.println(tester.addUser("Giorgio", 123)); System.out.println(tester.addUser("Giorgio", 456)); System.out.println(tester.addUser("Luca", 456)); System.out.println(tester.addUser("Ugo", 78910)); System.out.println("\n2. Test: verifico che non siano stati aggiunti né utenti con lo stesso nick né password senza utente.\n Risultato atteso: [Giorgio, Luca, Ugo]; [123, 456, 78910].\n"); System.out.println(tester.getUsersU()); System.out.println(tester.getPasswordsU()); System.out.println("\n3. Test: removeUser(String nick).\n"); tester.removeUser("Giorgio"); System.out.println("\n4. Test: verifico che la rimozione abbia avuto successo.\n Risultato atteso: [Luca, Ugo]; [456, 78910].\n"); System.out.println(tester.getUsersU()); System.out.println(tester.getPasswordsU()); System.out.println("\n5. Test: addDoc(String nick, String doc, int password).\n Risultato atteso: true, false, true.\n"); try { System.out.println(tester.addDoc("Luca", "Doc1", 456)); System.out.println(tester.addDoc("Luca", "Doc1", 456)); System.out.println(tester.addDoc("Ugo", "Doc2", 78910)); } catch(WrongIdException e) { e.printStackTrace(); } System.out.println("\n6. Test: verifico che non siano stati aggiunti documenti con lo stesso nome.\n Risultato atteso: [Luca, Ugo]; [Doc1, Doc2]; [456, 78910].\n"); System.out.println(tester.getUsersD()); System.out.println(tester.getDocsD()); System.out.println(tester.getPasswordsD()); System.out.println("\n7. Test: removeDoc(String nick, String doc, int password).\n Risultato atteso: true, false.\n"); try { System.out.println(tester.removeDoc("Luca", "Doc1", 456)); System.out.println(tester.removeDoc("Luca", "Doc1", 456)); } catch(WrongIdException e) { e.printStackTrace(); } System.out.println("\n8. Test: verifico che la rimozione abbia avuto successo.\n Risultato atteso: [Ugo]; [Doc2]; [78910].\n"); System.out.println(tester.getUsersD()); System.out.println(tester.getDocsD()); System.out.println(tester.getPasswordsD()); System.out.println("\n9. Test: readDoc(String nick, String doc, int password).\n Risultato atteso: \"Lettura eseguita con successo.\"\n"); try { tester.readDoc("Ugo", "Doc2", 78910); } catch(WrongIdException e) { e.printStackTrace(); } System.out.println("\n10. Test: shareDoc(String fromName, String toName, String doc, int password).\n Risultato atteso: {Luca=Doc2}\n"); try { tester.shareDoc("Ugo", "Luca", "Doc2", 78910); System.out.println(tester.getDocsShared()); } catch(WrongIdException e) { e.printStackTrace(); } System.out.println("\n11. Test: getNext(String user, int password).\n Risultato atteso: Doc2\n"); try { System.out.println(tester.getNext("Luca", 456)); } catch(WrongIdException e) { e.printStackTrace(); } catch(EmptyQueueException e) { e.printStackTrace(); } System.out.println("\n12. Test: verifico che Doc2 sia stato rimosso dalla lista delle condivisioni.\n Risultato atteso: {}.\n"); System.out.println(tester.getDocsShared()); } }
package com.website.vzw.User; import com.website.vzw.Address.Address; import com.website.vzw.City.City; import java.time.LocalDate; import java.util.Date; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "User") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "idUser") private Long idUser; @Column(name = "name") private String name; @Column(name = "surname") private String surname; @Column(name = "email") private String email; @Column(name = "birthDate") private Date birthDate; @Column(name = "gender") private String gender; @ManyToOne @JoinColumn(name = "fk_Address") private Address address; public User(String name, String surname, String email, Date birthDate, String gender, Address address) { this.name = name; this.surname = surname; this.email = email; this.birthDate = birthDate; this.gender = gender; this.address = address; this.address = address; } public User() {} public Long getIdUser() { return idUser; } public void setIdUser(Long idUser) { this.idUser = idUser; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
package it.bibliotecaweb.servlet.utente; import java.io.IOException; 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.Utente; import it.bibliotecaweb.service.MyServiceFactory; /** * Servlet implementation class ConfermaDisattivazioneUtenteServlet */ @WebServlet("/ExecuteDeleteUtenteServlet") public class ExecuteDeleteUtenteServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ExecuteDeleteUtenteServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); if (id != null && !id.equals("")) { try { Utente utente = MyServiceFactory.getUtenteServiceInstance().findById(Integer.parseInt(id)); MyServiceFactory.getUtenteServiceInstance().delete(utente);; request.setAttribute("effettuato", "Utente eliminato!"); request.getRequestDispatcher("ListaUtentiServlet").forward(request, response); } catch (Exception e) { e.printStackTrace(); } } request.setAttribute("errore", "Nessun utente selezionato!"); request.getRequestDispatcher("ListaUtentiServlet").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package patterns.creational.builder; public class ProductBuilder extends Builder { public ProductBuilder(Product product) { super(product); } @Override public void buildPartA() { product.setPartA("partA"); } @Override public void buildPartB() { product.setPartB("partB"); } public Product getProduct() { return product; } }
package br.com.pwc.nfe.integracao.xml; import java.io.File; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.annotation.PostConstruct; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import br.com.pwc.nfe.integracao.xml.config.ConfigEnum; import br.com.pwc.nfe.integracao.xml.config.IntegradorXmlMessageFactory; import br.com.pwc.nfe.integracao.xml.util.FileManager; import br.com.pwc.nfe.integracao.xml.util.FilenameFilterImpl; import br.com.pwc.nfe.integracao.xml.util.XmlInspector; /** * Classe responavel pela tarefa de integração. * * @author sergio.moreira * @author daniel.santos * */ @Scope(value="singleton") @Component public class RunJobTask { private static Logger LOGGER = Logger.getLogger(RunJobTask.class); @Autowired private Integrador integrador; @Autowired private XmlInspector inspector; @Autowired private IntegradorXmlMessageFactory messageFactory; @Resource(name = "configPrincipal") private Properties configProperties; @Autowired private FileManager fileManager; private Thread[] arrayDeThreads; private FileReader[] arrayDeLeitores; private int QTD_THREADS_ENVIO; private int fim; private int inicio; private int totalDeArquivos; private int sobra; private int qtdDeArquivosParaCadaThread; private File pastaDeEnvio; private File pastaErroDeComunicacao; private static ExecutorService executorService; @PostConstruct public void init() { QTD_THREADS_ENVIO = Integer.valueOf(configProperties.getProperty(ConfigEnum.INTEGRACAO_QTD_MSG_BUFFER.getKey())); executorService = Executors.newFixedThreadPool(QTD_THREADS_ENVIO); arrayDeLeitores = new FileReader[QTD_THREADS_ENVIO]; for (int i = 0; i < QTD_THREADS_ENVIO; i++) { arrayDeLeitores[i] = new FileReader(messageFactory, inspector, integrador, fileManager, configProperties); } // restaura arquivos das pastas de envio e falha na comunicação fileManager.configuraPastasDoSistema(); } public void execute() { for(int j = 0; j < QTD_THREADS_ENVIO; j++) { executorService.execute(arrayDeLeitores[j]); } } /** * Método que executa o processo de integração. */ public void executeOld() { // Movo os arquivos de erro de comunicação para a pasta de envio File[] arquivos = pastaErroDeComunicacao.listFiles(); fileManager.moveAllFiles(arquivos, pastaDeEnvio); LOGGER.info(messageFactory.getMessage(LISTANDO_ARQUIVOS_DE_ENVIO)); File[] files = pastaDeEnvio.listFiles(new FilenameFilterImpl(SUFFIX)); totalDeArquivos = files.length; if(totalDeArquivos > 0) { LOGGER.info(messageFactory.getMessage(MSG_INICIANDO_INTEGRACAO)); // Divido o total de arquivos pela quantidade de threads de envio // para saber com quantos arquivos cada thread irá trabalhar qtdDeArquivosParaCadaThread = totalDeArquivos / QTD_THREADS_ENVIO; // A divisão anterior pode não ser exata então irá restar // arquivos para serem enviados por outra thread sobra = totalDeArquivos % QTD_THREADS_ENVIO; if(qtdDeArquivosParaCadaThread > 0) { // cria o array de threads e o array de leitores arrayDeThreads = new Thread[QTD_THREADS_ENVIO]; arrayDeLeitores = new FileReader[QTD_THREADS_ENVIO]; // variáveis usadas para controlar // o intervalo de arquivos da pasta de envio inicio = 0; fim = qtdDeArquivosParaCadaThread; // monta os arrays de arquivos para serem enviados for(int i = 0; i < QTD_THREADS_ENVIO; i++) { ConcurrentHashMap<String, File> mapaDeArquivos = new ConcurrentHashMap<String, File>(); // percorre o intervalo de arquivos que será colocado em cada mapa for(int j = inicio; j < fim; j++) { File newFile = new File(files[j].getAbsolutePath() + SUFFIX); files[j].renameTo(newFile); // Se o arquivo é inválido move para pasta de inválidos if (!inspector.isValid(newFile)) { File destino = fileManager.file(configProperties.getProperty( ConfigEnum.INTEGRACAO_DIR_INVALIDOS.getKey()), newFile.getName()); LOGGER.info(messageFactory.getMessage(MSG_MOVENDO_PARA_INVALIDO) + " " + newFile.getName()); fileManager.moveFile(newFile, destino); } else { mapaDeArquivos.put(newFile.getName(), newFile); } } if(mapaDeArquivos.size() > 0) { // passa o mapa para o leitor executar // arrayDeLeitores[i] = new FileReader( // mapaDeArquivos, messageFactory, inspector, integrador, fileManager, configProperties); arrayDeThreads[i] = new Thread(arrayDeLeitores[i]); arrayDeThreads[i].setName(NAME_OF_THREADS + (i+1)); arrayDeThreads[i].start(); } // Ajusta o inicio e fim do próximo intervalo de arquivos inicio = fim; fim = fim + qtdDeArquivosParaCadaThread; } } // processa os arquivos que restaram da divisão if(sobra > 0) { ConcurrentHashMap<String, File> mapaDeArquivos = new ConcurrentHashMap<String, File>(); //o laço é decrescente porque quero os ultimos arquivos do array de files for(int k = totalDeArquivos; k > qtdDeArquivosParaCadaThread * QTD_THREADS_ENVIO; k--) { File newFile = new File(files[k-1].getAbsolutePath() + SUFFIX); files[k-1].renameTo(newFile); // Se o arquivo é inválido movo para pasta de inválidos if (!inspector.isValid(newFile)) { File destino = fileManager.file(configProperties.getProperty( ConfigEnum.INTEGRACAO_DIR_INVALIDOS.getKey()), newFile.getName()); LOGGER.info(messageFactory.getMessage(MSG_MOVENDO_PARA_INVALIDO) + " " + newFile.getName()); fileManager.moveFile(newFile, destino); } else { // Adiciona o sufixo no nome para não ser listado novamente mapaDeArquivos.put(newFile.getName(), newFile); } } if(mapaDeArquivos.size() > 0) { // Thread thread = new Thread(new FileReader( // mapaDeArquivos, messageFactory, inspector, // integrador, fileManager, configProperties)); // thread.setName(NAME_OF_THREADS + (QTD_THREADS_ENVIO + 1)); // thread.start(); } } } else { LOGGER.info(messageFactory.getMessage(MSG_NAO_EXISTEM_MENSAGENS)); } } public static ExecutorService getExecutorService() { return executorService; } private final static String SUFFIX = "~"; private static final String NAME_OF_THREADS = "FileReader "; private static final String MSG_INICIANDO_INTEGRACAO = "msgIniciandoIntegracao"; private static final String LISTANDO_ARQUIVOS_DE_ENVIO = "msgListandoArquivos"; private static final String MSG_NAO_EXISTEM_MENSAGENS = "msgNaoExistemMensagens"; private static final String MSG_MOVENDO_PARA_INVALIDO = "msgMovendoXmlParaInvalidos"; }
package com.seboid.udemcalendrier; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.Toast; public class ActivityDebug extends Activity implements OnClickListener { Button eventsB; Button majB; Button resetB; Button catB; Button souscatB; Button groupeB; Button lieuxB; // busy affichage IntentFilter busyFilter; BusyReceiver busyR; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); getWindow().requestFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.activity_debug); // setProgressBarIndeterminateVisibility(true); // setProgressBarVisibility(true); // setProgress(5000); eventsB=(Button)findViewById(R.id.buttonEvents); eventsB.setOnClickListener(this); majB=(Button)findViewById(R.id.buttonMAJ); majB.setOnClickListener(this); resetB=(Button)findViewById(R.id.buttonReset); resetB.setOnClickListener(this); catB=(Button)findViewById(R.id.buttonCat); catB.setOnClickListener(this); souscatB=(Button)findViewById(R.id.buttonSCat); souscatB.setOnClickListener(this); groupeB=(Button)findViewById(R.id.buttonGroupes); groupeB.setOnClickListener(this); lieuxB=(Button)findViewById(R.id.buttonLieux); lieuxB.setOnClickListener(this); // le busy receiver busyR=new BusyReceiver(); busyFilter=new IntentFilter("com.seboid.udem.BUSY"); } @Override protected void onResume() { super.onResume(); registerReceiver(busyR,busyFilter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(busyR); } // // un broadcast receiver pour affiche le status "busy"... // on veut afficher busy quand le service travaille... // class BusyReceiver extends BroadcastReceiver { @Override public void onReceive(Context ctx, Intent in) { Bundle b=in.getExtras(); boolean busy = b.getBoolean("busy"); int p = b.getInt("progress",-1); // 0--10000 if( b.containsKey("busy") ) { setProgressBarIndeterminateVisibility(busy); setProgressBarVisibility(busy); } if( p>0 ) setProgress(p); //Loader<CursorFeedCount> loader=getSupportLoaderManager().getLoader(LOADER_ID); //loader.forceLoad(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { Intent in; switch( v.getId() ) { case R.id.buttonMAJ: //Toast.makeText(ActivityDebug.this, "service is "+ServiceMiseAJour.class.getName(),Toast.LENGTH_LONG).show(); in = new Intent(ActivityDebug.this,ServiceMiseAJour.class); ActivityDebug.this.startService(in); // Calendar cal = Calendar.getInstance(); // Intent intent = new Intent(Intent.ACTION_EDIT); // intent.setType("vnd.android.cursor.item/event"); // intent.putExtra("beginTime", cal.getTimeInMillis()); // intent.putExtra("allDay", false); // intent.putExtra("rrule", "FREQ=DAILY"); // intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000); // intent.putExtra("title", "A Test Event from android app"); // startActivity(intent); break; case R.id.buttonEvents: // in = new Intent(this,ActivityDebugEvents.class); in = new Intent(this,ActivityDebugEventsSwipe.class); startActivity(in); break; case R.id.buttonReset: DBHelper dbh=new DBHelper(this); dbh.resetDB(); break; case R.id.buttonCat: in = new Intent(this,ActivityDebugEvents.class); { String[] from= {"_id","desc"}; int[] to= { R.id.text_t2,R.id.text_t1 }; in.putExtra("from", from); in.putExtra("to",to); in.putExtra("query","select _id,desc from "+DBHelper.TABLE_C+" order by desc asc"); in.putExtra("title","Categories"); in.putExtra("layout", R.layout.categories_row); in.putExtra("type",1); // categories startActivity(in); } break; case R.id.buttonSCat: in = new Intent(this,ActivityDebugEvents.class); { String[] from= {"_id","desc"}; int[] to= { R.id.text_t2,R.id.text_t1 }; in.putExtra("from", from); in.putExtra("to",to); in.putExtra("query","select _id,desc from "+DBHelper.TABLE_SC+" order by desc asc"); in.putExtra("title","Sous-Categories"); in.putExtra("layout", R.layout.categories_row); in.putExtra("type",2); // sous-categories startActivity(in); } break; case R.id.buttonGroupes: in = new Intent(this,ActivityDebugEvents.class); { String[] from= {"_id","desc"}; int[] to= { R.id.text_t2,R.id.text_t1 }; in.putExtra("from", from); in.putExtra("to",to); in.putExtra("query","select _id,desc from "+DBHelper.TABLE_G+" order by desc asc"); in.putExtra("title","Groupes"); in.putExtra("layout", R.layout.categories_row); in.putExtra("type",3); // groupes startActivity(in); } break; case R.id.buttonLieux: in = new Intent(this,ActivityDebugEvents.class); { String[] from= {"_id","desc"}; int[] to= { R.id.text_t2,R.id.text_t1 }; in.putExtra("from", from); in.putExtra("to",to); in.putExtra("query","select _id,desc,latitude,longitude from "+DBHelper.TABLE_L+" order by desc asc"); in.putExtra("title","Lieux"); in.putExtra("layout", R.layout.categories_row); in.putExtra("type",/*4*/5); // lieux 4=show events, 5=show map startActivity(in); } break; } } }
package com.yyter.ui4android.widget; import android.content.Context; import android.util.AttributeSet; /** * 该View确保宽和高相等,因此当指定的宽高或者图片原本的宽高不同时, * 将取两者的较小值。 * Created by yyter on 2014/12/6. */ public class CircleImageView extends RoundCornerImageView { public CircleImageView(Context context) { super(context); } public CircleImageView(Context context, AttributeSet attrs) { super(context, attrs); } public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); int radius = (int) (w * 0.5f + 0.5f); setxRadius(radius); setyRadius(radius); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int size = Math.min(getMeasuredWidth(), getMeasuredHeight()); setMeasuredDimension(size, size); } }
package com.design.factory.AbstractFactory; public class XVeggiesOfMushroom implements XVeggies { public String toString() { return "Mushrooms"; } }
package ru.vlapin.demo.paveldemo; import javax.annotation.PostConstruct; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; import org.springframework.context.annotation.Bean; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; @SpringBootApplication @ConfigurationPropertiesScan public class PavelDemoApplication { public PavelDemoApplication() { System.out.println("1 = " + 1); } public static void main(String[] args) { SpringApplication.run(PavelDemoApplication.class, args); // Arrays.stream("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." // .split(" ")) // .max((o1, o2) -> // (int) (o1.chars().filter(value -> (char) value == 'o').count() - o2.chars().filter(value -> (char) value == 'o').count())) // .ifPresent(System.out::println); } @Bean Integer integer() { return 555; } @PostConstruct private void init() { System.out.println("2 = " + 2); } @EventListener public void afterContextInitialization(ContextRefreshedEvent __) { System.out.println("3 = " + 3); } }
package com.zimu.ao.controller; import com.zimu.ao.enums.Status; /** * 状态控制器 * 控制玩家当前正在进行的状态(战斗状态,购物状态,等等) * @author zimu * */ public class StatusController { private Status status; public StatusController() { status = Status.NONE; } public void active(Status status) { this.status = status; } public void deactive() { status = Status.NONE; } public Status status() { return status; } public boolean inUnmovableStatus() { return status != Status.NONE; } }
import java.util.Scanner; public class Sumar{ public static void main(String[]arg){ Scanner Lee=new Scanner(System.in); int a,b,c=0,d=0; System.out.print("Dame un numero: "); a=Lee.nextInt(); System.out.print("Dame un numero mayor: "); b=Lee.nextInt(); a+=1; int i=a; while(i<b){ c+=i; System.out.print(i+" "); i++; } System.out.print("="+" "+c); System.out.print("\n"); for(int j=a;j<b;j++){ d+=j; System.out.print(j+" "); } System.out.print("="+" "+d); } }
package com.citi.yourbank.vo; import javax.validation.constraints.NotNull; import io.swagger.annotations.ApiModel; import lombok.Data; @ApiModel("RegisterUserRequest") @Data public class RegisterUserRequestVO { @NotNull private String userId; private String password; @NotNull private String emailId; @NotNull private String firstName; @NotNull private String lastName; private String phoneNumber; }
package com.example.xiaojw.tamodel; import okhttp3.Call; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part; import rx.Observable; public interface TA { @Multipart @POST("upload") retrofit2.Call<ResponseBody> upload(@Part("description")RequestBody des, @Part MultipartBody.Part file); }
/* * Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE file for licensing information. * * Created on 16 gru 2015 * Author: K. Benedyczak */ /** * Actions for the output translation profile. Not in the core module as depend on some types from this package * @author K. Benedyczak */ package pl.edu.icm.unity.stdext.translation.out;
// ********************************************************** // 1. 제 목: TORON ADMIN BEAN // 2. 프로그램명: ToronAdminBean.java // 3. 개 요: 토론방 관리자 bean // 4. 환 경: JDK 1.3 // 5. 버 젼: 1.0 // 6. 작 성: 박진희 2003. 7. 22 // 7. 수 정: // ********************************************************** package com.ziaan.study; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.DataBox; import com.ziaan.library.ErrorManager; import com.ziaan.library.ListSet; import com.ziaan.library.RequestBox; import com.ziaan.library.SQLString; import com.ziaan.library.StringManager; public class ToronAdminBean { public ToronAdminBean() { } /** 과목별 토론방 리스트 @param box receive from the form object and session @return ArrayList */ public ArrayList selectSubjToronList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls1 = null; ListSet ls2 = null; ArrayList list1 = null; ArrayList list2 = null; String sql1 = ""; String sql2 = ""; ToronData data1 = null; ToronData data2 = null; String v_Bcourse = ""; // 이전코스 String v_course = ""; // 현재코스 String v_Bcourseseq= ""; // 이전코스기수 String v_courseseq = ""; // 현재코스기수 int l = 0; String ss_grcode = box.getStringDefault("s_grcode","ALL"); // 교육그룹 String ss_gyear = box.getStringDefault("s_gyear","ALL"); // 년도 String ss_grseq = box.getStringDefault("s_grseq","ALL"); // 교육기수 String ss_uclass = box.getStringDefault("s_upperclass","ALL"); // 과목분류 String ss_mclass = box.getStringDefault("s_middleclass","ALL"); // 과목분류 String ss_lclass = box.getStringDefault("s_lowerclass","ALL"); // 과목분류 String ss_subjcourse=box.getStringDefault("s_subjcourse","ALL");// 과목&코스 String ss_subjseq = box.getStringDefault("s_subjseq","ALL"); // 과목 기수 String ss_action = box.getString("s_action"); String v_orderColumn = box.getString("p_orderColumn"); // 정렬할 컬럼명 String v_orderType = box.getString("p_orderType"); // 정렬할 순서 String s_userid = box.getSession("userid"); String s_gadmin = box.getSession("gadmin"); String v_gadmin = StringManager.substring(s_gadmin, 0, 1); try { if ( ss_action.equals("go") ) { connMgr = new DBConnectionManager(); list1 = new ArrayList(); list2 = new ArrayList(); // select grcode,gyear,grseq,course,scsubj,scyear,scsubjseq,scsubjnm,subj,year,subjseq,subjnm,edustart, // eduend,grcodenm,tpcnt,isonoff sql1 = "\n select a.grcode, a.gyear, a.grseq, a.course, a.scsubj, a.scyear, a.scsubjseq, a.scsubjnm, a.subj, a.year, a.subjseq "; sql1 += "\n , a.subjseqgr, a.subjnm, a.edustart, a.eduend, get_codenm('0004',a.isonoff) isonoff "; sql1 += "\n , (select grcodenm from tz_grcode where grcode = a.grcode) as grcodenm "; sql1 += "\n , (select count(*) from tz_torontp where subj = a.subj and year = a.year and subjseq = a.subjseq) as tpcnt, a.isonoff "; sql1 += "\n from vz_scsubjseq a "; if (v_gadmin.equals("P")) { sql1 += "\n , tz_classtutor d "; } sql1 += "\n where 1 = 1 "; if (v_gadmin.equals("P")) { sql1+="\n and a.subj = d.subj " + "\n and a.year = d.year " + "\n and a.subjseq = d.subjseq " + "\n and d.tuserid = " + SQLString.Format(s_userid); } if ( !ss_grcode.equals("ALL") ) { sql1 += "\n and a.grcode = '" + ss_grcode + "'"; } if ( !ss_gyear.equals("ALL") ) { sql1 += "\n and a.gyear = '" + ss_gyear + "'"; } if ( !ss_grseq.equals("ALL") ) { sql1 += "\n and a.grseq = '" + ss_grseq + "'"; } if ( !ss_uclass.equals("ALL") ) { sql1 += "\n and a.scupperclass = '" + ss_uclass + "'"; } if ( !ss_mclass.equals("ALL") ) { sql1 += "\n and a.scmiddleclass = '" + ss_mclass + "'"; } if ( !ss_lclass.equals("ALL") ) { sql1 += "\n and a.sclowerclass = '" + ss_lclass + "'"; } if ( !ss_subjcourse.equals("ALL") ) { sql1 += "\n and a.scsubj = '" + ss_subjcourse + "'"; } if ( !ss_subjseq.equals("ALL") ) { sql1 += "\n and a.scsubjseq = '" + ss_subjseq + "'"; } if ( v_orderColumn.equals("") ) { sql1 += " order by a.course, a.cyear, a.courseseq, a.subj, a.year, a.subjseqgr,a.subjseq "; } else { sql1 += "\n order by a.course, a.cyear, a.courseseq, " + v_orderColumn + v_orderType; } ls1 = connMgr.executeQuery(sql1); while ( ls1.next() ) { data1 = new ToronData(); data1.setGrcode( ls1.getString("grcode") ); data1.setGyear( ls1.getString("gyear") ); data1.setGrseq( ls1.getString("grseq") ); data1.setCourse( ls1.getString("course") ); data1.setScsubj( ls1.getString("scsubj") ); data1.setScyear( ls1.getString("scyear") ); data1.setScsubjseq( ls1.getString("scsubjseq") ); data1.setScsubjnm( ls1.getString("Scsubjnm") ); data1.setSubj( ls1.getString("subj") ); data1.setYear( ls1.getString("year") ); data1.setSubjseq( ls1.getString("subjseq") ); data1.setSubjseqgr( ls1.getString("subjseqgr") ); data1.setSubjnm( ls1.getString("subjnm") ); data1.setEdustart( ls1.getString("edustart") ); data1.setEduend( ls1.getString("eduend") ); data1.setGrcodenm( ls1.getString("grcodenm") ); data1.setCnt( ls1.getInt("tpcnt") ); data1.setIsonoff( ls1.getString("isonoff") ); list1.add(data1); } for ( int i = 0;i < list1.size(); i++ ) { data2 = (ToronData)list1.get(i); v_course = data2.getCourse(); v_courseseq = data2.getScsubjseq(); if ( !v_course.equals("000000") && !(v_Bcourse.equals(v_course) && v_Bcourseseq.equals(v_courseseq))) { sql2 = "select count(subj) cnt from TZ_SUBJSEQ "; sql2 += "where course = '" + v_course + "' and courseseq = '" +v_courseseq + "' "; if ( !ss_grcode.equals("ALL") ) { sql2 += " and grcode = '" + ss_grcode + "'"; } if ( !ss_gyear.equals("ALL") ) { sql2 += " and gyear = '" + ss_gyear + "'"; } if ( !ss_grseq.equals("ALL") ) { sql2 += " and grseq = '" + ss_grseq + "'"; } // System.out.println("sql2 == == == == == == > " +sql2); ls2 = connMgr.executeQuery(sql2); if ( ls2.next() ) { data2.setRowspan( ls2.getInt("cnt") ); data2.setIsnewcourse("Y"); } } else { data2.setRowspan(0); data2.setIsnewcourse("N"); } v_Bcourse = v_course; v_Bcourseseq= v_courseseq; list2.add(data2); if ( ls2 != null ) { try { ls2.close(); } catch ( Exception e ) { } } } } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql1 = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { } } if ( ls2 != null ) { try { ls2.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list2; } /** 토론방 리스트 @param box receive from the form object and session @return ArrayList */ public ArrayList selectTopicList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; ArrayList list = null; ToronData data = null; String v_year = box.getString("p_year"); // 년도 String v_subj = box.getString("p_subj"); // 과목 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 try { connMgr = new DBConnectionManager(); list = new ArrayList(); // select stated,ended,title,addate,name sql = " select A.tpcode, A.started, A.ended, A.title, A.addate, decode(A.adgadmin, 'ZZ', 'ZZ', 'P1', '강사', '운영자') adgadmin, "; sql += " (select name from TZ_MEMBER where userid = A.aduserid) as name "; sql += " from TZ_TORONTP A "; sql += " where subj='" +v_subj + "' and year='" +v_year + "' and subjseq='" +v_subjseq + "' "; sql += " order by tpcode desc "; // System.out.println("sql == == == == = > " +sql); ls = connMgr.executeQuery(sql); while ( ls.next() ) { data = new ToronData(); data.setTpcode( ls.getString("tpcode") ); data.setStarted( ls.getString("started") ); data.setEnded( ls.getString("ended") ); data.setTitle( ls.getString("title") ); data.setName( ls.getString("name") ); data.setAddate( ls.getString("addate") ); data.setAdgadmin( ls.getString("adgadmin")); list.add(data); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** 토론방 주제 조회 @param box receive from the form object and session @return ArrayList */ public ToronData selectTopic(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls2 = null; String sql1 = ""; String sql2 = ""; int isOk = 0; ToronData data2 = null; String v_year = box.getString("p_year"); // 년도 String v_subj = box.getString("p_subj"); // 과목 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_tpcode = box.getString("p_tpcode"); // 토론주제코드 String v_countCntYn= box.getString("p_countCntYn"); // 조회수 카운트 해줌 try { connMgr = new DBConnectionManager(); // update TZ_TORONTP if("Y".equals(v_countCntYn)) { sql1 = "update TZ_TORONTP set cnt=cnt +1 "; sql1 += "where subj=" +SQLString.Format(v_subj) + " and year=" +SQLString.Format(v_year); sql1 += " and subjseq=" +SQLString.Format(v_subjseq) + " and tpcode=" +SQLString.Format(v_tpcode); isOk = connMgr.executeUpdate(sql1); } // select stated,ended,title,addate,adcontent,aduserid,name,cnt sql2 = "select A.started,A.ended,A.title,A.addate,A.adcontent,A.aduserid, decode(A.adgadmin, 'ZZ', 'ZZ', 'P1', '강사', '운영자') adgadmin, "; sql2 += "(select name from TZ_MEMBER where userid = A.aduserid) as name,cnt "; sql2 += "from TZ_TORONTP A "; sql2 += "where subj=" +SQLString.Format(v_subj) + " and year=" +SQLString.Format(v_year); sql2 += " and subjseq=" +SQLString.Format(v_subjseq) + " and tpcode=" +SQLString.Format(v_tpcode); // System.out.println("sql2 == == == == = > " +sql2); ls2 = connMgr.executeQuery(sql2); if ( ls2.next() ) { data2=new ToronData(); data2.setStarted( ls2.getString("started") ); data2.setEnded( ls2.getString("ended") ); data2.setTitle( ls2.getString("title") ); data2.setAddate( ls2.getString("addate") ); data2.setAdcontent( ls2.getCharacterStream("adcontent") ); data2.setAduserid( ls2.getString("aduserid") ); data2.setName( ls2.getString("name") ); data2.setCnt( ls2.getInt("cnt") ); data2.setAdgadmin( ls2.getString("adgadmin")); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql1 = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls2 != null ) { try { ls2.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return data2; } /** 토론주제 등록 @param box receive from the form object and session @return int */ public int insertTopic(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt2 = null; String sql1 = ""; String sql2 = ""; ListSet ls1 = null; int isOk = 0; String v_user_id = box.getSession("userid"); String v_year = box.getString("p_year"); // 년도 String v_subj = box.getString("p_subj"); // 과목 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_title = box.getString("p_title"); // 토론주제 String v_adcontent = box.getString("p_adcontent"); // 내용clob String v_started = box.getString("p_started") +box.getString("p_stime"); // 토론 시작일 String v_ended = box.getString("p_ended") +box.getString("p_ltime"); // 토론 종료일 String v_tpcode = ""; String s_gadmin = box.getSession("gadmin"); //System.out.println(v_adcontent); /*********************************************************************************************/ // 나모에디터 본문 처리 (Mime Document Parsing 및 이미지 업로드) /* ConfigSet conf = new ConfigSet(); SmeNamoMime namo = new SmeNamoMime(v_adcontent); // 객체생성 boolean result = namo.parse(); // 실제 파싱 수행 if ( !result ) { // 파싱 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } if ( namo.isMultipart() ) { // 문서가 멀티파트인지 판단 String v_server = conf.getProperty("autoever.url.value"); String fPath = conf.getProperty("dir.namo"); // 파일 저장 경로 지정 String refUrl = conf.getProperty("url.namo");; // 웹에서 저장된 파일을 접근하기 위한 경로 String prefix = "torontp" + v_subj; // 파일명 접두어 result = namo.saveFile(fPath, v_server +refUrl, prefix); // 실제 파일 저장 } if ( !result ) { // 파일저장 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } v_adcontent = namo.getContent(); // 최종 컨텐트 얻기 */ /*********************************************************************************************/ try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // select max(tpcode) sql1 = "select max(to_number(tpcode)) from TZ_TORONTP"; ls1 = connMgr.executeQuery(sql1); if ( ls1.next() ) { v_tpcode = (StringManager.toInt( ls1.getString(1)) + 1) + ""; } // insert TZ_TORONTP table sql2 = "insert into TZ_TORONTP(year,subj,subjseq,tpcode,title,adcontent,aduserid,addate,started,ended,luserid,ldate, adgadmin) "; sql2 += "values (?, ?, ?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, ?, ?,to_char(sysdate,'YYYYMMDDHH24MISS'),?)"; // sql2 += "values (?, ?, ?, ?, ?, empty_clob(), ?, to_char(sysdate, 'YYYYMMDDHH24MISS'), ?, ?, ?,to_char(sysdate,'YYYYMMDDHH24MISS'),?)"; pstmt2 = connMgr.prepareStatement(sql2); pstmt2.setString(1, v_year); pstmt2.setString(2, v_subj); pstmt2.setString(3, v_subjseq); pstmt2.setString(4, v_tpcode); pstmt2.setString(5, v_title); pstmt2.setString(6, v_adcontent); // pstmt2.setCharacterStream(6, new StringReader(v_adcontent), v_adcontent.length() ); pstmt2.setString(7, v_user_id); pstmt2.setString(8, v_started); pstmt2.setString(9, v_ended); pstmt2.setString(10, v_user_id); pstmt2.setString(11, s_gadmin); isOk = pstmt2.executeUpdate(); /**CLOB 처리*******************************************************************************************/ sql2 = "select adcontent from TZ_TORONTP "; sql2 += " where year = " + StringManager.makeSQL(v_year); sql2 += " and subj = " + StringManager.makeSQL(v_subj); sql2 += " and subjseq = " + StringManager.makeSQL(v_subjseq); sql2 += " and tpcode = " + StringManager.makeSQL(v_tpcode); // connMgr.setOracleCLOB(sql2, v_adcontent); // CLOB 처리 if ( isOk > 0) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } else { if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } } } } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql2); throw new Exception("sql = " + sql2 + "\r\n" + ex.getMessage() ); } finally { if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e1 ) { } } if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** 토론주제 수정 @param box receive from the form object and session @return int */ public int updateTopic(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt1 = null; String sql1 = ""; String sql2 = ""; int isOk = 0; String v_user_id = box.getSession("userid"); String v_year = box.getString("p_year"); // 년도 String v_subj = box.getString("p_subj"); // 과목 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_title = box.getString("p_title"); // 토론주제 String v_adcontent = box.getString("p_adcontent"); // 내용 String v_started = box.getString("p_started") +box.getString("p_stime"); // 토론 시작일 String v_ended = box.getString("p_ended") +box.getString("p_ltime"); // 토론 종료일 String v_tpcode = box.getString("p_tpcode"); /*********************************************************************************************/ // 나모에디터 본문 처리 (Mime Document Parsing 및 이미지 업로드) /* ConfigSet conf = new ConfigSet(); SmeNamoMime namo = new SmeNamoMime(v_adcontent); // 객체생성 boolean result = namo.parse(); // 실제 파싱 수행 if ( !result ) { // 파싱 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } if ( namo.isMultipart() ) { // 문서가 멀티파트인지 판단 String v_server = conf.getProperty("autoever.url.value"); String fPath = conf.getProperty("dir.namo"); // 파일 저장 경로 지정 String refUrl = conf.getProperty("url.namo");; // 웹에서 저장된 파일을 접근하기 위한 경로 String prefix = "torontp" + v_subj; // 파일명 접두어 result = namo.saveFile(fPath, v_server +refUrl, prefix); // 실제 파일 저장 } if ( !result ) { // 파일저장 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } v_adcontent = namo.getContent(); // 최종 컨텐트 얻기 */ /*********************************************************************************************/ try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // update TZ_TORONTP table sql1 = "update TZ_TORONTP set title=?,adcontent=?,started=?,ended=? "; // sql1 = "update TZ_TORONTP set title=?,adcontent=empty_clob(),started=?,ended=? "; sql1 += "where subj=? and year=? and subjseq=? and tpcode=? "; pstmt1 = connMgr.prepareStatement(sql1); pstmt1.setString(1, v_title); pstmt1.setString(2, v_adcontent); // pstmt1.setCharacterStream(2, new StringReader(v_adcontent), v_adcontent.length() ); pstmt1.setString(3, v_started); pstmt1.setString(4, v_ended); pstmt1.setString(5, v_subj); pstmt1.setString(6, v_year); pstmt1.setString(7, v_subjseq); pstmt1.setString(8, v_tpcode); isOk = pstmt1.executeUpdate(); /**CLOB 처리*******************************************************************************************/ sql2 = "select adcontent from TZ_TORONTP "; sql2 += " where year = " + StringManager.makeSQL(v_year); sql2 += " and subj = " + StringManager.makeSQL(v_subj); sql2 += " and subjseq = " + StringManager.makeSQL(v_subjseq); sql2 += " and tpcode = " + StringManager.makeSQL(v_tpcode); // connMgr.setOracleCLOB(sql2, v_adcontent); // CLOB 처리 if ( isOk > 0) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } else { if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } } } } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** 토론주제 삭제 @param box receive from the form object and session @return int */ public int deleteTopic(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt1 = null; PreparedStatement pstmt2 = null; String sql1 = ""; String sql2 = ""; int isOk1 = 0; int isOk2 = 0; String v_user_id = box.getSession("userid"); String v_subj = box.getString("p_subj"); // 과목 String v_year = box.getString("p_year"); // 년도 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_tpcode = box.getString("p_tpcode"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // delete TZ_TORONTP table sql1 = "delete from TZ_TORONTP "; sql1 += "where subj=? and year=? and subjseq=? and tpcode=? "; pstmt1 = connMgr.prepareStatement(sql1); pstmt1.setString(1, v_subj); pstmt1.setString(2, v_year); pstmt1.setString(3, v_subjseq); pstmt1.setString(4, v_tpcode); isOk1 = pstmt1.executeUpdate(); if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } } // delete TZ_TORONTP table sql2 = "delete from TZ_TORON "; sql2 += "where subj=? and year=? and subjseq=? and tpcode=? "; pstmt2 = connMgr.prepareStatement(sql2); pstmt2.setString(1, v_subj); pstmt2.setString(2, v_year); pstmt2.setString(3, v_subjseq); pstmt2.setString(4, v_tpcode); isOk2 = pstmt2.executeUpdate(); if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e1 ) { } } if ( isOk1 > 0) connMgr.commit(); else connMgr.rollback(); } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } } if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk1; } /** 토론글 리스트 @param box receive from the form object and session @return ArrayList */ public ArrayList selectToronList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls1 = null; ArrayList list1 = null; String sql1 = ""; ToronData data1 = null; String v_year = box.getString("p_year"); // 년도 String v_subj = box.getString("p_subj"); // 과목 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_tpcode = box.getString("p_tpcode"); // 토론주제코드 int l = 0; try { connMgr = new DBConnectionManager(); list1 = new ArrayList(); // select seq,title,aduserid,addate,levels,name sql1 = "select seq,title,aduserid,addate,levels,cnt,agree,contrary, decode(A.adgadmin, 'ZZ', 'ZZ', 'P1', '강사', '운영자') adgadmin, "; sql1 += "(select name from TZ_MEMBER where userid = A.aduserid) as name "; sql1 += " from TZ_TORON A "; sql1 += "where subj=" +SQLString.Format(v_subj) + " and year=" +SQLString.Format(v_year); sql1 += " and subjseq=" +SQLString.Format(v_subjseq) + " and tpcode=" +SQLString.Format(v_tpcode); sql1 += " order by A.refseq desc, A.position asc "; // System.out.println("sql1 == == == == == == > " +sql1); ls1 = connMgr.executeQuery(sql1); while ( ls1.next() ) { data1 = new ToronData(); data1.setSeq( ls1.getInt("seq") ); data1.setTitle( ls1.getString("title") ); data1.setAduserid( ls1.getString("aduserid") ); data1.setAddate( ls1.getString("addate") ); data1.setLevels( ls1.getInt("levels") ); data1.setName( ls1.getString("name") ); data1.setAgree( ls1.getInt("agree")); data1.setContrary( ls1.getInt("contrary")); data1.setCnt( ls1.getInt("cnt")); data1.setAdgadmin( ls1.getString("adgadmin")); list1.add(data1); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql1 = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list1; } /** * 토론글 리스트(tpcode와 관계없이...) * @param box * @return * @throws Exception */ public ArrayList selectToronList2(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls1 = null; ArrayList list1 = null; String sql1 = ""; ToronData data1 = null; String v_year = box.getString("p_year"); // 년도 String v_subj = box.getString("p_subj"); // 과목 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_tpcode = box.getString("p_tpcode"); // 토론주제코드 String v_userid = box.getString("p_userid"); int l = 0; try { connMgr = new DBConnectionManager(); list1 = new ArrayList(); // select seq,title,aduserid,addate,levels,name sql1 = "select seq,title,aduserid,addate,levels,cnt,agree,contrary, tpcode,decode(A.adgadmin, 'ZZ', 'ZZ', 'P1', '강사', '운영자') adgadmin, \n "; sql1 += "(select name from TZ_MEMBER where userid = A.aduserid) as name \n "; sql1 += " from TZ_TORON A \n "; sql1 += "where subj=" +SQLString.Format(v_subj) + " and year=" +SQLString.Format(v_year) + " \n "; sql1 += " and subjseq = " +SQLString.Format(v_subjseq) + " \n "; sql1 += " and aduserid = " +SQLString.Format(v_userid) + " \n "; sql1 += " order by A.refseq desc, A.position asc \n "; // System.out.println("sql1 == == == == == == > " +sql1); ls1 = connMgr.executeQuery(sql1); while ( ls1.next() ) { data1 = new ToronData(); data1.setSeq( ls1.getInt("seq") ); data1.setTpcode(ls1.getString("tpcode")); data1.setTitle( ls1.getString("title") ); data1.setAduserid( ls1.getString("aduserid") ); data1.setAddate( ls1.getString("addate") ); data1.setLevels( ls1.getInt("levels") ); data1.setName( ls1.getString("name") ); data1.setAgree( ls1.getInt("agree")); data1.setContrary( ls1.getInt("contrary")); data1.setCnt( ls1.getInt("cnt")); data1.setAdgadmin( ls1.getString("adgadmin")); list1.add(data1); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql1 = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list1; } public DataBox selectToronStudentScore(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; DataBox dbox = null; String v_year = box.getString("p_year"); // 년도 String v_subj = box.getString("p_subj"); // 과목 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_userid = box.getString("p_userid"); try { connMgr = new DBConnectionManager(); sql = " select a.userid, a.etc1, nvl(b.isgraduated,'-') as isgraduated "; sql += " from tz_student a, tz_stold b "; sql += " where a.subj=b.subj(+)"; sql += " and a.year=b.year(+)"; sql += " and a.subjseq=b.subjseq(+)"; sql += " and a.userid=b.userid(+)"; sql += " and a.subj = " + StringManager.makeSQL(v_subj); sql += " and a.year = " + StringManager.makeSQL(v_year); sql += " and a.subjseq = " + StringManager.makeSQL(v_subjseq); sql += " and a.userid = " + StringManager.makeSQL(v_userid); ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return dbox; } /** 토론글 조회 @param box receive from the form object and session @return ArrayList */ public ToronData selectToron(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls2 = null; String sql1 = ""; String sql2 = ""; ToronData data2 = null; String v_year = box.getString("p_year"); // 년도 String v_subj = box.getString("p_subj"); // 과목 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_tpcode = box.getString("p_tpcode"); // 토론주제코드 int v_seq = box.getInt("p_seq"); // 일련번호 String s_userid = box.getSession("userid"); int isOk1 = 0; int l = 0; try { connMgr = new DBConnectionManager(); // update TZ_TORONTP sql1 = "update TZ_TORON set cnt=cnt +1 "; sql1 += "where subj=" +SQLString.Format(v_subj) + " and year=" +SQLString.Format(v_year); sql1 += " and subjseq=" +SQLString.Format(v_subjseq) + " and tpcode=" +SQLString.Format(v_tpcode); sql1 += " and seq=" +SQLString.Format(v_seq); isOk1 = connMgr.executeUpdate(sql1); // select seq,refseq,levels,position,title,adcontent,aduserid,cnt,addate,name sql2 = "select seq,refseq,levels,position,title,adcontent,aduserid,cnt,addate,agree,contrary, decode(A.adgadmin, 'ZZ', 'ZZ', 'P1', '강사', '운영자') adgadmin, \n"+ " ( \n"+ " select decode(count(*), 0, 'Y', 'N') \n"+ " from TZ_TORON c, TZ_TORON d \n"+ " where c.refseq = d.refseq \n"+ " and d.levels = (c.levels +1) \n"+ " and d.position = (c.position +1) \n"+ " and c.seq = a.seq \n"+ " ) delYn, ( \n"+ " select count(*) \n"+ " from tz_board_agreeinfo \n"+ " where subjseq = A.subjseq \n"+ " and subj = A.subj \n"+ " and year = A.year \n"+ " and tpcode = A.tpcode \n"+ " and seq = A.seq \n"+ " and userid = " +SQLString.Format(s_userid) + " ) agree_count, \n"; sql2 += "(select name from TZ_MEMBER where userid = A.aduserid) as name \n"; sql2 += " from TZ_TORON A \n"; sql2 += "where subj=" +SQLString.Format(v_subj) + " and year=" +SQLString.Format(v_year); sql2 += " and subjseq=" +SQLString.Format(v_subjseq) + " and tpcode=" +SQLString.Format(v_tpcode); sql2 += " and seq=" +SQLString.Format(v_seq); System.out.println("sql2 == == == == == == > " +sql2); ls2 = connMgr.executeQuery(sql2); if ( ls2.next() ) { data2=new ToronData(); data2.setSeq( ls2.getInt("seq") ); data2.setRefseq( ls2.getInt("refseq") ); data2.setLevels( ls2.getInt("levels") ); data2.setPosition( ls2.getInt("position") ); data2.setTitle( ls2.getString("title") ); data2.setAdcontent( ls2.getCharacterStream("adcontent") ); data2.setAduserid( ls2.getString("aduserid") ); data2.setCnt( ls2.getInt("cnt") ); data2.setAddate( ls2.getString("addate") ); data2.setName( ls2.getString("name") ); data2.setAgree( ls2.getInt("agree")); data2.setContrary( ls2.getInt("contrary")); data2.setDelYn( ls2.getString("delYn")); data2.setAdgadmin( ls2.getString("adgadmin")); data2.setAgreecount( ls2.getInt("agree_count")); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql1 = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls2 != null ) { try { ls2.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return data2; } /** 토론글 등록 @param box receive from the form object and session @return int */ public int insertToron(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt2 = null; String sql1 = ""; String sql2 = ""; ListSet ls1 = null; int isOk = 0; String v_user_id = box.getSession("userid"); String v_subj = box.getString("p_subj"); // 과목 String v_year = box.getString("p_year"); // 년도 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_tpcode = box.getString("p_tpcode"); // 토론주제코드 String v_title = box.getString("p_title"); // 제목 String v_adcontent = box.getString("p_adcontent"); // 내용 String s_gadmin = box.getSession("gadmin"); int v_seq = 0; /*********************************************************************************************/ // 나모에디터 본문 처리 (Mime Document Parsing 및 이미지 업로드) /* ConfigSet conf = new ConfigSet(); SmeNamoMime namo = new SmeNamoMime(v_adcontent); // 객체생성 boolean result = namo.parse(); // 실제 파싱 수행 if ( !result ) { // 파싱 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } if ( namo.isMultipart() ) { // 문서가 멀티파트인지 판단 String v_server = conf.getProperty("autoever.url.value"); String fPath = conf.getProperty("dir.namo"); // 파일 저장 경로 지정 String refUrl = conf.getProperty("url.namo");; // 웹에서 저장된 파일을 접근하기 위한 경로 String prefix = "torontp" + v_subj; // 파일명 접두어 result = namo.saveFile(fPath, v_server +refUrl, prefix); // 실제 파일 저장 } if ( !result ) { // 파일저장 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } v_adcontent = namo.getContent(); // 최종 컨텐트 얻기 */ /*********************************************************************************************/ try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // select max(seq) sql1 = "select nvl(max(seq), 0) from TZ_TORON "; ls1 = connMgr.executeQuery(sql1); if ( ls1.next() ) { v_seq = ls1.getInt(1) + 1; } ls1.close(); // insert TZ_TORON table sql2 = "insert into TZ_TORON(subj,year,subjseq,tpcode,seq,refseq,title,adcontent,aduserid,addate,luserid,ldate, agree, contrary, adgadmin) "; sql2 += "values (?, ?, ?, ?, ?, ?, ?, ?, ?, to_char(sysdate,'YYYYMMDDHH24MISS'), ?, to_char(sysdate,'YYYYMMDDHH24MISS'), 0, 0, ?)"; // sql2 += "values (?, ?, ?, ?, ?, ?, ?, empty_clob(), ?, to_char(sysdate,'YYYYMMDDHH24MISS'), ?, to_char(sysdate,'YYYYMMDDHH24MISS'), 0, 0, ?)"; pstmt2 = connMgr.prepareStatement(sql2); pstmt2.setString(1, v_subj); pstmt2.setString(2, v_year); pstmt2.setString(3, v_subjseq); pstmt2.setString(4, v_tpcode); pstmt2.setInt(5, v_seq); pstmt2.setInt(6, v_seq); pstmt2.setString(7, v_title); pstmt2.setString(8, v_adcontent); // pstmt2.setCharacterStream(8, new StringReader(v_adcontent), v_adcontent.length() ); pstmt2.setString(9, v_user_id); pstmt2.setString(10, v_user_id); pstmt2.setString(11, s_gadmin); isOk = pstmt2.executeUpdate(); /**CLOB 처리*******************************************************************************************/ sql2 = "select adcontent from TZ_TORON "; sql2 += " where year = " + StringManager.makeSQL(v_year); sql2 += " and subj = " + StringManager.makeSQL(v_subj); sql2 += " and subjseq = " + StringManager.makeSQL(v_subjseq); sql2 += " and tpcode = " + StringManager.makeSQL(v_tpcode); sql2 += " and seq = " + v_seq; // connMgr.setOracleCLOB(sql2, v_adcontent); // CLOB 처리 if ( isOk > 0) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } else { if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } } } } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql2); throw new Exception("sql = " + sql2 + "\r\n" + ex.getMessage() ); } finally { if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e1 ) { } } if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** 토론글 수정 @param box receive from the form object and session @return int */ public int updateToron(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt1 = null; String sql1 = ""; String sql2 = ""; int isOk = 0; String v_user_id = box.getSession("userid"); String v_year = box.getString("p_year"); // 년도 String v_subj = box.getString("p_subj"); // 과목 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_tpcode = box.getString("p_tpcode"); // 토론주제코드 int v_seq = box.getInt("p_seq"); // 의견일련번호 String v_title = box.getString("p_title"); // 토론주제 String v_adcontent = box.getString("p_adcontent"); // 내용 String v_started = box.getString("p_started") +box.getString("p_stime"); // 토론 시작일 String v_ended = box.getString("p_ended") +box.getString("p_ltime"); // 토론 종료일 /*********************************************************************************************/ // 나모에디터 본문 처리 (Mime Document Parsing 및 이미지 업로드) /* ConfigSet conf = new ConfigSet(); SmeNamoMime namo = new SmeNamoMime(v_adcontent); // 객체생성 boolean result = namo.parse(); // 실제 파싱 수행 if ( !result ) { // 파싱 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } if ( namo.isMultipart() ) { // 문서가 멀티파트인지 판단 String v_server = conf.getProperty("autoever.url.value"); String fPath = conf.getProperty("dir.namo"); // 파일 저장 경로 지정 String refUrl = conf.getProperty("url.namo");; // 웹에서 저장된 파일을 접근하기 위한 경로 String prefix = "torontp" + v_subj; // 파일명 접두어 result = namo.saveFile(fPath, v_server +refUrl, prefix); // 실제 파일 저장 } if ( !result ) { // 파일저장 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } v_adcontent = namo.getContent(); // 최종 컨텐트 얻기 */ /*********************************************************************************************/ try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // update TZ_TORONTP table sql1 = "update TZ_TORON set title=?,adcontent=? "; // sql1 = "update TZ_TORON set title=?,adcontent=empty_clob() "; sql1 += "where subj=? and year=? and subjseq=? and tpcode=? and seq=? "; pstmt1 = connMgr.prepareStatement(sql1); pstmt1.setString(1, v_title); pstmt1.setString(2, v_adcontent); // pstmt1.setCharacterStream(2, new StringReader(v_adcontent), v_adcontent.length() ); pstmt1.setString(3, v_subj); pstmt1.setString(4, v_year); pstmt1.setString(5, v_subjseq); pstmt1.setString(6, v_tpcode); pstmt1.setInt (7, v_seq); isOk = pstmt1.executeUpdate(); /**CLOB 처리*******************************************************************************************/ sql2 = "select adcontent from TZ_TORON "; sql2 += " where year = " + StringManager.makeSQL(v_year); sql2 += " and subj = " + StringManager.makeSQL(v_subj); sql2 += " and subjseq = " + StringManager.makeSQL(v_subjseq); sql2 += " and tpcode = " + StringManager.makeSQL(v_tpcode); sql2 += " and seq = " + v_seq; // connMgr.setOracleCLOB(sql2, v_adcontent); // CLOB 처리 if ( isOk > 0) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } else { if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } } } } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** 토론 답글 등록 @param box receive from the form object and session @return int */ public int insertToronReply(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt1 = null; PreparedStatement pstmt3 = null; String sql1 = ""; String sql2 = ""; String sql3 = ""; ListSet ls2 = null; int isOk1 = 0; int isOk3 = 0; String v_user_id = box.getSession("userid"); String v_subj = box.getString("p_subj"); // 과목 String v_year = box.getString("p_year"); // 년도 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_tpcode = box.getString("p_tpcode"); // 토론주제코드 String v_title = box.getString("p_title"); // 제목 String v_adcontent = box.getString("p_adcontent"); // 내용 int v_refseq = box.getInt("p_refseq"); // 상위글 번호 int v_levels = box.getInt("p_levels"); int v_position = box.getInt("p_position"); int v_seq = 0; /*********************************************************************************************/ // 나모에디터 본문 처리 (Mime Document Parsing 및 이미지 업로드) /* ConfigSet conf = new ConfigSet(); SmeNamoMime namo = new SmeNamoMime(v_adcontent); // 객체생성 boolean result = namo.parse(); // 실제 파싱 수행 if ( !result ) { // 파싱 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } if ( namo.isMultipart() ) { // 문서가 멀티파트인지 판단 String v_server = conf.getProperty("autoever.url.value"); String fPath = conf.getProperty("dir.namo"); // 파일 저장 경로 지정 String refUrl = conf.getProperty("url.namo");; // 웹에서 저장된 파일을 접근하기 위한 경로 String prefix = "torontp" + v_subj; // 파일명 접두어 result = namo.saveFile(fPath, v_server +refUrl, prefix); // 실제 파일 저장 } if ( !result ) { // 파일저장 실패시 System.out.println( namo.getDebugMsg() ); // 디버깅 메시지 출력 return 0; } v_adcontent = namo.getContent(); // 최종 컨텐트 얻기 */ /*********************************************************************************************/ try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // 기존 답변글 위치 한칸밑으로 변경 sql1 = "update TZ_TORON "; sql1 += " set position = position + 1 "; sql1 += " where refseq = ? "; sql1 += " and position > ? "; pstmt1 = connMgr.prepareStatement(sql1); pstmt1.setInt(1, v_refseq); pstmt1.setInt(2, v_position); isOk1 = pstmt1.executeUpdate(); // select max(seq) sql2 = "select max(seq) from TZ_TORON"; ls2 = connMgr.executeQuery(sql2); if ( ls2.next() ) { v_seq = ls2.getInt(1) + 1; } // insert TZ_TORON table sql3 = "insert into TZ_TORON(subj,year,subjseq,tpcode,seq,refseq,levels,position,title,adcontent,aduserid,addate,luserid,ldate, agree, contrary) "; sql3 += "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, to_char(sysdate,'YYYYMMDDHH24MISS'), ?, to_char(sysdate,'YYYYMMDDHH24MISS'), 0, 0)"; // sql3 += "values (?, ?, ?, ?, ?, ?, ?, ?, ?, empty_clob(), ?, to_char(sysdate,'YYYYMMDDHH24MISS'), ?, to_char(sysdate,'YYYYMMDDHH24MISS'), 0, 0)"; pstmt3 = connMgr.prepareStatement(sql3); pstmt3.setString(1, v_subj); pstmt3.setString(2, v_year); pstmt3.setString(3, v_subjseq); pstmt3.setString(4, v_tpcode); pstmt3.setInt(5, v_seq); pstmt3.setInt(6, v_refseq); pstmt3.setInt(7, v_levels + 1); pstmt3.setInt(8, v_position + 1); pstmt3.setString(9, v_title); pstmt3.setString(10, v_adcontent); // pstmt3.setCharacterStream(10, new StringReader(v_adcontent), v_adcontent.length() ); pstmt3.setString(11, v_user_id); pstmt3.setString(12, v_user_id); isOk3 = pstmt3.executeUpdate(); /**CLOB 처리*******************************************************************************************/ sql2 = "select adcontent from TZ_TORON "; sql2 += " where year = " + StringManager.makeSQL(v_year); sql2 += " and subj = " + StringManager.makeSQL(v_subj); sql2 += " and subjseq = " + StringManager.makeSQL(v_subjseq); sql2 += " and tpcode = " + StringManager.makeSQL(v_tpcode); sql2 += " and seq = " + v_seq; // connMgr.setOracleCLOB(sql2, v_adcontent); // CLOB 처리 if ( isOk3 > 0) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } else { if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } } } } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql3); throw new Exception("sql = " + sql3 + "\r\n" + ex.getMessage() ); } finally { if ( ls2 != null ) { try { ls2.close(); } catch ( Exception e1 ) { } } if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } } if ( pstmt3 != null ) { try { pstmt3.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk3; } /** 토론글 삭제 @param box receive from the form object and session @return int */ public int deleteToron(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt1 = null; String sql1 = ""; int isOk = 0; String v_user_id = box.getSession("userid"); String v_subj = box.getString("p_subj"); // 과목 String v_year = box.getString("p_year"); // 년도 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_tpcode = box.getString("p_tpcode"); // 토론주제코드 int v_seq = box.getInt("p_seq"); // 의견일련번호 try { connMgr = new DBConnectionManager(); // 답변 유무 체크(답변 있을시 삭제불가) if ( this.selectToronReply(v_seq) == 0 ) { // delete TZ_TORONTP table sql1 = "delete from TZ_TORON "; sql1 += "where subj=? and year=? and subjseq=? and tpcode=? and seq=?"; pstmt1 = connMgr.prepareStatement(sql1); pstmt1.setString(1, v_subj); pstmt1.setString(2, v_year); pstmt1.setString(3, v_subjseq); pstmt1.setString(4, v_tpcode); pstmt1.setInt(5, v_seq); isOk = pstmt1.executeUpdate(); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** * 삭제시 하위 답변 유무 체크 * @param seq 게시판 번호 * @return result 0 : 답변 없음, 1 : 답변 있음 * @throws Exception */ public int selectToronReply(int seq) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; int result = 0; try { connMgr = new DBConnectionManager(); sql = " select count(*) cnt "; sql += " from "; sql += " (select refseq, levels, position "; sql += " from TZ_TORON "; sql += " where seq = " + seq; sql += " ) a, TZ_TORON b "; sql += " where a.refseq = b.refseq "; sql += " and b.levels = (a.levels +1) "; sql += " and b.position = (a.position +1) "; // System.out.println("sql == == == == == == == = > " +sql); ls = connMgr.executeQuery(sql); if ( ls.next() ) { result = ls.getInt("cnt"); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return result; } /** 찬성 반대 카운트 업데이트 @param box receive from the form object and session @return int */ public int updateColumn(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt1 = null; String sql1 = ""; ListSet ls2 = null; String sql2 = ""; String sql3 = ""; int v_seq2 = 0; PreparedStatement pstmt3 = null; PreparedStatement pstmt = null; int isOk3 = 0; int isOk = 0; String v_user_id = box.getSession("userid"); String v_year = box.getString("p_year"); // 년도 String v_subj = box.getString("p_subj"); // 과목 String v_subjseq = box.getString("p_subjseq"); // 과목 기수 String v_tpcode = box.getString("p_tpcode"); // 토론주제코드 int v_seq = box.getInt("p_seq"); // 의견일련번호 String v_title = box.getString("p_title"); // 토론주제 String v_adcontent = box.getString("p_adcontent"); // 내용 String v_started = box.getString("p_started") +box.getString("p_stime"); // 토론 시작일 String v_ended = box.getString("p_ended") +box.getString("p_ltime"); // 토론 종료일 String v_column = box.getString("p_column"); String v_gubun = "N"; if("AGREE".equals(v_column)) { v_gubun = "Y"; } try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); sql1 = "update TZ_TORON set " + v_column + " = " + v_column + " + 1 "; sql1 += "where subj=? and year=? and subjseq=? and tpcode=? and seq=? "; pstmt1 = connMgr.prepareStatement(sql1); /*pstmt1.setString(1, v_column); pstmt1.setString(2, v_column);*/ pstmt1.setString(1, v_subj); pstmt1.setString(2, v_year); pstmt1.setString(3, v_subjseq); pstmt1.setString(4, v_tpcode); pstmt1.setInt (5, v_seq); isOk = pstmt1.executeUpdate(); sql2 = "select max(recseq) from tz_board_agreeinfo \n" + "where subj = ? \n" + "and year = ? \n" + "and subjseq = ? \n" + "and tpcode = ? \n" + "and seq = ? \n"; pstmt = connMgr.prepareStatement(sql2, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, v_subj); pstmt.setString(2, v_year); pstmt.setString(3, v_subjseq); pstmt.setString(4, v_tpcode); pstmt.setInt(5, v_seq); ls2 = new ListSet(pstmt); // ListSet (ResultSet) 객체생성 if ( ls2.next() ) { v_seq2 = ls2.getInt(1) + 1; } // insert tz_board_agreeinfo table // 찬성, 반대 이력 sql3 = "insert into tz_board_agreeinfo(subj, year, subjseq, tpcode, seq, recseq, userid, indate, gubun) "; sql3 += "values (?, ?, ?, ?, ?, ?, ?, to_char(sysdate,'YYYYMMDDHH24MISS'), ?)"; pstmt3 = connMgr.prepareStatement(sql3); pstmt3.setString(1, v_subj); pstmt3.setString(2, v_year); pstmt3.setString(3, v_subjseq); pstmt3.setString(4, v_tpcode); pstmt3.setInt(5, v_seq); pstmt3.setInt(6, v_seq2); pstmt3.setString(7, v_user_id); pstmt3.setString(8, v_gubun); isOk3 = pstmt3.executeUpdate(); if ( isOk > 0) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } else { if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } } } } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } } if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } } if ( pstmt3 != null ) { try { pstmt3.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } }
/* * 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 EjerciciosProgramacion2; /** * * @author PocyxDesigner */ public class Ejer6Tema2 { public static void main(String[] args) { double cantidad = 5; double iva =0.21; double total; total = (cantidad * iva)+cantidad ; System.out.println(cantidad+" € mas el IVA es "+total+" €"); } }
package p12; import java.util.ArrayList; import java.util.Scanner; public class ListExam { private ArrayList<String> alStr; ListExam(){ alStr=new ArrayList<String>(); } void add(String str) { if(alStr.isEmpty()) { System.out.println("처음 값을 입력하셨군요!"); } else { System.out.println("전에 넣은 값: "+alStr.get((alStr.size()-1))); System.out.println("현재 값:"+str); } alStr.add(str+""); } String get(int id) { return alStr.get(id)+""; } void remove(int id) { alStr.remove(id); } void inputAlStr() { Scanner sc=new Scanner(System.in); System.out.println("숫자 스트링을 넣어주세요 구분자는 ,입니다"); String str=sc.nextLine(); String[] strs=str.split(","); for(String ss:strs) { add(ss); } sc.close(); } int size() { return alStr.size(); } void split() { } void printAlStr() { int temp=0; for(String str:alStr) { System.out.print((temp++)+"번째 인덱스 "+str+"\t"); } } void printAlStr2() { for(int i=0;i<alStr.size();i++) { } } }
package com.david.secretsanta.services; import com.david.secretsanta.models.PersonFamily; import java.util.Optional; public interface PersonFamilyService { PersonFamily createPersonFamily (String name,String forename,String idFamilyGroup) ; PersonFamily findPersonFamiliy (String idPerson); }
package pl.dkiszka.bank.account.services; import io.vavr.control.Try; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.axonframework.commandhandling.gateway.CommandGateway; import org.springframework.stereotype.Service; import pl.dkiszka.bank.account.commands.CloseAccountCommand; import pl.dkiszka.bank.account.commands.DepositFundsCommand; import pl.dkiszka.bank.account.commands.OpenAccountCommand; import pl.dkiszka.bank.account.commands.WithdrawFundsCommand; import pl.dkiszka.bank.account.dto.BaseResponse; import pl.dkiszka.bank.account.dto.OpenAccountResponse; import java.util.UUID; /** * @author Dominik Kiszka {dominikk19} * @project bank-application * @date 26.04.2021 */ @Service @RequiredArgsConstructor @Slf4j public class AccountService { private final CommandGateway commandGateway; public OpenAccountResponse openAccount(OpenAccountCommand command) { command.setId(UUID.randomUUID().toString()); return Try.of(() -> { commandGateway.send(command); log.info("Send open account command"); return new OpenAccountResponse("Account successfully opened", command.getId()); }).onFailure(exe -> { log.error("Error while processing request to open account for id " + command.getId()); throw new CommandGatewayException("Error while processing request to open account for id " + command.getId()); }).get(); } public BaseResponse closeAccount(String id) { return Try.of(() -> { commandGateway.send(new CloseAccountCommand(id)); log.info("Send close account command"); return new BaseResponse("Account successfully closed"); }).onFailure(exe -> { log.error("Error while processing request to close account for id " + id); throw new CommandGatewayException("Error while processing closed account for id " + id); }).get(); } public BaseResponse withdrawFunds(String id, WithdrawFundsCommand command) { return Try.of(() -> { command.setId(id); commandGateway.send(command).get(); log.info("Withdrawal successfully completed"); return new BaseResponse("Withdrawal successfully completed"); }).onFailure(exe -> { log.error("Error while processing request to withdraw funds from account for id " + command.getId()); throw new CommandGatewayException("Error while processing to withdraw funds from account for id " + command.getId()); }).get(); } public BaseResponse depositFunds(String id, DepositFundsCommand command) { return Try.of(() -> { command.setId(id); commandGateway.send(command); log.info("Funds successfully deposited"); return new BaseResponse("Funds successfully deposited"); }).onFailure(exe -> { log.error("Error while processing request to deposit funds from account for id " + command.getId()); throw new CommandGatewayException("Error while processing request to deposit funds from open account for id " + command.getId()); }).get(); } }
package com.oak.wshop.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.oak.wshop.model.Post; import com.oak.wshop.repository.PostRepository; @Service public class PostService { @Autowired PostRepository postRepository; public Optional<Post> findPost(String id) { return postRepository.findById(id); } public List<Post> findByTitle(String text) { return postRepository.findByTitleContainingIgnoreCase(text); } public List<Post> searchWordForDate(String text) { return postRepository.searchWordForDate(text); } }
package ua.siemens.dbtool.serializers; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import ua.siemens.dbtool.model.entities.Partner; import java.lang.reflect.Type; /** * The class is custom serializer for {@link Partner} * <p> * * @author Perevoznyk Pavlo * creation date 31 oct 2017 * @version 1.0 */ public class PartnerSerializer implements JsonSerializer<Partner> { @Override public JsonElement serialize(Partner obj, Type typeOfSrc, JsonSerializationContext context) { JsonObject resultJson = new JsonObject(); resultJson.addProperty("id", obj.getId()); resultJson.addProperty("name", obj.getName()); return resultJson; } }
package matthbo.mods.darkworld.world; import java.util.Random; import matthbo.mods.darkworld.init.ModBlocks; import matthbo.mods.darkworld.init.ModDimensions; import net.minecraft.block.Block; import net.minecraft.block.state.pattern.BlockHelper; import net.minecraft.util.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.feature.WorldGenMinable; import net.minecraftforge.fml.common.IWorldGenerator; public class DarkWorldGenerator implements IWorldGenerator { public final int DWID = ModDimensions.dimensionIDDarkWorld; public DarkWorldGenerator() {} @Override public void generate(Random rand, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { //BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(chunkX, chunkZ); chunkX *= 16; chunkZ *= 16; if(world.provider.getDimensionId() == DWID){ genStandardOre1(world, ModBlocks.darkDirt, 20, 32, chunkX, 0, 256, chunkZ, rand); genStandardOre1(world, ModBlocks.darkGravel, 10, 32, chunkX, 0, 256, chunkZ, rand); genStandardOre1(world, ModBlocks.darkCoalOre, 20, 16, chunkX, 0, 128, chunkZ, rand); genStandardOre1(world, ModBlocks.darkIronOre, 20, 8, chunkX, 0, 64, chunkZ, rand); genStandardOre1(world, ModBlocks.darkGoldOre, 2, 8, chunkX, 0, 32, chunkZ, rand); genStandardOre1(world, ModBlocks.darkRedstoneOre, 8, 7, chunkX, 0, 16, chunkZ, rand); genStandardOre1(world, ModBlocks.darkDiamondOre, 1, 7, chunkX, 0, 16, chunkZ, rand); genStandardOre2(world, ModBlocks.darkLapisOre, 1, 6, chunkX, 16, 16, chunkZ, rand); } } protected void genStandardOre1(World world, Block block,int veins, int BPV, int chunkX, int chunkYSpecial, int chunkY, int chunkZ, Random rand) { for (int l = 0; l < veins; ++l) { int x = chunkX + rand.nextInt(16); int y = rand.nextInt(chunkY - chunkYSpecial) + chunkYSpecial; int z = chunkZ + rand.nextInt(16); (new WorldGenMinable(block.getDefaultState(), BPV, BlockHelper.forBlock(ModBlocks.darkStone))).generate(world, rand, new BlockPos(x,y,z)); } } protected void genStandardOre2(World world, Block block,int veins, int BPV, int chunkX, int chunkYSpecial, int chunkY, int chunkZ, Random rand) { for (int l = 0; l < veins; ++l) { int x = chunkX + rand.nextInt(16); int y = rand.nextInt(chunkY) + rand.nextInt(chunkY) + (chunkYSpecial - chunkY); int z = chunkZ + rand.nextInt(16); (new WorldGenMinable(block.getDefaultState(), BPV, BlockHelper.forBlock(ModBlocks.darkStone))).generate(world, rand, new BlockPos(x,y,z)); } } }
package taojinqu.springboot.jaxrs.service; import java.io.IOException; import java.net.URI; import java.net.URL; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.glassfish.jersey.internal.util.collection.MultivaluedStringMap; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = StartApp.class) public class OrderServiceTester { @Test public void testGetOrderById() { Client client = ClientBuilder.newClient(); Response res = client.target("http://127.0.0.1:8080/orderService/getOrderById?id=1003") .request(MediaType.APPLICATION_JSON).get(); String message = res.readEntity(String.class); System.out.println(message); } @Test public void testGetOrderByCode() { Client client = ClientBuilder.newClient(); Response res = client.target("http://127.0.0.1:8080/orderService/getOrderByCode/CO10020") .request(MediaType.APPLICATION_JSON).post(null); int status = res.getStatus(); Assert.assertEquals(200, status); String message = res.readEntity(String.class); System.out.println(message); } @Test public void testSaveProduct() throws IOException { Client client = ClientBuilder.newClient(); WebTarget target = client .target(URI.create(new URL("http://127.0.0.1:8080/orderService/saveProduct").toExternalForm())); WebTarget t = target.path("/1009").queryParam("name", "产品1009").queryParam("price", "11.23"); String r = t.request().get(String.class); System.out.println(r); } /** * post方式提交表单 * * @throws IOException */ @Test public void testSaveOrderForm() throws IOException { MultivaluedMap<String, String> store = new MultivaluedStringMap(10); store.putSingle("id", "1005"); store.putSingle("code", "C1005"); store.putSingle("platform", "LAZAD"); Entity<Form> entity = Entity.form(store); Client client = ClientBuilder.newClient(); Response res = client.target("http://127.0.0.1:8080/orderService/saveOrderForm").request().post(entity); int status = res.getStatus(); Assert.assertEquals(200, status); String message = res.readEntity(String.class); System.out.println(message); } /** * post方式提交表单 * * @throws IOException */ @Test public void saveOrderForm2() throws IOException { MultivaluedMap<String, String> store = new MultivaluedStringMap(10); store.putSingle("id", "1005"); store.putSingle("code", "C1005"); store.putSingle("platform", "LAZAD"); Entity<Form> entity = Entity.form(store); Client client = ClientBuilder.newClient(); Response res = client.target("http://127.0.0.1:8080/orderService/saveOrderForm2").request().post(entity); int status = res.getStatus(); Assert.assertEquals(200, status); String message = res.readEntity(String.class); System.out.println(message); } }
package com.stepin.mushroom_recognizer; import androidx.lifecycle.ViewModelProviders; import android.app.Activity; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.Button; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; public class descriptions_fragment extends Fragment implements View.OnTouchListener { ImageView imageView_description1; ImageView imageView_description2; int active_picture_number; TextView textView_description_had; TextView textView_description_body; TextView textView_description_number; int[] images_id_array; ImageSwitcher imageSwitcher; ScrollView scrollView; Button button_back; float pos_x_1; float pos_x_2; boolean action; boolean big_size; int list_position; int id_picture1; int id_picture2; int id_picture3; Activity activity; private DescriptionsFragmentViewModel mViewModel; public static descriptions_fragment newInstance() { return new descriptions_fragment(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.activity_description, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewModel = ViewModelProviders.of(this).get(DescriptionsFragmentViewModel.class); // TODO: Use the ViewModel activity = getActivity(); scrollView = activity.findViewById(R.id.scrollView_description); activity.findViewById(R.id.button_description_back).setVisibility(View.GONE); active_picture_number = 0; imageSwitcher = activity.findViewById(R.id.imageSwitcher_description); imageSwitcher.setOnTouchListener(this); imageView_description1 = activity.findViewById(R.id.imageView_description1); imageView_description2 = activity.findViewById(R.id.imageView_description2); textView_description_body = activity.findViewById(R.id.textView_description_body); textView_description_had = activity.findViewById(R.id.textView_description_had); textView_description_number = activity.findViewById(R.id.textView_description_number); } public void data_from_activity(String name, String description, String[] images_names_array) { id_picture1 = getResources().getIdentifier(images_names_array[0], "drawable", "com.stepin.mushroom_recognizer"); id_picture2 = getResources().getIdentifier(images_names_array[1], "drawable", "com.stepin.mushroom_recognizer"); id_picture3 = getResources().getIdentifier(images_names_array[2], "drawable", "com.stepin.mushroom_recognizer"); images_id_array = new int[]{id_picture1, id_picture2, id_picture3}; active_picture_number = 0; textView_description_number.setText("Фото " + (active_picture_number + 1) + " из 3"); textView_description_body.setText(description); textView_description_had.setText(name); scrollView.scrollTo(1,1); imageSwitcher.showPrevious(); ((ImageView) imageSwitcher.getCurrentView()).setImageResource(images_id_array[active_picture_number]); } @Override public boolean onTouch(View v, MotionEvent event) { switch (v.getId()) { case R.id.imageSwitcher_description: { if (event.getAction() == 0) pos_x_2 = event.getX(); if (event.getAction() == 1) { if (event.getX() < pos_x_2) { Animation inAnimation = new TranslateAnimation(500,0,1,1); inAnimation.setDuration(300); Animation outAnimation = new TranslateAnimation(0,-500,1,1); outAnimation.setDuration(300); imageSwitcher.setInAnimation(inAnimation); imageSwitcher.setOutAnimation(outAnimation); if (active_picture_number == 2) active_picture_number = 0; else active_picture_number += 1; ((ImageView) imageSwitcher.getNextView()).setImageResource(images_id_array[active_picture_number]); imageSwitcher.showNext(); textView_description_number.setText("Фото " + (active_picture_number + 1) + " из 3"); } else if (event.getX() > pos_x_2) { Animation inAnimation = new TranslateAnimation(-500,0,1,1); inAnimation.setDuration(300); Animation outAnimation = new TranslateAnimation(0,500,1,1); outAnimation.setDuration(300); imageSwitcher.setInAnimation(inAnimation); imageSwitcher.setOutAnimation(outAnimation); if (active_picture_number == 0) active_picture_number = 2; else active_picture_number -= 1; ((ImageView) imageSwitcher.getNextView()).setImageResource(images_id_array[active_picture_number]); imageSwitcher.showNext(); textView_description_number.setText("Фото " + (active_picture_number + 1) + " из 3"); } else if (event.getX() == pos_x_2) { ((call_for_activity)activity).show_dialog(images_id_array[active_picture_number]); } } break; } } return true; } public interface call_for_activity { void show_dialog(int picture_id); } }
package Model; import android.widget.Button; public class jobApply { String companyName; String contact; String emailid; String advertname; String jobqualificatio; String experience; String id; String date; public jobApply(String companyName, String contact, String emailid, String advertname, String jobqualificatio, String experience, String id, String date) { this.companyName = companyName; this.contact = contact; this.emailid = emailid; this.advertname = advertname; this.jobqualificatio = jobqualificatio; this.experience = experience; this.id = id; this.date = date; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getEmailid() { return emailid; } public void setEmailid(String emailid) { this.emailid = emailid; } public String getAdvertname() { return advertname; } public void setAdvertname(String advertname) { this.advertname = advertname; } public String getJobqualificatio() { return jobqualificatio; } public void setJobqualificatio(String jobqualificatio) { this.jobqualificatio = jobqualificatio; } public String getExperience() { return experience; } public void setExperience(String experience) { this.experience = experience; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public jobApply(){ } }
package com.demo.model; import com.demo.model.entity.Usuario; public class ModeloUsuario extends Model { }
package com.example.sean.onedroid; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MoreInfo extends Fragment { public static String values = ""; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.activity_more_info, container, false); } /** * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)} * has returned, but before any saved state has been restored in to the view. * This gives subclasses a chance to initialize themselves once * they know their view hierarchy has been completely created. The fragment's * view hierarchy is not however attached to its parent at this point. * * @param view The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}. * @param savedInstanceState If non-null, this fragment is being re-constructed */ @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { //Create a text view to add more information about each component, with a switch case to determine what information gets displayed where. TextView textView = (TextView) view.findViewById(R.id.moreInfo); switch (values) { case "textView_more_info": textView.setText(R.string.textView_more_info); break; case "button_more_info": textView.setText(R.string.button_more_info); break; default: textView.setText("@TODO: Add more info"); break; } super.onViewCreated(view, savedInstanceState); } }
package DataSets; import com.fasterxml.jackson.annotation.JsonProperty; import javax.persistence.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @Entity @Table(name = "Teacher") public class TeachersDataSet { private String role = ""; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", nullable = false, insertable = true, updatable = true) @JsonProperty("id") private int id; @Column(name = "name", nullable = false, length = 35) @JsonProperty("name") private String name; @Column(name = "surname", nullable = false, length = 40) @JsonProperty("surname") private String surname; @Column(name = "patronymic") @JsonProperty("patronymic") private String patronymic; @Column(name = "email", updatable = false, unique = true, nullable = false, length = 50) @JsonProperty("email") private String email; @Column(name = "password", nullable = false, length = 50) @JsonProperty("password") private String password; @Column(name = "regdate") @JsonProperty("regdate") private String regDate; @OneToMany(fetch = FetchType.EAGER, mappedBy = "teacher_id", cascade = CascadeType.ALL, orphanRemoval = true) @JsonProperty("groups") private Set<GroupsDataSet> groups = new HashSet<>(); @OneToMany(fetch = FetchType.EAGER, mappedBy = "teacher_id", cascade = CascadeType.ALL, orphanRemoval = true) @JsonProperty("tests") private Set<TestsDataSet> tests = new HashSet<>(); @Column(name = "organization", length = 50) private String organization; public TeachersDataSet(){ } public TeachersDataSet(String name, String surname, String patronymic, String email, String password, String regDate, String organization, String role) { this.name = name; this.surname = surname; this.patronymic = patronymic; this.email = email; this.password = password; this.regDate = regDate; this.organization = organization; groups = new HashSet<>(); this.role = role; tests = new HashSet<>(); } public TeachersDataSet(String name, String surname, String email, String password, String regDate, String role) { this.name = name; this.surname = surname; this.email = email; this.password = password; this.regDate = regDate; groups = new HashSet<>(); this.role = role; tests = new HashSet<>(); } public void addTest(TestsDataSet test){ test.setTeacher_id(this); tests.add(test); } public void removeTest(TestsDataSet test){ tests.remove(test); } public void addGroup(GroupsDataSet group){ group.setTeacher_id(this); groups.add(group); } public void removeGroup(GroupsDataSet group){ groups.remove(group); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getPatronymic() { return patronymic; } public void setPatronymic(String patronymic) { this.patronymic = patronymic; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRegDate() { return regDate; } public void setRegDate(String regDate) { this.regDate = regDate; } public Set<GroupsDataSet> getGroups() { return groups; } public void setGroups(Set<GroupsDataSet> groups) { this.groups = groups; } public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } @Override public String toString() { return "TeachersDataSet{" + "id=" + id + ", email='" + email + '\'' + '}'; } /*public int getGroups_id() { return groups_id; } public void setGroups_id(int groups_id) { this.groups_id = groups_id; }*/ }
package com.my.learn.core_java2.ch2; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.util.Scanner; /** * Created by yidianadmin on 14-10-9. */ public class SocketTest { public static void main(String[] args) throws IOException { Socket socket = new Socket(); socket.connect(new InetSocketAddress("time-A.timefreq.bldrdoc.gov", 13)); try { InputStream inputStream = socket.getInputStream(); Scanner in = new Scanner(inputStream); while (in.hasNextLine()) { System.out.println(in.nextLine()); } } finally { socket.close(); } } }
package com.webserver.shoppingmall.post.service.impl; import com.webserver.shoppingmall.post.repository.PostRepository; import com.webserver.shoppingmall.post.repository.CommentRepository; import com.webserver.shoppingmall.post.service.CommentService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @RequiredArgsConstructor @Service public class CommentServiceImpl implements CommentService { private final CommentRepository replyRepository; private final PostRepository postRepository; }
/** * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright (C) 2017 NEMESIS (Lima - Peru) * Sistemas - Desarrollo de Sistemas Informaticos * Luis Bustamante Villar lbustamante@nemesisdata.com * All rights reserved. Used by permission * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ **/ package com.sutran.client.main; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.sutran.client.util.SutranClientConstants; public class SutranClientMain { static final Logger logger = LogManager.getLogger(SutranClientMain.class.getName()); public static void main(String[] args) { try { new ClassPathXmlApplicationContext(SutranClientConstants.CONTEXT_PATHS); } catch (Exception e) { logger.error("Error en inicio de contexto: ", e); } } }
package com.eshop.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.activity.InvalidActivityException; import com.eshop.connection.DBConnection; import com.eshop.exceptions.ArticleException; import com.eshop.exceptions.InvalidInputException; import com.eshop.interfaces.DAO; import com.eshop.models.Article; import com.eshop.models.Camcorder; import com.eshop.models.Computer; public class CamcorderDAO implements DAO { Connection connection = DBConnection.getInstance().getConnection(); @Override public Collection<Article> showAll() throws SQLException, InvalidInputException, InvalidInputException { List<Article> camcorders = new ArrayList<Article>(); String query = "SELECT c.*, l.* FROM camcorder c JOIN label l on(c.label_id = l.id);"; PreparedStatement ps = connection.prepareStatement(query); ResultSet rs = ps.executeQuery(); while (rs.next()) { String label = rs.getString("label"); String model = rs.getString("model"); double price = rs.getDouble("price"); String image = rs.getString("image"); double resolution = rs.getDouble("resolution"); double displaySize = rs.getDouble("display_size"); int digitalZoom = rs.getInt("digital_zoom"); String cameraType = rs.getString("camera_type"); int id = rs.getInt("id"); try { camcorders.add(new Camcorder(image, label, model, price, resolution, cameraType, displaySize, digitalZoom, id)); } catch (InvalidActivityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } connection.close(); return Collections.unmodifiableList(camcorders); } public void insertCamcorder(Camcorder camcorder) throws SQLException { try { String labelQuery = "SELECT label FROM label WHERE label LIKE '" + camcorder.getLabel() + "';"; PreparedStatement labelPs = connection.prepareStatement(labelQuery); ResultSet labelRs = labelPs.executeQuery(); int labelId = 0; if (labelRs.next()) { labelId = labelRs.getInt("id"); } else { labelId = new KeysDAO().insertLabel(camcorder.getLabel()); } PreparedStatement camcorderPs = connection .prepareStatement("INSERT INTO camcorder VALUES(null, ?, ?, ?, ?, ?, ?, ?, ?)"); camcorderPs.setDouble(1, camcorder.getResolution()); camcorderPs.setDouble(2, camcorder.getDisplaySize()); camcorderPs.setInt(3, camcorder.getDigitalZoom()); camcorderPs.setDouble(4, camcorder.getPrice()); camcorderPs.setString(5, camcorder.getModel()); camcorderPs.setString(6, camcorder.getImage()); camcorderPs.setString(7, camcorder.getCameraType()); camcorderPs.setInt(8, labelId); camcorderPs.executeUpdate(); connection.close(); } catch (SQLException e) { connection.close(); e.printStackTrace(); } } @Override public Computer getArticleById(int articleId) throws SQLException, InvalidInputException { // TODO Auto-generated method stub return null; } @Override public Collection<Article> getArticleByLabel(String articlelabel) throws SQLException, InvalidInputException { // TODO Auto-generated method stub return null; } @Override public void deleteArticleById(int id) throws SQLException { // TODO Auto-generated method stub } @Override public void insertArticle(Article article) throws ArticleException { // TODO Auto-generated method stub } }
package com.capgemini.Resource_Management.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.capgemini.Resource_Management.model.ProjectDetails; @Repository public interface ProjectRepository extends JpaRepository<ProjectDetails,Long>{ }
package com.android.wendler.wendlerandroid.main.presenter; import com.android.wendler.wendlerandroid.main.contract.SetContract; import com.android.wendler.wendlerandroid.main.model.Lift; import com.android.wendler.wendlerandroid.main.model.User; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.observers.DisposableObserver; import io.reactivex.schedulers.Schedulers; /** * Created by QiFeng on 7/6/17. */ public class SetPresenter implements SetContract.Presenter { SetContract.Interactor mInteractor; SetContract.View mView; public SetPresenter(SetContract.Interactor interactor){ mInteractor = interactor; } @Override public void advanceWeek(User user, Lift lift) { lift.advanceWeek(); mView.advanceWeek(); if (user.getToken() == null) return; mInteractor.updateUser(user) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .unsubscribeOn(Schedulers.io()) .subscribeWith(new DisposableObserver<User>() { @Override public void onNext(@NonNull User user) { } @Override public void onError(@NonNull Throwable e) { e.printStackTrace(); if (mView != null) { mView.showConnectionError(); } } @Override public void onComplete() { } }); } @Override public void bindView(SetContract.View view) { mView = view; } @Override public void unbind() { mView = null; } }
/* * Copyright (c) 2004 Steve Northover and Mike Wilson * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ package part1.ch9; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; import java.io.*; public class Tree7 { public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setText("Lazy Tree"); Tree tree = new Tree(shell, SWT.BORDER); /* Initialize the roots of the tree */ File[] roots = File.listRoots(); for (int i = 0; i < roots.length; i++) { TreeItem root = new TreeItem(tree, SWT.NULL); root.setText(roots[i].toString()); root.setData(roots[i]); /* Use a dummy item to force the '+' */ new TreeItem(root, SWT.NULL); } /* Use SWT.Expand to lazily fill the tree */ tree.addListener(SWT.Expand, new Listener() { public void handleEvent(Event event) { /* * If the item has not contain a * dummy node, return. A dummy item * is a single child of the root that * does not have any application data. */ TreeItem root = (TreeItem) event.item; TreeItem[] items = root.getItems(); if (items.length != 1) return; if (items[0].getData() != null) return; items[0].dispose(); /* Create the item children */ File file = (File) root.getData(); File[] files = file.listFiles(); if (files == null) return; for (int i = 0; i < files.length; i++) { TreeItem item =new TreeItem(root,SWT.NULL); item.setText(files[i].getName()); item.setData(files[i]); /* Use a dummy item to force the '+' */ if (files[i].isDirectory()) { new TreeItem(item, SWT.NULL); } } } }); /* Set size of the tree and open the shell */ tree.setSize(300, 300); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
package com.stocktrading.stockquote.codec; import com.fasterxml.jackson.databind.JsonNode; import com.mongodb.client.model.Aggregates; import com.mongodb.client.model.Filters; import com.stocktrading.stockquote.enumeration.IDPrefixes; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import org.bson.conversions.Bson; public class IDPrefixCodec implements Codec<IDPrefixes> { @Override public IDPrefixes decode(BsonReader bsonReader, DecoderContext decoderContext) { String objectId = bsonReader.readString(); Bson query = Aggregates.match(Filters.eq("_id", objectId)); JsonNode json; // Optional.ofNullable(Connection.addresses.aggregate(Collections.singletonList(query))).ifPresent(d -> DocumentToJsonNodeConverter.documentToJsonNode( d.first())); //return Connection.addresses.find(query).iterator().tryNext().getCountry(); return null; } @Override public void encode(BsonWriter bsonWriter, IDPrefixes prefix, EncoderContext encoderContext) { } @Override public Class<IDPrefixes> getEncoderClass() { return IDPrefixes.class; } }
package evaluation; import java.util.Arrays; import java.util.LinkedHashMap; public class PairTestAnswer { public final static LinkedHashMap<Integer, PairTestAnswer> ANSWERS; public enum Truth { CORRECT(1), UNCERTAIN(0), INCORRECT(-1); public final int level; Truth(int level) { this.level = level; } public boolean isTrue() { return this.level > 0; } } public final int no; public final String text; public final Truth truth; static { ANSWERS = new LinkedHashMap<Integer, PairTestAnswer>(); Arrays.asList( new PairTestAnswer(1, "correct", Truth.CORRECT), new PairTestAnswer(2, "uncertain", Truth.UNCERTAIN), new PairTestAnswer(3, "incorrect", Truth.INCORRECT) ).stream().forEach(a -> ANSWERS.put(a.no, a)); } public PairTestAnswer(int no, String text, Truth truth) { this.no = no; this.text = text; this.truth = truth; } }
package com.anger.service.userservice.service; import com.anger.service.userservice.dao.UserDao; import com.anger.service.userservice.dto.UserDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; @Service public class DataLoader { private UserRepository userRepository; @Autowired public DataLoader(UserRepository userRepository){ this.userRepository = userRepository; } @PostConstruct private void loadData(){ // save a couple of customers UserDao userDao = userRepository.findByLogin("1"); if (userDao == null) { // userRepository.save(new UserDao("1", "Smith", "Smith", "Alan", "Smith", "smith@test.com", false,"","","","",null)); // userRepository.save(new UserDao("2", "Alex", "Alex", "Alex", "Long", "alex@test.com", false,"","","","",null)); // userRepository.save(new UserDao("3", "Gaj", "Gaj", "Gajan", "Sat", "gajan@test.com", false,"","","","",null)); } } }
package com.wipro.objectserialization; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Date; @SuppressWarnings("serial") public class Employee implements Serializable{ private String name; private Date dateOfBirth; private String department; private String designation; private double salary; Employee() { name="name"; dateOfBirth=new Date(); department="department"; designation="designation"; salary=Double.MAX_VALUE; } Employee(String name,Date dateOfBirth,String department,String designation,double salary) { this.name=name; this.dateOfBirth=dateOfBirth; this.department=department; this.designation=designation; this.salary=salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public static void main(String[] args) { // TODO Auto-generated method stub String name="Nikhil"; String department="R&D"; String designation="Employee"; double salary=500000; @SuppressWarnings("deprecation") Date dateOfBirth=new Date(2000,04,21); Employee employee=new Employee(name,dateOfBirth,department,designation,salary); String path="G:\\WTN-workspace\\WTN\\Milestone1\\src\\com\\wipro\\objectserialization\\"; try { FileOutputStream fos=new FileOutputStream(path+"Data"); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(employee); oos.close(); FileInputStream fis=new FileInputStream(path+"Data"); ObjectInputStream ois=new ObjectInputStream(fis); Employee empobj=(Employee)ois.readObject(); System.out.println(empobj); System.out.println(empobj.getName()); System.out.println(empobj.getDateOfBirth()); System.out.println(empobj.getDepartment()); System.out.println(empobj.getDesignation()); System.out.println(empobj.getSalary()); ois.close(); } catch(Exception e) { System.out.println(e); } } }
package com.daexsys.automata.gui.listeners; import com.daexsys.automata.gui.GUI; import com.daexsys.automata.world.WorldLayer; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class MouseHandler implements MouseListener { private GUI gui; private boolean mouseDown = false; public MouseHandler(GUI gui) { this.gui = gui; } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) { gui.layerBuildingOn = WorldLayer.GROUND; } else { gui.layerBuildingOn = WorldLayer.ABOVE_GROUND; } gui.playerPlaceTile(e.getX(), e.getY(), gui); mouseDown = true; } @Override public void mouseReleased(MouseEvent e) { mouseDown = false; } @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} public boolean isMouseDown() { return mouseDown; } public GUI getGui() { return gui; } }
package com.example.admin.mvp.xulylogin; public interface PresenterlXuLyDangNhap { void kiemTraDangNhap(String name, String pass); }
package edu.nyu.cs9053.homework3.oo; import java.io.PrintStream; public class Letter { private final char[][] asciiVerbose; private final PrintStream out; public Letter(char[][] asciiVerbose, PrintStream out) { this.asciiVerbose = asciiVerbose; this.out = out; } public void print() { for (int i = 0; i < 10; i++){ out.println(asciiVerbose[i]); } } }
package za.ac.ngosa.repository; import za.ac.ngosa.domain.Showing; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** * Created by User on 2015/08/10. */ @Repository public interface ShowingRepository extends CrudRepository<Showing,Long> { public Showing findOne(Long code); }
/* * Created on Jul 9, 2009 * Created by Paul Gardner * * Copyright 2009 Vuze, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package com.aelitis.azureus.core.content; import org.gudy.azureus2.core3.util.Base32; import org.gudy.azureus2.plugins.download.Download; import com.aelitis.azureus.core.cnetwork.ContentNetwork; public abstract class RelatedContent { public final static String[] NO_TAGS = {}; final private String title; final private byte[] hash; final private String tracker; final private long size; private int date; private int seeds_leechers; private byte content_network; private byte[] related_to_hash; private byte[] tracker_keys; private byte[] ws_keys; private String[] tags; public RelatedContent( byte[] _related_to_hash, String _title, byte[] _hash, String _tracker, byte[] _tracker_keys, byte[] _ws_keys, String[] _tags, long _size, int _date, int _seeds_leechers, byte _cnet ) { related_to_hash = _related_to_hash; title = _title; hash = _hash; tracker = _tracker; tracker_keys = _tracker_keys; ws_keys = _ws_keys; tags = _tags; size = _size; date = _date; seeds_leechers = _seeds_leechers; content_network = _cnet; } public RelatedContent( String _title, byte[] _hash, String _tracker, long _size, int _date, int _seeds_leechers, byte _cnet ) { // legacy constructor as referenced from plugin - remove oneday! this( _title, _hash, _tracker, null, null, null, _size, _date, _seeds_leechers, _cnet ); } public RelatedContent( String _title, byte[] _hash, String _tracker, byte[] _tracker_keys, byte[] _ws_keys, String[] _tags, long _size, int _date, int _seeds_leechers, byte _cnet ) { title = _title; hash = _hash; tracker = _tracker; tracker_keys = _tracker_keys; ws_keys = _ws_keys; tags = _tags; size = _size; date = _date; seeds_leechers = _seeds_leechers; content_network = _cnet; } protected void setRelatedToHash( byte[] h ) { related_to_hash = h; } public byte[] getRelatedToHash() { return( related_to_hash ); } public abstract Download getRelatedToDownload(); public String getTitle() { return( title ); } public abstract int getRank(); public byte[] getHash() { return( hash ); } public abstract int getLevel(); public abstract boolean isUnread(); public abstract void setUnread( boolean unread ); public abstract int getLastSeenSecs(); public String getTracker() { return( tracker ); } public byte[] getTrackerKeys() { return( tracker_keys ); } public byte[] getWebSeedKeys() { return( ws_keys ); } public String[] getTags() { return( tags==null?NO_TAGS:tags ); } protected void setTags( String[] _tags ) { tags = _tags; } public long getSize() { return( size ); } public long getPublishDate() { return( date*60*60*1000L ); } protected int getDateHours() { return( date ); } protected void setDateHours( int _date ) { date = _date; } public int getLeechers() { if ( seeds_leechers == -1 ){ return( -1 ); } return( seeds_leechers&0xffff ); } public int getSeeds() { if ( seeds_leechers == -1 ){ return( -1 ); } return( (seeds_leechers>>16) & 0xffff ); } protected int getSeedsLeechers() { return( seeds_leechers ); } protected void setSeedsLeechers( int _sl ) { seeds_leechers = _sl; } public long getContentNetwork() { return((content_network&0xff)==0xff?ContentNetwork.CONTENT_NETWORK_UNKNOWN:(content_network&0xff)); } protected void setContentNetwork( long cnet ) { content_network = (byte)cnet; } public abstract void delete(); public String getString() { return( "title=" + title + ", hash=" + (hash==null?"null":Base32.encode( hash )) + ", tracker=" + tracker +", date=" + date + ", sl=" + seeds_leechers + ", cnet=" + content_network ); } }
package com.eomcs.util; public class Score { public String name;//설계도 public int kor;//설계도 public int math;//설계도 public int eng;//설계도 public int sum ;//설계도 public float aver;//설계도 public void compute() {//non static은값을 줘야한다 s1,s2 this.sum = this.kor + this.eng + this.math; this.aver = this.sum / 3f; } }
package at.fhv.teama.easyticket.server.program; import at.fhv.teama.easyticket.dto.ProgramDto; import at.fhv.teama.easyticket.server.mapping.MapperContext; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import javax.transaction.Transactional; import java.util.Set; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest @Transactional public class ProgramControllerTest { @Autowired private ProgramRepository programRepository; @Autowired private ProgramController programController; @Autowired private ProgramMapper programMapper; @Test @WithMockUser public void getAllPrograms() { Program program1 = new Program(); program1.setDescription("Test1"); program1 = programRepository.save(program1); Program program2 = new Program(); program2.setDescription("Test2"); program2 = programRepository.save(program2); Program program3 = new Program(); program3.setDescription("Test3"); program3 = programRepository.save(program3); ProgramDto program1Dto = programMapper.programToProgramDto(program1, new MapperContext()); ProgramDto program2Dto = programMapper.programToProgramDto(program2, new MapperContext()); ProgramDto program3Dto = programMapper.programToProgramDto(program3, new MapperContext()); assertEquals(Set.of(program1Dto, program2Dto, program3Dto), programController.getAllPrograms()); } @Test @WithMockUser public void save() { Program program1 = new Program(); program1.setDescription("Test1"); ProgramDto program1Dto = programMapper.programToProgramDto(program1, new MapperContext()); program1Dto = programController.saveProgram(program1Dto); Program program2 = new Program(); program2.setDescription("Test2"); ProgramDto program2Dto = programMapper.programToProgramDto(program2, new MapperContext()); program2Dto = programController.saveProgram(program2Dto); Program program3 = new Program(); program3.setDescription("Test3"); ProgramDto program3Dto = programMapper.programToProgramDto(program3, new MapperContext()); program3Dto = programController.saveProgram(program3Dto); assertEquals(Set.of(program1Dto, program2Dto, program3Dto), programController.getAllPrograms()); } @Test public void getAllGenres() { Program program1 = new Program(); program1.setGenre("Test1"); ProgramDto program1Dto = programMapper.programToProgramDto(program1, new MapperContext()); program1Dto = programController.saveProgram(program1Dto); Program program2 = new Program(); program2.setGenre("Test2"); ProgramDto program2Dto = programMapper.programToProgramDto(program2, new MapperContext()); program2Dto = programController.saveProgram(program2Dto); Program program3 = new Program(); program3.setGenre("Test3"); ProgramDto program3Dto = programMapper.programToProgramDto(program3, new MapperContext()); program3Dto = programController.saveProgram(program3Dto); assertEquals(Set.of("Test1", "Test2", "Test3"), programController.getAllGenres()); } }
package com.prep.algorithm; public class Bucketsort { public static void sort(int[] a, int maxVal){ int [] bucket=new int[maxVal+1]; for (int i=0; i<bucket.length; i++){ bucket[i]=0; } for (int i=0; i<a.length; i++){ bucket[a[i]]++; } int outPos=0; for (int i=0; i<bucket.length; i++){ for (int j=0; j<bucket[i]; j++){ a[outPos++]=i; } } } public static void main(String[] args){ int [] data= {90,80,70,60,50,40,30,20,10,10}; //ArrayUtil.randomIntArray(10,maxVal+1); sort(data,90); for(int i=0;i<data.length;i++) System.out.print(data[i] +" , "); System.out.println("\r\n"); } }
package org.yxm.modules.ting.aidlservice; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; import android.os.RemoteException; import android.support.annotation.Nullable; import org.yxm.lib.rxbus.RxBus; import org.yxm.modules.base.utils.LogUtils; import org.yxm.modules.ting.IMusicPlayer; import org.yxm.modules.ting.entity.ting.PaySongEntity; import org.yxm.modules.ting.event.MusicEvent; import org.yxm.modules.ting.net.TingNetManager; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class AidlMusicService extends Service { private static final String TAG = "AidlMusicService"; private MediaPlayer mMediaPlayer; @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } private IMusicPlayer.Stub mBinder = new IMusicPlayer.Stub() { @Override public void playMusicWithPause(String songId) throws RemoteException { if (mMediaPlayer == null) { playMusicWithoutPause(songId); postPlayEvent(); return; } if (mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); postPauseEvent(); } else { mMediaPlayer.start(); postPlayEvent(); } } @Override public void playMusicWithoutPause(String songId) throws RemoteException { if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); } mMediaPlayer.reset(); playNetMusic(songId); } }; private void playNetMusic(String songId) { TingNetManager.getPaySongData(songId, new Callback<PaySongEntity>() { @Override public void onResponse(Call<PaySongEntity> call, Response<PaySongEntity> response) { PaySongEntity entity = response.body(); try { mMediaPlayer.setDataSource(entity.bitrate.file_link); mMediaPlayer.prepare(); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mMediaPlayer.start(); postPlayEvent(); } }); } catch (Exception e) { e.printStackTrace(); postPauseEvent(); } } @Override public void onFailure(Call<PaySongEntity> call, Throwable t) { LogUtils.d(TAG, "onFailure"); postPauseEvent(); } }); } public void postPlayEvent() { MusicEvent event = new MusicEvent(); event.state = MusicEvent.STATE_PLAY; RxBus.get().post(event); } public void postPauseEvent() { MusicEvent event = new MusicEvent(); event.state = MusicEvent.STATE_PAUSE; RxBus.get().post(event); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.context.junit.jupiter.web; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.ApplicationContextInitializer; import org.springframework.core.annotation.AliasFor; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; /** * {@code @SpringJUnitWebConfig} is a <em>composed annotation</em> that combines * {@link ExtendWith @ExtendWith(SpringExtension.class)} from JUnit Jupiter with * {@link ContextConfiguration @ContextConfiguration} and * {@link WebAppConfiguration @WebAppConfiguration} from the <em>Spring TestContext * Framework</em>. * * <p>As of Spring Framework 5.3, this annotation will effectively be inherited * from an enclosing test class by default. See * {@link org.springframework.test.context.NestedTestConfiguration @NestedTestConfiguration} * for details. * * @author Sam Brannen * @since 5.0 * @see ExtendWith * @see SpringExtension * @see ContextConfiguration * @see WebAppConfiguration * @see org.springframework.test.context.junit.jupiter.SpringJUnitConfig */ @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface SpringJUnitWebConfig { /** * Alias for {@link ContextConfiguration#classes}. */ @AliasFor(annotation = ContextConfiguration.class, attribute = "classes") Class<?>[] value() default {}; /** * Alias for {@link ContextConfiguration#classes}. */ @AliasFor(annotation = ContextConfiguration.class) Class<?>[] classes() default {}; /** * Alias for {@link ContextConfiguration#locations}. */ @AliasFor(annotation = ContextConfiguration.class) String[] locations() default {}; /** * Alias for {@link ContextConfiguration#initializers}. */ @AliasFor(annotation = ContextConfiguration.class) Class<? extends ApplicationContextInitializer<?>>[] initializers() default {}; /** * Alias for {@link ContextConfiguration#inheritLocations}. */ @AliasFor(annotation = ContextConfiguration.class) boolean inheritLocations() default true; /** * Alias for {@link ContextConfiguration#inheritInitializers}. */ @AliasFor(annotation = ContextConfiguration.class) boolean inheritInitializers() default true; /** * Alias for {@link ContextConfiguration#name}. */ @AliasFor(annotation = ContextConfiguration.class) String name() default ""; /** * Alias for {@link WebAppConfiguration#value}. */ @AliasFor(annotation = WebAppConfiguration.class, attribute = "value") String resourcePath() default "src/main/webapp"; }
package database; import controllers.ShoppingCart; import models.*; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import javax.persistence.ParameterMode; import javax.persistence.StoredProcedureQuery; import java.util.ArrayList; import java.util.Calendar; import java.util.LinkedList; import java.util.List; public class MysqlDatabaseHandler implements DatabaseHandler { private SessionFactory factory; private static MysqlDatabaseHandler instance; private MysqlDatabaseHandler() { // create session factory factory = new Configuration() .configure("hibernate.cfg.xml") .addAnnotatedClass(Book.class) .addAnnotatedClass(BookAuthors.class) .addAnnotatedClass(Category.class) .addAnnotatedClass(LibraryOrders.class) .addAnnotatedClass(Publisher.class) .addAnnotatedClass(PublisherAddresses.class) .addAnnotatedClass(PublisherPhones.class) .addAnnotatedClass(User.class) .addAnnotatedClass(UserOrders.class) .buildSessionFactory(); // create session } public static DatabaseHandler getInstance() { if (instance == null) instance = new MysqlDatabaseHandler(); return instance; } @Override public boolean signUp(User user) { Session session = factory.getCurrentSession(); session.beginTransaction(); session.save(user); try { session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } @Override public boolean login(String username, String password) { Session session = factory.getCurrentSession(); String query = "From User u where u.userName= '" + username + "'"; session.beginTransaction(); try { User user = (User) session.createQuery(query).getResultList().get(0); session.getTransaction().commit(); if (user.passwordEqualityCheck(password)) { LoggedUser loggedUser = LoggedUser.getInstance(); loggedUser.setUser(user); loggedUser.setCart(new ShoppingCart()); loggedUser.setLoggedIn(true); return true; } return false; } catch (Exception e) { e.printStackTrace(); return false; } } @Override public void logout() { Session session = factory.getCurrentSession(); session.close(); LoggedUser.getInstance().logOut(); } @Override public boolean addNewBook(Book book) { return add(book); } @Override public boolean updateBookData(Book newBook) { User user = LoggedUser.getInstance().getUser(); if (!user.getIsManger()) return false; Session session = factory.getCurrentSession(); session.beginTransaction(); session.update(newBook); try { session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } @Override public boolean UpdateUserData() { User user = LoggedUser.getInstance().getUser(); Session session = factory.getCurrentSession(); session.beginTransaction(); session.update(user); try { session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } @Override public boolean orderFromSupplier(String isbn, int quantity) { if (!LoggedUser.getInstance().getUser().getIsManger()) return false; Session session = factory.getCurrentSession(); session.beginTransaction(); LibraryOrders order = new LibraryOrders(isbn, quantity); session.save(order); session.getTransaction().commit(); return true; } @Override public boolean confirmOrder(LibraryOrders order) { User user = LoggedUser.getInstance().getUser(); if (!user.getIsManger()) return false; Session session = factory.getCurrentSession(); session.beginTransaction(); order.setConfirmed(true); session.update(order); try { session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } @Override public boolean promoteUser(String username) { User manager = LoggedUser.getInstance().getUser(); Session session = factory.getCurrentSession(); if (manager.getIsManger()) { String query = "From User u where u.userName= '" + username + "'"; System.out.println(query); session.beginTransaction(); User user = (User) session.createQuery(query).getResultList().get(0); try { session.getTransaction().commit(); user.setIsManger(true); session = factory.getCurrentSession(); session.beginTransaction(); session.update(user); session.getTransaction().commit(); return true; } catch (Exception e) { session.getTransaction().rollback(); e.printStackTrace(); return false; } } return false; } @Override public int getprevMonthSales() { Session session = factory.getCurrentSession(); session.beginTransaction(); StoredProcedureQuery query = session.createStoredProcedureQuery("get_total_sales"); query.registerStoredProcedureParameter("sales", Integer.class, ParameterMode.OUT); query.execute(); if (query.getOutputParameterValue("sales") == null) return 0; int sales = (int) query.getOutputParameterValue("sales"); session.getTransaction().commit(); return sales; } @Override public String getTop5Customers() { Session session = factory.getCurrentSession(); session.beginTransaction(); StoredProcedureQuery query = session.createStoredProcedureQuery("get_top_users"); query.execute(); if (query.getResultList() == null) return ""; List<String> users = (List<String>) query.getResultList(); session.getTransaction().commit(); StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; i <= users.size(); i++) { stringBuilder.append(i + ". "); stringBuilder.append(users.get(i - 1)); stringBuilder.append("\n"); } return stringBuilder.toString(); } @Override public String viewTopSellingBooks() { Session session = factory.getCurrentSession(); session.beginTransaction(); StoredProcedureQuery query = session.createStoredProcedureQuery("get_top_books"); query.execute(); if (query.getResultList() == null) return ""; List<String> books = (List<String>) query.getResultList(); session.getTransaction().commit(); StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; i <= books.size(); i++) { stringBuilder.append(i + ". "); stringBuilder.append(books.get(i - 1)); stringBuilder.append("\n"); } return stringBuilder.toString(); } @Override public List<Book> findBook(BookDAO bookData) { Session session = factory.getCurrentSession(); List<Book> books; boolean where=false; StringBuilder query = new StringBuilder("From Book b"); boolean flag = false; if (bookData.getIsbn() != null) { query.append(" where "); where=true; query.append(" b.isbn like '"); query.append(bookData.getIsbn()); query.append("%'"); flag = true; } if (bookData.getTitle() != null) { if(!where) query.append(" where "); where=true; if (flag) query.append(" and "); query.append(" b.title like '"); query.append(bookData.getTitle()); query.append("%'"); flag = true; } if (bookData.getLowerPrice() != 0) { if(!where) query.append(" where "); where=true; if (flag) query.append(" and "); query.append(" b.price >= "); query.append(bookData.getLowerPrice()); flag = true; } if (bookData.getUpperPrice() != 0) { if(!where) query.append(" where "); where=true; if (flag) query.append(" and "); query.append(" b.price <= "); query.append(bookData.getUpperPrice()); flag = true; } if (bookData.getPublisher() != null) { if(!where) query.append(" where "); where=true; if (flag) query.append(" and "); query.append(" b.publisherName = '"); query.append(bookData.getPublisher()); query.append("'"); flag = true; } if (bookData.getCategories() != null) { if(!where) query.append(" where "); if (flag) query.append(" and "); query.append(" b.categoryName in ("); int i = 0; for (String category : bookData.getCategories()) { query.append(" '"); query.append(category); query.append("' "); if (i != bookData.getCategories().size() - 1) { query.append(","); } i++; } query.append(")"); } System.out.println(query.toString()); session.beginTransaction(); try { books = session.createQuery(query.toString()).getResultList(); session.getTransaction().commit(); } catch (Exception e) { session.getTransaction().rollback(); e.printStackTrace(); return null; } if (books == null) return new LinkedList<>(); if (bookData.getAuthor() != null) { List<Book> removed = new ArrayList<Book>(); for (Book b : books) { if (!isAuthor(b, bookData.getAuthor())) removed.add(b); } books.removeAll(removed); } return books; } private boolean isAuthor(Book b, String author) { Session session = factory.getCurrentSession(); String query ="From BookAuthors b where b.pk.isbn= '"+b.getIsbn()+"' and b.pk.authorName= '"+author+"'"; session.beginTransaction(); try { List<?> authors = session.createQuery(query).getResultList(); session.getTransaction().commit(); return authors != null&&authors.size()!=0; } catch (Exception e) { session.getTransaction().rollback(); e.printStackTrace(); return false; } } @Override public void addToShoppingCard(String isbn, int quantity) { User user = LoggedUser.getInstance().getUser(); UserOrders order = new UserOrders(isbn, user.getUserName(), quantity); ShoppingCart cart = LoggedUser.getInstance().getCart(); cart.addOrder(order); } @Override public List<UserOrders> ShowShoppingCardInfo() { ShoppingCart cart = LoggedUser.getInstance().getCart(); return cart.getOrders(); } @Override public boolean removeFromShoppingCard(String isbn) { ShoppingCart cart = LoggedUser.getInstance().getCart(); for (UserOrders order : cart.getOrders()) { if (order.getIsbn().equals(isbn)) { cart.getOrders().remove(order); return true; } } return false; } @Override public boolean checkout(String creditCardNum, java.sql.Date expirationDate) { ShoppingCart cart = LoggedUser.getInstance().getCart(); Session session = factory.getCurrentSession(); session.beginTransaction(); for (UserOrders order : cart.getOrders()) { java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime()); order.setCheckOutDate(date); order.setCreditCardNum(creditCardNum); order.setExpirationDate(expirationDate); if (order.isValidCreditCardNum() && order.isValidExpirationDate()) { session.save(order); } else { System.out.println("Invalid Credit Card info."); return false; } } try { session.getTransaction().commit(); } catch (Exception e) { session.getTransaction().rollback(); e.printStackTrace(); return false; } return true; } @Override public List<LibraryOrders> getOrders() { Session session = factory.getCurrentSession(); String query = "From LibraryOrders l"; session.beginTransaction(); try { List<?> orders = session.createQuery(query).getResultList(); session.getTransaction().commit(); return (List<LibraryOrders>) orders; } catch (Exception e) { session.getTransaction().rollback(); e.printStackTrace(); return null; } } @Override public List<String> getCategories() { Session session = factory.getCurrentSession(); String query = "From Category c"; session.beginTransaction(); try { List<?> categories = session.createQuery(query).getResultList(); List<String> result = new LinkedList<>(); session.getTransaction().commit(); for (Category c : (List<Category>) categories) { result.add(c.getCategoryName()); } return result; } catch (Exception e) { session.getTransaction().rollback(); e.printStackTrace(); return null; } } @Override public List<Publisher> getPublishers() { Session session = factory.getCurrentSession(); String query = "From Publisher p"; session.beginTransaction(); try { List<?> publishers = session.createQuery(query).getResultList(); session.getTransaction().commit(); return (List<Publisher>) publishers; } catch (Exception e) { session.getTransaction().rollback(); e.printStackTrace(); return null; } } @Override public boolean addNewPublisher(Publisher publisher) { return add(publisher); } @Override public boolean addNewAuthor(BookAuthors author) { return add(author); } @Override public boolean addPublisherAddresses(Publisher publisher, List<String> addresses) { boolean res = true; for (String address : addresses) { res &= add(new PublisherAddresses(publisher.getPublisherName(), address)); if (!res) return false; } return true; } @Override public boolean addPublisherPhones(Publisher publisher, List<String> phones) { boolean res = true; for (String phone : phones) { res &= add(new PublisherPhones(publisher.getPublisherName(), phone)); if (!res) return false; } return true; } @Override public boolean removeBook(Book book) { Session session=factory.getCurrentSession(); session.beginTransaction(); session.remove(book); try{ session.getTransaction().commit(); }catch (Exception e){ e.printStackTrace(); session.getTransaction().rollback(); return false; } return true; } private boolean add(Object o) { User user = LoggedUser.getInstance().getUser(); if (!user.getIsManger()) return false; Session session = factory.getCurrentSession(); session.beginTransaction(); session.save(o); try { session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }
package com.taskmanag.taskmanag.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MwcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/login").setViewName("login"); registry.addViewController("/registration").setViewName("registration"); } @Bean public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerCustomizer(){ return container->{ container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,"/")); };} }
package com.nepc.asset.manager.configuration; /** * Constants used across the application * * @author Rubén Jiménez */ public class Constants { public static final char DISABLED_VALUE = '0'; public static final char ENABLED_VALUE = '1'; }
package modelo.excepciones; public class CasilleroOcupado extends RuntimeException { private static final long serialVersionUID = 7526472295622776147L; }
package com.sjquechao.cashier.model; import com.google.gson.Gson; import com.sjquechao.cashier.cons.Cons; import com.sjquechao.cashier.model.api.IApi; import com.sjquechao.cashier.utils.LogUtils; import com.sjquechao.cashier.view.application.App; import java.io.IOException; import java.util.Iterator; import java.util.Set; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; import rx.schedulers.Schedulers; /** * Created by Administrator on 2017/2/26. */ public class ApiService { protected static final Gson gson; private static final LogUtils logUtils = LogUtils.getInstance(ApiService.class); protected static final IApi api; static { gson = new Gson(); // 构建OkHttp并添加拦截器 OkHttpClient.Builder builder = new OkHttpClient.Builder(); Interceptor interceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); // Debug模式跳过 if (!App.isDBG()) { return chain.proceed(request); } String method = request.method(); HttpUrl url = request.url(); logUtils.append("method", method) .append("url", url) .print(); Headers headers = request.headers(); Set<String> names = headers.names(); Iterator<String> iterator = names.iterator(); logUtils.append("headers"); while (iterator.hasNext()) { String name = iterator.next(); String value = headers.get(name); logUtils.append("name", name) .append("value", value); } logUtils.print(); RequestBody body = request.body(); if (body != null) { long contentLength = body.contentLength(); MediaType mediaType = body.contentType(); logUtils.append("RequestBody") .append("contentLength", contentLength) .append("mediaType", mediaType) .print(); } return chain.proceed(request); } }; builder.addNetworkInterceptor(interceptor); // 构建Retrofit Retrofit retrofit = new Retrofit.Builder() .baseUrl(Cons.Http.Url.URL_BASE) .addConverterFactory(GsonConverterFactory.create()) // 添加对Gson的支持 .addConverterFactory(ScalarsConverterFactory.create()) .client(builder.build()) .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) .build(); // 将Retrofit与IApi相绑定 api = retrofit.create(IApi.class); } }
package org.sunshinelibrary.turtle.reader; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import org.sunshinelibrary.turtle.utils.Configurations; import org.sunshinelibrary.turtle.utils.Logger; /** * User: fxp * Date: 10/12/13 * Time: 4:35 PM */ public class PdfActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Logger.i("reader request,pdf"); Intent intent = getIntent(); if (intent == null) { finish(); return; } String url = intent.getData().getQueryParameter("url"); if (!TextUtils.isEmpty(url)) { if (!url.startsWith("http://")) { url = Configurations.localHost + url; } Logger.i("open pdf:" + url); try { Uri uri = Uri.parse(url); Intent readerIntent = new Intent(Intent.ACTION_VIEW, uri); readerIntent.setPackage("com.adobe.reader"); startActivity(readerIntent); } catch (Exception e) { Logger.e("start reader failed," + url); } } finish(); } }
package com.example.PollingApplication.controllers; import com.example.PollingApplication.domain.Poll; import com.example.PollingApplication.services.PollService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController public class PollController { @Autowired private PollService pollService; @CrossOrigin(origins = "http://localhost:8080/polls") @RequestMapping(value="/polls", method= RequestMethod.GET) public ResponseEntity<Iterable<Poll>> getAllPolls() { return pollService.getAllPolls(); } @RequestMapping(value="/polls", method=RequestMethod.POST) public ResponseEntity<?> createPoll(@Valid @RequestBody Poll poll) { return pollService.createPoll(poll); } @RequestMapping(value="/polls/{pollId}", method=RequestMethod.GET) public ResponseEntity<?> getPoll(@PathVariable Long pollId) { return pollService.getPoll(pollId); } @RequestMapping(value="/polls/{pollId}", method=RequestMethod.PUT) public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId) { return pollService.updatePoll(poll, pollId); } @RequestMapping(value="/polls/{pollId}", method=RequestMethod.DELETE) public ResponseEntity<?> deletePoll(@PathVariable Long pollId) { return pollService.deletePoll(pollId); } }
package com.meetingapp.android.ui; import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.widget.TimePicker; import java.util.Calendar; /** * Created on 30.11.2017. */ public class MeetingTimePicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener { TimePickerDialog.OnTimeSetListener listener; public void setListener(TimePickerDialog.OnTimeSetListener listener) { this.listener = listener; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar calendar = Calendar.getInstance(); return new TimePickerDialog(getContext(), this, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true); } @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { if (listener != null) { listener.onTimeSet(view, hourOfDay, minute); } } }
package driver; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import state.stateManager.ScreenShell; /** * This is the primary driver class for this game. * * Created by Hongyu Wang on 5/5/2016. */ public class GameLoop extends Game { @Override public void create () { ScreenShell.initiate(); } @Override public void render () { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); super.render(); } @Override public void dispose() { screen.dispose(); StaticDisposables.dispose(); } static public class StaticDisposables{ static Array<Disposable> disposables; public static void addDisposable(Disposable e){ if (disposables == null) disposables = new Array<>(); disposables.add(e); } static void dispose(){ for (Disposable e : disposables){ e.dispose(); } } } }
/** * Diese Datei gehört zum Android/Java Framework zur Veranstaltung "Computergrafik für * Augmented Reality" von Prof. Dr. Philipp Jenke an der Hochschule für Angewandte * Wissenschaften (HAW) Hamburg. Weder Teile der Software noch das Framework als Ganzes dürfen * ohne die Einwilligung von Philipp Jenke außerhalb von Forschungs- und Lehrprojekten an der HAW * Hamburg verwendet werden. * <p> * This file is part of the Android/Java framework for the course "Computer graphics for augmented * reality" by Prof. Dr. Philipp Jenke at the University of Applied (UAS) Sciences Hamburg. Neither * parts of the framework nor the complete framework may be used outside of research or student * projects at the UAS Hamburg. */ package edu.hawhamburg.shared.datastructures.mesh; import java.util.ArrayList; import java.util.List; import edu.hawhamburg.shared.math.Vector; /** * Implementation of a indexed vertex list triangle mesh. */ public class TriangleMesh implements ITriangleMesh { /** * Vertices. */ private List<Vertex> vertices = new ArrayList<Vertex>(); /** * Triangles. */ private List<Triangle> triangles = new ArrayList<Triangle>(); /** * Texture coordinates. */ private List<Vector> textureCoordinates = new ArrayList<Vector>(); /** * Texture object, leave null if no texture is used. */ private String textureName = null; public TriangleMesh() { } public TriangleMesh(String textureName) { this.textureName = textureName; } @Override public void clear() { vertices.clear(); triangles.clear(); textureCoordinates.clear(); } @Override public void addTriangle(int vertexIndex1, int vertexIndex2, int vertexIndex3) { triangles.add(new Triangle(vertexIndex1, vertexIndex2, vertexIndex3)); } @Override public void addTriangle(AbstractTriangle t) { if (t instanceof Triangle) { triangles.add((Triangle) t); } else { throw new IllegalArgumentException("Can only add Triangle objects."); } } @Override public int addVertex(Vector position) { vertices.add(new Vertex(position)); return vertices.size() - 1; } public int addVertex(Vector position, Vector color) { Vertex v = new Vertex(position); v.setColor(color); vertices.add(v); return vertices.size() - 1; } @Override public Vertex getVertex(int index) { return vertices.get(index); } @Override public int getNumberOfTriangles() { return triangles.size(); } @Override public int getNumberOfVertices() { return vertices.size(); } @Override public Triangle getTriangle(int triangleIndex) { return triangles.get(triangleIndex); } @Override public Vector getTextureCoordinate(int texCoordIndex) { return textureCoordinates.get(texCoordIndex); } @Override public void computeTriangleNormals() { for (int triangleIndex = 0; triangleIndex < getNumberOfTriangles(); triangleIndex++) { Triangle t = triangles.get(triangleIndex); Vector a = vertices.get(t.getVertexIndex(0)).getPosition(); Vector b = vertices.get(t.getVertexIndex(1)).getPosition(); Vector c = vertices.get(t.getVertexIndex(2)).getPosition(); Vector normal = b.subtract(a).cross(c.subtract(a)); double norm = normal.getNorm(); if (norm > 1e-5) { normal.multiply(1.0 / norm); } t.setNormal(normal); } } @Override public void addTextureCoordinate(Vector t) { textureCoordinates.add(t); } @Override public int getNumberOfTextureCoordinates() { return textureCoordinates.size(); } @Override public void setColor(Vector color) { if (color.getDimension() != 4) { return; } for (Triangle triangle : triangles) { triangle.setColor(color); } for (Vertex vertex : vertices) { vertex.setColor(color); } } }
package com.jerry.racecondition; /** * Date: 2017/10/3 10:53 * * @author jerry.R */ public class Threads implements Runnable { RequestIDGenerator requestIDGenerator = RequestIDGenerator.getInstance(); @Override public void run() { try { sleep(); } catch (InterruptedException e) { e.printStackTrace(); } } private void sleep() throws InterruptedException { //System.out.println(Thread.currentThread().getName() + "---" + requestIDGenerator.getSeq()); requestIDGenerator.getSeq(); } }
package be.odisee.se4.hetnest.service; import be.odisee.se4.hetnest.dao.*; import be.odisee.se4.hetnest.domain.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.*; import java.util.List; /** * @author User * @version 1.0 * @created 17-Mar-2019 14:19:05 */ @Service("hetNestService") @Transactional(propagation = Propagation.SUPPORTS, readOnly=true) public class HetNestServiceImpl implements HetNestService { public Ingredient m_Ingredient; public Brouwsel m_Brouwsel; public Aanbieding m_Aanbieding; public HetNestServiceImpl(){ } public void finalize() throws Throwable { } public void voorraadVoegToe(){ } public void voorraadNeemAf(){ } public void leveringBestel(){ } public void leveringKeurGoed(){ } public void leveringKeurAf(){ } public void leveringAnnuleer(){ } public void leveringVraagAnnulatieAan(){ } public void aanbiedingAccepteerAanbod(){ } public void aanbiedingWeigerAanbod(){ } public void aanbiedingOnderhandelAanbod(){ } public void maakBrouwselAan(){ } public void voegBrouwEntryToe(){ } public void verwijderBrouwEntry(){ } public void neemBrouwLogSnapshot(){ } public void archiveerBrouwsel(){ } public void voltooiBrouwsel(){ } /** * * @param hoeveelheid */ public void lerveringMaakAan(int hoeveelheid){ } public void leveringAangekomen(){ } public void aanbiedingenVraagOp(){ } @Autowired private UserRepository userrepository = null; public List<User> geefAllePersonen() { return userrepository.findAll(); } }
package com.zenika.microservices.resanet.controller; import org.springframework.web.bind.annotation.RestController; @RestController public class PaysController { }
import java.util.Scanner; class question4a{ public static void main(String[] args) { //variables Scanner sc = new Scanner(System.in); double r = 0; double area = 0; //input //sc.nextDouble(); //sc.nextInt(); //sc.nextBoolean(); //sc.nextLine(); System.out.println("Circle Radius Calc"); System.out.println("-----"); System.out.println(""); System.out.print("Enter the circle's area: "); area = sc.nextDouble(); //calculations && display radius r = Math.sqrt (area / Math.PI); System.out.println("The circle with area " + area + " units^2 has a radius of "+ r +" units. "); } }
package com.wongel.test; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; /** * Created by tseringwongelgurung on 11/23/17. */ public class MyAdapter extends RecyclerView.Adapter<MyVH> { private List<Student> list; private OnMyClickListner listner; public MyAdapter(List<Student> list, OnMyClickListner listner) { this.list = list; this.listner = listner; } @Override public MyVH onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_adapter, null); return new MyVH(view,listner); } @Override public void onBindViewHolder(MyVH holder, int position) { Student student = list.get(position); holder.edtName.setText(student.getName()); } @Override public int getItemCount() { return list.size(); } }
package ec.edu.upse.dao; import java.util.ArrayList; import java.util.List; import javax.persistence.Query; import ec.edu.upse.modelo.TblSgaPeriodonivel; public class PeriodoNivelDao extends ClaseDao{ @SuppressWarnings("unchecked") public List<TblSgaPeriodonivel> getNivelByPeriodo(Integer idPeriodo) { List<TblSgaPeriodonivel> retorno = new ArrayList<TblSgaPeriodonivel>(); Query query = getEntityManager().createNamedQuery("TblSgaPeriodonivel.buscarPorPeriodo"); query.setHint("javax.persistence.cache.storeMode", "REFRESH"); query.setParameter("idPeriodo", idPeriodo); retorno = (List<TblSgaPeriodonivel>) query.getResultList(); return retorno; } }
/* * Copyright (c) 2012, Riven * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Riven nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.indiespot.media; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import craterstudio.util.concur.SimpleBlockingQueue; import net.indiespot.media.impl.FFmpeg; import net.indiespot.media.impl.VideoMetadata; public class Movie implements Closeable { public static Movie open(File movieFile) throws IOException { VideoMetadata metadata = FFmpeg.extractMetadata(movieFile); InputStream rgb24Stream = FFmpeg.extractVideoAsRGB24(movieFile); InputStream wav16Stream = FFmpeg.extractAudioAsWAV(movieFile); AudioStream audioStream = new AudioStream(wav16Stream); VideoStream videoStream = new VideoStream(rgb24Stream, metadata); videoStream = new ThreadedVideoStream(videoStream, metadata, 3); return new Movie(metadata, videoStream, audioStream); } private Movie(VideoMetadata metadata, VideoStream videoStream, AudioStream audioStream) { this.metadata = metadata; this.videoStream = videoStream; this.audioStream = audioStream; } // private final VideoMetadata metadata; public int width() { return metadata.width; } public int height() { return metadata.height; } public float framerate() { return metadata.framerate; } // private final VideoStream videoStream; private final AudioStream audioStream; public VideoStream videoStream() { return videoStream; } public AudioStream audioStream() { return audioStream; } // private long initFrame; private long frameInterval; public void init() { initFrame = System.nanoTime(); audioIndex = 0; videoIndex = 0; frameInterval = (long) (1000_000_000L / metadata.framerate); } // private static final int AUDIO_UNAVAILABLE = -1; private static final int AUDIO_TERMINATED = -2; private int audioIndex; private int videoIndex; public void onMissingAudio() { audioIndex = AUDIO_UNAVAILABLE; } public void onEndOfAudio() { audioIndex = AUDIO_TERMINATED; } public void onRenderedAudioBuffer() { this.audioIndex++; } public void onUpdatedVideoFrame() { this.videoIndex++; } public boolean isTimeForNextFrame() { switch (audioIndex) { case AUDIO_TERMINATED: // reached end of audio return true; case AUDIO_UNAVAILABLE: // sync video with clock return videoIndex * frameInterval <= System.nanoTime() - initFrame; default: // sync video with audio return videoIndex <= audioIndex; } } @Override public void close() throws IOException { audioStream().close(); videoStream().close(); } } class ThreadedVideoStream extends VideoStream { private final VideoStream backing; private final SimpleBlockingQueue<ByteBuffer> emptyQueue, filledQueue; public ThreadedVideoStream(final VideoStream backing, VideoMetadata metadata, int buffers) { super(backing.videoStream, metadata); this.backing = backing; this.emptyQueue = new SimpleBlockingQueue<>(); this.filledQueue = new SimpleBlockingQueue<>(); for (int i = 0; i < buffers; i++) { this.emptyQueue.put(ByteBuffer.allocateDirect(metadata.width * metadata.height * 3)); } new Thread(new Runnable() { @Override public void run() { while (true) { ByteBuffer rgbBuffer = emptyQueue.take(); rgbBuffer.clear(); if (backing.readFrameInto(rgbBuffer) == null) { break; } rgbBuffer.flip(); filledQueue.put(rgbBuffer); } filledQueue.put(null); } }).start(); } public ByteBuffer readFrameInto(ByteBuffer rgbBuffer) { if (rgbBuffer != null) { this.emptyQueue.put(rgbBuffer); } return this.filledQueue.take(); } @Override public void close() throws IOException { this.backing.close(); } }
package com.lipnus.gleam; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.MediaPlayer; import android.nfc.NfcAdapter; import android.nfc.tech.NfcF; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.util.AttributeSet; import android.view.TextureView; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.eftimoff.viewpagertransformers.CubeOutTransformer; import com.lipnus.gleam.fragment.ScreenSlidePageFragment; public class MainActivity extends AppCompatActivity { // 뷰페이저 private ViewPager mPager; private PagerAdapter mPagerAdapter; TextView tv; NfcAdapter na; // NFC 어댑터 PendingIntent pi; // 수신받은 데이터가 저장된 인텐트 IntentFilter[] mIntentFilters; // 인텐트 필터 String[][] mNFCTechLists; //음악플레이어 MediaPlayer mp = new MediaPlayer(); //네비게이션 이미지 ImageView navi1, navi2, navi3, navi4, navi5; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //툴바 없에기/ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Instantiate a ViewPager and a PagerAdapter. mPager = (ViewPager) findViewById(R.id.pager); mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager()); mPager.setAdapter(mPagerAdapter); //전환효과(false, true에 의해서 앞뒤의 레이어 순위가 바뀜) mPager.setPageTransformer(true, new CubeOutTransformer()); //뷰페이저에 변화가 있을때의 리스너(쓰진 않음) mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { naviAllBlack(); switch (position){ case 0: Glide.with(getApplicationContext()) .load( R.drawable.icon11 ) .into(navi1); navi1.setScaleType(ImageView.ScaleType.FIT_XY); break; case 1: Glide.with(getApplicationContext()) .load( R.drawable.icon22 ) .into(navi2); navi2.setScaleType(ImageView.ScaleType.FIT_XY); break; case 2: Glide.with(getApplicationContext()) .load( R.drawable.icon33 ) .into(navi3); navi3.setScaleType(ImageView.ScaleType.FIT_XY); break; case 3: Glide.with(getApplicationContext()) .load( R.drawable.icon44 ) .into(navi4); navi4.setScaleType(ImageView.ScaleType.FIT_XY); break; case 4: Glide.with(getApplicationContext()) .load( R.drawable.icon55 ) .into(navi5); navi5.setScaleType(ImageView.ScaleType.FIT_XY); break; } } @Override public void onPageScrollStateChanged(int state) { } }); navi1 = (ImageView) findViewById(R.id.main_navi1); navi2 = (ImageView) findViewById(R.id.main_navi2); navi3 = (ImageView) findViewById(R.id.main_navi3); navi4 = (ImageView) findViewById(R.id.main_navi4); navi5 = (ImageView) findViewById(R.id.main_navi5); naviAllBlack(); Glide.with(this) .load( R.drawable.icon11 ) .into(navi1); navi1.setScaleType(ImageView.ScaleType.FIT_XY); //NFC tv = (TextView) findViewById(R.id.textMessage); na = NfcAdapter.getDefaultAdapter(this); // NFC 어댑터 if (na == null) { tv.setText("This phone is not NFC_enable."); // 경고 메시지로 변경 후 종료 return; } // NFC 칩 존재 X tv.setText("Scan a NFC tag"); Intent i = new Intent(this, getClass()); i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); pi = PendingIntent.getActivity(this, 0, i, 0); IntentFilter iFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); // NFC 데이터 활성화에 필요한 인텐트 필터 생성 try { iFilter.addDataType("*/*"); mIntentFilters = new IntentFilter[]{iFilter}; } catch (Exception e) { tv.setText("Make IntentFilter error"); } mNFCTechLists = new String[][]{new String[]{NfcF.class.getName()}}; } public void naviAllBlack(){ Glide.with(this) .load( R.drawable.icon1 ) .into(navi1); navi1.setScaleType(ImageView.ScaleType.FIT_XY); Glide.with(this) .load( R.drawable.icon2 ) .into(navi2); navi2.setScaleType(ImageView.ScaleType.FIT_XY); Glide.with(this) .load( R.drawable.icon3 ) .into(navi3); navi3.setScaleType(ImageView.ScaleType.FIT_XY); Glide.with(this) .load( R.drawable.icon4 ) .into(navi4); navi4.setScaleType(ImageView.ScaleType.FIT_XY); Glide.with(this) .load( R.drawable.icon5 ) .into(navi5); navi5.setScaleType(ImageView.ScaleType.FIT_XY); } public void onClick_navi(View v){ switch(v.getId()){ case R.id.main_navi1: mPager.setCurrentItem(0, true); break; case R.id.main_navi2: mPager.setCurrentItem(1, true); break; case R.id.main_navi3: mPager.setCurrentItem(2, true); break; case R.id.main_navi4: mPager.setCurrentItem(3, true); break; case R.id.main_navi5: mPager.setCurrentItem(4, true); break; } } /** * A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in * sequence. */ private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { public ScreenSlidePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return ScreenSlidePageFragment.PlaceholderFragment.newInstance(position + 1); } @Override public int getCount() { //뷰페이저의 총 페이지수 return 5; } } //=============================================================================================== // NFC 검출부분 //=============================================================================================== public void detectSound(){ mp.release(); mp = MediaPlayer.create(this, R.raw.sound_mac); mp.start(); } public void onResume() { super.onResume(); if (na != null) { //na.enableForegroundDispatch(this, pi, null, null); na.enableForegroundDispatch(this, pi, null, null); } } public void onPause() { super.onPause(); if (na != null) { na.disableForegroundDispatch(this); } } @Override public void onNewIntent(Intent i) { String action = i.getAction(); // intent에서 action 추출 String tag = i.getParcelableExtra(NfcAdapter.EXTRA_TAG).toString(); // 태그 정보를 받아 string으로 변환 String strMsg = action + "\n\n" + tag; tv.setText(strMsg); // NFC 태그페이지일때만 태그를 인식 if(mPager.getCurrentItem()==0){ Toast.makeText(getApplicationContext(), "NFC 인식", Toast.LENGTH_LONG).show(); detectSound(); Intent intent = new Intent(getApplicationContext(),InformationActivity.class); startActivity(intent); } } }
package io.pivotal.racquetandroid.manager; import javax.inject.Inject; import io.pivotal.racquetandroid.RacquetApplication; import io.pivotal.racquetandroid.RacquetRestService; public class NetworkManager { }
package com.citibank.ods.modules.client.officercmpl.functionality; import org.apache.struts.action.ActionForm; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.functionality.ODSListFnc; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO; import com.citibank.ods.modules.client.officercmpl.form.OfficerCmplMovementListForm; import com.citibank.ods.modules.client.officercmpl.functionality.valueobject.OfficerCmplMovementListFncVO; import com.citibank.ods.persistence.pl.dao.TplOfficerCmplMovDAO; import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory; /** * @author bruno.zanetti * * Classe Fnc de consulta em Lista dos dados de movimento */ public class OfficerCmplMovementListFnc extends BaseOfficerCmplListFnc implements ODSListFnc { /** * Realiza as validações iniciais para a execução da consulta em lista */ public void validateList( BaseFncVO fncVO_ ) { /** * "[Method description]" * * @param * @return * @exception * @see */ } /** * Recupera uma instância de um FncVO */ public BaseFncVO createFncVO() { return new OfficerCmplMovementListFncVO(); } /** * Atualiza os dados do FncVO a partir do Fomr */ public void updateFncVOFromForm( ActionForm form_, BaseFncVO fncVO_ ) { // Atualizando campos comuns super.updateFncVOFromForm( form_, fncVO_ ); // Acertando os tipos OfficerCmplMovementListFncVO officerCmplMovementFncVO = ( OfficerCmplMovementListFncVO ) fncVO_; OfficerCmplMovementListForm officerCmplMovementListForm = ( OfficerCmplMovementListForm ) form_; String lastUpdUserIdSrc = ( officerCmplMovementListForm.getLastUpdUserIdSrc() != null && officerCmplMovementListForm.getLastUpdUserIdSrc().length() > 0 ? officerCmplMovementListForm.getLastUpdUserIdSrc() : null ); officerCmplMovementFncVO.setLastUpdUserIdSrc( lastUpdUserIdSrc ); } /** * Realiza a consulta em lista do movimento */ public void list( BaseFncVO fncVO_ ) { OfficerCmplMovementListFncVO officerCmplMovementListFncVO = ( OfficerCmplMovementListFncVO ) fncVO_; //Obtém a instância da Factory ODSDAOFactory factory = ODSDAOFactory.getInstance(); //Obtém a instância do DAO necessário TplOfficerCmplMovDAO officerDAO = factory.getTplOfficerCmplMovDAO(); // Recupera valores do DAO DataSet result = officerDAO.list( officerCmplMovementListFncVO.getOffcrIntnlNbrSrc(), officerCmplMovementListFncVO.getOffcrNbrSrc(), officerCmplMovementListFncVO.getOffcrTypeCodeSrc(), officerCmplMovementListFncVO.getLastUpdUserIdSrc(), officerCmplMovementListFncVO.getOffcrTextSrc()); //Atualiza o(s) atributo(s) do fncVO com o(s) dado(s) retornado(s) officerCmplMovementListFncVO.setResults( result ); if ( result.size() > 0 ) { officerCmplMovementListFncVO.addMessage( BaseODSFncVO.C_MESSAGE_SUCESS ); } else { officerCmplMovementListFncVO.addMessage( BaseODSFncVO.C_NO_REGISTER_FOUND ); } } }
package com.daylyweb.music.utils; import java.sql.SQLException; import javax.annotation.Resource; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Component; /** * @ClassName: ConnectionFactory * @Description: log4j2的数据源工厂 * @author: 丶Tik * @date: 2017年11月22日 下午1:33:41 * */ @Component public class ConnectionFactory { public static DataSource dataSource; public static ApplicationContext context = new ClassPathXmlApplicationContext( "classpath:spring.xml"); public static DataSource getDataSource() throws SQLException { dataSource = (DataSource) context.getBean("dataSource"); return dataSource; } }
package com.jdbc.test.generator; import com.jdbc.test.annotations.*; import com.jdbc.test.exceptions.SqlQueryGeneratorException; import com.jdbc.test.model.User; import java.lang.reflect.Field; import java.util.Arrays; import java.util.stream.Collectors; /** * Created by aram on 1/14/2018. */ public class SqlQueryGenerator { private Class daoClass; public SqlQueryGenerator(Class daoClass) throws SqlQueryGeneratorException { if (!daoClass.isAnnotationPresent(DAOTable.class)) { throw new SqlQueryGeneratorException("Class must be annotated with DAOTable annotation"); } this.daoClass = daoClass; } public String getCreateTableQuery() throws SqlQueryGeneratorException { StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append(String.format("CREATE TABLE %s (", ((DAOTable) daoClass.getAnnotation(DAOTable.class)).name())); Field[] fields = Arrays.stream(User.class.getDeclaredFields()) .filter((field) -> field.isAnnotationPresent(DAOField.class)).toArray(Field[]::new); boolean isPrimaryKeySet = false; for (int i = 0; i < fields.length; i++) { queryBuilder.append(String.format("%s %s", fields[i].getName(), getSqlTypeFromJavaType(fields[i].getType()))); if (!fields[i].isAnnotationPresent(DAONullable.class)) { queryBuilder.append(" NOT NULL"); } if (fields[i].isAnnotationPresent(DAOPrimary.class)) { if (isPrimaryKeySet) { throw new SqlQueryGeneratorException("There can be at most one primary key"); } isPrimaryKeySet = true; queryBuilder.append(" PRIMARY KEY"); } if (fields[i].isAnnotationPresent(DAOIdentity.class)) { if (!getSqlTypeFromJavaType(fields[i].getType()).contains("int")) { throw new SqlQueryGeneratorException("Only integer columns can be identity"); } queryBuilder.append(" AUTO_INCREMENT"); } if (i != fields.length - 1) { queryBuilder.append(","); } } queryBuilder.append(")"); return queryBuilder.toString(); } public String getInsertQuery() { Field[] fields = Arrays.stream(User.class.getDeclaredFields()) .filter((field) -> field.isAnnotationPresent(DAOField.class)).toArray(Field[]::new); String columns = Arrays.stream(fields) .filter((x) -> !x.isAnnotationPresent(DAOIdentity.class)) .map((x) -> x.getName()).collect(Collectors.joining(", ")); String values = Arrays.stream(fields) .filter((x) -> !x.isAnnotationPresent(DAOIdentity.class)) .map((x) -> "?").collect(Collectors.joining(", ")); return String.format("INSERT INTO %s (%s) VALUES (%s)", ((DAOTable) daoClass.getAnnotation(DAOTable.class)).name(), columns, values); } private String getSqlTypeFromJavaType(Class type) { switch (type.getTypeName()) { case "byte": case "java.lang.Byte": return "tinyint"; case "short": case "java.lang.Short": return "smallint"; case "int": case "java.lang.Integer": return "int"; case "long": case "java.lang.Long": return "bigint"; case "float": case "java.lang.Float": return "float"; case "double": case "java.lang.Double": return "double"; case "boolean": case "java.lang.Boolean": return "bit"; case "char": case "java.lang.Character": return "char"; case "java.lang.String": return "text"; } throw new RuntimeException("Only primitives their wrappers and String are supported at this moment"); } }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.time.LocalDate; import java.time.LocalTime; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { static EmployeeService employeeService; public static void main(String[] args) throws IOException { employeeService = new EmployeeService(); System.out.println("columns example: Date | Hour | First Name | Last Name | Section"); System.out.println("Enter csv file name: "); Scanner scanner = new Scanner(System.in); String fileName = scanner.nextLine(); List<String> lines = new ArrayList<>(); String strLine; try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) { while ((strLine = reader.readLine()) != null) { lines.add(strLine); } } catch (Exception e) { System.out.println("Error: " + e.getMessage()); scanner.next(); scanner.close(); return; } List<Employee> employees = new ArrayList<>(); for (int i = 0; i < lines.size(); i++) { if(lines.get(i).split(";").length < 5) { continue; } String firstName = lines.get(i).split(";")[2].trim(); if (firstName.length() == 0) { continue; } String line = lines.get(i); String lastName = line.split(";")[3].trim(); String section = line.split(";")[4].trim(); String[] dateString = line.split(";")[0].split("\\."); String[] timeString = line.split(";")[1].split(":"); if(timeString[0].length() == 1) timeString[0] = "0" + timeString[0]; LocalDate date = LocalDate.parse(dateString[2] + "-" + dateString[1] + "-" + dateString[0]); LocalTime time = LocalTime.parse(timeString[0] + ":" + timeString[1]); Employee employee = new Employee(firstName, lastName, section, date, time); employees.add(employee); } employeeService.order(employees); employees = employeeService.filter(employees); employeeService.writeToCsv("report.csv", employees); employees.forEach(System.out::println); System.out.println("\n\n"); System.out.println("Data saved in report.csv"); scanner.next(); scanner.close(); } }
/* * Copyright 2002-2017 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.jmx.export.metadata; import javax.management.modelmbean.ModelMBeanNotificationInfo; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Utility methods for converting Spring JMX metadata into their plain JMX equivalents. * * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 */ public abstract class JmxMetadataUtils { /** * Convert the supplied {@link ManagedNotification} into the corresponding * {@link javax.management.modelmbean.ModelMBeanNotificationInfo}. */ public static ModelMBeanNotificationInfo convertToModelMBeanNotificationInfo(ManagedNotification notificationInfo) { String[] notifTypes = notificationInfo.getNotificationTypes(); if (ObjectUtils.isEmpty(notifTypes)) { throw new IllegalArgumentException("Must specify at least one notification type"); } String name = notificationInfo.getName(); if (!StringUtils.hasText(name)) { throw new IllegalArgumentException("Must specify notification name"); } String description = notificationInfo.getDescription(); return new ModelMBeanNotificationInfo(notifTypes, name, description); } }
package com.yidatec.weixin.util; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TestMain { @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String args[]) { List<String> list = new ArrayList<String>(); list.add("2010-01-29 14:25"); list.add("2010-01-30 08:15"); list.add("2010-01-30 08:15"); list.add("2010-01-29 09:00"); list.add("2010-01-30 16:45"); list.add("2010-01-29 09:00"); list.add("2010-01-30 11:50:15"); list.add("2010-01-30 11:51"); list.add("2010-01-30 11:50:14"); Collections.sort(list, new Comparator() { public int compare(Object o, Object o1) { String str1 = o.toString(); String str2 = o1.toString(); return str1.compareTo(str2); } }); for (String str : list) { System.out.println(str); } } }
/* * 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.treat.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import com.lenovohit.hwe.base.model.AuditableModel; /** * TREAT_TEST_DETAIL * * @author zyus * @version 1.0.0 2017-12-16 */ @Entity @Table(name = "TREAT_TEST_DETAIL") public class TestDetail extends AuditableModel implements java.io.Serializable { /** 版本号 */ private static final long serialVersionUID = 3077345804976891816L; /** hosId */ private String hosId; /** hosNo */ private String hosNo; /** hosName */ private String hosName; /** testId */ private String testId; /** subjectCode */ private String subjectCode; /** subject */ private String subject; /** result */ private String result; /** flag */ private String flag; /** unit */ private String unit; /** reference */ private String reference; /** status */ private String status; /** * 获取hosId * * @return hosId */ @Column(name = "HOS_ID", nullable = true, length = 32) public String getHosId() { return this.hosId; } /** * 设置hosId * * @param hosId */ public void setHosId(String hosId) { this.hosId = hosId; } /** * 获取hosNo * * @return hosNo */ @Column(name = "HOS_NO", nullable = true, length = 50) public String getHosNo() { return this.hosNo; } /** * 设置hosNo * * @param hosNo */ public void setHosNo(String hosNo) { this.hosNo = hosNo; } /** * 获取hosName * * @return hosName */ @Column(name = "HOS_NAME", nullable = true, length = 50) public String getHosName() { return this.hosName; } /** * 设置hosName * * @param hosName */ public void setHosName(String hosName) { this.hosName = hosName; } /** * 获取testId * * @return testId */ @Column(name = "TEST_ID", nullable = true, length = 32) public String getTestId() { return this.testId; } /** * 设置testId * * @param testId */ public void setTestId(String testId) { this.testId = testId; } /** * 获取subjectCode * * @return subjectCode */ @Column(name = "SUBJECT_CODE", nullable = true, length = 50) public String getSubjectCode() { return this.subjectCode; } /** * 设置subjectCode * * @param subjectCode */ public void setSubjectCode(String subjectCode) { this.subjectCode = subjectCode; } /** * 获取subject * * @return subject */ @Column(name = "SUBJECT", nullable = true, length = 100) public String getSubject() { return this.subject; } /** * 设置subject * * @param subject */ public void setSubject(String subject) { this.subject = subject; } /** * 获取result * * @return result */ @Column(name = "RESULT", nullable = true, length = 50) public String getResult() { return this.result; } /** * 设置result * * @param result */ public void setResult(String result) { this.result = result; } /** * 获取flag * * @return flag */ @Column(name = "FLAG", nullable = true, length = 1) public String getFlag() { return this.flag; } /** * 设置flag * * @param flag */ public void setFlag(String flag) { this.flag = flag; } /** * 获取unit * * @return unit */ @Column(name = "UNIT", nullable = true, length = 50) public String getUnit() { return this.unit; } /** * 设置unit * * @param unit */ public void setUnit(String unit) { this.unit = unit; } /** * 获取reference * * @return reference */ @Column(name = "REFERENCE", nullable = true, length = 50) public String getReference() { return this.reference; } /** * 设置reference * * @param reference */ public void setReference(String reference) { this.reference = reference; } /** * 获取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; } }
package com.xixiwan.platform.sys.dto; import lombok.Data; @Data public class NodeState { /** * 是否选中节点,用复选框样式的符号表示。 */ private Boolean checked = Boolean.FALSE; /** * 是否禁用节点(不可选择、可扩展或可检查)。 */ private Boolean disabled = Boolean.FALSE; /** * 一个节点是否扩展,即打开。优先于全局选项级别。 */ private Boolean expanded = Boolean.FALSE; /** * 是否选择节点。 */ private Boolean selected = Boolean.FALSE; }
package com.controller; import com.bean.User; import com.mapper.UserMapper; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping(value = "mybatis") public class MybatisController { private SqlSessionFactory sqlSessionFactory; // @Resource // private UserMapper userMapper; @RequestMapping(value = "user") public void test(){ List<User> userList = new ArrayList<>(); SqlSession sqlSession = null; try { InputStream inputStream = Resources.getResourceAsStream("mybatis.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); inputStream.close(); sqlSession = sqlSessionFactory.openSession(); User user = new User(); user.setPwd("中文"); user.setUserId(2); sqlSession.insert("User.insertUser",user); sqlSession.commit(); userList = sqlSession.selectList("User.selectAll"); }catch (Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } for (User user: userList){ System.out.println(user.getId()+" "+user.getUserId()+" "+user.getPwd()); } } @RequestMapping(value = "mapper") public void annotation(){ System.out.println("中文?"); // List<User> userList = userMapper.selectAll(); // for (User user: userList){ // System.out.println(user.getId()+" "+user.getUserId()+" "+user.getPwd()); // } } }
package Models; public class GenericOrderLine { private int quantity; public GenericOrderLine(int quantity) { this.quantity = quantity; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } }
package com.zhaoyan.ladderball.dao.recordermatch; import com.zhaoyan.ladderball.domain.recordermatch.db.RecorderTmpMatch; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate4.HibernateTemplate; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class HibernateRecorderTmpMatchDao implements RecorderTmpMatchDao{ Logger logger = LoggerFactory.getLogger(HibernateRecorderTmpMatchDao.class); @Autowired HibernateTemplate hibernateTemplate; @Override public RecorderTmpMatch getRecorderMatchById(long id) { return hibernateTemplate.get(RecorderTmpMatch.class, id); } @Override public void addRecorderMatch(RecorderTmpMatch recorderMatch) { hibernateTemplate.save(recorderMatch); hibernateTemplate.flush(); hibernateTemplate.clear(); } @Override public void modifyRecorderMatch(RecorderTmpMatch recorderMatch) { hibernateTemplate.update(recorderMatch); } @Override public void deleteRecorderMatch(RecorderTmpMatch recorderMatch) { hibernateTemplate.delete(recorderMatch); } @Override public List<RecorderTmpMatch> getRecorderTmpMatchByRecorder(long recorderId) { DetachedCriteria criteria = DetachedCriteria.forClass(RecorderTmpMatch.class); criteria.add(Restrictions.eq("recorderId", recorderId)); List<RecorderTmpMatch> recorderTmpMatches = (List<RecorderTmpMatch>) hibernateTemplate.findByCriteria(criteria); return recorderTmpMatches; } @Override public RecorderTmpMatch getRecorderTmpMatchByRecorderMatch(long recorderId, long tmpMatchId) { DetachedCriteria criteria = DetachedCriteria.forClass(RecorderTmpMatch.class); criteria.add(Restrictions.eq("recorderId", recorderId)); criteria.add(Restrictions.eq("matchId", tmpMatchId)); List<RecorderTmpMatch> recorderMatches = (List<RecorderTmpMatch>) hibernateTemplate.findByCriteria(criteria); if (!recorderMatches.isEmpty()) { return recorderMatches.get(0); } return null; } @Override public RecorderTmpMatch addRecorderTmpMatch(RecorderTmpMatch recorderTmpMatch) { hibernateTemplate.save(recorderTmpMatch); hibernateTemplate.flush(); hibernateTemplate.clear(); return recorderTmpMatch; } @Override public List<RecorderTmpMatch> getToAsignTmpMatchByRecorder(long recorderId) { DetachedCriteria criteria = DetachedCriteria.forClass(RecorderTmpMatch.class); // 认领的是其他记录者 criteria.add(Restrictions.ne("recorderId", recorderId)); // 认领的是主队 criteria.add(Restrictions.eq("asignedTeam", RecorderTmpMatch.ASIGNED_TEAM_HOME)); // 比赛的还有队伍没有被认领 criteria.add(Restrictions.eq("isMatchAsigned", false)); List<RecorderTmpMatch> recorderTmpMatches = (List<RecorderTmpMatch>) hibernateTemplate.findByCriteria(criteria); return recorderTmpMatches; } @Override public boolean isTmpMatchAsignedToRecorder(long recorderId, long matchId) { DetachedCriteria criteria = DetachedCriteria.forClass(RecorderTmpMatch.class); criteria.add(Restrictions.eq("recorderId", recorderId)); criteria.add(Restrictions.eq("matchId", matchId)); List<RecorderTmpMatch> recorderTmpMatches = (List<RecorderTmpMatch>) hibernateTemplate.findByCriteria(criteria); return !recorderTmpMatches.isEmpty(); } @Override public boolean asignTmpMatchVisitor(long recorderId, long matchId) { RecorderTmpMatch recorderTmpMatch = new RecorderTmpMatch(); recorderTmpMatch.recorderId = recorderId; recorderTmpMatch.matchId = matchId; recorderTmpMatch.asignedTeam = RecorderTmpMatch.ASIGNED_TEAM_VISITOR; // 这场比赛的两个队伍都被认领 recorderTmpMatch.isMatchAsigned = true; hibernateTemplate.save(recorderTmpMatch); // 将这场比赛的另一个认领者的比赛也修改为比赛已被认领完。 DetachedCriteria criteria = DetachedCriteria.forClass(RecorderTmpMatch.class); // 认领的是其他记录者 criteria.add(Restrictions.ne("recorderId", recorderId)); criteria.add(Restrictions.eq("matchId", matchId)); List<RecorderTmpMatch> recorderTmpMatches = (List<RecorderTmpMatch>) hibernateTemplate.findByCriteria(criteria); if (recorderTmpMatches != null) { for(RecorderTmpMatch r : recorderTmpMatches) { r.isMatchAsigned = true; hibernateTemplate.update(r); } } return true; } }
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.context.junit.jupiter.nested; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.NestedTestConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.context.junit.jupiter.nested.ContextConfigurationNestedTests.TopLevelConfig; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.NestedTestConfiguration.EnclosingConfiguration.INHERIT; import static org.springframework.test.context.NestedTestConfiguration.EnclosingConfiguration.OVERRIDE; /** * Integration tests that verify support for {@code @Nested} test classes using * {@link ContextConfiguration @ContextConfiguration} in conjunction with the * {@link SpringExtension} in a JUnit Jupiter environment. * * @author Sam Brannen * @since 5.0 * @see ConstructorInjectionNestedTests * @see org.springframework.test.context.junit4.nested.NestedTestsWithSpringRulesTests */ @SpringJUnitConfig(TopLevelConfig.class) @NestedTestConfiguration(OVERRIDE) // since INHERIT is now the global default class ContextConfigurationNestedTests { private static final String FOO = "foo"; private static final String BAR = "bar"; private static final String BAZ = "baz"; @Autowired String foo; @Test void topLevelTest() { assertThat(foo).isEqualTo(FOO); } @Nested @SpringJUnitConfig(NestedConfig.class) class NestedTests { @Autowired(required = false) @Qualifier("foo") String localFoo; @Autowired String bar; @Test void test() { // In contrast to nested test classes running in JUnit 4, the foo // field in the outer instance should have been injected from the // test ApplicationContext for the outer instance. assertThat(foo).isEqualTo(FOO); assertThat(this.localFoo).as("foo bean should not be present").isNull(); assertThat(this.bar).isEqualTo(BAR); } } @Nested @NestedTestConfiguration(INHERIT) class NestedTestCaseWithInheritedConfigTests { @Autowired(required = false) @Qualifier("foo") String localFoo; @Autowired String bar; @Test void test() { // Since the configuration is inherited, the foo field in the outer instance // and the bar field in the inner instance should both have been injected // from the test ApplicationContext for the outer instance. assertThat(foo).isEqualTo(FOO); assertThat(this.localFoo).isEqualTo(FOO); assertThat(this.bar).isEqualTo(FOO); } @Nested @NestedTestConfiguration(OVERRIDE) @SpringJUnitConfig(NestedConfig.class) class DoubleNestedWithOverriddenConfigTests { @Autowired(required = false) @Qualifier("foo") String localFoo; @Autowired String bar; @Test void test() { // In contrast to nested test classes running in JUnit 4, the foo // field in the outer instance should have been injected from the // test ApplicationContext for the outer instance. assertThat(foo).isEqualTo(FOO); assertThat(this.localFoo).as("foo bean should not be present").isNull(); assertThat(this.bar).isEqualTo(BAR); } @Nested @NestedTestConfiguration(INHERIT) class TripleNestedWithInheritedConfigTests { @Autowired(required = false) @Qualifier("foo") String localFoo; @Autowired String bar; @Test void test() { assertThat(foo).isEqualTo(FOO); assertThat(this.localFoo).as("foo bean should not be present").isNull(); assertThat(this.bar).isEqualTo(BAR); } } @Nested @NestedTestConfiguration(INHERIT) class TripleNestedWithInheritedConfigAndTestInterfaceTests implements TestInterface { @Autowired(required = false) @Qualifier("foo") String localFoo; @Autowired String bar; @Autowired String baz; @Test void test() { assertThat(foo).isEqualTo(FOO); assertThat(this.localFoo).as("foo bean should not be present").isNull(); assertThat(this.bar).isEqualTo(BAR); assertThat(this.baz).isEqualTo(BAZ); } } } } // ------------------------------------------------------------------------- @Configuration static class TopLevelConfig { @Bean String foo() { return FOO; } } @Configuration static class NestedConfig { @Bean String bar() { return BAR; } } @Configuration static class TestInterfaceConfig { @Bean String baz() { return BAZ; } } @ContextConfiguration(classes = TestInterfaceConfig.class) interface TestInterface { } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author BestWanted */ public class ggeasyserver extends ServerSocket{ //Attributi private String status; //Costruttore public ggeasyserver(int porta) throws IOException { super(porta); status = "Server avviato"; } //Metodi public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } /* public static void main(String[] args) { Server server = null; try { server = new Server(8989); } catch(IOException e) { System.out.println("Problema nella creazione del server alla porta 8989"); return; } System.out.println("Status del server: "+server.getStatus()); while(true) { server.setStatus("In Attesa"); System.out.println("Status del server: "+server.getStatus()); try { Socket socket = server.accept(); BufferedWriter scrittore = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); BufferedReader inputTastiera = new BufferedReader(new InputStreamReader(System.in)); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); BufferedReader in = new BufferedReader(isr); if(socket.isConnected()) { System.out.println(socket.getInetAddress() + " si è connesso al server!"); String messaggioRicevuto = in.readLine(); System.out.println("Messaggio ricevuto da "+socket.getInetAddress()+": "+messaggioRicevuto); //scrittore.write("Ho ricevuto questo messaggio da te: "+messaggioRicevuto); } //scrittore.close(); } catch(IOException e) { return; } } } } */ }
package ro.ase.cts.teste.test.categorii; public class GetPromovabilitateCategory { }
package me.basiqueevangelist.datapackify; import me.basiqueevangelist.datapackify.commands.DumpErrorsCommand; import me.basiqueevangelist.datapackify.potionrecipes.PotionRecipes; import me.basiqueevangelist.datapackify.trades.VillagerTrades; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback; public class Datapackify implements ModInitializer { public static final String NAMESPACE = "datapackify"; public void onInitialize() { VillagerTrades.init(); PotionRecipes.init(); CommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> { DumpErrorsCommand.register(dispatcher); }); } }
package com.heihei.fragment.live.widget; import java.util.ArrayList; import android.animation.Animator; import android.animation.Animator.AnimatorListener; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.content.Context; import android.util.AttributeSet; import android.view.animation.OvershootInterpolator; import android.widget.LinearLayout; import com.base.animator.NumberEvaluator; /** * 礼物数量带动画的view * * @author chengbo */ public class GiftNumberView extends LinearLayout { public GiftNumberView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public GiftNumberView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public GiftNumberView(Context context) { super(context); init(); } @Override public void setOrientation(int orientation) { if (orientation != LinearLayout.HORIZONTAL) { throw new RuntimeException("not support the orientation"); } super.setOrientation(orientation); } private void init() { setOrientation(LinearLayout.HORIZONTAL); initViews(); } private void initViews() { removeAllViews(); String newStr = String.valueOf(currentNum); createAndAddView("X"); for (int i = 0; i < newStr.length(); i++) { createAndAddView(newStr.charAt(i) + ""); } } /** * 创建并加入一个view * * @param num */ private IncreNumberView createAndAddView(String numStr) { IncreNumberView inv = new IncreNumberView(getContext()); inv.setDefaultNumber(numStr); addView(inv, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); return inv; } private int currentNum = 0; /** * 数字增长 * * @param number */ public void increaseNumber(int number) { setNumber(currentNum + number); } public void setNumber(int number) { if (number < 0) { throw new RuntimeException(""); } if (number == 0) { this.currentNum = number; removeAllViews(); initViews(); return; } String oldStr = String.valueOf(currentNum); if (currentNum == number) { return; } if (number > currentNum) {// 数字变大了 String newStr = String.valueOf(number); if (oldStr.length() == newStr.length()) {// 如果位数相等则直接设置数字,显示动画 ArrayList<IncreNumberView> childs = new ArrayList<>();//需要做动画的view集合 for (int i = 0; i < oldStr.length(); i++) { IncreNumberView inv = (IncreNumberView) getChildAt(i + 1); String a = newStr.charAt(i) + ""; if (!a.equals(inv.getNumber())) { childs.add(inv); inv.setNumber(a); } } createAnimator(childs).start(); } else if (oldStr.length() < newStr.length()) {//如果位数不相等则需要新增view ArrayList<IncreNumberView> childs = new ArrayList<>();//需要做动画的view集合 for (int i = 0; i < newStr.length(); i++) { if (i < oldStr.length()) { IncreNumberView inv = (IncreNumberView) getChildAt(i + 1); String a = newStr.charAt(i) + ""; if (!a.equals(inv.getNumber())) { childs.add(inv); } inv.setNumber(a); } else { IncreNumberView inv = createAndAddView(newStr.charAt(i) + ""); childs.add(inv); } createAnimator(childs).start(); } } currentNum = number; } else { currentNum = number; initViews(); } } private ValueAnimator createAnimator(final ArrayList<IncreNumberView> views) { ValueAnimator animator = ValueAnimator.ofObject(new NumberEvaluator(), 0, getHeight()); animator.setDuration(200); animator.setInterpolator(new OvershootInterpolator(2.0f)); animator.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int offset = (int) animation.getAnimatedValue(); for (int i = 0; i < views.size(); i++) { views.get(i).setOffset(offset); } } }); animator.addListener(new AnimatorListener() { @Override public void onAnimationStart(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationRepeat(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animator animation) { views.clear(); } @Override public void onAnimationCancel(Animator animation) { // TODO Auto-generated method stub } }); return animator; } }
package com.lipnus.gleam.etc; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.speech.RecognizerIntent; import java.util.List; /** * Created by Sunpil on 2016-06-05. */ public class VoiceRecognition { private PackageManager pm; public final int VOICE_RECOGNITION_REQUEST_CODE = 1234; public VoiceRecognition(Context ctx) { this.pm = ctx.getPackageManager(); } // 음성 인식을 지원하는지 확인 public boolean recognitionAvailable() { List<ResolveInfo> activities = pm.queryIntentActivities(new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); if (activities.size() != 0) { return true; // 지원할 경우 true 반환 } else { return false; // 지원하지 않을 경우 false 반환 } } // 구글 음성 인식 intent 생성 public Intent getVoiceRecognitionIntent(String message) { Intent intent = new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, message); return intent; } }
package cn.net.bluechips.zsystem.service; import org.springframework.stereotype.Service; import cn.com.topit.base.GenericService; import cn.net.bluechips.zsystem.entity.Department; import cn.net.bluechips.zsystem.entity.Project; import cn.net.bluechips.zsystem.repository.DepartmentRepository; import cn.net.bluechips.zsystem.repository.ProjectRepository; @Service public class ProjectService extends GenericService<ProjectRepository, Project> { }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.jearl.web.jsf; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import org.jearl.ejb.Facade; import org.jearl.ejb.exception.DocumentException; import org.jearl.ejb.exception.EntityCRUDException; import org.jearl.ejb.exception.FavoriteException; import org.jearl.ejb.model.Entity; import org.jearl.ejb.model.document.Document; import org.jearl.ejb.translatable.LanguageEnum; import org.jearl.logback.ErrorCategory; import org.jearl.logback.Log; import org.jearl.logback.LogService; import org.jearl.web.jsf.exception.ManagedBeanException; import org.jearl.web.jsf.message.BeanMessages; import org.jearl.web.jsf.message.BeanMessagesImpl; import org.jearl.web.jsf.message.Message; import org.jearl.web.session.exception.SessionException; /** * * @author amasyalim */ public abstract class AbstractManagedBean<T, PRIMARY, USER> extends AbstractBasicManagedBean implements ManagedBean<T, PRIMARY, USER>, Serializable { private static final String CONTAINER = "JEARL"; private static final Log log = new LogService(AbstractManagedBean.class); private static final String ERROR_MESSAGE = "Error"; private T entity; private final String className; private final boolean hasSession; private List<Document> documentList; public AbstractManagedBean(boolean hasSession) { super(); this.className = this.getClass().getSimpleName(); this.hasSession = hasSession; this.documentList = null; try { T temp = session.<T>readFromSession(className); if (temp != null && hasSession) { this.entity = temp; } else { this.entity = newEntity(); } } catch (SessionException ex) { this.entity = newEntity(); log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); } catch (Exception ex) { this.entity = newEntity(); log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); } try { onValueChange(); } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); } } @Override public abstract T newEntity(); @Override public abstract T newEntity(PRIMARY id); @Override public abstract PRIMARY getId(T entity); @Override public abstract String getName(T entity); @Override public abstract Facade<T, USER> getFacade(); @Override public BeanMessages getBeanMessages() { return new BeanMessagesImpl(); } @Override public abstract List<T> getList(); @Override public abstract List<SelectItem> getSelectItems(); @Override public abstract LanguageEnum getLanguage(); protected void onValueChange() { this.documentList = null; } @Override public PRIMARY getId() { return getId(entity); } @Override public void setId(PRIMARY value) { setId(value, getBeanMessages().getSetIdSuccessMessage(), getBeanMessages().getSetIdErrorMessage()); } protected final Boolean setId(PRIMARY value, Message successMessage, Message errorMessage) { try { setEntity(getFacade().find(value)); setInfo(successMessage); return true; } catch (EntityCRUDException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } } @Override public T getEntity() { return entity; } @Override public void setEntity(T entity) { setEntity(entity, getBeanMessages().getSetEntitySuccessMessage(), getBeanMessages().getSetEntityErrorMessage()); } protected final Boolean setEntity(T entity, Message successMessage, Message errorMessage) { try { if (entity == null) { log.warn("Entity Set Null"); this.entity = newEntity(); } else { this.entity = entity; } if (hasSession) { if (this.entity == null) { session.deleteFromSession(className); } else { session.writeToSession(className, this.entity); } } onValueChange(); setInfo(successMessage); return true; } catch (SessionException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } } @Override public boolean isHasObject() { return getId() != null; } @Override public final void loadBaseVariables(Boolean deleted, Boolean isCreate) { if (isInheritedFromLoggerInterface()) { Entity myEntity = (Entity) this.entity; myEntity.setDeleted(deleted); myEntity.setModified(new Date(System.currentTimeMillis())); if (userId != null) { myEntity.setModifier(getFacade().getUser(userId)); } myEntity.setModifierip(userIp); if (isCreate) { myEntity.setVersion(0); } } } @Override public String create() { create(getBeanMessages().getCreateSuccessMesage(), getBeanMessages().getCreateErrorMesage()); return null; } protected final Boolean create(Message successMessage, Message errorMessage) { try { loadBaseVariables(false, true); getFacade().create(entity); getFacade().updateDocuments(getEntity(), getDocumentList()); setEntity(entity); setInfo(successMessage); return true; } catch (EntityCRUDException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (DocumentException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } } @Override public String edit() { edit(getBeanMessages().getEditSuccessMessage(), getBeanMessages().getEditErrorMessage()); return null; } protected final Boolean edit(Message successMessage, Message errorMessage) { try { loadBaseVariables(false, false); getFacade().edit(entity); getFacade().updateDocuments(getEntity(), getDocumentList()); setEntity(getFacade().find(getId())); setInfo(successMessage); return true; } catch (EntityCRUDException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (DocumentException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } } @Override public String remove() { remove(getBeanMessages().getEditSuccessMessage(), getBeanMessages().getRemoveErrorMessage()); return null; } protected final Boolean remove(Message successMessage, Message errorMessage) { try { loadBaseVariables(true, false); getFacade().edit(entity); setEntity(null); setInfo(successMessage); return true; } catch (EntityCRUDException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } } @Override public String removePhysical() { removePhysical(getBeanMessages().getRemovePyhsicalSuccessMessage(), getBeanMessages().getRemovePyhsicalErrorMessage()); return null; } protected final Boolean removePhysical(Message successMessage, Message errorMessage) { try { loadBaseVariables(true, false); getFacade().remove(entity); setEntity(null); setInfo(successMessage); return true; } catch (EntityCRUDException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } } @Override public String reload() { reload(getBeanMessages().getReloadSuccessMessage(), getBeanMessages().getReloadErrorMessage()); return null; } protected final Boolean reload(Message successMessage, Message errorMessage) { try { setEntity(getFacade().find(getId())); setInfo(successMessage); return true; } catch (EntityCRUDException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } } @Override public String reloadNoChange() { reloadNoChange(getBeanMessages().getReloadNoChangeSuccessMessage(), getBeanMessages().getReloadNoChangeErrorMessage()); return null; } protected final Boolean reloadNoChange(Message successMessage, Message errorMessage) { try { this.entity = getFacade().find(getId()); if (hasSession) { if (this.entity == null) { session.deleteFromSession(className); } else { session.writeToSession(className, this.entity); } } setInfo(successMessage); return true; } catch (EntityCRUDException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (SessionException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } } @Override public String clear() { setEntity(null); return null; } protected final List<SelectItem> getSelectItemsEntity(List<T> myList, Boolean addNull) throws ManagedBeanException { List<SelectItem> items = new ArrayList<SelectItem>(); try { if (addNull) { items.add(new SelectItem(null, "_")); } if (myList != null) { for (int i = 0; i < myList.size(); i++) { items.add(new SelectItem(myList.get(i), getName(myList.get(i)))); } } } catch (Exception ex) { throw new ManagedBeanException(ex); } return items; } protected final List<SelectItem> getSelectItems(List<T> myList, Boolean addNull) throws ManagedBeanException { List<SelectItem> items = new ArrayList<SelectItem>(); try { if (addNull) { items.add(new SelectItem(null, "_")); } if (myList != null) { for (int i = 0; i < myList.size(); i++) { items.add(new SelectItem(getId(myList.get(i)), getName(myList.get(i)))); } } } catch (Exception ex) { throw new ManagedBeanException(ex); } return items; } @Override public List<T> findAll() { return findAll(getBeanMessages().getFindAllSuccessMessage(), getBeanMessages().getFindAllErrorMessage()); } protected final List<T> findAll(Message successMessage, Message errorMessage) { try { List<T> list = getFacade().findAll(); setInfo(successMessage); return list; } catch (EntityCRUDException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return null; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return null; } } @Override public Document handleFileUpload(String fileName, byte[] fileContent) { return handleFileUpload(fileName, fileContent, getBeanMessages().getHandleFileUploadSuccessMesage(), getBeanMessages().getHandleFileUploadErrorMesage()); } protected final Document handleFileUpload(String fileName, byte[] fileContent, Message successMessage, Message errorMessage) { try { Document docuemnt; docuemnt = getFacade().uploadDocument(getEntity(), fileName, fileContent, userId, userIp); getDocumentList().add(docuemnt); setInfo(successMessage); return docuemnt; } catch (DocumentException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return null; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return null; } } @Override public String removeDocument(Integer docId) { removeDocument(docId, getBeanMessages().getRemoveDocumentSuccessMessage(), getBeanMessages().getRemoveDocumentErrorMessage()); return null; } protected final Boolean removeDocument(Integer docId, Message successMessage, Message errorMessage) { try { getFacade().removeDocument(docId); setInfo(successMessage); return true; } catch (DocumentException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } } @Override public List<Document> getFileList() { return getFileList(getBeanMessages().getFileListSuccessMessage(), getBeanMessages().getFileListErrorMessage()); } protected final List<Document> getFileList(Message successMessage, Message errorMessage) { if (isHasObject()) { try { List<Document> documents = getFacade().findDocuments(getEntity()); setInfo(successMessage); return documents; } catch (DocumentException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return null; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return null; } } else { return null; } } @Override public Integer getDocumentValue() { return getDocumentValue(getBeanMessages().getGetDocumentValueErrorMessage()); } protected final Integer getDocumentValue(Message errorMessage) { try { return session.<Integer>readFromSession("DOC_Document"); } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return null; } } @Override public void setDocumentValue(Integer docId) { setDocumentValue(docId, getBeanMessages().getSetDocumentValueErrorMessage()); } protected final void setDocumentValue(Integer docId, Message errorMessage) { try { session.writeToSession("DOC_Document", docId); } catch (SessionException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); } } @Override public String makeFavorite() { makeFavorite(getBeanMessages().getMakeFavoriteSuccessMessage(), getBeanMessages().getMakeFavoriteErrorMessage()); return null; } protected final Boolean makeFavorite(Message successMessage, Message errorMessage) { try { getFacade().makeFavorite(userId, getEntity(), new Date(System.currentTimeMillis()), userIp); setInfo(successMessage); return true; } catch (FavoriteException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } } @Override public List<T> getFavoriteList() { return getFavoriteList(getBeanMessages().getGetFavoriteListErrorMessage()); } protected final List<T> getFavoriteList(Message errorMessage) { try { return getFacade().findFavorites(userId); } catch (FavoriteException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return null; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return null; } } @Override public Boolean getFavorite() { return getFavorite(getBeanMessages().getGetFavoriteErrorMessage()); } protected final Boolean getFavorite(Message message) { try { return getFacade().isFavorite(userId, getEntity()); } catch (FavoriteException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(message); return null; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(message); return null; } } @Override public String removeFavorite() { removeFavorite(getBeanMessages().getRemoveFavoriteSuccessMessage(), getBeanMessages().getRemoveFavoriteErrorMessage()); return null; } protected final Boolean removeFavorite(Message successMessage, Message errrorMessage) { try { getFacade().removeFavorite(getEntity(), userId); setInfo(successMessage); return true; } catch (FavoriteException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errrorMessage); return false; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errrorMessage); return false; } } @Override public String createReport() { createReport(getBeanMessages().getCreateReportSuccessMessage(), getBeanMessages().getCreateReportErrorMessage()); return null; } protected final Boolean createReport(Message successMessage, Message errorMessage) { try { FacesContext.getCurrentInstance().getExternalContext().dispatch("/incm/Document"); setInfo(successMessage); return true; } catch (Exception ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); setError(errorMessage, ex); return false; } } protected final boolean isInheritedFromLoggerInterface() { return entity instanceof Entity; } public List<Document> getDocumentList() { if (documentList == null) { try { documentList = getFacade().findDocuments(getEntity()); } catch (DocumentException ex) { log.error(AbstractManagedBean.CONTAINER, userId, ErrorCategory.SYSTEM_ERROR, ERROR_MESSAGE, ex); } } return documentList; } protected final boolean isHasSession() { return hasSession; } }
package com.artogrid.app.sim.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.artogrid.bundle.marketstream.service.*; import com.artogrid.framework.core.controller.BaseController; import com.artogrid.framework.model.MarketStream; @Controller public class MarketStreamController extends BaseController { @Autowired private MarketStreamService marketStreamService; @RequestMapping(value = "getMarketStreamListByGoodsCode") @ResponseBody public String getMarketStreamListByGoodsCode(String goodsCode,String size){ List<MarketStream> result = marketStreamService.getMarketStreamListByGoodsCode(goodsCode, Integer.parseInt(size)); if (result != null) { String resultJSON= toJSON(result); resultJSON=resultJSON.replace("\\", ""); resultJSON=resultJSON.replace("\"body\":\"{", "\"body\":{"); resultJSON=resultJSON.replace("\"}\",\"goodsId\"", "\"},\"goodsId\""); return resultJSON; } else { return toErrorJSON("查找内容失败或者没有"); } } }
package com.kyliethedev.ecommercetoy.domain.item; import com.kyliethedev.ecommercetoy.domain.Category; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Singular; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Getter @AllArgsConstructor @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "DTYPE") @Entity public abstract class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ITEM_ID") private Long id; private String name; private int price; private int stockQuantity; @Singular @ManyToMany(mappedBy = "items") private List<Category> categories; // Setter public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } public void setPrice(int price) { this.price = price; } public void setStockQuantity(int stockQuantity) { this.stockQuantity = stockQuantity; } public void setCategories(List<Category> categories) { this.categories = categories; } }
package co.sblock.commands.cheat; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.map.MapView; import org.bukkit.map.MapView.Scale; import com.google.common.collect.ImmutableList; import co.sblock.Sblock; import co.sblock.chat.Language; import co.sblock.commands.SblockCommand; /** * Yeah, screw the new mechanics. * * @author Jikoo */ public class CenterMapCommand extends SblockCommand { public CenterMapCommand(Sblock plugin) { super(plugin, "centermap"); setPermissionLevel("helper"); setUsage("/centermap [x] [z] [world]"); } @SuppressWarnings("deprecation") @Override protected boolean onCommand(CommandSender sender, String label, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(getLang().getValue("command.general.noConsole")); return true; } Player player = (Player) sender; ItemStack mapItem = player.getInventory().getItemInMainHand(); if (mapItem.getType() != Material.EMPTY_MAP) { sender.sendMessage(Language.getColor("bad") + "You must be holding a blank map in your main hand."); return true; } MapView view = Bukkit.createMap(player.getWorld()); view.setScale(Scale.FARTHEST); int x, z; if (args.length > 1) { try { x = Integer.valueOf(args[0]); z = Integer.valueOf(args[1]); } catch (NumberFormatException e) { sender.sendMessage(Language.getColor("bad") + "Invalid coordinates! Ex. /centermap 0 0"); return true; } if (args.length > 2) { World world = Bukkit.getWorld(args[2]); if (world == null) { sender.sendMessage(Language.getColor("bad") + "Invalid world! Ex. /centermap 0 0 Earth_the_end"); return true; } view.setWorld(world); } } else { x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); } view.setCenterX(x); view.setCenterZ(z); player.getInventory().setItemInMainHand(new ItemStack(Material.MAP, 1, view.getId())); return true; } @Override public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { return ImmutableList.of(); } }
package com.tvm.completableFuture; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Supplier; public class CompletableFutureBasic { public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { ExecutorService es = Executors.newFixedThreadPool(2); CompletableFuture<String> completableFuture = new CompletableFuture<>(); /** Static methods runAsync and supplyAsync allow us to create a CompletableFuture instance out of Runnable and Supplier functional types correspondingly. Both Runnable and Supplier are functional interfaces that allow passing their instances as lambda expressions thanks to the new Java 8 feature. The Runnable interface is the same old interface that is used in threads and it does not allow to return a value. */ CompletableFuture<Void> runAsync = completableFuture.runAsync( () -> { System.out.println("Running an instance of Runnable which doesn;t return any result in Thread " + Thread.currentThread().getName()); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); Void void1 = runAsync.get(7000, TimeUnit.MILLISECONDS); System.out.println("The return from Runnable is always void i.e. null = " + void1 + " " + Thread.currentThread().getName()); /** The Supplier interface is a generic functional interface with a single method that has no arguments and returns a value of a parameterized type. This allows to provide an instance of the Supplier as a lambda expression that does the calculation and returns the result. */ CompletableFuture<String> supplyAsync = completableFuture.supplyAsync(new Supplier<String>() { @Override public String get() { String str = " Returning String from supplier and running in Thread " + Thread.currentThread().getName(); return str; } }); System.out.println("The return from Supplier of completable future"+supplyAsync.get()); System.out.println("Main Method "+ Thread.currentThread().getName()); } }
package shacs.dmotion.com.shacs; import android.app.Activity; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.IBinder; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Set; import java.util.UUID; public class BluetoothService { private static BluetoothService _instance = null; private static final String TAG = "BluetoothService"; public static final int ENABLE_BT = 1; public static final int CONNECT_BT = 2; public static final int VOLUME_BT = 3; public static final int TIMER_BT = 4; private Activity mActivity; private Handler mHandler; // private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final UUID MY_UUID = UUID.fromString("88E86285-7DD4-8C8F-7173-CDFEA69F9C32"); private BluetoothAdapter btAdapter; private ConnectThread mConnectThread; private ConnectedThread mConnectedThread; private int mState; public static String strDeviceAddr; // 상태를 나타내는 상태 변수 public static final int STATE_NONE = 0; public static final int STATE_LISTEN = 1; public static final int STATE_CONNECTING = 2; public static final int STATE_CONNECTED = 3; public static final int STATE_CONNECT_FAILED = 10; public static final int STATE_CONNECT_LOST = 11; public static synchronized BluetoothService getInstance(Activity ac, Handler handler) { if (_instance == null) _instance = new BluetoothService(ac, handler); return _instance; } public BluetoothService(Activity ac, Handler handler) { mActivity = ac; mHandler = handler; // BluetoothAdapter 얻기 btAdapter = BluetoothAdapter.getDefaultAdapter(); } public boolean getDeviceState() { Log.d(TAG, "Check the Bluetooth support"); if(btAdapter == null) { Log.d(TAG, "Bluetooth is not available"); return false; } else { Log.d(TAG, "Bluetooth is available"); return true; } } public void enableBluetooth() { Log.i(TAG, "Check the enabled Bluetooth"); if(btAdapter.isEnabled()) { // 기기의 블루투스 상태가 On인 경우 Log.d(TAG, "Bluetooth Enable Now"); } else { // 기기의 블루투스 상태가 Off인 경우 Log.d(TAG, "Bluetooth Enable Request"); Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); mActivity.startActivityForResult(i, ENABLE_BT); } } public Set<BluetoothDevice> getBondedDevices() { Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices(); return pairedDevices; } // Bluetooth 상태 set private synchronized void setState(int state) { Log.d(TAG, "setState() " + mState + " -> " + state); mState = state; } // Bluetooth 상태 get public synchronized int getState() { return mState; } public synchronized void start() { Log.d(TAG, "start"); // Cancel any thread attempting to make a connection if (mConnectThread == null) { } else { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mConnectedThread == null) { } else { mConnectedThread.cancel(); mConnectedThread = null; } } public synchronized void connectBLE(String strDeviceAddr) { BluetoothDevice device = btAdapter.getRemoteDevice(strDeviceAddr); device.createBond(); } // ConnectThread 초기화 device의 모든 연결 제거 public synchronized void connect(String strDeviceAddr) { this.strDeviceAddr = strDeviceAddr; BluetoothDevice device = btAdapter.getRemoteDevice(strDeviceAddr); Log.d(TAG, "connect to: " + device); // Cancel any thread attempting to make a connection if (mState == STATE_CONNECTING) { if (mConnectThread == null) { } else { mConnectThread.cancel(); mConnectThread = null; } } // Cancel any thread currently running a connection if (mConnectedThread == null) { } else { mConnectedThread.cancel(); mConnectedThread = null; } // Start the thread to connect with the given device mConnectThread = new ConnectThread(device); mConnectThread.start(); setState(STATE_CONNECTING); } // ConnectedThread 초기화 public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { Log.d(TAG, "connected"); // Cancel the thread that completed the connection if (mConnectThread == null) { } else { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mConnectedThread == null) { } else { mConnectedThread.cancel(); mConnectedThread = null; } // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(socket); mConnectedThread.start(); setState(STATE_CONNECTED); } // 모든 thread stop public synchronized void stop() { Log.d(TAG, "stop"); if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } setState(STATE_NONE); } // 값을 쓰는 부분(보내는 부분) public void write(byte[] out) { // Create temporary object ConnectedThread r; // Synchronize a copy of the ConnectedThread synchronized (this) { if (mState != STATE_CONNECTED) return; r = mConnectedThread; r.write(out); } } // 연결 실패했을때 private void connectionFailed() { setState(STATE_LISTEN); } // 연결을 잃었을 때 private void connectionLost() { setState(STATE_LISTEN); mHandler.sendEmptyMessage(STATE_CONNECT_FAILED); } private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { mmDevice = device; BluetoothSocket tmp = null; // 디바이스 정보를 얻어서 BluetoothSocket 생성 try { tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { Log.e(TAG, "create() failed", e); } mmSocket = tmp; } public void run() { Log.i(TAG, "BEGIN mConnectThread"); setName("ConnectThread"); btAdapter.cancelDiscovery(); // BluetoothSocket 연결 시도 try { // BluetoothSocket 연결 시도에 대한 return 값은 succes 또는 exception이다. mmSocket.connect(); Log.d(TAG, "Connect Success"); } catch (IOException e) { connectionFailed(); // 연결 실패시 불러오는 메소드 Log.d(TAG, "Connect Fail"); // socket을 닫는다. try { mmSocket.close(); } catch (IOException e2) { Log.e(TAG, "unable to close() socket during connection failure", e2); } // 연결 대기상태인 메소드를 호출한다. BluetoothService.this.start(); mHandler.sendEmptyMessage(STATE_CONNECT_FAILED); return; } // ConnectThread 클래스를 reset한다. synchronized (BluetoothService.this) { mConnectThread = null; } // ConnectThread를 시작한다. connected(mmSocket, mmDevice); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } } private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { Log.d(TAG, "create ConnectedThread"); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // BluetoothSocket의 inputstream 과 outputstream을 얻는다. try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; mHandler.sendEmptyMessage(STATE_CONNECTED); } public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[1024]; int bytes; // Keep listening to the InputStream while connected while (true) { try { // InputStream으로부터 값을 받는 읽는 부분(값을 받는다) bytes = mmInStream.read(buffer); if(bytes > 0) { String strReadString = buffer.toString(); Log.d(TAG, strReadString); } } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); break; } } } /** * Write to the connected OutStream. * @param buffer The bytes to write */ public void write(byte[] buffer) { try { // 값을 쓰는 부분(값을 보낸다) mmOutStream.write(buffer); } catch (IOException e) { Log.e(TAG, "Exception during write", e); } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } } }
package com.vuforia.samples.VuforiaSamples.ui.Common; /** * Created by aquat on 2017/12/26. */ public class CommentInfo { public String userId; public String userName; public int sex; public String userCmt; public double star; // public String insertDate; // public int commentId; public int markerId; //public boolean displayFlg; //public boolean deleteFlg; public String insertDate; // public int updateDate; /* "commentId":3 "markerId":1 "userId":1 "userCmt":"test2" "star":0.0 "displayFlg":true "deleteFlg":false "insertDate":1515823639128 "updateDate":1515823639128}*/ //コンストラクタ public CommentInfo(){} }
package uk.co.tekkies.readings.day; import uk.co.tekkies.readings.model.Passage; public interface DayPresenter { void reLoad(); void setCalendar(int year, int month, int day); void addItem(Passage passage); void notifyDataSetChanged(); }
package com.itheima.day_13.demo_03; public interface Flyable { void fly(String s); }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Vector; public class GenerateVector { public static Vector mVector() { String everything = ""; try { BufferedReader br = new BufferedReader(new FileReader("../../ranData.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } everything = sb.toString(); } catch (IOException e){ e.printStackTrace(); } final String[] rawIn = everything.split("\n"); final int[] in = new int[rawIn.length]; for(int i =0; i < in.length;i++) { in[i] = Integer.parseInt(rawIn[i]); } Vector<Integer> myVector = new Vector<>(); for(int i = 0; i < in.length;i++) { myVector.add(in[i]); } /*for(int i = 0; i< myVector.size();i++) { System.out.println(myVector.elementAt(i)); }*/ return myVector; } }