text
stringlengths
10
2.72M
package com.metaco.api.contracts; import com.google.gson.annotations.SerializedName; public class Definition { @SerializedName("ticker") private String ticker; @SerializedName("display") private String display; @SerializedName("contract") private String contract; @SerializedName("keywords") private String keywords; @SerializedName("unit") private String unit; @SerializedName("divisibility") private Integer divisibility; @SerializedName("asset_id") private String assetId; @SerializedName("issuer") private Issuer issuer; @SerializedName("kyc") private Kyc kyc; public Definition() { } public String getTicker() { return ticker; } public void setTicker(String ticker) { this.ticker = ticker; } public String getDisplay() { return display; } public void setDisplay(String display) { this.display = display; } public String getContract() { return contract; } public void setContract(String contract) { this.contract = contract; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public Integer getDivisibility() { return divisibility; } public void setDivisibility(Integer divisibility) { this.divisibility = divisibility; } public String getAssetId() { return assetId; } public void setAssetId(String assetId) { this.assetId = assetId; } public Issuer getIssuer() { return issuer; } public void setIssuer(Issuer issuer) { this.issuer = issuer; } public Kyc getKyc() { return kyc; } public void setKyc(Kyc kyc) { this.kyc = kyc; } }
package com.mahang.weather.view.animation; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.FrameLayout; public interface AnimationController { void setWeatherCode(int code); void initialize(ViewGroup rootView, Toolbar toolbar, Window window); }
package com.log4j; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; @Component @RequestMapping("/") public class Log4jController { private static Logger logger = Logger.getLogger(Log4jController.class); @RequestMapping("/Message.do") public String getMessage() { logger.info("inside message()....of" + this.getClass().getCanonicalName()); logger.trace("Trace message---> inside message()...."); logger.debug("debug message--> inside message()...."); logger.warn("warn message--> inside message()...."); logger.error("error massage--> inside message()...."); logger.fatal("fatal message--> inside message()...."); try { Integer.parseInt("3241hc43"); } catch (NumberFormatException e) { logger.error("Exception occred"); } System.out.println("inside getmessage()......."); return "Message.jsp"; } }
package classes.core.DAO; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.sql.Timestamp; import dominio.evento.IDominio; import dominio.produto.Categoria; import dominio.produto.Fornecedor; import dominio.produto.Produto; public class ProdutoDAO extends AbsDAO { @Override public void salvar(IDominio entidade) throws SQLException { conectar(); PreparedStatement ps = null; Produto produto = (Produto) entidade; try { conexao.setAutoCommit(false); StringBuilder sql = new StringBuilder(); sql.append("INSERT into produtos (nome, perecivel, descricao, id_categoria)"); sql.append(" VALUES (?,?,?,?)"); System.out.println("QUERIE: " + sql.toString()); ps = conexao.prepareStatement(sql.toString()); ps.setString(1, produto.getNome()); ps.setBoolean(2, produto.isPerecivel()); ps.setString(3, produto.getDescricao()); ps.setInt(4, produto.getCategoria().getId()); ps.executeUpdate(); conexao.commit(); } catch (SQLException e) { try { conexao.rollback(); } catch (Exception e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } // final FINALLY } @Override public void alterar(IDominio entidade) throws SQLException { conectar(); PreparedStatement ps = null; Produto produto = (Produto) entidade; try { conexao.setAutoCommit(false); StringBuilder sql = new StringBuilder(); sql.append("UPDATE produtos set nome=?, perecivel=?, descricao=?, id_categoria=?"); sql.append(" WHERE prd_id=?"); ps = conexao.prepareStatement(sql.toString()); ps.setString(1, produto.getNome()); ps.setBoolean(2, produto.isPerecivel()); ps.setString(3, produto.getDescricao()); ps.setInt(4, produto.getCategoria().getId()); ps.setInt(5, produto.getId()); ps.executeUpdate(); conexao.commit(); } catch (SQLException e) { try { conexao.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } // fim do try/catch INTERNO e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } // final FINALLY } @Override public List<IDominio> consultar(IDominio entidade) throws SQLException { conectar(); PreparedStatement ps = null; List<IDominio> produtos = new ArrayList<IDominio>(); Produto produto = (Produto) entidade; System.out.println("ID no DAO: " + produto.getId()); try { int i = 1; conexao.setAutoCommit(false); StringBuilder sql = new StringBuilder(); sql.append("SELECT p.*, c.* from produtos p inner join categorias_produto c on c.cat_id = p.id_categoria"); sql.append(" where 1=1"); if(produto.getId() != 0) { sql.append(" AND prd_id = ?"); } else if(produto.getNome() != null && produto.getNome() != "") { sql.append(" AND p.nome LIKE '%" + produto.getNome() + "%' "); } ps = conexao.prepareStatement(sql.toString()); if(produto.getId() != 0) { System.out.println(); ps.setInt(i, produto.getId()); i++; } System.out.println(ps.toString()); ResultSet resultado = ps.executeQuery(); while(resultado.next()) { Produto pdtBuscado = new Produto(); Categoria ctgBuscada = new Categoria(); pdtBuscado.setId(resultado.getInt("p.prd_id")); pdtBuscado.setNome(resultado.getString("p.nome")); pdtBuscado.setPerecivel(resultado.getInt("p.perecivel") == 1 ? true : false); pdtBuscado.setDescricao(resultado.getString("p.descricao")); ctgBuscada.setId(resultado.getInt("c.cat_id")); ctgBuscada.setNome(resultado.getString("c.nome")); pdtBuscado.setCategoria(ctgBuscada); produtos.add(pdtBuscado); } } catch (SQLException e) { try { conexao.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } // fim do try/catch INTERNO e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } // final FINALLY return produtos; } @Override public void excluir(IDominio entidade) throws SQLException { conectar(); PreparedStatement ps = null; Produto produto = (Produto) entidade; System.out.println("ID no DAO: " + produto.getId()); try { conexao.setAutoCommit(false); StringBuilder sql = new StringBuilder(); sql.append("DELETE from produtos"); sql.append(" where prd_id=?"); ps = conexao.prepareStatement(sql.toString()); ps.setInt(1, produto.getId()); ps.executeUpdate(); conexao.commit(); } catch (SQLException e) { try { conexao.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } // fim do try/catch INTERNO e.printStackTrace(); } finally { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } // final FINALLY } }
package com.tscloud.common.framework.domain.entity.manager; import com.tscloud.common.framework.domain.TrackableEntity; import java.io.Serializable; public class MenuRole extends TrackableEntity implements Serializable { private static final long serialVersionUID = -3266999810873563659L; private String menuId; private String roleId; public String getMenuId() { return menuId; } public void setMenuId(String menuId) { this.menuId = menuId; } public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } }
package com.televernote.evernote; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.Log; import com.evernote.client.android.AsyncNoteStoreClient; import com.evernote.client.android.EvernoteSession; import com.evernote.client.android.EvernoteUtil; import com.evernote.client.android.InvalidAuthenticationException; import com.evernote.client.android.OnClientCallback; import com.evernote.edam.error.EDAMNotFoundException; import com.evernote.edam.error.EDAMSystemException; import com.evernote.edam.error.EDAMUserException; import com.evernote.edam.notestore.NoteFilter; import com.evernote.edam.notestore.NoteList; import com.evernote.edam.type.LinkedNotebook; import com.evernote.edam.type.Note; import com.evernote.edam.type.NoteAttributes; import com.evernote.edam.type.NoteSortOrder; import com.evernote.edam.type.Notebook; import com.evernote.edam.type.SharedNotebook; import com.evernote.edam.type.SharedNotebookPrivilegeLevel; import com.evernote.thrift.TException; import com.evernote.thrift.transport.TTransportException; import com.televernote.activities.ViewMessagesActivity; public class EvernoteInteractor { private static final String PREFIXER = "Televernote: "; private static final String LOGTAG = "EvernoteInteractor"; private static final String CONSUMER_KEY = "eric5-5494"; private static final String CONSUMER_SECRET = "2b514688c7e57a5d"; private static final EvernoteSession.EvernoteService EVERNOTE_SERVICE = EvernoteSession.EvernoteService.SANDBOX; private static final boolean SUPPORT_APP_LINKED_NOTEBOOKS = true; private static List<Notebook> currentNotebooks; // Current evernote session private static EvernoteSession getSession(Context session) { return EvernoteSession.getInstance(session, CONSUMER_KEY, CONSUMER_SECRET, EVERNOTE_SERVICE, SUPPORT_APP_LINKED_NOTEBOOKS); } //methods to interact with evernote API public static boolean isLogged(Context session) { return getSession(session).isLoggedIn(); } public static void logOut(Context ctx) { try { getSession(ctx).logOut(ctx); } catch (InvalidAuthenticationException e) { e.printStackTrace(); } } //called every time app is started; check {s that necessary files are in place //if not, makes such necessary files public static void initializeIfNeeded(Context session) { final EvernoteSession mEvernoteSession = getSession(session); try { AsyncNoteStoreClient store = mEvernoteSession.getClientFactory().createNoteStoreClient(); store.listNotebooks(new OnClientCallback<List<Notebook>>() { @Override public void onSuccess(final List<Notebook> notebooks) { List<String> namesList = new ArrayList<String>(notebooks.size()); boolean hasInitial = false; currentNotebooks = notebooks.subList(0, notebooks.size()); for (Notebook notebook : notebooks) { namesList.add(notebook.getName()); //lol@hardcoded in strings if (notebook.getName().equals("Televernote Info")) { hasInitial = true; } } if (!hasInitial) { //make new notes try { //createNote(mEvernoteSession, "Televernote Info", "Televernote!"); createNotebook(mEvernoteSession, "Televernote Info"); } catch (TTransportException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public void onException(Exception e) { Log.e(LOGTAG, "Error retrieving notebooks", e); } }); //AsyncUserStoreClient store1= getSession(session).getClientFactory().createUserStoreClient(); } catch (TTransportException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //where user is the email of the user you wish to add public static void addUser(Context context, String user) { final String f_user = user; final EvernoteSession mEvernoteSession = getSession(context); for (Notebook notebook : currentNotebooks) { if (notebook.getName().equals(PREFIXER+"user")) { //already have this user added return; } } try { Notebook notebook = new Notebook(); notebook.setGuid(notebook.getGuid()); notebook.setName(PREFIXER+user); notebook.setStack("Televernote"); mEvernoteSession.getClientFactory().createNoteStoreClient().createNotebook(notebook, new OnClientCallback<Notebook>() { @Override public void onSuccess(Notebook data) { // TODO Auto-generated method stub currentNotebooks.add(data); SharedNotebook shared = new SharedNotebook(); shared.setNotebookGuid(data.getGuid()); shared.setAllowPreview(true); shared.setPrivilege(SharedNotebookPrivilegeLevel.MODIFY_NOTEBOOK_PLUS_ACTIVITY); shared.setEmail(f_user); try { mEvernoteSession.getClientFactory().createNoteStoreClient().createSharedNotebook(shared, new OnClientCallback<SharedNotebook>() { @Override public void onSuccess(SharedNotebook data) { // TODO Auto-generated method stub } @Override public void onException(Exception exception) { // TODO Auto-generated method stub } }); } catch (TTransportException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onException(Exception exception) { // TODO Auto-generated method stub } }); } catch (TTransportException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void createNotebook(Context context, String name) throws TTransportException { EvernoteSession mEvernoteSession = getSession(context); createNotebook(mEvernoteSession, name); } public static void createNotebook(EvernoteSession mEvernoteSession, String name) throws TTransportException { Notebook notebook = new Notebook(); notebook.setGuid(notebook.getGuid()); notebook.setName(name); notebook.setStack("Televernote"); mEvernoteSession.getClientFactory().createNoteStoreClient().createNotebook(notebook, new OnClientCallback<Notebook>() { @Override public void onSuccess(Notebook data) { // TODO Auto-generated method stub currentNotebooks.add(data); } @Override public void onException(Exception exception) { // TODO Auto-generated method stub } }); } public static void createNote(Context context, String title, String content, String data, String recipient) throws TTransportException { EvernoteSession mEvernoteSession = getSession(context); createNote(mEvernoteSession, title, content, data, recipient); } public static void createNote(final EvernoteSession mEvernoteSession, String title, String content, final String timeData, String recipient) throws TTransportException { if (mEvernoteSession.isLoggedIn()) { List<String> tags = new ArrayList<String>(); tags.add("televernote"); Note note = new Note(); note.setTitle(title); /*if (content.length() >= 5) { note.setTitle(content.substring(0, 4)); } else { note.setTitle(content); }*/ String nbGuid = getNotebookGUIDForUser(recipient); note.setNotebookGuid(nbGuid); //note.getAttributes().setCreatorId(userId); //note.setTagGuids(tags); NoteAttributes attr; int userId = mEvernoteSession.getAuthenticationResult().getUserId(); if (note.getAttributes() == null) { attr = new NoteAttributes(); } else { attr = note.getAttributes(); } attr.setCreatorId(userId); note.setAttributes(attr); note.setTagNames(tags); note.setContent(EvernoteUtil.NOTE_PREFIX + content + EvernoteUtil.NOTE_SUFFIX); mEvernoteSession.getClientFactory().createNoteStoreClient().createNote(note, new OnClientCallback<Note>() { @Override public void onSuccess(final Note data) { //Toast.makeText(getApplicationContext(), data.getTitle() + " has been created", Toast.LENGTH_LONG).show(); //note.setCreated(userId); try { mEvernoteSession.getClientFactory().createNoteStoreClient().setNoteApplicationDataEntry(data.getGuid(), "timestamp", timeData, new OnClientCallback<Integer>() { @Override public void onSuccess(Integer data) { // TODO Auto-generated method stub } @Override public void onException(Exception exception) { // TODO Auto-generated method stub } }); } catch (TTransportException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onException(Exception exception) { Log.e(LOGTAG, "Error creating note", exception); } }); } } public static String getNotebookGUIDForUser(String user) { String name; for (Notebook notebook: currentNotebooks) { name = notebook.getName(); if (name.startsWith(PREFIXER)) { if (name.equals(PREFIXER + user)) { //this is the notebook we want return notebook.getGuid(); } } } return ""; } public static boolean isNotebookLinked(String guid) { String name; for (Notebook notebook: currentNotebooks) { if (notebook.getGuid().equals(guid)) { return !notebook.isSetSharedNotebookIds(); } } return true; } public static void getAllMessages(Context context, final ViewMessagesActivity sender) { List<String> tags = new ArrayList<String>(); tags.add("televernote"); final EvernoteSession mEvernoteSession = getSession(context); /*String name; for (Notebook notebook: currentNotebooks) { name = notebook.getName(); if (name.startsWith(PREFIXER)) { } }*/ try { AsyncNoteStoreClient store = mEvernoteSession.getClientFactory().createNoteStoreClient(); store.listLinkedNotebooks(new OnClientCallback<List<LinkedNotebook>>() { @Override public void onSuccess(List<LinkedNotebook> data) { // TODO Auto-generated method stub final List<Note> retNotes = new ArrayList<Note>(); int index = 0; for (LinkedNotebook linked: data) { index++; final boolean end = (index == data.size() - 1); try { mEvernoteSession.getClientFactory().createLinkedNoteStoreClient(linked); } catch (EDAMUserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (EDAMSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (EDAMNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } NoteFilter filter = new NoteFilter(); filter.setOrder(NoteSortOrder.UPDATED.getValue()); //filter.setTagGuids(tags); filter.setWords("televernote"); filter.setAscending(true); try { mEvernoteSession.getClientFactory().createNoteStoreClient().findNotes(filter, 0, 50, new OnClientCallback<NoteList> () { @Override public void onSuccess(NoteList data) { // TODO Auto-generated method stub List<Note> notes = data.getNotes(); int userId = mEvernoteSession.getAuthenticationResult().getUserId(); System.out.println("My User ID: "+userId); for (Note m: notes) { m.getAttributes().getSourceURL(); System.out.println("Note ID: "+m.getAttributes().getCreatorId()); //System.out.println("Note ID: "+m.getCreated()); //if (m.getAttributes().getCreatorId() != userId) { //if (m.getCreated() != userId) { if (isNotebookLinked(m.getNotebookGuid())) { retNotes.add(m); } } if (end) { sender.receiveNotes(notes); } //sender.receiveNotes(notes); } @Override public void onException(Exception exception) { // TODO Auto-generated method stub } }); } catch (TTransportException e) { // TODO Auto-generated catch block e.printStackTrace(); } } sender.receiveNotes(retNotes); } @Override public void onException(Exception exception) { // TODO Auto-generated method stub } }); } catch (TTransportException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void unpackageNodeData(Context context, Note note, final ViewMessagesActivity sender, final int index) { EvernoteSession mEvernoteSession = getSession(context); try { mEvernoteSession.getClientFactory().createNoteStoreClient().getNoteApplicationDataEntry(note.getGuid(),"timestamp", new OnClientCallback<String>() { @Override public void onSuccess(String data) { // TODO Auto-generated method stub System.out.println("S"); sender.receiveData(data, index); } @Override public void onException(Exception exception) { // TODO Auto-generated method stub System.out.println("Failed to get timestamp data"); } }); } catch (TTransportException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.codingchili.instance.model.questing; import com.codingchili.instance.model.events.Event; import com.codingchili.instance.model.events.EventType; /** * @author Robin Duda * * Emitted when a quest log has been updated. */ public class QuestUpdateEvent implements Event { private String id; private String name; public QuestUpdateEvent(Quest quest) { this.id = quest.getId(); this.name = quest.getName(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public EventType getRoute() { return EventType.quest_update; } }
package com.fumei.bg.service.impl; import com.fumei.bg.domain.web.Partner; import com.fumei.bg.mapper.PartnerMapper; import com.fumei.bg.service.IPartnerService; import org.springframework.stereotype.Service; import java.util.List; /** * @author zkh */ @Service public class PartnerServiceImpl implements IPartnerService { private final PartnerMapper mapper; public PartnerServiceImpl(PartnerMapper mapper) { this.mapper = mapper; } /** * 查询合作人列表 * * @param partner 条件 * @return 合作人列表 */ @Override public List<Partner> getPartnerList(Partner partner) { return mapper.selectPartnerList(partner); } /** * 保存合作人信息 * @param partner 合作人信息 * @return 执行结果 1成功 0失败 */ @Override public int save(Partner partner) { return mapper.insert(partner); } /** * 修改合作人信息 * @param partner 合作人信息 * @return 执行结果 1成功 0失败 */ @Override public int edit(Partner partner) { return mapper.updateByPrimaryKey(partner); } /** * 删除合作人信息 * @param pId 合作人信息id * @return 执行结果 1成功 0失败 */ @Override public int remove(Long pId) { return mapper.deleteByPrimaryKey(pId); } }
package com.esum.xtrus.security.pki; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.commons.io.IOUtils; import com.esum.framework.FrameworkSystemVariables; import com.esum.framework.security.SecurityConstants; import com.esum.framework.security.SecurityInit; import com.esum.framework.security.pki.manager.PKIStoreManager; import com.esum.framework.security.pki.manager.info.PKIPKCS78Info; import com.esum.framework.security.xml.XMLSecurityConstants; import com.esum.framework.security.xml.encrypt.XMLEncrypt; import com.esum.framework.security.xml.manager.encrypt.XMLEncryptInfo; import com.esum.framework.security.xml.manager.encrypt.XMLEncryptInfoManager; import junit.framework.TestCase; public class SEED_CBC_LoadTest extends TestCase { public void testGetBase64BinaryObject() throws Exception { System.setProperty(FrameworkSystemVariables.SECURITY_TOOLKIT_VARIABLE, SecurityConstants.TOOLKIT_BOUNCY_CASTLE); SecurityInit.initSecurityProvider(); byte[] data = IOUtils.toByteArray(new FileInputStream(new File("D:/work/dev/xtrus302/xtrus/esum-framework/data/security/test.xml"))); String privateKeyPath = "D:/work/dev/xtrus302/xtrus/esum-framework/data/security/signgate/kmPri.key"; String privateKeyPassword = "a123456A"; String certificatePath = "D:/work/dev/xtrus302/xtrus/esum-framework/data/security/signgate/kmCert.der"; PKIPKCS78Info pki78Info = new PKIPKCS78Info(privateKeyPath, privateKeyPassword, certificatePath); PKIStoreManager.getInstance().addPKIStoreInfo("test", pki78Info); String pkiAlias = "test"; String dataEncMethod = "http://www.tta.or.kr/2001/04/xmlenc#seed-cbc"; String keyEncMethod = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"; String initVectorValue = XMLSecurityConstants.INITIAL_VECTOR_SEED_CUSTOMS; XMLEncryptInfo xmlEncryptInfo = new XMLEncryptInfo(pkiAlias, dataEncMethod, keyEncMethod, null); XMLEncryptInfoManager.getInstance().addXMLEncryptInfo("test", xmlEncryptInfo); XMLEncrypt encrypt = XMLEncrypt.getInstance(); byte[] encrypted = encrypt.encrypt(xmlEncryptInfo, data); File file = new File("D:/work/dev/xtrus302/xtrus/esum-framework/data/security/test_encrypted.xml"); FileOutputStream out = new FileOutputStream(file); out.write(encrypted); out.close(); System.out.println(new String(encrypted)); } }
package service; import dao.UserDao; import entity.User; public class UserServiceImpl implements UserService { UserDao userDao = new UserDao(); // 註冊 @Override public int register(User user) { return userDao.register(user); } // 登陸 @Override public int login(String userName, String password) { return userDao.login(userName,password); } // 根據使用者名稱查詢資訊 @Override public User findByName(String userName) { return userDao.findByName(userName); } }
package com.blog.dusk.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.util.Date; @Entity public class goods { @Id @GeneratedValue @Column(name = "g_id") private Integer gId; @Column(name = "g_name") private String gName; @Column(name = "g_inserttime") private Date gInserttime; @Column(name = "g_cost") private Double gCost; @Column(name = "g_sale") private Double gSale; @Column(name = "g_Discount") private Double gDiscount; @Column(name = "g_Stock") private Integer gStock; @Column(name = "g_service") private String gService; public Integer getgId() { return gId; } public void setgId(Integer gId) { this.gId = gId; } public String getgName() { return gName; } public void setgName(String gName) { this.gName = gName == null ? null : gName.trim(); } public Date getgInserttime() { return gInserttime; } public void setgInserttime(Date gInserttime) { this.gInserttime = gInserttime; } public Double getgCost() { return gCost; } public void setgCost(Double gCost) { this.gCost = gCost; } public Double getgSale() { return gSale; } public void setgSale(Double gSale) { this.gSale = gSale; } public Double getgDiscount() { return gDiscount; } public void setgDiscount(Double gDiscount) { this.gDiscount = gDiscount; } public Integer getgStock() { return gStock; } public void setgStock(Integer gStock) { this.gStock = gStock; } public String getgService() { return gService; } public void setgService(String gService) { this.gService = gService == null ? null : gService.trim(); } }
package io; import java.io.Serializable; /** * 简述: * * @author WangLipeng 1243027794@qq.com * @version 1.0 * @since 2020/1/10 14:49 */ public class User implements Serializable { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.javawebtutor; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.javawebtutor.Entities.Dostava; import com.javawebtutor.Entities.ProizvodiMaloprodaja; import com.javawebtutor.Entities.RacunMaloprodaja; public class FizickoLice { //proces kupovine za fizicko lice public static void main(String[] args) { TCService Mall=new TCServiceImpl(); BufferedReader br=null; List<ProizvodiMaloprodaja> korpa=new ArrayList<ProizvodiMaloprodaja>(); try { System.out.println("Dobrodosli u trzni centar. Za kupovinu unesite 1, za kraj 0"); br=new BufferedReader(new InputStreamReader(System.in)); String line=br.readLine(); while(!line.equals("0")) { Mall.prikaziProizvodeUMaloprodaji(); System.out.println("Izaberite proizvod i unesite njegov id"); int id=Integer.parseInt(br.readLine()); ProizvodiMaloprodaja pr=Mall.vratiProizvodMaloprodaja(id); System.out.println("Vas izbor je "+pr.getNazivProizvoda()); System.out.println("Unesite kolicinu proizvoda koju zelite"); line=br.readLine(); int kol=Integer.parseInt(line); pr.setKolicina(kol); if(Mall.proveriUMaloprodaji(pr.getId(), kol)) korpa.add(pr); line=br.readLine(); } double suma=Mall.vratiCenu(korpa); if(suma!=0) { System.out.println("Izaberite nacin placanja 1-kes, 2-kartica"); String placanje=null; String dostava="ne"; String adresa=""; line=br.readLine(); int broj=Integer.parseInt(line); if(broj==2) { placanje="kartica"; } else //placanje je po defaultu kesom { placanje="kes"; } Mall.kupiMaloprodaja(korpa); RacunMaloprodaja racun=new RacunMaloprodaja(suma,placanje, dostava, new Date()); System.out.println("Da li zelite da vam se kupljeni proizvodi dostave na adresu 1-da 2-ne"); line=br.readLine(); broj=Integer.parseInt(line); if(broj==1) { dostava="da"; System.out.println("Unesite adresu za dostavu"); adresa=br.readLine(); racun.setDostava(dostava); Dostava d=new Dostava(adresa, new Date()); d.setIsporuceno("ne"); racun.setIdDostava(d); } else //po defaultu ne vrsi se dostava { dostava="ne"; } racun.setDostava(dostava); Mall.dodajRacunMaloprodaja(racun); Mall.dostavi(racun); } Mall.Feedback(); Mall.prikaziProsecnuOcenu(); } catch(Exception ec) { System.out.println(ec); } } }
package com.allure.service.framework.component; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; /** * Created by yang_shoulai on 7/20/2017. */ @Component public class PasswordEncrypt extends BCryptPasswordEncoder { }
package com.prep.datastructure; public class HashTable { HashEntry[] table=null; public int TABLE_SIZE=5; public HashTable(){ table=new HashEntry[TABLE_SIZE]; for(int i=0;i<TABLE_SIZE;i++){ table[i]=null; } } public boolean isContains(int k){ for(int i=0;i<TABLE_SIZE;i++){ if(table[i].getKey()==k) return true; } return false; } public HashEntry get(int k){ int hash=k%TABLE_SIZE; while(table[hash]!=null && table[hash].getKey()!= k) hash=(hash+1)%TABLE_SIZE; if(table[hash]==null) return null; else return table[hash]; } public void set(int k,String v){ int hash=k%TABLE_SIZE; while(table[hash]!=null && table[hash].getKey()!=k){ hash=(hash+1)%TABLE_SIZE; } table[hash]=new HashEntry(k,v); } public void remove(int k){ int hash=k%TABLE_SIZE; while(table[hash]!=null && table[hash].getKey()!=k) hash=(hash+1)%TABLE_SIZE; table[hash]=null; } }
package com.example.ips; import com.example.ips.export.Constant; import com.example.ips.shiro.MyByteSource; import com.example.ips.util.AESUtil; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.util.ByteSource; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @SpringBootTest public class IpsApplicationTests { /** * 数据库账号密码加解密测试 */ @Test public void mybatisInfoTest() { String userName="whale"; String pass="s&s404"; //加密 byte[] userName16=AESUtil.encrypt(userName, Constant.SYS_SALT); byte[] pass16=AESUtil.encrypt(pass, Constant.SYS_SALT); String encryptResultUser = AESUtil.parseByte2HexStr(userName16); String encryptResultPass = AESUtil.parseByte2HexStr(pass16); System.out.println("开始加密..."); System.out.println("用户名:"+encryptResultUser); System.out.println("密码:"+encryptResultPass); System.out.println("加密结束..."); //解密 System.out.println("开始解密..."); byte[] usernamedecryptFrom = AESUtil.parseHexStr2Byte(encryptResultUser); byte[] usernamedecryptResult = AESUtil.decrypt(usernamedecryptFrom, Constant.SYS_SALT); byte[] passworddecryptFrom = AESUtil.parseHexStr2Byte(encryptResultPass); byte[] passworddecryptResult = AESUtil.decrypt(passworddecryptFrom, Constant.SYS_SALT); System.out.println("用户名:"+new String(usernamedecryptResult)); System.out.println("密码:"+new String(passworddecryptResult)); System.out.println("解密结束..."); } /** * 系统登录密码加盐加密 */ @Test public void sysPasswordMd5() { //加密方式 String hashAlgorithmName = "MD5"; //盐:为了即使相同的密码不同的盐加密后的结果也不同 ByteSource byteSalt = new MyByteSource(Constant.SYS_SALT); //密码 Object source = "123456"; //加密次数 int hashIterations = 2; SimpleHash result = new SimpleHash(hashAlgorithmName, source, byteSalt, hashIterations); System.out.println(result.toString()); } /** * 时间相减算法 * @throws ParseException */ @Test public void timeDel() throws ParseException { SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date begin=dfs.parse("2004-01-02 11:09:21"); Date end = dfs.parse("2004-01-03 12:11:33"); long between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒 long hour1=between/3600; long minute1=between%3600/60; long second1=between%60/1; System.out.println(""+hour1+"小时"+minute1+"分"+second1+"秒"); } }
package com.sshfortress.common.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; import com.sshfortress.common.enums.HttpChannelType; import com.sshfortress.common.enums.UserTypeEnums; import com.sshfortress.common.model.SessionUser; import com.sshfortress.common.util.JsonUtil; import com.sshfortress.common.util.OperationContextHolder; import com.sshfortress.common.util.SignUtils; public class DoSessionFilter extends OncePerRequestFilter { /** * jar包不要引错 org.apache.commons.logging.* */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { WebApplicationContext webApplicationContext = WebApplicationContextUtils .getWebApplicationContext(request.getSession().getServletContext()); //System.out.println("进入过滤器开始"); TicketHelper ticketHelper = (TicketHelper) webApplicationContext.getBean("ticketHelper"); // 取ticket(加签的) String ticket = ticketHelper.getTicket(request, HttpChannelType.APP); // 共享session_id失效或者不存在时 if (StringUtils.isBlank(ticket)) { //filterChain.doFilter(request, response); //System.out.println("解签 第一步"); //return; ticket=""; } // 解签ticket String dticket = SignUtils.decrypt(ticket); if (StringUtils.isBlank(dticket)) { //filterChain.doFilter(request, response); //System.out.println("第2步 解签"); //return; dticket=""; } SessionUser sessionUser = null; try { if(!StringUtils.isBlank(dticket)){ sessionUser = (SessionUser) JsonUtil.toObject(dticket, SessionUser.class); } if (sessionUser == null || !UserTypeEnums.getEnumByCode(sessionUser.getUserType()).isAppMember()) { filterChain.doFilter(request, response); } else { // TODO(待做) // 注册上下文 OperationContextHolder.setIsLoggerUser(sessionUser); ticketHelper.setCookie(request, response, ticket); filterChain.doFilter(request, response); } //System.out.println("进入过滤器结束"); } catch (Exception e) { filterChain.doFilter(request, response); } finally { // 每个request请求结束后清理该用户上下文") //System.out.println("执行过滤器FINALLY方法"); OperationContextHolder.clearUser(); } } }
package com.daikit.graphql.meta.internal; import java.util.ArrayList; import java.util.List; import com.daikit.graphql.meta.entity.GQLEntityMetaData; /** * Meta data computed informations for {@link GQLEntityMetaData} * * @author Thibaut Caselli */ public abstract class GQLAbstractEntityMetaDataInfos { private final GQLEntityMetaData entity; private GQLAbstractEntityMetaDataInfos superEntity; // Super interfaces recursively private final List<GQLAbstractEntityMetaDataInfos> superInterfaces = new ArrayList<>(); // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // CONSTRUCTORS // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- /** * Constructor * * @param entity * the GQLAbstractEntityMetaData */ public GQLAbstractEntityMetaDataInfos(final GQLEntityMetaData entity) { this.entity = entity; } // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // METHODS // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- /** * @return whether this instance is for concrete meta data */ public boolean isConcrete() { return this instanceof GQLConcreteEntityMetaDataInfos; } // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // GETTERS / SETTERS // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- /** * @return the entity */ public GQLEntityMetaData getEntity() { return entity; } /** * @return the superEntity */ public GQLAbstractEntityMetaDataInfos getSuperEntity() { return superEntity; } /** * @param superEntity * the superEntity to set */ public void setSuperEntity(final GQLAbstractEntityMetaDataInfos superEntity) { this.superEntity = superEntity; } /** * @return the superInterfaces */ public List<GQLAbstractEntityMetaDataInfos> getSuperInterfaces() { return superInterfaces; } }
package misc; public class EqiTest { public static void main(String[] args) { // TODO Auto-generated method stub Customer c1 = new Customer(); c1.setName("Sel"); Customer c2 = new Customer(); c2.setName("Sel"); Customer c3 =c1; String p1 = "Selva"; String p2 = "Selva"; System.out.println(c1==c2); System.out.println(c1==c3); System.out.println(p1==p2); } }
package com.cai.seckill.service; import com.cai.seckill.dao.GoodsDao; import com.cai.seckill.pojo.Goods; import com.cai.seckill.pojo.SeckillGoods; import com.cai.seckill.vo.GoodsVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class GoodsService { @Autowired private GoodsDao goodsDao; public List<GoodsVo> listGoodsVo(){ return goodsDao.listGoodsVo(); } public GoodsVo getById(long goodsId) { return goodsDao.getById(goodsId); } public boolean reducestock(GoodsVo goods){ SeckillGoods sgoods = new SeckillGoods(); sgoods.setGoodsId(goods.getId()); return goodsDao.reducestock(sgoods) > 0; } }
package linkedlist; /** * An iterator of Doubly Linked List * * @author zhouqing * */ public class Iterator { Link current; DoublyLinkedList mylist; public Iterator(DoublyLinkedList DList){ mylist=DList; reset(); } public void reset(){ current=mylist.first; } public void laset(){ current=mylist.last; } public void nextLink(){ current=current.next; } public void priorLink(){ current=current.prior; } public Link getCurrent(){ return current; } public boolean atEnd(){ return current.next==null? true:false; } public void insertBefore(int data){ Link lk=new Link(); lk.data=data; if(current.prior!=null){ current.prior.next=lk; lk.prior=current.prior; } else mylist.first=lk; lk.next=current; current.prior=lk; } public void insertAfter(int data){ Link lk=new Link(); lk.data=data; if(current.next!=null){ current.next.prior=lk; lk.next=current.next; } else{ mylist.last=lk; } lk.prior=current; current.next=lk; } public int deleteCurrent(){ if(current.prior!=null){ current.prior.next=current.next; current=current.prior; } else mylist.first=current.next; if(current.next!=null){ current.next.prior=current.prior; current=current.next; } else mylist.last=current.prior; return current.data; } }
package com.krishna.assistsample.firebase; import com.google.firebase.iid.FirebaseInstanceId; public class FCMInstanceIdService extends com.google.firebase.iid.FirebaseInstanceIdService { @Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); } }
package com.tomaszdebski.decerto.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Quote { public Quote() { } @Id @GeneratedValue private long id; @Column(name = "author_first_name") private String authorFirstName; @Column(name = "author_last_name") private String authorLastName; @Column(name = "content") private String content; public Quote(String authorFirstName, String authorLastName, String content) { this.authorFirstName = authorFirstName; this.authorLastName = authorLastName; this.content = content; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getAuthorFirstName() { return authorFirstName; } public void setAuthorFirstName(String authorFirstName) { this.authorFirstName = authorFirstName; } public String getAuthorLastName() { return authorLastName; } public void setAuthorLastName(String authorLastName) { this.authorLastName = authorLastName; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Quote quote = (Quote) o; if (id != quote.id) return false; if (authorFirstName != null ? !authorFirstName.equals(quote.authorFirstName) : quote.authorFirstName != null) return false; if (authorLastName != null ? !authorLastName.equals(quote.authorLastName) : quote.authorLastName != null) return false; return content != null ? content.equals(quote.content) : quote.content == null; } @Override public int hashCode() { int result = (int) (id ^ (id >>> 32)); result = 31 * result + (authorFirstName != null ? authorFirstName.hashCode() : 0); result = 31 * result + (authorLastName != null ? authorLastName.hashCode() : 0); result = 31 * result + (content != null ? content.hashCode() : 0); return result; } public static QuoteBuilder builder() { return new QuoteBuilder(); } public static class QuoteBuilder { private long id; private String authorFirstName; private String authorLastName; private String content; public QuoteBuilder withId(Long id) { this.id = id; return this; } public QuoteBuilder withAuthorFirstName(String authorFirstName) { this.authorFirstName = authorFirstName; return this; } public QuoteBuilder withAuthorLastName(String authorLastName) { this.authorLastName = authorLastName; return this; } public QuoteBuilder withContent(String content) { this.content = content; return this; } public Quote build() { return new Quote(authorFirstName, authorLastName, content); } } }
package com.ahu.controller; import com.ahu.constant.MessageConstant; import com.ahu.entity.Result; import com.ahu.pojo.OrderSetting; import com.ahu.service.OrderSettingService; import com.ahu.utils.POIUtils; import com.alibaba.dubbo.config.annotation.Reference; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * @author :hodor007 * @date :Created in 2020/11/25 * @description : * @version: 1.0 */ @RestController @RequestMapping("/ordersetting") public class OrderSettingController { @Reference private OrderSettingService orderSettingService; @RequestMapping("/upload") public Result upload(MultipartFile excelFile){ List<OrderSetting> orderSettingList = new ArrayList<>(); try { List<String[]> rows = POIUtils.readExcel(excelFile); if(rows != null && rows.size() > 0){ //遍历行,存入对象 for (String[] row : rows) { OrderSetting orderSetting = new OrderSetting(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = simpleDateFormat.parse(row[0]); orderSetting.setOrderDate(date); orderSetting.setNumber(Integer.parseInt(row[1])); orderSettingList.add(orderSetting); } //调用service保存 orderSettingService.upload(orderSettingList); return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS); } } catch (IOException | ParseException e) { e.printStackTrace(); return new Result(true, MessageConstant.IMPORT_ORDERSETTING_FAIL); } return null; } @RequestMapping("/getOrderListByMonth") public Result getOrderListByMonth(String date){ try { List<Map> dates = orderSettingService.getOrderListByMonth(date); return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,dates); } catch (Exception e) { e.printStackTrace(); return new Result(true,MessageConstant.QUERY_ORDER_FAIL); } } @RequestMapping("/setOrderNum") public Result setOrderNum(@RequestBody OrderSetting orderSetting){ try { orderSettingService.setNumByDay(orderSetting); return new Result(true,MessageConstant.ORDERSETTING_SUCCESS); } catch (Exception e) { e.printStackTrace(); return new Result(true,MessageConstant.ORDERSETTING_FAIL); } } }
package com.example.demo.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.example.demo.domain.Category; import com.example.demo.domain.Item; import com.example.demo.form.AddItemForm; import com.example.demo.form.SearchByItemNameForm; import com.example.demo.service.AddItemService; import com.example.demo.service.ShowItemListService; /** * * 商品追加に関するコントローラ. * * @author masashi.nose * */ @Controller @RequestMapping("") public class AddItemController { @Autowired private AddItemService addItemService; @Autowired private ShowItemListService showItemListService; @Autowired private ShowItemListController showItemListController; @ModelAttribute public AddItemForm setUpForm() { return new AddItemForm(); } @ModelAttribute public SearchByItemNameForm setUpNameForm() { return new SearchByItemNameForm(); } /** * 商品追加画面へ遷移します. * * @param model リクエストスコープ作成 * @return 商品追加画面 */ @RequestMapping("/toAdd") public String toAdd(Model model) { List<Category> parentCategoryList = showItemListService.findParentCategoryList(); List<Category> childCategoryList = showItemListService.findGrandChildCategoryList(); List<Category> grandChildCategoryList = showItemListService.findGrandChildCategoryList(); model.addAttribute("parentList", parentCategoryList); model.addAttribute("childList", childCategoryList); model.addAttribute("grandChildList", grandChildCategoryList); return "add"; } /** * * 商品を追加します. * * @param form リクエストパラメータ * @param result * @param model リクエストスコープ作成 * @return 商品一覧画面 */ @RequestMapping("/add") public String add(@Validated AddItemForm form, BindingResult result, Model model) { // // if (result.hasErrors()) { // return toAdd(model); // } Item item = new Item(); item.setName(form.getName()); item.setPrice(form.getIntPrice()); item.setBrand(form.getBrand()); item.setCondition(form.getIntCondition()); item.setDescription(form.getDescription()); addItemService.addItem(item); return "redirect:/finish"; } @RequestMapping("/finish") public String finish() { return "add_finish"; } }
// ********************************************************** // 1. 제 목: 학습 종료 관련 BEAN // 2. 프로그램명: CPFinishBean.java // 3. 개 요: 학습 종료 관련 BEAN // 4. 환 경: JDK 1.4 // 5. 버 젼: 0.1 // 6. 작 성: S.W.Kang 2004. 12. 5 // 7. 수 정: 이창훈 2004.12.23 // // ********************************************************** package com.ziaan.cp; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.ziaan.common.GetCodenm; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.DataBox; import com.ziaan.library.FormatDate; import com.ziaan.library.ListSet; import com.ziaan.library.SQLString; /** *과목결과등록 *<p> 제목:CPFinishBean.java</p> *<p> 설명:과목결과등록 빈</p> *<p> Copyright: Copright(c)2004</p> *<p> Company: VLC</p> *@author 이창훈 *@version 1.0 */ public class CPFinishBean { public static final int FINISH_COMPLETE = 0; // 수료처리 종료 public static final int FINISH_CANCEL = 1; // 수료취소 가능 public static final int FINISH_PROCESS = 3; // 수료처리 public static final int SCORE_COMPUTE = 4; // 점수재계산 public static final String ONOFF_GUBUN = "0004"; public static final String SUBJ_NOT_INCLUDE_COURSE = "000000"; public CPFinishBean() { } /** 과목기수 세부정보 세팅(수료기준,가중치 및 과목정보) @param connMgr DB연결개체 @param p_subj 과목코드 @param p_year 교육년도 @param p_subjseq 과목기수 @return CPSubjseqData 과목기수정보 */ public CPSubjseqData getSubjseqInfo(DBConnectionManager connMgr, String p_subj, String p_year, String p_subjseq) throws Exception { ListSet ls = null; String sql = ""; CPSubjseqData data = new CPSubjseqData(); // 과목기수 정보 sql = " select b.isclosed, b.edustart, b.eduend, "; sql += " b.wstep, b.wmtest, b.wftest, b.wreport, "; sql += " b.wact, b.wetc1, b.wetc2, b.whtest, "; sql += " b.gradscore, b.gradstep, b.gradexam, b.gradftest, "; sql += " b.gradhtest, b.gradreport, "; sql += " b.grcode, b.grseq, b.gyear, b.subjnm, "; sql += " a.isonoff, b.biyong "; sql += " from tz_subj a, "; sql += " tz_subjseq b"; sql += " where a.subj = b.subj "; sql += " and b.subj = " + SQLString.Format(p_subj); sql += " and b.year = " + SQLString.Format(p_year); sql += " and b.subjseq = " + SQLString.Format(p_subjseq); // System.out.println("111111 == =??? >> >> >> > " +sql); try { ls = connMgr.executeQuery(sql); while ( ls.next() ) { data.setIsclosed( ls.getString("isclosed") ); data.setEdustart( ls.getString("edustart") ); data.setEduend ( ls.getString("eduend") ); data.setWstep ((int)ls.getDouble("wstep") ); data.setWmtest ((int)ls.getDouble("wmtest") ); data.setWftest ((int)ls.getDouble("wftest") ); data.setWhtest ((int)ls.getDouble("whtest") ); data.setWreport ((int)ls.getDouble("wreport") ); data.setWact ((int)ls.getDouble("wact") ); data.setWetc1 ((int)ls.getDouble("wetc1") ); data.setWetc2 ((int)ls.getDouble("wetc2") ); data.setGradscore( ls.getInt("gradscore") ); data.setGradstep( ls.getInt("gradstep") ); data.setGradexam( ls.getInt("gradexam") ); data.setGradftest( ls.getInt("gradftest") ); data.setGradhtest( ls.getInt("gradhtest") ); data.setGradreport( ls.getInt("gradreport") ); data.setGrcode( ls.getString("grcode") ); data.setGyear( ls.getString("gyear") ); data.setGrseq( ls.getString("grseq") ); data.setSubjnm( ls.getString("subjnm") ); data.setGrcodenm(GetCodenm.get_grcodenm(data.getGrcode() )); data.setGrseqnm(GetCodenm.get_grseqnm(data.getGrcode(), data.getGyear(), data.getGrseq() )); data.setIsonoff( ls.getString("isonoff") ); data.setBiyong( ls.getInt("biyong") ); } } catch ( Exception ex ) { throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } } return data; } /** 과목기수 세부정보 세팅(수료기준,가중치 및 과목정보) @param connMgr DB연결개체 @param p_subj 과목코드 @param p_year 교육년도 @param p_subjseq 과목기수 @return CPSubjseqData 과목기수정보 */ public DataBox getSubjseqInfoDbox(DBConnectionManager connMgr, String p_subj, String p_year, String p_subjseq) throws Exception { ListSet ls = null; String sql = ""; CPSubjseqData data = new CPSubjseqData(); DataBox dbox = null; // 과목기수 정보 sql = " select b.isclosed, b.edustart, b.eduend, "; sql += " b.wstep, b.wmtest, b.wftest, b.wreport, "; sql += " b.wact, b.wetc1, b.wetc2, b.whtest, "; sql += " b.gradscore, b.gradstep, b.gradexam, b.gradftest, "; sql += " b.gradhtest, b.gradreport, "; sql += " b.grcode, b.grseq, b.gyear, b.subjnm, "; sql += " a.isonoff, b.biyong "; sql += " from tz_subj a, "; sql += " tz_subjseq b"; sql += " where a.subj = b.subj "; sql += " and b.subj = " + SQLString.Format(p_subj); sql += " and b.year = " + SQLString.Format(p_year); sql += " and b.subjseq = " + SQLString.Format(p_subjseq); try { ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); dbox.put("d_grcodenm", GetCodenm.get_grcodenm(data.getGrcode() )); dbox.put("d_grseqnm", GetCodenm.get_grseqnm(data.getGrcode(), data.getGyear(), data.getGrseq() )); } } catch ( Exception ex ) { throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } } return dbox; } /** 수강생정보 업데이트 @param connMgr DB연결개체 @param p_gubun 실행구분 @param p_command 액션구분 @return PreparedStatement PreparedStatement */ public PreparedStatement getPreparedStatement(DBConnectionManager connMgr, String p_gubun, String p_command) throws Exception { PreparedStatement pstmt = null; String sql = ""; if ( p_gubun.equals("SUBJECT_STUDENT") ) { if ( p_command.equals("update_result") ) { sql = " update tz_student "; sql += " set score = ?, "; sql += " tstep = ?, "; sql += " mtest = ?, "; sql += " ftest = ?, "; sql += " htest = ?, "; sql += " report = ?, "; sql += " act = ?, "; sql += " etc1 = ?, "; sql += " etc2 = ?, "; sql += " avtstep = ?, "; sql += " avmtest = ?, "; sql += " avftest = ?, "; sql += " avreport= ?, "; sql += " avact = ?, "; sql += " avetc1 = ?, "; sql += " avetc2 = ?, "; sql += " isgraduated= ?, "; sql += " notgraduetc= ?, "; sql += " luserid = ?, "; sql += " ldate = ?, "; sql += " rank = ? "; sql += " where subj = ? "; sql += " and year = ? "; sql += " and subjseq = ? "; sql += " and userid = ? "; } else if ( p_command.equals("update_status") ) { sql = " update tz_student "; sql += " set score = ?, "; sql += " tstep = ?, "; sql += " mtest = ?, "; sql += " ftest = ?, "; sql += " htest = ?, "; sql += " report = ?, "; sql += " act = ?, "; sql += " etc1 = ?, "; sql += " etc2 = ?, "; sql += " avtstep = ?, "; sql += " avmtest = ?, "; sql += " avftest = ?, "; sql += " avreport= ?, "; sql += " avact = ?, "; sql += " avetc1 = ?, "; sql += " avetc2 = ?, "; sql += " luserid = ?, "; sql += " ldate = ? "; sql += " where subj = ? "; sql += " and year = ? "; sql += " and subjseq = ? "; sql += " and userid = ? "; } } else if ( p_gubun.equals("MEMBER") ) { if ( p_command.equals("select") ) { sql = " select name, comp, '' jikup, '' jikwi, '' jikwinm "; sql += " from tz_member "; sql += " where userid = ? "; } } else if ( p_gubun.equals("SUBJECT_SANGDAM") ) { if ( p_command.equals("insert") ) { sql += " insert into tz_sangdam( \n"; sql += " NO, USERID, CUSERID, CTEXT, \n"; sql += " STATUS, SDATE, LDATE, MCODE, \n"; sql += " SCODE, ETIME, TITLE, FTEXT, \n"; sql += " RSEQ, SUBJ, YEAR, SUBJSEQ, \n"; sql += " GUBUN \n"; sql += " )values( \n"; sql += " ?, ?, ?, ?, \n"; sql += " ?, ?, ?, ?, \n"; sql += " ?, ?, ?, ?, \n"; sql += " ?, ?, ?, ?, \n"; sql += " ? \n"; sql += " ) \n"; } } // System.out.println("sql == = >> >> " +sql); try { pstmt = connMgr.prepareStatement(sql); } catch ( Exception ex ) { throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { } return pstmt; } /** 교육결과등록처리 @param pstmt_update_student PreparedStatement @param data 결과데이터 @param p_luserid 등록자아이디 @return int 정상실행여부 */ public int update_subj_score(PreparedStatement pstmt_update_student, CPStoldData data, String p_luserid) throws Exception { ResultSet rs = null; int isOk = 0; int v_count = 0; try { // 1.tz_student update pstmt_update_student.setDouble( 1, data.getScore() ); pstmt_update_student.setDouble( 2, data.getTstep() ); pstmt_update_student.setDouble( 3, data.getMtest() ); pstmt_update_student.setDouble( 4, data.getFtest() ); pstmt_update_student.setDouble( 5, data.getHtest() ); pstmt_update_student.setDouble( 6, data.getReport() ); pstmt_update_student.setDouble( 7, data.getAct() ); pstmt_update_student.setDouble( 8, data.getEtc1() ); pstmt_update_student.setDouble( 9, data.getEtc2() ); pstmt_update_student.setDouble(10, data.getAvtstep() ); pstmt_update_student.setDouble(11, data.getAvmtest() ); pstmt_update_student.setDouble(12, data.getAvftest() ); pstmt_update_student.setDouble(13, data.getAvreport() ); pstmt_update_student.setDouble(14, data.getAvact() ); pstmt_update_student.setDouble(15, data.getAvetc1() ); pstmt_update_student.setDouble(16, data.getAvetc2() ); pstmt_update_student.setString(17, data.getIsgraduated() ); pstmt_update_student.setString(18, data.getNotgraduetc() ); pstmt_update_student.setString(19, p_luserid); pstmt_update_student.setString(20, FormatDate.getDate("yyyyMMddHHmmss") ); pstmt_update_student.setString(21, data.getRank() ); pstmt_update_student.setString(22, data.getSubj() ); pstmt_update_student.setString(23, data.getYear() ); pstmt_update_student.setString(24, data.getSubjseq() ); pstmt_update_student.setString(25, data.getUserid() ); // System.out.println("1 == >> " +data.getScore() ); // System.out.println("2 == >> " +data.getTstep() ); // System.out.println("3 == >> " +data.getMtest() ); // System.out.println("4 == >> " +data.getFtest() ); // System.out.println("5 == >> " +data.getHtest() ); // System.out.println("6 == >> " +data.getReport() ); // System.out.println("7 == >> " +data.getAct() ); // System.out.println("8 == >> " +data.getEtc1() ); // System.out.println("9 == >> " +data.getEtc2() ); // System.out.println("0 == >> " +data.getAvtstep() ); // System.out.println("1 == >> " +data.getAvmtest() ); // System.out.println("2 == >> " +data.getAvftest() ); // System.out.println("3 == >> " +data.getAvreport() ); // System.out.println("4 == >> " +data.getAvact() ); // System.out.println("5 == >> " +dataAvetc1() ); // System.out.println("6 == >> " +data.getAvetc2() ); // System.out.println("7 == >> " +data.getIsgraduated() ); // System.out.println("8 == >> " +data.getNotgraduetc() ); // System.out.println("9 == >> " +p_luserid); // System.out.println("0 == >> " +FormatDate.getDate("yyyyMMddHHmmss") ); // System.out.println("1 == >> " +data.getRank() ); // System.out.println("2 == >> " +data.getSubj() ); // System.out.println("3 == >> " +data.getYear() ); // System.out.println("4 == >> " +data.getSubjseq() ); // System.out.println("5 == >> " +data.getUserid() ); isOk = pstmt_update_student.executeUpdate(); } catch ( Exception ex ) { throw new Exception(ex.getMessage() ); } finally { if ( rs != null ) { try { rs.close(); } catch ( Exception e ) { } } } return isOk; } /** 교육현황등록처리 @param pstmt_update_student PreparedStatement @param data 결과데이터 @param p_luserid 등록자아이디 @return int 정상실행여부 */ public int update_subjstatus_score(PreparedStatement pstmt_update_student, CPStoldData data, String p_luserid) throws Exception { ResultSet rs = null; int isOk = 0; int v_count = 0; try { // 1.tz_student update pstmt_update_student.setDouble( 1, data.getScore() ); pstmt_update_student.setDouble( 2, data.getTstep() ); pstmt_update_student.setDouble( 3, data.getMtest() ); pstmt_update_student.setDouble( 4, data.getFtest() ); pstmt_update_student.setDouble( 5, data.getHtest() ); pstmt_update_student.setDouble( 6, data.getReport() ); pstmt_update_student.setDouble( 7, data.getAct() ); pstmt_update_student.setDouble( 8, data.getEtc1() ); pstmt_update_student.setDouble( 9, data.getEtc2() ); pstmt_update_student.setDouble(10, data.getAvtstep() ); pstmt_update_student.setDouble(11, data.getAvmtest() ); pstmt_update_student.setDouble(12, data.getAvftest() ); pstmt_update_student.setDouble(13, data.getAvreport() ); pstmt_update_student.setDouble(14, data.getAvact() ); pstmt_update_student.setDouble(15, data.getAvetc1() ); pstmt_update_student.setDouble(16, data.getAvetc2() ); pstmt_update_student.setString(17, p_luserid); pstmt_update_student.setString(18, FormatDate.getDate("yyyyMMddHHmmss") ); pstmt_update_student.setString(19, data.getSubj() ); pstmt_update_student.setString(20, data.getYear() ); pstmt_update_student.setString(21, data.getSubjseq() ); pstmt_update_student.setString(22, data.getUserid() ); isOk = pstmt_update_student.executeUpdate(); } catch ( Exception ex ) { throw new Exception(ex.getMessage() ); } finally { if ( rs != null ) { try { rs.close(); } catch ( Exception e ) { } } } return isOk; } /** 상담내역등록 @param pstmt_update_student PreparedStatement @param data 결과데이터 @param p_luserid 등록자아이디 @return int 정상실행여부 */ public int insert_sangdam(DBConnectionManager connMgr, PreparedStatement pstmt_insert_sangdam, CPStoldData data, String p_luserid, String p_sangdamtxt) throws Exception { ResultSet rs = null; int isOk = 0; int v_maxno = 0; String sql = ""; String v_luserid = p_luserid; String v_sangdamtxt = p_sangdamtxt; ListSet ls = null; try { sql = "select max(no) +1 mxno from tz_sangdam"; ls = connMgr.executeQuery(sql); if ( ls.next() ) { v_maxno = ls.getInt("mxno"); } else { v_maxno = 1; } /* sql += " NO, USERID, CUSERID, CTEXT, \n"; sql += " STATUS, SDATE, LDATE, MCODE, \n"; sql += " SCODE, ETIME, TITLE, FTEXT, \n"; sql += " RSEQ, SUBJ, YEAR, SUBJSEQ, \n"; sql += " GUBUN \n"; */ // 1.tz_sangdam insert pstmt_insert_sangdam.setInt(1, v_maxno); pstmt_insert_sangdam.setString(2, data.getUserid() ); pstmt_insert_sangdam.setString(3, v_luserid); pstmt_insert_sangdam.setString(4, v_sangdamtxt); pstmt_insert_sangdam.setString(5, "3"); pstmt_insert_sangdam.setString(6, FormatDate.getDate("yyyyMMddHH") ); pstmt_insert_sangdam.setString(7, FormatDate.getDate("yyyyMMddHHmmss") ); pstmt_insert_sangdam.setString(8, "6"); pstmt_insert_sangdam.setString(9, ""); pstmt_insert_sangdam.setString(10, "0"); pstmt_insert_sangdam.setString(11, v_sangdamtxt); pstmt_insert_sangdam.setString(12, v_sangdamtxt); pstmt_insert_sangdam.setInt(13, 0); pstmt_insert_sangdam.setString(14, data.getSubj() ); pstmt_insert_sangdam.setString(15, data.getYear() ); pstmt_insert_sangdam.setString(16, data.getSubjseq() ); pstmt_insert_sangdam.setString(17, "out"); isOk = pstmt_insert_sangdam.executeUpdate(); } catch ( Exception ex ) { throw new Exception(ex.getMessage() ); } finally { if ( rs != null ) { try { rs.close(); } catch ( Exception e ) { } } if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } } return isOk; } /** 가중치 적용 score 계산 @param connMgr DB연결개체 @param data 결과데이터 @return int 정상실행여부 */ public int calc_subj_score(DBConnectionManager connMgr, CPStoldData data) throws Exception { int isOk = 1; try { data.setAvtstep((double)Math.round(data.getTstep()*data.getWstep() )/100); data.setAvreport((double)Math.round(data.getReport()*data.getWreport() )/100); data.setAvmtest((double)Math.round(data.getMtest()*data.getWmtest() )/100); data.setAvftest((double)Math.round(data.getFtest()*data.getWftest() )/100); data.setAvhtest((double)Math.round(data.getHtest()*data.getWhtest() )/100); data.setAvact ((double)Math.round(data.getAct()*data.getWact() )/100); data.setAvetc1((double)Math.round(data.getEtc1()*data.getWetc1() )/100); data.setAvetc2((double)Math.round(data.getEtc2()*data.getWetc2() )/100); System.out.println(" data.getAvtstep : " + data.getAvtstep() ); System.out.println(" data.getAvreport : " + data.getAvreport() ); System.out.println(" data.getAvmtest : " + data.getAvmtest() ); System.out.println(" data.getAvftest : " + data.getAvftest() ); System.out.println(" data.getAvact : " + data.getAvact() ); System.out.println(" data.getAvetc1 : " + data.getAvetc1() ); System.out.println(" data.getAvetc2 : " + data.getAvetc2() ); /*-------- Calc Final Grade ----------------------------------------------------*/ data.setScore(data.getAvtstep() + data.getAvmtest() + data.getAvftest() + data.getAvhtest() + data.getAvreport() + data.getAvact() + data.getAvetc1() + data.getAvetc2() ); } catch ( Exception ex ) { throw new Exception(ex.getMessage() ); } finally { } return isOk; } }
import java.util.ArrayList; import java.util.LinkedList; import java.util.TreeSet; /******************************************************* * Jonah Bukowsky * * class to mimic kernel managing virtual and physical frames *******************************************************/ public class Kernel { /* ram size */ private int RAM; /* page/frame size */ private int PAGE_SIZE; /* linked list of processes running */ private LinkedList<PCBEntry> pcb; /* tree set of free frame indexes */ private TreeSet<Integer> freeFrames; /* index of frame with value of PID it is used by */ private FrameTableEntry[] frameTable; /* list of instructions for kernel to perform */ private ArrayList<String> instructions; /* history objects to store information needed to undo */ private ArrayList<HistoryStructure> historyStructures; /* output of kernel describing what is happening */ private ArrayList<String> logStrings; /* current index in array of instructions */ private int instructionIndex; /******************************************************* * initializes instance variables not affected by constructor *******************************************************/ { instructionIndex = 0; pcb = new LinkedList<>(); freeFrames = new TreeSet<>(); historyStructures = new ArrayList<>(); logStrings = new ArrayList<>(); } /******************************************************* * default constructor * * @param instructions the instruction set for the kernel to perform * @param ramSize desired RAM size * @param pageSize desired PAGE size *******************************************************/ public Kernel(ArrayList<String> instructions, int ramSize, int pageSize) { this.instructions = instructions; this.RAM = ramSize; this.PAGE_SIZE = pageSize; frameTable = new FrameTableEntry[RAM / PAGE_SIZE]; for (int i = 0; i < frameTable.length; i++) { freeFrames.add(i); frameTable[i] = null; } } /******************************************************* * parses and executes next instruction from instruction set *******************************************************/ public void parseNextInstruction() { String instruction = instructions.get(instructionIndex++); if (historyStructures.size() > instructionIndex - 1) { historyStructures.remove(instructionIndex - 1); } historyStructures.add(instructionIndex - 1, new HistoryStructure()); if (!instruction.contains("-1")) { int pID = Integer.parseInt(instruction.substring(0, instruction.indexOf(" "))); instruction = instruction.substring(instruction.indexOf(" ") + 1); int codeSize = Integer.parseInt(instruction.substring(0, instruction.indexOf(" "))); instruction = instruction.substring(instruction.indexOf(" ") + 1); int dataSize = Integer.parseInt(instruction); this.loadProcess(pID, codeSize, dataSize); } else { int pID = Integer.parseInt(instruction.substring(0, instruction.indexOf(" "))); logStrings.add("Freeing process " + pID); this.freeProcess(pID); logStrings.add("Process " + pID + " freed"); } } /******************************************************* * undoes last instruction from instruction set *******************************************************/ public void undoLastInstruction() { logStrings.add("Undoing last instruction"); String instruction = instructions.get(--instructionIndex); if (!instruction.contains("-1")) { int pID = Integer.parseInt(instruction.substring(0, instruction.indexOf(" "))); freeProcess(pID); } else { int pID = Integer.parseInt(instruction.substring(0, instruction.indexOf(" "))); String loadInstruction; int localIndex = instructionIndex - 1; while (true) { loadInstruction = instructions.get(localIndex--); if (pID == Integer.parseInt(loadInstruction.substring(0, loadInstruction.indexOf(" ")))) { break; } } this.loadProcess(pID, historyStructures.get(localIndex + 1).getCodeFrames(), historyStructures.get(localIndex + 1).getDataFrames()); } logStrings.add("Undo complete"); } /******************************************************* * performs necessary operations to load process into RAM * * @param pID process ID * @param codeSize size of code section * @param dataSize size of data section *******************************************************/ private void loadProcess(int pID, int codeSize, int dataSize) { int codePages = (codeSize + PAGE_SIZE - 1) / PAGE_SIZE; int dataPages = (dataSize + PAGE_SIZE - 1) / PAGE_SIZE; PCBEntry pcbEntry = new PCBEntry(pID); logStrings.add("Loading program " + pID + " into RAM: code=" + codeSize + " (" + codePages + " pages), data=" + dataSize + " (" + dataPages + " pages)"); this.assignPages(pcbEntry, codePages, dataPages); pcb.add(pcbEntry); logStrings.add("Program " + pID + " loaded"); } /******************************************************* * special version of loadProcess for undo to properly work * * @param pID process ID * @param codeFrames previous frames code section was allocated in * @param dataFrames previous frames data section was allocated in *******************************************************/ private void loadProcess(int pID, ArrayList<Integer> codeFrames, ArrayList<Integer> dataFrames) { PCBEntry pcbEntry = new PCBEntry(pID); for (int i = 0; i < codeFrames.size(); i++) { freeFrames.remove(codeFrames.get(i)); frameTable[codeFrames.get(i)] = new FrameTableEntry(pID, i, FrameTableEntry.FRAME_TYPE.CODE); } for (int i = 0; i < dataFrames.size(); i++) { freeFrames.remove(dataFrames.get(i)); frameTable[dataFrames.get(i)] = new FrameTableEntry(pID, i, FrameTableEntry.FRAME_TYPE.DATA); } pcbEntry.addCodePages(codeFrames.size()); pcbEntry.addDataPages(dataFrames.size()); pcb.add(pcbEntry); } /******************************************************* * frees specified process from RAM * * @param pID process ID *******************************************************/ private void freeProcess(int pID) { for (PCBEntry pcbEntry : pcb) { if (pcbEntry.getpID() == pID) { pcb.remove(pcbEntry); break; } } for (int i = 0; i < frameTable.length; i++) { if (frameTable[i] != null && frameTable[i].getpID() == pID) { frameTable[i] = null; freeFrames.add(i); } } } /******************************************************* * assigns code and data pages to physical frames in RAM * * @param p PCB entry for process * @param codePages number of code pages needed * @param dataPages number od data pages needed *******************************************************/ private void assignPages(PCBEntry p, int codePages, int dataPages) { for (int i = 0; i < codePages; i++) { int nextFreeFrame = freeFrames.first(); freeFrames.remove(nextFreeFrame); frameTable[nextFreeFrame] = new FrameTableEntry(p.getpID(), i, FrameTableEntry.FRAME_TYPE.CODE); historyStructures.get(instructionIndex - 1).addCodeFrame(nextFreeFrame); logStrings.add("\tProcess " + p.getpID() + ":\t loaded code page " + i + " to frame " + nextFreeFrame); } for (int i = 0; i < dataPages; i++) { int nextFreeFrame = freeFrames.first(); freeFrames.remove(nextFreeFrame); frameTable[nextFreeFrame] = new FrameTableEntry(p.getpID(), i, FrameTableEntry.FRAME_TYPE.DATA); historyStructures.get(instructionIndex - 1).addDataFrame(nextFreeFrame); logStrings.add("\tProcess " + p.getpID() + ":\t loaded data page " + i + " to frame " + nextFreeFrame); } p.addCodePages(codePages); p.addDataPages(dataPages); } /******************************************************* * returns current status of each frame in physical memory * * @return ArrayList<String> status of each frame *******************************************************/ public ArrayList<String> getNewTexts() { ArrayList<String> newTexts = new ArrayList<>(); for (FrameTableEntry frameTableEntry : frameTable) { if (frameTableEntry == null) { newTexts.add("Free"); } else { newTexts.add("Process " + frameTableEntry.getpID() + " -> " + (frameTableEntry.getFrameType() == FrameTableEntry.FRAME_TYPE.CODE ? "C" : "D") + frameTableEntry.getPageMapping()); } } return newTexts; } /******************************************************* * returns whether all instructions have been executed * * @return boolean true if done, false if not *******************************************************/ public boolean getDone() { return (instructionIndex >= instructions.size()); } /******************************************************* * returns whether the current instruction is the first * * @return boolean true if first instruction, false if not *******************************************************/ public boolean getFirst() { return (instructionIndex <= 0); } /******************************************************* * returns number of frames in physical memory * * @return int number of frames in physical memory *******************************************************/ public int getNumFrames() { return RAM / PAGE_SIZE; } /******************************************************* * returns PCB * * @return LinkedList<PCBEntry> the PCB *******************************************************/ public LinkedList<PCBEntry> getPcb() { return pcb; } /******************************************************* * returns the log strings of the kernel * * @return ArrayList<String> log strings of the kernel *******************************************************/ public ArrayList<String> getLogStrings() { return logStrings; } }
package com.epam.training.klimov.rentalservice.exceptions; /** * Created by Администратор on 10.05.2017. */ public class UnknownCommandException extends Exception { }
package com.trump.auction.back.activity.model; import com.cf.common.utils.DateUtil; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.Date; /** * @description: 分享活动扩展类 * @author: zhangqingqiang * @date: 2018-03-21 21:06 **/ @Data @ToString @JsonInclude(JsonInclude.Include.NON_NULL) public class ActivityExt extends ActivityShare implements Serializable{ private String startDate; private String endDate; private String entrance; public Date getStartDateYmd() { if (StringUtils.isEmpty(startDate)){ return null; } return DateUtil.getDate(startDate,"yyyy-MM-dd HH:mm:ss"); } public Date getEndDateYmd() { if (StringUtils.isEmpty(endDate)){ return null; } return DateUtil.getDate(endDate,"yyyy-MM-dd HH:mm:ss"); } }
package com.core.velocity; import com.core.support.BaseActionSupport; import com.util.HttpClientUtil; import com.util.JsonUtil; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import java.io.*; import java.util.Properties; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 17-3-30 * Time: 下午12:33 * To change this template use File | Settings | File Templates. */ @SuppressWarnings("ALL") public class velocityVm extends BaseActionSupport { /** * 生成velocity模板 * @param dkServiceUrl * @param name * @param pindex * @param currentPage 当前页 * @param maxPage 最大页面,总记录数 total */ public void velocityJsp(String dkServiceUrl,int currentPage,String maxPage,String vmName,String jsonArrayName) { Properties p = new Properties(); p.setProperty("file.resource.loader.class", ClasspathResourceLoader.class.getName()); // 设置编码 p.setProperty(Velocity.INPUT_ENCODING, "UTF-8"); p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8"); // VelocityEngine 是单例模式 VelocityEngine velocityEngine = new VelocityEngine(p); velocityEngine.init(); Template template = velocityEngine.getTemplate(vmName+".vm"); VelocityContext ctx = new VelocityContext(); //获取所以数据 ctx = getAllCtxData(ctx, dkServiceUrl,currentPage,maxPage,vmName,jsonArrayName); //生成模板 String path= Thread.currentThread().getContextClassLoader().getResource("").getPath().replace("/WEB-INF/classes", "") + "/static/" + vmName + ".html"; BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8")); template.merge(ctx, bw); bw.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } //返回VelocityContext对象 public VelocityContext getAllCtxData(VelocityContext ctx,String dkServiceUrl,int currentPage,String maxPage,String vmName,String jsonArrayName) { JSONArray jsonArray = getAllData(ctx, dkServiceUrl, currentPage, maxPage, vmName); if (jsonArray != null) { ctx.put(jsonArrayName,jsonArray); } return ctx; } //获取数据 public JSONArray getAllData(VelocityContext ctx,String dkServiceUrl,int currentPage,String maxPage,String vmName) { String jsonStr = HttpClientUtil.getHttpclient(dkServiceUrl); JSONArray arr = new JSONArray(); try { if (jsonStr != null) { JSONObject jsonObject = JSONObject.fromObject(jsonStr); String responseStr = jsonObject.getString("response"); JSONObject responseJsonObject = JSONObject.fromObject(responseStr); maxPage = responseJsonObject.get("ptotal").toString(); ctx.put("maxPage",maxPage); ctx.put("vmName", vmName); if (responseJsonObject != null) { boolean isDataReturn = responseJsonObject.containsKey("data"); String dataStr = ""; boolean isError = false; if (isDataReturn) { dataStr = responseJsonObject.getString("data"); arr = JsonUtil.strToArr(jsonStr); } else { isError = responseJsonObject.containsKey("error"); } if (!isError && isDataReturn) { totalRows = Integer.valueOf(responseJsonObject.getString("total")); totalPage = Integer.valueOf(responseJsonObject.getString("ptotal")); maxPage=responseJsonObject.getString("ptotal"); super.setTotalPage(totalPage); ctx.put("totalRows", totalRows); ctx.put("totalPage", totalPage); ctx.put("currentPage", currentPage); ctx.put("maxpage",maxPage); } } } } catch (Exception e) { e.printStackTrace(); } return arr; } }
package test; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Scanner; public class Graph { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); Integer input = scan.nextInt(); while (input != null) { Integer n = input; Integer m = scan.nextInt(); // Integer[][] graph = new Integer[n][n]; HashMap<Integer, HashMap<Integer, Boolean>> graph = new HashMap<Integer, HashMap<Integer, Boolean>>(); for (int i = 0; i < m; i++) { Integer node_1 = scan.nextInt(); Integer node_2 = scan.nextInt(); HashMap<Integer, Boolean> nodeMap; if (graph.containsKey(node_1)) { nodeMap = graph.get(node_1); } else { nodeMap = new HashMap<Integer, Boolean>(); } nodeMap.put(node_2, true); graph.put(node_1, nodeMap); if (graph.containsKey(node_2)) { nodeMap = graph.get(node_2); } else { nodeMap = new HashMap<Integer, Boolean>(); } nodeMap.put(node_1, true); graph.put(node_2, nodeMap); // graph[node_1][node_2] = 1; // graph[node_1][node_1] = 1; } Iterator<HashMap.Entry<Integer, HashMap<Integer, Boolean>>> entries = graph.entrySet().iterator(); boolean flag = true; while (entries.hasNext()) { HashMap.Entry<Integer, HashMap<Integer, Boolean>> entry = entries.next(); Integer node = entry.getKey(); List<Integer> toProcess = new ArrayList<Integer>(); HashMap<Integer, Boolean> processed = new HashMap<Integer, Boolean>(); toProcess.add(node); while (toProcess.size() > 0) { Integer currentNode = toProcess.remove(0); HashMap<Integer, Boolean> ajaNodes = graph.get(currentNode); processed.put(currentNode, true); for (Integer node_2 : ajaNodes.keySet()) { if (processed.containsKey(node_2)) { continue; } if(toProcess.contains(node_2)) { continue; } toProcess.add(node_2); } graph.get(node).put(currentNode, true); } if (graph.get(node).keySet().size() < n) { // System.out.println(graph.get(node).keySet().size()); System.out.println("NO"); flag=false; break; } } if(flag==true) { System.out.println("YES"); } if (!scan.hasNext()) { break; }else { input = scan.nextInt(); } } } }
package algo3.fiuba.modelo.cartas; import algo3.fiuba.modelo.cartas.efectos.EfectoCarta; import algo3.fiuba.modelo.cartas.estados_cartas.EnJuego; import algo3.fiuba.modelo.excepciones.SacrificiosIncorrectosExcepcion; import algo3.fiuba.modelo.jugador.Jugador; import java.util.List; public abstract class Magica extends NoMonstruo { public Magica(String nombre, EfectoCarta efecto) { super(nombre, efecto); } @Override public boolean activarTrampa() { return false; } @Override public boolean negarAtaque() { return false; } @Override public void colocarEnCampo(Jugador jugador, EnJuego tipoEnJuego, Monstruo... sacrificios) { if (sacrificios.length != 0) throw new SacrificiosIncorrectosExcepcion("No se pueden hacer sacrificios para invocar esta carta."); super.colocarEnCampo(jugador, tipoEnJuego, sacrificios); jugador.colocarCartaEnCampo(this, tipoEnJuego, sacrificios); } @Override public List<AccionCarta> accionesDisponibles() { return estadoEnTurno.accionesCartaDisponibles(this, estadoCarta); } }
package service; import db.BreakdownDAO; import db.TemplateDAO; import model.Breakdown; import model.GradingRule; import model.Template; import utils.ErrCode; import java.util.*; /** *@author Qi Yin */ public class TemplateService { //template name, template private static Map<String, Template> templateMap; private static TemplateService instance = new TemplateService(); private TemplateService() { templateMap = new HashMap<>(); } public static TemplateService getInstance() { // if (instance == null) { // instance = new TemplateService(); // } return instance; } public Map<String, Template> getTemplateMap() { templateMap = TemplateDAO.getInstance().getTemplateMap(); return templateMap; } public Map<String,String> getAllTemplateName() { // return name for every saved template, format: Map<breakdownID, templateName> Map<String, String> result = new HashMap<>(); for(Map.Entry<String, Template> m : templateMap.entrySet()) { result.put(m.getValue().getBreakdownID(), m.getValue().getName()); } return result; } public Template getTemplateById(String templateId) { return TemplateDAO.getInstance().getTemplate(templateId); } public void generateGradingRuleID(GradingRule gradingRule, String parentId){ gradingRule.setId(UUID.randomUUID().toString()); gradingRule.setParentID(parentId); if(gradingRule.getChildren() != null && gradingRule.getChildren().size() != 0) { for(GradingRule g : gradingRule.getChildren()) { generateGradingRuleID(g, gradingRule.getId()); } } } //save a template from a existing breakdown public int saveTemplate(String courseId, String templateName) { Breakdown breakdown = BreakdownDAO.getInstance().getBreakdown(courseId); Map<String, GradingRule> gradingRuleMap = breakdown.getGradingRules(); Map<String, GradingRule> newGradingRuleMap = new HashMap<>(); for(GradingRule gradingRule : gradingRuleMap.values()) { generateGradingRuleID(gradingRule, ""); newGradingRuleMap.put(gradingRule.getId(), gradingRule); } breakdown.setGradingRules(newGradingRuleMap); Template template = new Template(UUID.randomUUID().toString(), templateName, breakdown.getGradingRules(), breakdown.getLetterRule()); return TemplateDAO.getInstance().updateTemplate(template); } }
/** * Copyright (C) Alibaba Cloud Computing, 2012 * All rights reserved. * * 版权所有 (C)阿里巴巴云计算,2012 */ package com.aliyun.oss.model; import static com.aliyun.oss.common.utils.CodingUtils.assertParameterNotNull; import static com.aliyun.oss.internal.OSSUtils.OSS_RESOURCE_MANAGER; import static com.aliyun.oss.internal.OSSUtils.ensureBucketNameValid; import static com.aliyun.oss.internal.OSSUtils.ensureObjectKeyValid; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * 指定从OSS下载Object的请求参数。 */ public class GetObjectRequest extends WebServiceRequest { // Object所在的Bucket的名称 private String bucketName; // Object Key private String key; // 指定返回Object内容的字节范围。 private long[] range; // CONSIDER use List<String> or just a String? private List<String> matchingETagConstraints = new ArrayList<String>(); private List<String> nonmatchingEtagConstraints = new ArrayList<String>(); private Date unmodifiedSinceConstraint; private Date modifiedSinceConstraint; private ResponseHeaderOverrides responseHeaders; /** * Fields releated with getobject operation by using url signature. */ private URL absoluteUrl; private boolean useUrlSignature = false; /** * 构造函数。 * @param bucketName * Bucket名称。 * @param key * Object Key。 */ public GetObjectRequest(String bucketName, String key) { setBucketName(bucketName); setKey(key); } /** * 使用URL签名及用户自定义头作为参数的构造函数。 * @param absoluteUri URL签名 */ public GetObjectRequest(URL absoluteUrl, Map<String, String> customHeaders) { this.absoluteUrl = absoluteUrl; this.useUrlSignature = true; this.getHeaders().putAll(customHeaders); } /** * 返回Bucket名称。 * @return Bucket名称。 */ public String getBucketName() { return bucketName; } /** * 设置Bucket名称。 * @param bucketName */ public void setBucketName(String bucketName) { assertParameterNotNull(bucketName, "bucketName"); ensureBucketNameValid(bucketName); this.bucketName = bucketName; } /** * 返回Object Key。 * @return Object Key。 */ public String getKey() { return key; } /** * 设置Object Key。 * @param key * Object Key。 */ public void setKey(String key) { assertParameterNotNull(key, "key"); ensureObjectKeyValid(key); this.key = key; } /** * 返回一个值表示请求应当返回Object内容的字节范围。 * @return 一个值表示请求应当返回Object内容的字节范围。 */ public long[] getRange() { return range; } /** * 设置一个值表示请求应当返回Object内容的字节范围(可选)。 * @param start * <p>范围的起始值。</p> * <p>当值大于或等于0时,表示起始的字节位置。 * 当值为-1时,表示不设置起始的字节位置,此时end参数不能-1, * 例如end为100,Range请求头的值为bytes=-100,表示获取最后100个字节。 * </p> * @param end * <p>范围的结束值。</p> * <p>当值小于或等于0时,表示结束的字节位或最后的字节数。 * 当值为-1时,表示不设置结束的字节位置,此时start参数不能为-1, * 例如start为99,Range请求头的值为bytes=99-,表示获取第100个字节及 * 以后的所有内容。 * </p> */ public void setRange(long start, long end) { if (start < 0 && end < 0) { throw new IllegalArgumentException( OSS_RESOURCE_MANAGER.getString("InvalidRangeValues")); } range = new long[] {start, end}; } /** * 返回“If-Match”参数,表示:如果传入期望的 ETag 和 object 的 ETag 匹配,正常的发送文件。 * 如果不符合,返回错误。 * @return 表示期望object的ETag与之匹配的ETag列表。 */ public List<String> getMatchingETagConstraints() { return matchingETagConstraints; } /** * 返回“If-Match”参数(可选)。 * 表示如果传入期望的 ETag 和 Object 的 ETag 匹配,则正常的发送文件。 * 如果不符合,则返回错误。 * @param eTagList * 表示期望object的ETag与之匹配的ETag列表。 * 目前OSS支持传入一个ETag,如果传入多于一个ETag,将只有列表中的第一个有效。 */ public void setMatchingETagConstraints(List<String> eTagList) { this.matchingETagConstraints = eTagList; } /** * 返回“If-None-Match”参数,可以用来检查文件是否有更新。 * 如果传入的 ETag值和Object的ETag 相同,返回错误;否则正常传输文件。 * @return 表示期望Object的ETag与之不匹配的ETag列表。 */ public List<String> getNonmatchingETagConstraints() { return nonmatchingEtagConstraints; } /** * 返回“If-None-Match”参数,可以用来检查文件是否有更新(可选)。 * 如果传入的 ETag值和Object的ETag 相同,返回错误;否则正常传输文件。 * @param eTagList * 表示期望Object的ETag与之不匹配的ETag列表。 * 目前OSS支持传入一个ETag,如果传入多于一个ETag,将只有列表中的第一个有效。 */ public void setNonmatchingETagConstraints(List<String> eTagList) { this.nonmatchingEtagConstraints = eTagList; } /** * 返回“If-Unmodified-Since”参数。 * 表示:如果传入参数中的时间等于或者晚于文件实际修改时间,则传送文件; * 如果早于实际修改时间,则返回错误。 * @return “If-Unmodified-Since”参数。 */ public Date getUnmodifiedSinceConstraint() { return unmodifiedSinceConstraint; } /** * 设置“If-Unmodified-Since”参数(可选)。 * 表示:如果传入参数中的时间等于或者晚于文件实际修改时间,则传送文件; * 如果早于实际修改时间,则返回错误。 * @param date * “If-Unmodified-Since”参数。 */ public void setUnmodifiedSinceConstraint(Date date) { this.unmodifiedSinceConstraint = date; } /** * 返回“If-Modified-Since”参数。 * 表示:如果指定的时间早于实际修改时间,则正常传送文件,并返回 200 OK; * 如果参数中的时间和实际修改时间一样或者更晚,会返回错误。 * @return “If-Modified-Since”参数。 */ public Date getModifiedSinceConstraint() { return modifiedSinceConstraint; } /** * 设置“If-Modified-Since”参数(可选)。 * 表示:如果指定的时间早于实际修改时间,则正常传送文件,并返回 200 OK; * 如果参数中的时间和实际修改时间一样或者更晚,会返回错误。 * @param date * “If-Modified-Since”参数。 */ public void setModifiedSinceConstraint(Date date) { this.modifiedSinceConstraint = date; } /** * 返回要重载的返回请求头。 * @return 要重载的返回请求头。 */ public ResponseHeaderOverrides getResponseHeaders() { return responseHeaders; } /** * 设置要重载的返回请求头(可选)。 * @param responseHeaders * 要重载的返回请求头。 */ public void setResponseHeaders(ResponseHeaderOverrides responseHeaders) { this.responseHeaders = responseHeaders; } public URL getAbsoluteUri() { return absoluteUrl; } public void setAbsoluteUri(URL absoluteUri) { this.absoluteUrl = absoluteUri; } public boolean isUseUrlSignature() { return useUrlSignature; } public void setUseUrlSignature(boolean useUrlSignature) { this.useUrlSignature = useUrlSignature; } }
/* * 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 DayAheadInterface; import jade.core.Agent; import personalassistant.MarketParticipants; import personalassistant.PersonalAssistant; import personalassistant.PersonalAssistantGUI; import wholesalemarket_LMP.Pricing_Mechanism_Form; import wholesalemarket_LMP.Wholesale_InputData; import wholesalemarket_SMP.SMP_Market_Controller; /** * * @author Filipe */ public class Dayaheadinterface extends Agent{ /** * */ private static final long serialVersionUID = 1L; private MarketParticipants participants; private String[][] producerOffers = new String[23][2]; private String[][] buyerOffers = new String[23][2]; //private PersonalAssistant mo_pa; /* * Pricing Mechanism GUI variables */ private PersonalAssistantGUI mo_gui; private Wholesale_InputData lmpMode; private SMP_Market_Controller smpMode; @Override protected void setup(){ } public Dayaheadinterface(){ } /* * Pricing Mechanism GUI constructor */ public Dayaheadinterface(PersonalAssistantGUI _market, Wholesale_InputData _lmpMode, SMP_Market_Controller _smpMode){ mo_gui = _market; lmpMode = _lmpMode; smpMode = _smpMode; } public void pricingMechanismForm(String mode){ Pricing_Mechanism_Form priceMechanism = new Pricing_Mechanism_Form(mo_gui, lmpMode, smpMode); priceMechanism.setVisible(true); switch(mode){ case "DayAheadMarket": priceMechanism.editWindow_options(true); break; case "IntraDayMarket": priceMechanism.editWindow_options(false); break; default: break; } } /* * Call GenCo Data GUI */ public void chooseParticipants(PersonalAssistant market, boolean isProducer, boolean isDayAhead, boolean isSMP, boolean isOTC){ participants = new MarketParticipants(market, isProducer, isDayAhead, isSMP, isOTC); participants.setVisible(true); } /* * Method to store producer offer values */ public void storeProducerOffers( String[][] _producerOffer ){ this.producerOffers = _producerOffer; } /* * Method to store buyer offer values */ public void storeBuyerOffers( String[][] _buyerOffer ){ this.buyerOffers = _buyerOffer; } /* * Send producer offer values */ public String[][] sendProducerOffer(){ return this.producerOffers; } /* * Send buyer offer values */ public String[][] sendBuyerOffer(){ return this.buyerOffers; } }
package com.rohraff.netpccontactapp.mapper; import com.rohraff.netpccontactapp.model.Category; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper public interface CategoryMapper { @Insert("INSERT INTO CATEGORY (name) VALUES(#{name})") @Options(useGeneratedKeys = true, keyProperty = "categoryId") int insertCategory(Category category); @Select("SELECT * FROM CATEGORY") List<Category> getCategories(); }
package br.com.View; import java.awt.EventQueue; import java.util.List; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import br.com.UsuarioController.AlunosController; import br.com.modelo.Alunos; import javax.swing.JLabel; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import java.awt.event.ActionListener; import java.io.IOException; import java.sql.SQLException; import java.awt.event.ActionEvent; import javax.swing.JButton; import javax.swing.JComboBox; import java.awt.Font; import javax.swing.ImageIcon; import java.awt.Color; public class TelaPrincipal extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; private DefaultTableModel modelo; private AlunosController AlunosController; private JTable table_1; private JLabel nomeLabel; private JLabel dataNascimentoLabel; private JLabel cursoLabel; private JLabel situacaoLabel; private JMenuItem adicionarAlunoMenuItem; /** * Launch the application. */ public static void main(String[] args) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { } EventQueue.invokeLater(new Runnable() { public void run() { try { TelaPrincipal frame = new TelaPrincipal(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public TelaPrincipal() { setResizable(false); this.AlunosController = new AlunosController(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 800, 500); // contentPane = new JPanel(); try { // "C:\\Users\\wagne\\Desktop\\Aps interface\\Prancheta 1.png" fundo para teste // "C:\\Users\\wagne\\Desktop\\Aps interface\\FundoTesteAPS.png" Outro fundo para teste contentPane = new FundoBg("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\Fundos de tela\\FundoTesteAPS.png"); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } setContentPane(contentPane); table_1 = new JTable(); table_1.setBounds(10, 218, 764, 169); modelo = (DefaultTableModel) table_1.getModel(); modelo.addColumn("RA"); modelo.addColumn("NOME"); modelo.addColumn("DATA DE NASCIMENTO"); modelo.addColumn("Nome Curso"); modelo.addColumn("Situação"); contentPane.setLayout(null); contentPane.add(table_1); JLabel raLabel = new JLabel("RA"); raLabel.setForeground(Color.BLACK); raLabel.setBounds(10, 204, 46, 14); contentPane.add(raLabel); nomeLabel = new JLabel("Aluno"); nomeLabel.setForeground(Color.BLACK); nomeLabel.setBounds(162, 204, 46, 14); contentPane.add(nomeLabel); dataNascimentoLabel = new JLabel("Data de Nascimento"); dataNascimentoLabel.setForeground(Color.BLACK); dataNascimentoLabel.setBounds(315, 204, 138, 14); contentPane.add(dataNascimentoLabel); cursoLabel = new JLabel("Curso"); cursoLabel.setForeground(Color.BLACK); cursoLabel.setBounds(468, 204, 46, 14); contentPane.add(cursoLabel); situacaoLabel = new JLabel("Situação"); situacaoLabel.setForeground(Color.BLACK); situacaoLabel.setBounds(619, 204, 93, 14); contentPane.add(situacaoLabel); JMenuBar menuBar = new JMenuBar(); menuBar.setBounds(0, 0, 794, 22); contentPane.add(menuBar); JMenu menuAlunos = new JMenu("Alunos"); menuAlunos.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\study.png")); menuBar.add(menuAlunos); // Item do menu Alunos, Adicionar adicionarAlunoMenuItem = new JMenuItem("Adicionar"); adicionarAlunoMenuItem.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\plus.png")); menuAlunos.add(adicionarAlunoMenuItem); // Item do menu Alunos, Remover JMenuItem RemoverAlunoMenu = new JMenuItem("Remover"); RemoverAlunoMenu.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\delete.png")); menuAlunos.add(RemoverAlunoMenu); JMenu mnNewMenu = new JMenu("Usuários"); mnNewMenu.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\user.png")); menuBar.add(mnNewMenu); JMenuItem AdicionarUsuarioMenuItem = new JMenuItem("Adicionar"); AdicionarUsuarioMenuItem .setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\userAdicionar.png")); mnNewMenu.add(AdicionarUsuarioMenuItem); JMenuItem removerUsuarioItem = new JMenuItem("Remover"); removerUsuarioItem .setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\userRemover.png")); mnNewMenu.add(removerUsuarioItem); JMenuItem mntmNewMenuItem = new JMenuItem("Log off"); mntmNewMenuItem.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\Log off.png")); mnNewMenu.add(mntmNewMenuItem); // Botão de atualizar a tabela JButton btnNewButton = new JButton("Atualizar"); btnNewButton.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\botao-atualizar.png")); btnNewButton.setBounds(637, 170, 115, 23); contentPane.add(btnNewButton); // Caixa de cursos JComboBox<String> cursoCombox = new JComboBox<String>(); cursoCombox.setBounds(23, 157, 138, 22); contentPane.add(cursoCombox); cursoCombox.addItem("Curso"); List<String> cursos = this.cursosListar(); for (String string : cursos) { cursoCombox.addItem(string); } // Caixa de Seleção de Situações da matricula JComboBox<String> SituacaoCombox = new JComboBox<String>(); SituacaoCombox.setBounds(184, 157, 138, 22); contentPane.add(SituacaoCombox); SituacaoCombox.addItem("Selecione"); List<String> Situacao = this.SituacaoListar(); for (String string : Situacao) { SituacaoCombox.addItem(string); } // Botão Alterar JButton AlterarBotao = new JButton("Alterar"); AlterarBotao.setBounds(10, 422, 89, 23); contentPane.add(AlterarBotao); JLabel cursosLabel = new JLabel("Cursos"); cursosLabel.setForeground(Color.BLACK); cursosLabel.setFont(new Font("Tahoma", Font.PLAIN, 14)); cursosLabel.setBounds(23, 143, 46, 14); contentPane.add(cursosLabel); JLabel matriculaLabel = new JLabel("Status"); matriculaLabel.setForeground(Color.BLACK); matriculaLabel.setFont(new Font("Tahoma", Font.PLAIN, 14)); matriculaLabel.setBounds(184, 143, 135, 14); contentPane.add(matriculaLabel); // Evento que acontece quando clica no botão Atualizar btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { limparTabela(); preencherTabelaComCurso(); } }); preencherTabelaComCurso(); // Evento que acontece quando clica no item Adicionar do menu alunos adicionarAlunoMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AdicionarAlunoFrame novaView = new AdicionarAlunoFrame(); novaView.setVisible(true); novaView.setLocationRelativeTo(null); } }); // Evento que acontece quando clica no item remover do menu alunos RemoverAlunoMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RemoverAlunoFrame novaView = new RemoverAlunoFrame(); novaView.setVisible(true); novaView.setLocationRelativeTo(null); } }); // Evento que acontece quando clica no item Adicionar do menu Usuarios AdicionarUsuarioMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AdicionarUsuarioFrame novaView = new AdicionarUsuarioFrame(); novaView.setVisible(true); novaView.setLocationRelativeTo(null); } }); // Evento que acontece quando clica no item Remover menu do Usuarios removerUsuarioItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RemoverUsuarioFrame novaView = new RemoverUsuarioFrame(); novaView.setVisible(true); novaView.setLocationRelativeTo(null); } }); // Evento que acontece quando clica no botão alterar AlterarBotao.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (cursoCombox.getSelectedItem().equals("Curso") == true) { JOptionPane.showMessageDialog(null, "Selecione um curso", "Nenhum curso Selecionado", JOptionPane.ERROR_MESSAGE); } else if (SituacaoCombox.getSelectedItem().equals("Selecione") == true) { JOptionPane.showMessageDialog(null, "Selecione um status da matricula", "Nenhum Status da matricula foi selecionado", JOptionPane.ERROR_MESSAGE); } else { try { alterar(converterCursoEmInt(String.valueOf(cursoCombox.getSelectedItem())), converterSituacaoEmInt(String.valueOf(SituacaoCombox.getSelectedItem()))); JOptionPane.showMessageDialog(null, "Alterações aplicadas!", "Alterações feitas", JOptionPane.INFORMATION_MESSAGE); // limparTabela(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); //Evento do botão log off mntmNewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); NovaTelaLogin novaTelaLogin = new NovaTelaLogin(); novaTelaLogin.setVisible(true); } }); } // METODOS DA VIEW public void preencherTabela() { List<Alunos> alunos = ListarAlunos(); try { for (Alunos aluno : alunos) { modelo.addRow(new Object[] { aluno.getRA(), aluno.getNome(), aluno.getDataNascimento() }); } } catch (Exception e) { throw e; } } private void limparTabela() { int UltimaTabela = modelo.getRowCount() - 1; System.out.println(UltimaTabela); modelo.removeRow(UltimaTabela); modelo.getDataVector().clear(); } private void preencherTabelaComCurso() { List<Alunos> alunos = ListarAlunosComCurso(); try { for (Alunos aluno : alunos) { modelo.addRow(new Object[] { aluno.getRA(), aluno.getNome(), aluno.getDataNascimento(), aluno.getCursonome(), aluno.getSituacaoNome() }); } } catch (Exception e) { throw e; } } private List<Alunos> ListarAlunos() { return this.AlunosController.listar(); } private List<Alunos> ListarAlunosComCurso() { return this.AlunosController.listarComCurso(); } private List<String> cursosListar() { return AlunosController.listarCursos(); } private List<String> SituacaoListar() { return AlunosController.listarSituacao(); } public int converterCursoEmInt(String CursoNome) throws SQLException { return this.AlunosController.ConversorCursoNomeId(CursoNome); } public int converterSituacaoEmInt(String Situacaonome) throws SQLException { return this.AlunosController.ConversosSituacaoId(Situacaonome); } private void alterar(int Cursoid, int Situacaoid) { Object objetoDaLinha = (Object) modelo.getValueAt(table_1.getSelectedRow(), table_1.getSelectedColumn()); if (objetoDaLinha instanceof String) { String ra = (String) objetoDaLinha; String nome = (String) modelo.getValueAt(table_1.getSelectedRow(), 1); String data_nascimento = (String) modelo.getValueAt(table_1.getSelectedRow(), 2); this.AlunosController.Alterar(nome, data_nascimento, Cursoid, Situacaoid, ra); } else { JOptionPane.showMessageDialog(this, "Por favor, selecionar o RA"); } } }
package com.animation; import com.animation.parallel.DistortionParallel; import com.animation.sequential.DistortionSequential; import com.components.GeneralFrame; import com.components.ScoreLabel; import com.utils.CornerPosition; import com.utils.ImageHelper; import com.utils.Mode; import com.utils.WaveFunction; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.*; public class WaveAnimation extends Thread { private final GeneralFrame frame; private final JLabel jLabel; private final ImageHelper imageHelper; private final ScoreLabel scoreLabel; private final HashMap<CornerPosition, int[]> cornerPixels; private final Mode mode; public static final AtomicInteger speedValue = new AtomicInteger(); public static final AtomicInteger delayValue = new AtomicInteger(); public static final AtomicInteger distortionRadiusValue = new AtomicInteger(); public static final AtomicInteger distortionRadiusValueSquare = new AtomicInteger(); public static final AtomicBoolean stopAnimationFlag = new AtomicBoolean(true); private boolean isPassFinish = false; public WaveAnimation( GeneralFrame frame, JLabel jLabel, ImageHelper imageHelper, ScoreLabel scoreLabel, Mode mode) { this.frame = frame; this.jLabel = jLabel; this.imageHelper = imageHelper; this.scoreLabel = scoreLabel; this.cornerPixels = new HashMap<>(); this.cornerPixels.put(CornerPosition.TOPLEFT, new int[] {0, 0}); this.cornerPixels.put(CornerPosition.TOPRIGHT, new int[] {imageHelper.getWidth() - 1, 0}); this.cornerPixels.put(CornerPosition.BOTTOMLEFT, new int[] {0, imageHelper.getHeight() - 1}); this.cornerPixels.put( CornerPosition.BOTTOMRIGHT, new int[] {imageHelper.getWidth() - 1, imageHelper.getHeight() - 1}); this.mode = mode; } private HashMap<CornerPosition, int[]> getRandomCornerPixel() { short index = (short) Math.round(Math.random() * 3); CornerPosition key = this.cornerPixels.keySet().toArray(new CornerPosition[0])[index]; int[] value = this.cornerPixels.get(key); HashMap<CornerPosition, int[]> result = new HashMap<>(); result.put(key, value); return result; } private ArrayList<int[]> buildWaveFunctionKeyPoints( int c, double tan, double step, CornerPosition corner) { ArrayList<int[]> points = new ArrayList<>(); for (double x = 0; x < this.imageHelper.getWidth(); x += step) { int yCurrent = WaveFunction.getLinearValue(x, c, tan); int xCurrent = (int) Math.round(x); if (yCurrent < 0 || yCurrent >= this.imageHelper.getHeight() || xCurrent < 0 || xCurrent >= this.imageHelper.getWidth()) continue; this.isPassFinish = false; points.add(new int[] {xCurrent, yCurrent}); } return points; } public void startAnimation() { int c; double angle = 45; CornerPosition corner = CornerPosition.TOPLEFT; int[] currentCornerPixels = this.cornerPixels.get(corner); int[][][] originalImageArray = this.imageHelper.get3dArray(); while (!WaveAnimation.stopAnimationFlag.get()) { this.isPassFinish = false; // Pass loop double angleRadians = Math.toRadians(90 - angle); double tan = Math.tan(angleRadians); int speed = (int) Math.abs(Math.round(tan)); c = (int) (currentCornerPixels[1] + currentCornerPixels[0] * tan); double step = Math.max(0.1, Math.abs(distortionRadiusValue.get() * Math.cos(angleRadians))); step = Math.min(step, distortionRadiusValue.get()); this.scoreLabel.setCorner(corner.getPosition()); this.scoreLabel.setAngle(angle); this.scoreLabel.increaseScore(); while (!this.isPassFinish && !WaveAnimation.stopAnimationFlag.get()) { int[][][] distorImageArray = ImageHelper.copyOfRGBArray( originalImageArray, this.imageHelper.getWidth(), this.imageHelper.getHeight()); isPassFinish = true; ArrayList<int[]> keyPoints = buildWaveFunctionKeyPoints(c, tan, step, corner); if (keyPoints.size() == 0) { continue; } BufferedImage distorImg = null; switch (this.mode) { case SEQUENTIAL: distorImg = DistortionSequential.distorImage( distorImageArray, this.imageHelper.getWidth(), this.imageHelper.getHeight(), keyPoints); break; case PARALLEL: distorImg = DistortionParallel.distorImage( distorImageArray, this.imageHelper.getWidth(), this.imageHelper.getHeight(), keyPoints); break; } this.jLabel.setIcon(new ImageIcon(distorImg)); this.frame.updateCanvas(); double sign = Math.signum(Math.sin(Math.toRadians(angle))); int speedValueLocal = speedValue.get(); c += (sign) * (speedValueLocal + speed) + Math.abs(Math.abs(sign) - 1) * (speedValueLocal + speed); try { Thread.sleep(delayValue.get()); } catch (InterruptedException e) { e.printStackTrace(); } } angle = Math.random() * 360; HashMap<CornerPosition, int[]> randomCorner = getRandomCornerPixel(); corner = randomCorner.keySet().toArray(new CornerPosition[0])[0]; currentCornerPixels = randomCorner.get(corner); } stopAnimation(); } public void stopAnimation() { this.scoreLabel.setCorner(CornerPosition.TOPLEFT.getPosition()); this.scoreLabel.setAngle(45); this.scoreLabel.setScore(0); this.jLabel.setIcon(new ImageIcon(this.imageHelper.getImage())); this.frame.updateCanvas(); } @Override public void run() { startAnimation(); } }
package com.git.cloud.handler.automation.se.common; //AIX-DB-HA默认参数 public enum StorageDBHAEnum { RES_POOL_TYPE,//资源池类型 AVAILABLE_RATE_THRESHOLD,//存储可用率 PLATINUM_SAN_STORAGE_COUNT,//白金SAN选择存储数量 GLOD_SAN_STORAGE_COUNT,//金SAN选择存储数量 SILVER_SAN_STORAGE_COUNT,//银SAN选择存储数量 PLATINUM_HEARTBEAT_COUNT,//白金心跳盘数量 GLOD_HEARTBEAT_COUNT,//金级心跳盘数量 SILVER_HEARTBEAT_COUNT,//银级心跳盘数量 HEARTBEAT_NAME,//心跳盘 HEARTBEAT_CAPACITY,//心跳盘容量大小 DATA_DISK_NAME,//DATA盘名称 DATA_DISK_CAPACITY,//DATA盘容量大小 ARCH_DISK_NAME,//ARCH盘名称 ARCH_DISK_CAPACITY,//ARCH盘容量大小 CELL_CAPACITY//分盘单位大小 }
package com.cuisine.restaurant.controller; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; 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 com.google.gson.Gson; @WebServlet("/restaurant/commemt/statistic") public class commentStatisticController extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://dev.notepubs.com:9898/cuisine?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC"; Connection connection = DriverManager.getConnection(url, "cuisine", "12345"); Statement statement = connection.createStatement(); String sql = "SELECT * FROM commentStatistic"; String restaurantId = request.getParameter("restaurantId"); if (restaurantId != null) sql += " where restaurantId=" + restaurantId; ResultSet resultSet = statement.executeQuery(sql); List<Data> list = new ArrayList<>(); while (resultSet.next()) { Data data = new Data(); data.setRestaurantId(resultSet.getInt(1)); data.setEditorId(resultSet.getInt(2)); data.setEditorName(resultSet.getString(3)); data.setEditorDescription(resultSet.getString(4)); data.setAverageScore(resultSet.getDouble(5)); data.setCommentCount(resultSet.getInt(6)); data.setEditorImage(resultSet.getString(7)); list.add(data); } response.setCharacterEncoding("UTF-8"); response.setContentType("text/; charset=UTF-8"); response.getWriter().write(new Gson().toJson(list)); } catch (SQLException e) { System.out.println("SQLException: " + e); } catch (ClassNotFoundException e) { System.out.println("ClassNotFoundException: " + e); } } public class Data { int restaurantId; int editorId; String editorName; String editorDescription; double averageScore; int commentCount; String editorImage; public int getRestaurantId() { return restaurantId; } public void setRestaurantId(int restaurantId) { this.restaurantId = restaurantId; } public int getEditorId() { return editorId; } public void setEditorId(int editorId) { this.editorId = editorId; } public String getEditorName() { return editorName; } public void setEditorName(String editorName) { this.editorName = editorName; } public String getEditorDescription() { return editorDescription; } public void setEditorDescription(String editorDescription) { this.editorDescription = editorDescription; } public double getAverageScore() { return averageScore; } public void setAverageScore(double averageScore) { this.averageScore = averageScore; } public int getCommentCount() { return commentCount; } public void setCommentCount(int commentCount) { this.commentCount = commentCount; } public String getEditorImage() { return editorImage; } public void setEditorImage(String editorImage) { this.editorImage = editorImage; } } }
package site.lzlz.mainbody.service.wechat.message; import org.junit.Assert; 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.test.context.junit4.SpringRunner; import site.lzlz.mainbody.entity.wechat.TextMessage; import java.util.HashMap; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest public class TextMessageServiceTest { @Autowired TextMessageService textMessageService; @Test public void handlerMessage() { HashMap<String,String> map = new HashMap<>(); map.put("Content","help"); TextMessage message = textMessageService.handlerMessage(map); System.out.println(message.getContent()); Assert.assertNotEquals(message.getContent(),"暂不支持此消息,回复 “help” 或 “帮助” 获取更多信息"); map.put("Content","asdasdadfasdfa"); message = textMessageService.handlerMessage(map); Assert.assertEquals(message.getContent(),"暂不支持此消息,回复 “help” 或 “帮助” 获取更多信息"); } }
package c.bwegener.bookstore; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Spinner; import java.util.ArrayList; import java.util.List; public class CustomerListActivity extends AppCompatActivity { private DBHelper db; private List<Customer> allCustomersList; private List<Customer> filteredCustomersList; private ListView customerListView; private CustomerListAdapter customerListAdapter; private EditText searchCustomersET; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_customer_list); deleteDatabase(DBHelper.DATABASE_NAME); db = new DBHelper(this); db.importCustomersFromCSV("customers.csv"); allCustomersList = db.getAllCustomers(); filteredCustomersList = new ArrayList<>(allCustomersList); customerListView = (ListView) findViewById(R.id.customerListView); customerListAdapter = new CustomerListAdapter(this, R.layout.customer_list_item, filteredCustomersList); customerListView.setAdapter(customerListAdapter); searchCustomersET = (EditText) findViewById(R.id.searchCustomersET); searchCustomersET.addTextChangedListener(searchCustomersTextWatcher); } public void viewCustomerDetails(View v) { if(v instanceof LinearLayout) { LinearLayout selectedLayout = (LinearLayout) v; Customer selectedCustomer = (Customer) selectedLayout.getTag(); Log.i("Antique Bookstore", selectedCustomer.toString()); Intent detailsIntent = new Intent(this, CustomerDetailsActivity.class); detailsIntent.putExtra("SelectedCustomer", selectedCustomer); startActivity(detailsIntent); } } // This only works for titles right now public TextWatcher searchCustomersTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { String entry = charSequence.toString().trim().toUpperCase(); // Clear the list adapter customerListAdapter.clear(); // Loop through the Books for(Customer c : allCustomersList) // if the book title starts with the entry, add it back to the list adapter if(c.getFirstName().toUpperCase().startsWith(entry)) customerListAdapter.add(c); } @Override public void afterTextChanged(Editable editable) { } }; public void handleButtons(View v) { switch(v.getId()) { case R.id.goBackArrow: Intent launchHomeScreen = new Intent(this, HomeScreenActivity.class); startActivity(launchHomeScreen); break; case R.id.addCustomerButton: Intent launchAddCustomer = new Intent(this, AddCustomerActivity.class); startActivity(launchAddCustomer); break; } } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.mock.web; import java.util.concurrent.atomic.AtomicInteger; import jakarta.servlet.http.HttpSessionBindingEvent; import jakarta.servlet.http.HttpSessionBindingListener; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Unit tests for {@link MockHttpSession}. * * @author Sam Brannen * @author Vedran Pavic * @since 3.2 */ class MockHttpSessionTests { private final MockHttpSession session = new MockHttpSession(); @Test void invalidateOnce() { assertThat(session.isInvalid()).isFalse(); session.invalidate(); assertThat(session.isInvalid()).isTrue(); } @Test void invalidateTwice() { session.invalidate(); assertThatIllegalStateException().isThrownBy( session::invalidate); } @Test void getCreationTimeOnInvalidatedSession() { session.invalidate(); assertThatIllegalStateException().isThrownBy( session::getCreationTime); } @Test void getLastAccessedTimeOnInvalidatedSession() { session.invalidate(); assertThatIllegalStateException().isThrownBy( session::getLastAccessedTime); } @Test void getAttributeOnInvalidatedSession() { session.invalidate(); assertThatIllegalStateException().isThrownBy(() -> session.getAttribute("foo")); } @Test void getAttributeNamesOnInvalidatedSession() { session.invalidate(); assertThatIllegalStateException().isThrownBy( session::getAttributeNames); } @Test void setAttributeOnInvalidatedSession() { session.invalidate(); assertThatIllegalStateException().isThrownBy(() -> session.setAttribute("name", "value")); } @Test void removeAttributeOnInvalidatedSession() { session.invalidate(); assertThatIllegalStateException().isThrownBy(() -> session.removeAttribute("name")); } @Test void isNewOnInvalidatedSession() { session.invalidate(); assertThatIllegalStateException().isThrownBy( session::isNew); } @Test void bindingListenerBindListener() { String bindingListenerName = "bindingListener"; CountingHttpSessionBindingListener bindingListener = new CountingHttpSessionBindingListener(); session.setAttribute(bindingListenerName, bindingListener); assertThat(bindingListener.getCounter()).isEqualTo(1); } @Test void bindingListenerBindListenerThenUnbind() { String bindingListenerName = "bindingListener"; CountingHttpSessionBindingListener bindingListener = new CountingHttpSessionBindingListener(); session.setAttribute(bindingListenerName, bindingListener); session.removeAttribute(bindingListenerName); assertThat(bindingListener.getCounter()).isEqualTo(0); } @Test void bindingListenerBindSameListenerTwice() { String bindingListenerName = "bindingListener"; CountingHttpSessionBindingListener bindingListener = new CountingHttpSessionBindingListener(); session.setAttribute(bindingListenerName, bindingListener); session.setAttribute(bindingListenerName, bindingListener); assertThat(bindingListener.getCounter()).isEqualTo(1); } @Test void bindingListenerBindListenerOverwrite() { String bindingListenerName = "bindingListener"; CountingHttpSessionBindingListener bindingListener1 = new CountingHttpSessionBindingListener(); CountingHttpSessionBindingListener bindingListener2 = new CountingHttpSessionBindingListener(); session.setAttribute(bindingListenerName, bindingListener1); session.setAttribute(bindingListenerName, bindingListener2); assertThat(bindingListener1.getCounter()).isEqualTo(0); assertThat(bindingListener2.getCounter()).isEqualTo(1); } private static class CountingHttpSessionBindingListener implements HttpSessionBindingListener { private final AtomicInteger counter = new AtomicInteger(); @Override public void valueBound(HttpSessionBindingEvent event) { this.counter.incrementAndGet(); } @Override public void valueUnbound(HttpSessionBindingEvent event) { this.counter.decrementAndGet(); } int getCounter() { return this.counter.get(); } } }
package org.abrahamalarcon.datastream.dom.response; public class DatastoreResponse extends BaseResponse { String uuid; Response response; Location location; Forecast forecast; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public Response getResponse() { return response; } public void setResponse(Response response) { this.response = response; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public Forecast getForecast() { return forecast; } public void setForecast(Forecast forecast) { this.forecast = forecast; } }
package codePlus.AGBasic1.dp; import java.util.Scanner; public class DP_11052 { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int number = scn.nextInt(); //구매하고자 하는 카드 개수 int [] cardPack= new int[number+1]; //카드의 가격을 담기 위한 베열 (배열의 인덱스는 카드의 개수, 배열의 값은 카드팩의 가격) //카드팩의 가격들이 차례로 price 배열에 삽입됨 for(int i=1; i<=number; i++) { cardPack[i]= scn.nextInt(); } System.out.println(); int maxPrice[] = new int[number+1]; //dp[]: N개의 카드를 구매할 때 금액의 최댓값을 저장 //이 때 배열의 모든 값은 0으로 초기화 //dp[0] = 카드를 0개 구매했을 때의 최댓값이므로 0 for(int i=1; i<=number; i++) { //구매하고자 하는 카드 개수(i)만큼 돌리기 //1개를 구매할 때부터 N개를 구매할 때까지 System.out.println(); System.out.println("구매하고자 하는 카드의 개수가 "+i+"개 일 때"); for(int j=1; j<=i; j++) { //i개의 카드를 얻기 위해 가능한 모든 경우의 수 중 최댓값 찾기 System.out.println("maxPrice["+i+"]= "+maxPrice[i]); System.out.println("maxPrice["+(i-j)+"]= "+maxPrice[i-j]+", cardPack["+j+"]= "+cardPack[j]); maxPrice[i] = Math.max(maxPrice[i], maxPrice[i-j]+cardPack[j]); } //d[] 배열에 값을 넣은 이후, 출력해보기 for(int k=0; k<maxPrice.length; k++) { System.out.print(maxPrice[k]+" "); } System.out.println(); } System.out.println(); System.out.println("d배열의 최종 값"); for(int i=0; i<maxPrice.length; i++) { System.out.print(maxPrice[i]+" "); } System.out.println(); System.out.println(); System.out.println("카드"+number+"개를 갖기 위해 지불해야 하는 금액의 최댓값= "+maxPrice[number]); } }
package classes; import java.util.Scanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; public class InConsole implements Input { String message; @Override public String in() { System.out.print("입력해주세요: "); //Console에서 입력을 받기 위해 Scanner객체 사용 Scanner sc = new Scanner(System.in); //입력받은 값을 message 라는 문자열 값에 대입 String message = sc.nextLine(); // System.out.println(message); //Scanner객체 종료 sc.close(); //message라는 문자열 반환 return message; } }
package net.lantrack.framework.sysbase.entity; import java.io.Serializable; import javax.validation.constraints.NotNull; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.Length; /** * 数据规则 * @date 2019年3月21日 */ public class SysDatarule implements Serializable { private Integer id; /** * 菜单id */ private Integer menuId; /** * 规则名称 */ private String ruleName; /** * 规则字段 */ private String tField; /** * 规则条件 */ private String tExpress; /** * 规则值 */ private String tValue; /** * 自定义SQL */ private String sqlSegment; /** * 备注 */ private String remarks; /** * 删除标记(0否1是) */ private String delFlag; /** * 过滤实体类名(列表查询条件中的类名) */ private String classname; private static final long serialVersionUID = 1L; public SysDatarule(Integer id, Integer menuId, String ruleName, String tField, String tExpress, String tValue, String sqlSegment, String remarks, String delFlag, String classname) { this.id = id; this.menuId = menuId; this.ruleName = ruleName; this.tField = tField; this.tExpress = tExpress; this.tValue = tValue; this.sqlSegment = sqlSegment; this.remarks = remarks; this.delFlag = delFlag; this.classname = classname; } public SysDatarule() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @NotNull public Integer getMenuId() { return menuId; } public void setMenuId(Integer menuId) { this.menuId = menuId; } @Length(min=1,max=64,message="规则名称应在1~64字符之间") public String getRuleName() { return ruleName; } public void setRuleName(String ruleName) { this.ruleName = ruleName == null ? null : ruleName.trim(); } @Length(min=0,max=64,message="规则字段不能超过64个字符") public String gettField() { return tField; } public void settField(String tField) { this.tField = tField == null ? null : tField.trim(); } @Length(min=0,max=64,message="规则条件不能超过64个字符") public String gettExpress() { return tExpress; } public void settExpress(String tExpress) { this.tExpress = tExpress == null ? null : tExpress.trim(); } @Length(min=0,max=64,message="规则值不能超过64个字符") public String gettValue() { return tValue; } public void settValue(String tValue) { this.tValue = tValue == null ? null : tValue.trim(); } @Length(min=0,max=1000,message="自定义sql规则值不能超过1000个字符") public String getSqlSegment() { return sqlSegment; } public void setSqlSegment(String sqlSegment) { this.sqlSegment = sqlSegment == null ? null : sqlSegment.trim(); } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks == null ? null : remarks.trim(); } public String getDelFlag() { return delFlag; } public void setDelFlag(String delFlag) { this.delFlag = delFlag == null ? null : delFlag.trim(); } public String getClassname() { return classname; } public void setClassname(String classname) { this.classname = classname == null ? null : classname.trim(); } /** * 获取数据过滤权限 * @return * @date 2019年3月21日 */ public String getDataScopeSql(){ StringBuffer sqlBuffer = new StringBuffer(); if(StringUtils.isNotBlank(tField)&&StringUtils.isNotBlank(tValue)){ sqlBuffer.append(" AND " +tField+" "+StringEscapeUtils.unescapeHtml4(tExpress)+" "+tValue+" "); } if(StringUtils.isNotBlank(sqlSegment)){ sqlBuffer.append(" AND "+StringEscapeUtils.unescapeHtml4(sqlSegment)+" "); } return sqlBuffer.toString(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", menuId=").append(menuId); sb.append(", ruleName=").append(ruleName); sb.append(", tField=").append(tField); sb.append(", tExpress=").append(tExpress); sb.append(", tValue=").append(tValue); sb.append(", sqlSegment=").append(sqlSegment); sb.append(", remarks=").append(remarks); sb.append(", delFlag=").append(delFlag); sb.append(", classname=").append(classname); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
package com.midea.designmodel.princple; /** * 开闭原则 * 1.开闭原则时一个软件实体类/函数/模块应该对扩展开放(对提供方),对修改关闭(对使用方) * 用抽象构件 */ public class OpenAndClose { public static void main(String[] args) { Draw d=new Draw(); Sanjiaoxing s=new Sanjiaoxing(1); Zhengfangx z=new Zhengfangx(2); //如果再增加一个图形就会增加很多代码 所以要将图形抽象画 然后具体图形集成鸡肋实现抽象方法 d.draw(s); d.draw(z); } } class Draw{ void draw(Shape s){ if(s.type==1){ drawSan(); }else if(s.type==2){ drawZheng(); } } void drawSan(){ System.out.println("绘制三角形"); } void drawZheng(){ System.out.println("绘制正方形"); } } class Shape{ int type; } class Sanjiaoxing extends Shape{ Sanjiaoxing(int type){ super.type=type; } } class Zhengfangx extends Shape{ Zhengfangx(int type){ super.type=type; } }
package org.ufla.tsrefactoring.javaparser; import java.io.File; import java.util.ArrayList; import java.util.List; import org.ufla.tsrefactoring.dto.ResultTestSmellDTO; import org.ufla.tsrefactoring.enums.TestSmell; public class Analyzer { private static List<ResultTestSmellDTO> resultEmptyTest = new ArrayList<ResultTestSmellDTO>(); private static final String[] FILE_PATH = { "D:\\eclipse-workspace\\Gadgetbride\\app\\src\\test" }; private static List<ResultTestSmellDTO> getFiles(TestSmell testSmell) { for (String path : FILE_PATH) { resultEmptyTest.clear(); Parser.listClasses(new File(path), testSmell); resultEmptyTest = Parser.getAllClassData(); } return resultEmptyTest; } public static List<ResultTestSmellDTO> getFilesAnalyzed(TestSmell testSmell) { return getFiles(testSmell); } }
package com.yunsi.oop.bean.sub; import com.yunsi.oop.bean.Human; public class Cooker extends Human{ private int workage; private int worktime; private String food; public Cooker(String n,String f){ this.setName(n); this.food=f; } public Cooker(){ } void setworkage(int n){ this.workage=n; } void addFood(String f){ this.food+="กข"+f; } void addworkTime(int x){ this.worktime+=x; } }
package com.dio.citydestroyer.Dao; import com.dio.citydestroyer.City.City; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Component public class CityDaoImpl implements CityDao { private SessionFactory sessionFactory; @Override @Transactional public void save(City city) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.saveOrUpdate(city); transaction.commit(); session.close(); } @SuppressWarnings("unchecked") @Override @Transactional public List<City> list() { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); String string = "FROM City"; Query query = session.createQuery(string); List<City> list = query.list(); transaction.commit(); session.close(); return list; } @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
package io.hankki.recipe.domain.service; public class RecipeLogic { }
package com.company; /* * Find the fastest runner. Print the name and his/her time (in minutes). * Write a method that takes as input an array of integers and returns the index corresponding to the person with the lowest * time. Run this method on the array of times. Print out the name and time corresponding to the returned index. * * Write a second method to find the second-best runner. The second method should use the first method to determine the * best runner, and then loop through all values to find the second-best (second lowest) time. **/ import java.util.Collections; public class Main { public static void main(String[] args) { // Arrays are indexed with same length so you know who has the corresponding time String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt" ,"Alex", "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda", "Aaron" ,"Kate" }; int[] times = new int[]{ 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265 }; // Test to see if there is anything in the arrays and if not exit with error message if(times.length == 0 && names.length == 0) { System.out.print ("There are not registered names or times in the arrays!\n Bailing out now!"); System.exit (0); } for(int i = 0; i< names.length; i++) { System.out.println( names[i] + ":" + times[i]); } int index = FastestAndSlowestTimes (times, names); SecondFastest (times, names, index); } public static int FastestAndSlowestTimes (int times[], String names[]) { int FastestTime = times[0]; int SlowestTime = times[0]; int index = 0; String SlowestRunnerName = ""; String FastestRunnerName = ""; for(int i = 0; i < times.length; i++) { if (times[i] > SlowestTime) { SlowestTime = times[i]; SlowestRunnerName = names[i]; } else if (times[i] < FastestTime) { FastestTime = times[i]; FastestRunnerName = names[i]; index = i; } } System.out.println ("\nThe fastest runner is " + FastestRunnerName + " with a time of " + FastestTime + " minutes."); System.out.println ("\nThe slowest runner is " + SlowestRunnerName + " with a time of " + SlowestTime + " minutes."); return index; } public static void SecondFastest ( int times[], String names[], int index) { int FastestTime = times[index]; int SecondFastestTime = 0; String SecondRunnerName = ""; for(int i = 0; i < times.length; i++) { if(times[i] > FastestTime) { SecondFastestTime = times[i]; SecondRunnerName = names[i]; } } System.out.println ("\nThe second fastest runner is " + SecondRunnerName + " with a time of " + SecondFastestTime + " minutes."); } }
package view.ui; import java.awt.BorderLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JPanel; import model.ListingContext; public class ListingPanel extends JPanel { private ListingContext listingContext; public ListingPanel(ListingContext listingContext) { this.listingContext = listingContext; setLayout(new BorderLayout()); initializeComponents(); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { System.out.println("AAA"); } }); } private void initializeComponents() { add(new DrivesInfoToolbar(listingContext), BorderLayout.NORTH); add(new DirectoryInfoPanel(listingContext), BorderLayout.CENTER); } }
package com.emc.subscribe.dto; import java.util.Map; import java.util.Set; public class RegisterTopicResDTO { private String userId; private Set<String> topicOk; private Map<String,String> topicError; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Set<String> getTopicOk() { return topicOk; } public void setTopicOk(Set<String> topicOk) { this.topicOk = topicOk; } public Map<String, String> getTopicError() { return topicError; } public void setTopicError(Map<String, String> topicError) { this.topicError = topicError; } }
package com.lasform.core.business.repository; import com.lasform.core.model.entity.State; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface StateRepository extends CrudRepository<State,Long> { List<State> findAllByCountryId( long countryId ); }
package edu.mit.cci.simulation.ice.beans; import com.icesoft.faces.component.inputfile.FileInfo; import java.io.File; // This is the file that's uploaded by the client public class FileToUpload { // file info attributes private FileInfo fileInfo; // file that was uplaoded private File file; /** * Create a new InputFileDat object. * * @param fileInfo FileInfo object created by the inputFile component for * a given File object. */ public FileToUpload(FileInfo fileInfo) { this.fileInfo = fileInfo; this.file = fileInfo.getFile(); } public FileInfo getFileInfo() { return fileInfo; } public void setFileInfo(FileInfo fileInfo) { this.fileInfo = fileInfo; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } }
package br.com.hitbra.services; import br.com.hitbra.model.VendorModel; public interface VendorCommand { void execute( VendorModel model ); }
package EdgePuzzle; import java.awt.*; import java.awt.image.*; import javax.imageio.*; import java.io.*; public class Piece { private static BufferedImage[] images; public static BufferedImage background; private BufferedImage image; private int[] edges; private int rotation; public static void loadImages() { images = new BufferedImage[8]; try { images[0] = ImageIO.read(new File("Gender-top.png")); images[1] = ImageIO.read(new File("Gender-bottom.png")); images[2] = ImageIO.read(new File("Ghost-top.png")); images[3] = ImageIO.read(new File("Ghost-bottom.png")); images[4] = ImageIO.read(new File("Omega-top.png")); images[5] = ImageIO.read(new File("Omega-bottom.png")); images[6] = ImageIO.read(new File("Shadow-top.png")); images[7] = ImageIO.read(new File("Shadow-bottom.png")); background = ImageIO.read(new File("background.png")); } catch(IOException e) { System.err.println(e); } } public Piece(String signature) { if(signature.length() != 4) { throw new IllegalArgumentException("Input file contains invalid puzzle piece."); } edges = new int[4]; rotation = 0; for(int i = 0; i < edges.length; ++i) { switch(signature.charAt(i)) { case 'c': edges[i] = 0; break; case 'C': edges[i] = 1; break; case 'm': edges[i] = 2; break; case 'M': edges[i] = 3; break; case 'y': edges[i] = 4; break; case 'Y': edges[i] = 5; break; case 'k': edges[i] = 6; break; case 'K': edges[i] = 7; break; default: throw new IllegalArgumentException("Input file contains invalid puzzle piece."); } } image = new BufferedImage(background.getWidth(), background.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D)image.createGraphics(); g.drawImage(background, 0, 0, null); double[][] angles = new double[4][2]; angles[0][0] = 180.0; angles[0][1] = 0.0; angles[1][0] = 270.0; angles[1][1] = 90.0; angles[2][0] = 0.0; angles[2][1] = 180.0; angles[3][0] = 90.0; angles[3][1] = 270.0; for(int i = 0; i < edges.length; ++i) { BufferedImage rotated = rotate(images[edges[i]], angles[i][edges[i]%2]); if(i == 0) { g.drawImage(rotated, image.getWidth()/2 - rotated.getWidth()/2, 0, null); } else if(i == 1) { g.drawImage(rotated, image.getWidth() - rotated.getWidth(), image.getHeight()/2 - rotated.getHeight()/2, null); } else if(i == 2) { g.drawImage(rotated, image.getWidth()/2 - rotated.getWidth()/2, image.getHeight() - rotated.getHeight(), null); } else { g.drawImage(rotated, 0, image.getHeight()/2 - rotated.getHeight()/2, null); } } } public void rotate() { ++rotation; rotation %= 4; } public int getAt(int place) { return edges[(rotation + place)%4]; } public boolean test(int[] needed) { for(int i = 0; i < needed.length; ++i) { if(needed[i] != -1 && needed[i] != edges[(i + rotation)%4]) { return false; } } return true; } public BufferedImage getImage() { BufferedImage rotated = null; if(rotation == 0) { rotated = rotate(image, 0.0); } else if(rotation == 1) { rotated = rotate(image, 270.0); } else if(rotation == 2) { rotated = rotate(image, 180.0); } else if(rotation == 3) { rotated = rotate(image, 90.0); } return rotated; } public BufferedImage rotate(BufferedImage img, double angle) { double sin = Math.abs(Math.sin(Math.toRadians(angle))); double cos = Math.abs(Math.cos(Math.toRadians(angle))); int width = img.getWidth(); int height = img.getHeight(); int newWidth = (int) Math.floor(width*cos + height*sin); int newHeight = (int) Math.floor(height*cos + width*sin); BufferedImage bimg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = bimg.createGraphics(); g.translate((newWidth-width)/2, (newHeight-height)/2); g.rotate(Math.toRadians(angle), width/2, height/2); g.drawRenderedImage(img, null); g.dispose(); return bimg; } }
package com.trump.auction.trade.configure.datasource; import java.sql.SQLException; import java.util.HashMap; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; import javax.sql.DataSource; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.boot.autoconfigure.SpringBootVFS; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import com.github.pagehelper.PageHelper; import io.shardingjdbc.core.api.ShardingDataSourceFactory; import io.shardingjdbc.core.api.config.ShardingRuleConfiguration; import io.shardingjdbc.core.api.config.TableRuleConfiguration; import lombok.extern.slf4j.Slf4j; @Slf4j @Configuration public class DataSourceHelp { @Value("${mybatis.mapperLocations}") private String mapperLocations; @Value("${mybatis.typeAliasesPackage}") private String typeAliasesPackage; @Value("${auction.bid.detail.table.range}") private String auctionBidetailTableRange; /*@Autowired public DataSource shardingDataSource; @PostConstruct public void init(){ HashMap<String, DataSource> dataSourceMap = new HashMap<>(); dataSourceMap .put("shardingDataSource", shardingDataSource); TableRuleConfiguration tbUserTableRuleConfig = new TableRuleConfiguration(); tbUserTableRuleConfig.setLogicTable("auction_bid_detail"); tbUserTableRuleConfig.setActualDataNodes("shardingDataSource.auction_bid_detail_${["+auctionBidetailTableRange+"]}"); ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); shardingRuleConfig.getTableRuleConfigs().add(tbUserTableRuleConfig); try { shardingDataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, new ConcurrentHashMap(), new Properties()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setVfs(SpringBootVFS.class); bean.setTypeAliasesPackage(typeAliasesPackage); Properties props = new Properties(); props.setProperty("reasonable", "true"); props.setProperty("supportMethodsArguments", "true"); props.setProperty("returnPageInfo", "check"); props.setProperty("params", "count=countSql"); props.setProperty("dialect", "mysql"); props.setProperty("offsetAsPageNum", "true"); props.setProperty("rowBoundsWithCount", "true"); try { bean.setDataSource(dataSource); PageHelper pageHelper = new PageHelper(); pageHelper.setProperties(props); bean.setPlugins(new Interceptor[]{pageHelper}); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); bean.setMapperLocations(resolver.getResources(mapperLocations)); return bean.getObject(); } catch (Throwable e) { throw new RuntimeException(e); } } }
package com.proxiad.games.extranet.dto; import lombok.Builder; import lombok.Data; @Data @Builder public class LoginAccessDto { private String token; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ArRadioButtonsScratch; import javax.swing.JFrame; /** * * @author burtm5944 */ public class FraMain extends JFrame{ public FraMain(){ PanMain panMain = new PanMain(); add(new PanMain()); setTitle("TV Scratch"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//DO_NOTHING_ON_CLOSE setSize(500, 500); //1370, 730 for fullscreen for laptop this.setResizable(true); setLocationRelativeTo(null); setVisible(true); } }
package com.upgrad.FoodOrderingApp.api.controller; import com.upgrad.FoodOrderingApp.api.model.*; import com.upgrad.FoodOrderingApp.service.businness.CategoryService; import com.upgrad.FoodOrderingApp.service.businness.RestaurantService; import com.upgrad.FoodOrderingApp.service.entity.*; import com.upgrad.FoodOrderingApp.service.exception.AuthorizationFailedException; import com.upgrad.FoodOrderingApp.service.exception.CategoryNotFoundException; import com.upgrad.FoodOrderingApp.service.exception.RestaurantNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.UUID; @RestController @RequestMapping("/") public class RestaurantController { @Autowired private RestaurantService restaurantService; @Autowired private CategoryService categoryService; @RequestMapping(method = RequestMethod.GET,path = "/restaurant/name/{reastaurant_name}") public ResponseEntity<RestaurantListResponse> getRestaurantList(@PathVariable("reastaurant_name") final String restaurantName) throws RestaurantNotFoundException { List<RestaurantEntity> restaurantEntities = restaurantService.getRestaurantList(restaurantName); List<RestaurantList> restaurantLists = new ArrayList<>(); for (RestaurantEntity l:restaurantEntities) { RestaurantList restaurantList=new RestaurantList(); RestaurantDetailsResponseAddress restaurantDetailsResponseAddress=new RestaurantDetailsResponseAddress(); RestaurantDetailsResponseAddressState restaurantDetailsResponseAddressState=new RestaurantDetailsResponseAddressState(); restaurantDetailsResponseAddress.city(l.getAddress().getCity()); restaurantDetailsResponseAddress.id(UUID.fromString(l.getAddress().getUuid())); restaurantDetailsResponseAddress.locality(l.getAddress().getLocality()); restaurantDetailsResponseAddress.flatBuildingName(l.getAddress().getFlatbuilnumber()); restaurantDetailsResponseAddress.pincode(l.getAddress().getPincode()); restaurantDetailsResponseAddressState.stateName(l.getAddress().getState().getStatename()); restaurantDetailsResponseAddressState.id(UUID.fromString(l.getAddress().getState().getUuid())); restaurantDetailsResponseAddress.state(restaurantDetailsResponseAddressState); restaurantList.id(UUID.fromString(l.getUuid())); restaurantList.averagePrice(l.getAvgprice()); restaurantList.photoURL(l.getPhotourl()); restaurantList.restaurantName(l.getRestaurantName()); restaurantList.customerRating(l.getCustomerRating()); restaurantList.numberCustomersRated(l.getCustomersrated()); restaurantList.address(restaurantDetailsResponseAddress); restaurantList.categories("Indian"); restaurantLists.add(restaurantList); } RestaurantListResponse restaurantListResponse=new RestaurantListResponse(); restaurantListResponse.restaurants(restaurantLists); return new ResponseEntity<RestaurantListResponse>(restaurantListResponse,HttpStatus.OK); } @RequestMapping(method = RequestMethod.GET,path = "/restaurant/category/{category_id}") public ResponseEntity<RestaurantListResponse> getRestaurantByCategory(@PathVariable("category_id") final String categoryid) throws CategoryNotFoundException { List<RestaurantEntity> restaurantEntities = restaurantService.getRestaurantLists(categoryid); List<RestaurantList> restaurantLists = new ArrayList<>(); for (RestaurantEntity l:restaurantEntities) { RestaurantList restaurantList=new RestaurantList(); RestaurantDetailsResponseAddress restaurantDetailsResponseAddress=new RestaurantDetailsResponseAddress(); RestaurantDetailsResponseAddressState restaurantDetailsResponseAddressState=new RestaurantDetailsResponseAddressState(); restaurantDetailsResponseAddress.city(l.getAddress().getCity()); restaurantDetailsResponseAddress.id(UUID.fromString(l.getAddress().getUuid())); restaurantDetailsResponseAddress.locality(l.getAddress().getLocality()); restaurantDetailsResponseAddress.flatBuildingName(l.getAddress().getFlatbuilnumber()); restaurantDetailsResponseAddress.pincode(l.getAddress().getPincode()); restaurantDetailsResponseAddressState.stateName(l.getAddress().getState().getStatename()); restaurantDetailsResponseAddressState.id(UUID.fromString(l.getAddress().getState().getUuid())); restaurantDetailsResponseAddress.state(restaurantDetailsResponseAddressState); restaurantList.id(UUID.fromString(l.getUuid())); restaurantList.averagePrice(l.getAvgprice()); restaurantList.photoURL(l.getPhotourl()); restaurantList.restaurantName(l.getRestaurantName()); restaurantList.customerRating(l.getCustomerRating()); restaurantList.numberCustomersRated(l.getCustomersrated()); restaurantList.address(restaurantDetailsResponseAddress); restaurantList.categories("Indian"); restaurantLists.add(restaurantList); } RestaurantListResponse restaurantListResponse=new RestaurantListResponse(); restaurantListResponse.restaurants(restaurantLists); return new ResponseEntity<RestaurantListResponse>(restaurantListResponse,HttpStatus.OK); } @RequestMapping(method = RequestMethod.GET,path = "/api/restaurant/{restaurant_id}") public ResponseEntity<RestaurantDetailsResponse> getRestaurantByUuid(@PathVariable("restaurant_id") final String restaurantid) throws RestaurantNotFoundException { RestaurantEntity restaurantEntities = restaurantService.getRestaurant(restaurantid); RestaurantDetailsResponse restaurantLists = new RestaurantDetailsResponse(); RestaurantList restaurantList=new RestaurantList(); RestaurantDetailsResponseAddress restaurantDetailsResponseAddress=new RestaurantDetailsResponseAddress(); RestaurantDetailsResponseAddressState restaurantDetailsResponseAddressState=new RestaurantDetailsResponseAddressState(); restaurantDetailsResponseAddress.city(restaurantEntities.getAddress().getCity()); restaurantDetailsResponseAddress.id(UUID.fromString(restaurantEntities.getAddress().getUuid())); restaurantDetailsResponseAddress.locality(restaurantEntities.getAddress().getLocality()); restaurantDetailsResponseAddress.flatBuildingName(restaurantEntities.getAddress().getFlatbuilnumber()); restaurantDetailsResponseAddress.pincode(restaurantEntities.getAddress().getPincode()); restaurantDetailsResponseAddressState.stateName(restaurantEntities.getAddress().getState().getStatename()); restaurantDetailsResponseAddressState.id(UUID.fromString(restaurantEntities.getAddress().getState().getUuid())); restaurantDetailsResponseAddress.state(restaurantDetailsResponseAddressState); restaurantLists.id(UUID.fromString(restaurantEntities.getUuid())); restaurantLists.averagePrice(restaurantEntities.getAvgprice()); restaurantLists.photoURL(restaurantEntities.getPhotourl()); restaurantLists.restaurantName(restaurantEntities.getRestaurantName()); restaurantLists.customerRating(restaurantEntities.getCustomerRating()); restaurantLists.numberCustomersRated(restaurantEntities.getCustomersrated()); restaurantLists.address(restaurantDetailsResponseAddress); List<RestaurantcategoryEntity> restaurantcategoryEntities = restaurantService.getRestaurantCategory(restaurantEntities); List<CategoryList> categoryLists = new ArrayList<>(); for (RestaurantcategoryEntity r:restaurantcategoryEntities) { CategoryList categoryList=new CategoryList(); categoryList.categoryName(r.getCategory().getCategoryName()); categoryList.id(UUID.fromString(r.getCategory().getUuid())); List<CategoryItemEntity> categoryItemEntities=categoryService.getItemLists(r.getCategory()); List<ItemList> itemLists=new ArrayList<>(); for (CategoryItemEntity c:categoryItemEntities) { ItemList itemList = new ItemList(); itemList.id(UUID.fromString(c.getItem().getUuid())); itemList.price(c.getItem().getPrice()); itemList.itemName(c.getItem().getItemnames()); String type=c.getItem().getType(); if(type.equals("0")){ itemList.itemType(ItemList.ItemTypeEnum.fromValue("VEG")); } else { itemList.itemType(ItemList.ItemTypeEnum.fromValue("NON_VEG")); } itemLists.add(itemList); } categoryList.itemList(itemLists); categoryLists.add(categoryList); } restaurantLists.categories(categoryLists); return new ResponseEntity<RestaurantDetailsResponse>(restaurantLists,HttpStatus.OK); } }
package com.myvodafone.android.front.dlink; import android.content.Intent; import com.myvodafone.android.business.account.AccountListener; import com.myvodafone.android.business.account.AccountManager; import com.myvodafone.android.business.managers.MemoryCacheManager; import com.myvodafone.android.front.VFGRActivity; import com.myvodafone.android.front.auth.ActLoginMobile; import com.myvodafone.android.front.helpers.Dialogs; import com.myvodafone.android.front.home.ActHome; import com.myvodafone.android.model.business.VFAccount; import com.myvodafone.android.model.business.VFMobileAccount; import com.myvodafone.android.utils.StaticTools; import java.lang.ref.WeakReference; /** * Created by kakaso on 1/17/2017. */ public class ThankYouListener extends DLinkBaseListener implements AccountListener { VFGRActivity activity; public ThankYouListener(VFGRActivity activity){ setActivity(activity); } public void setActivity(VFGRActivity activity) { this.activity = activity; } @Override public void execAction() { if(MemoryCacheManager.getSelectedAccount()!=null) { if (MemoryCacheManager.getSelectedAccount().getAccountType() == VFAccount.TYPE_MOBILE_VF3G) { navThankYou(); } else if (MemoryCacheManager.getSelectedAccount().getAccountType() == VFAccount.TYPE_MOBILE) { handleMobile(activity, (VFMobileAccount) MemoryCacheManager.getSelectedAccount()); } else if (MemoryCacheManager.getSelectedAccount().getAccountType() == VFAccount.TYPE_FIXED_LINE) { handleFixed(activity); } } else if(StaticTools.isBizAdmin(MemoryCacheManager.getProfile().getActiveLoginMobile())){ MemoryCacheManager.setSelectedAccount(MemoryCacheManager.getProfile().getActiveLoginMobile()); Dialogs.closeProgress(); Intent intent = new Intent(activity, ActHome.class); intent.putExtra(ActHome.FLAG_BIZ_SELECT, true); intent.putExtra(ActHome.FLAG_NAV_LINK, ActDeepLinking.NAV_LINK_THANKYOU); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(intent); activity.finish(); } } private void handleFixed(VFGRActivity activity) { navToHome(activity); } private void handleMobile(VFGRActivity activity, VFMobileAccount selectedAccount) { if(selectedAccount.isMatched()){ navThankYou(); } else { if(MemoryCacheManager.getProfile().getActiveLoginMobileXG()!=null){ MemoryCacheManager.setSelectedAccount(MemoryCacheManager.getProfile().getActiveLoginMobileXG()); navThankYou(); } else { navToHome(activity); } } } @Override public void connectAccount(boolean showDialog) { loginMobile(activity, ActLoginMobile.FLAG_DLINK_CONNECT); } @Override public void fallback(int errorCode, boolean fromBackground) { StaticTools.Log("LastSelected", "callback: fallback"); activity.handleAccountErrors(activity,new AccountManager(activity, new WeakReference<AccountListener>(this)), errorCode, fromBackground, false, null); } @Override public void backgroundTaskCompleted(boolean success) { } private void navThankYou(){ Dialogs.closeProgress(); Intent intent = new Intent(activity, ActHome.class); intent.putExtra(ActHome.FLAG_NAV_LINK, ActDeepLinking.NAV_LINK_THANKYOU); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(intent); activity.finish(); } }
package com.data.main.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.data.main.service.queysso; @Controller @RequestMapping(value = "/sbdata") @PropertySource("classpath:/config/application.properties") public class controller { @Autowired queysso queysso; /*** * 测试查询 返回固定值 展示页面 * * @return */ @RequestMapping(value = "/test") @ResponseBody public String test() { return "测试一,字符串show页面。"; } /*** * SHOW 页面跳转,视图解析去 * * @return */ @RequestMapping(value = "/queypage") public ModelAndView showpage() { System.out.println("******2018、09、28******"); ModelAndView mv = new ModelAndView(); mv.setViewName("queysso"); mv.addObject("name", "queysso"); return mv; } /*** * 查询数据库 把值返回到页面 * * @return */ @RequestMapping(value = "/queyData") public ModelAndView queysso() { String name = queysso.querySSoservice(); ModelAndView mv = new ModelAndView(); mv.setViewName(name); mv.addObject("name", name); return mv; } }
package com.example.springsecuritywithmongo.config; import com.example.springsecuritywithmongo.filters.JwtRequestFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /** * created by lovedeep in com.example.springsecuritywithmongo.config */ @EnableWebSecurity public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Qualifier("MongoUserDetail") @Autowired UserDetailsService userDetailsService; @Autowired private JwtRequestFilter jwtRequestFilter; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().mvcMatchers("/home"); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf().disable() .authorizeRequests().antMatchers("/authenticate").permitAll() .mvcMatchers("/admin").hasAuthority("ADMIN") .antMatchers("/admin").hasRole("ADMIN") .antMatchers("/user").hasAuthority("staff"). anyRequest().authenticated().and(). exceptionHandling().and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } // @Override // protected void configure(AuthenticationManagerBuilder auth) throws Exception { // auth.userDetailsService(userDetailsService); // } // // // @Override // protected void configure(HttpSecurity http) throws Exception { //// http. //// csrf().disable(). //// sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS). //// and(). //// authorizeRequests(). //// anyRequest().authenticated(). //// and(). //// anonymous().disable() //// .mvcMatchers("/admin").hasAuthority("ADMIN") //// .antMatchers("/admin").hasRole("ADMIN") //// .antMatchers("/user").hasAnyRole("ADMIN", "USER") //// .antMatchers("/").permitAll().and() //// .exceptionHandling().accessDeniedPage("/access"); ////// .antMatchers("/switchuserto").hasRole("SUPER_ADMIN"); //// } // // http.authorizeRequests() // .mvcMatchers("/admin").hasAuthority("ADMIN") // .antMatchers("/admin").hasRole("ADMIN") // .antMatchers("/user").hasAnyRole("ADMIN", "USER") // .antMatchers("/").permitAll().and() // .exceptionHandling().accessDeniedPage("/access") // .and().formLogin(); //// .and().formLogin().disable(); // // } // @Bean // public PasswordEncoder getPasswordEncoder() { // return NoOpPasswordEncoder.getInstance(); // } // // // // // // // // // // // // // // // // }
package xtrus.user.comp.nhmca.message; import com.esum.framework.core.event.log.ErrorInfo; public interface McaMessageHandler { /** * 수신한 메시지를 처리하고, 처리 결과에 대한 Message를 생성하여 리턴한다. * ErrorInfo정보는 xTrus와 연계가 이뤄진 경우, 해당 NHMCA 켬포넌트에서 채널로 데이터를 처리한 결과에 대한 정보를 가진다. * errorInfo가 null이면 정상적으로 채널로 데이터를 전송한것이며, 그렇지 않으면 처리 중에 에러가 발생한 경우이다. * * @param messageId xTrus에서 처리한 메시지 관리 ID. * @param message MCAServer로 부터 수신한 메시지. * @param errorInfo xTrus연계시 해당 컴포넌트에 처리한 상태 정보. * @return */ public Message handleMessage(String messageId, Message message, ErrorInfo errorInfo); }
package com.softeem.test; import java.util.List; import org.junit.Test; import com.softeem.bean.GoodsBean; import com.softeem.dao.ICategoryDao; import com.softeem.dao.IGoodsDao; import com.softeem.dao.impl.CategoryDaoImpl; import com.softeem.dao.impl.GoodsDaoImpl; public class TestDao { @Test public void testCategoryDao() { ICategoryDao dao = new CategoryDaoImpl(); System.out.println(dao.selectAllCategory()); } @Test public void testGoodsDao(){ IGoodsDao goodsDao = new GoodsDaoImpl(); List<GoodsBean> goodsBeans = goodsDao.selectIndexGoods(0, 12); System.out.println(goodsBeans); } @Test public void testGoodsDao1(){ IGoodsDao goodsDao = new GoodsDaoImpl(); GoodsBean goods = goodsDao.selectById(1); System.out.println(goods); } }
package sandbox.worker.temperature; import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; import sandbox.repositories.TemperatureMeasure; import sandbox.repositories.TemperatureMeasureRepository; @Component public class TemperatureReceiver { protected final Logger logger = Loggers.getLogger(TemperatureReceiver.class); @Autowired TemperatureMeasureRepository temperatureMeasureRepository; @JmsListener(destination = "${temperature.topic}", concurrency = "${temperature.concurrency}") public void receive(TemperatureMeasure temperatureMeasure) { logger.info("Received Temperature: " + temperatureMeasure); temperatureMeasureRepository.save(temperatureMeasure); } }
package org.db.ddbserver; import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedList; public class SqlResult implements Serializable{ /** * */ private static final long serialVersionUID = 7417871626714039826L; private int result_id; private int site; private String table; private ArrayList<String> name; private ArrayList<SqlColomn> l; public SqlResult() { l = new ArrayList<SqlColomn>(); name = new ArrayList<String>(); } public ArrayList<String> getName() { return name; } public void setName(ArrayList<String> name) { this.name = name; } public int getResult_id() { return result_id; } public void setResult_id(int result_id) { this.result_id = result_id; } public int getSite() { return site; } public void setSite(int site) { this.site = site; } public String getTable() { return table; } public void setTable(String table) { this.table = table; } public ArrayList<SqlColomn> getL() { return l; } public void setL(ArrayList<SqlColomn> l) { this.l = l; } }
package company.my.lesson15; // Класс для хранения объектов запрошенных с базы данных // структура класса соответствует структуре необходимых нам данных public class DBItem { int id; String title; String content; // Пустой конструктор служит для инициализации // экземпляров этого класса в других классах без // первоначальных значений public DBItem() {} // Конструктор принимающий два значения служит // для заполнения только id и заголовка элементов // в этом примере этот конструктор используется в // запросе функции getTitles() класса Database public DBItem(int id, String title) { this.id = id; this.title = title; } // Конструктор принимающий три значений используется // для инициализации переменной для получения данных по // id через функцию getItemById, который возвращает значения строк // для столбцов значения id, которых соответствует запрошенному id public DBItem(int id, String title, String content) { this.id = id; this.title = title; this.content = content; } }
package cn.tedu.reivew; import java.math.BigDecimal; import java.util.Scanner; //求加减乘除 public class Test845 { public static void main(String[] args) { // f1();//普通的//不精确 f2(); } private static void f2() { System.out.println("请您输入第一个小数:"); double a=new Scanner(System.in).nextDouble(); System.out.println("请您输入第二个小数:"); double b=new Scanner(System.in).nextDouble(); BigDecimal bd1 = new BigDecimal(a+"");//变成String类型 加空串 BigDecimal bd2 = new BigDecimal(b+""); System.out.println(bd1.add(bd2)); System.out.println(bd1.subtract(bd2)); System.out.println(bd1.multiply(bd2)); System.out.println(bd1.divide(bd2,3,BigDecimal.ROUND_HALF_UP)); } private static void f1() { System.out.println("请您输入第一个小数:"); double a=new Scanner(System.in).nextDouble(); System.out.println("请您输入第二个小数:"); double b=new Scanner(System.in).nextDouble(); System.out.println(a+b); System.out.println(a-b); System.out.println(a*b); System.out.println(a/b); } }
package repository.hr; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import model.dto.hr.TeacherDTO; @Repository public class TchModifyRepository { private String namespace = "applyMapper"; @Autowired private SqlSession sqlSession; public Integer reposit(TeacherDTO dto) { String statement = namespace + ".tchModify"; return sqlSession.update(statement,dto); } } //
package com.project; import java.awt.Graphics; public interface Handleable { public void render(Graphics g); public void tick(); public float getZ(); }
package encryption; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyPair; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.util.logging.Level; import java.util.logging.Logger; public class Encryption { public static void main(String[] args) throws Exception { String[] fileName = new String[3]; fileName[0] = "keystore.jks"; fileName[1] = "E:/HND/SS/CW/Encryption/fileToEncrypt.txt"; fileName[2] = "EncryptedFile"; //generate public and private key pair KeyPair pair = getKeyPairFromKeyStore(fileName[0]); // Encryption the message Encrypt encrypt = new Encrypt(); // read text file String message = readTextFile(fileName[1]); System.out.println("Original message: " + message); //encrypt it String cipherText = encrypt.encrypt(message, pair.getPublic()); System.out.println(cipherText); //write encrypted text to the file writeTextFile(fileName[2], cipherText); } public static KeyPair getKeyPairFromKeyStore(String keyFile) throws Exception { // Generated with: // keytool -genkeypair -alias mykey -storepass s3cr3t -keypass s3cr3t -keyalg // RSA -keystore keystore.jks InputStream ins = Encryption.class.getResourceAsStream(keyFile); KeyStore keyStore = KeyStore.getInstance("JCEKS"); keyStore.load(ins, "s3cr3t".toCharArray()); // Keystore password KeyStore.PasswordProtection keyPassword = // Key password new KeyStore.PasswordProtection("s3cr3t".toCharArray()); KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry("mykey", keyPassword); java.security.cert.Certificate cert = keyStore.getCertificate("mykey"); PublicKey publicKey = cert.getPublicKey(); PrivateKey privateKey = privateKeyEntry.getPrivateKey(); return new KeyPair(publicKey, privateKey); } private static String readTextFile(String textFile){ String data = null; try { data = new String(Files.readAllBytes(Paths.get(textFile))); } catch (IOException ex) { Logger.getLogger(Encryption.class.getName()).log(Level.SEVERE, null, ex); } return data; } private static void writeTextFile(String encryptedFile, String cipherText) { try { try (FileWriter fileWriter = new FileWriter(encryptedFile)) { fileWriter.write(cipherText); } } catch (IOException e) { } } }
package com.mustafayuksel.notificationapplication.util; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.mustafayuksel.notificationapplication.domain.User; import com.mustafayuksel.notificationapplication.response.BaseResponse; import com.mustafayuksel.notificationapplication.service.impl.UserAnniversaryNotificationJob; public final class NotificationPusherUtil { private static final String ONE_SIGNAL_URL = "https://onesignal.com/api/v1/notifications"; private static final Logger LOGGER = LogManager.getLogger(UserAnniversaryNotificationJob.class); private NotificationPusherUtil() { } public static BaseResponse push(User user, String notificationMessageContent) { try { String jsonResponse; URL url = new URL(ONE_SIGNAL_URL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestMethod("POST"); String strJsonBody = "{" + "\"app_id\": \"" + user.getApplication().getApplicationOneSignalId() + "\"" + ",\"include_player_ids\": [\"" + user.getNotificationId() + "\"]," + "\"data\": {\"foo\": \"bar\"}," + "\"contents\": {\"en\": \"" + notificationMessageContent + "\"}" + "}"; LOGGER.info("Notification request for user id " + user.getId() + ": " + strJsonBody); byte[] sendBytes = strJsonBody.getBytes("UTF-8"); con.setFixedLengthStreamingMode(sendBytes.length); OutputStream outputStream = con.getOutputStream(); outputStream.write(sendBytes); int httpResponse = con.getResponseCode(); LOGGER.info("httpResponse for user id " + user.getId() + ": " + httpResponse); if (httpResponse >= HttpURLConnection.HTTP_OK && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) { Scanner scanner = new Scanner(con.getInputStream(), "UTF-8"); jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); LOGGER.info("httpResponse for user id " + user.getId() + ": " + jsonResponse); if (jsonResponse.contains("errors")) { return new BaseResponse(jsonResponse, false); } return new BaseResponse(jsonResponse, true); } else { Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8"); jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); LOGGER.info("httpResponse for user id " + user.getId() + ": " + jsonResponse); return new BaseResponse(jsonResponse, false); } } catch (Throwable t) { LOGGER.error(t.getLocalizedMessage()); return new BaseResponse(t.getLocalizedMessage(), false); } } }
package com.gbq.dao; import java.util.List; import com.gbq.po.User; public interface UserMapper { User findUserById(int id); List<User> findAllUser(); List<User> findUserByUsername(String username); void addUser(User user); void updateUser(User user); void deleteUserById(int id); }
/* Test 31: * * In questo test controlliamo la correttezza dell' espressioni: * expr1 - expr2 */ package gimnasium; class s1 { void pippo() { double x; int var1, var2; double var3; boolean var4; x=12-11; x=11.5-12; x=12-11.5; x=12.3-11.5; x=var1-var2; x=var3-var2; x=var2-var3; x=var2-var4; // errore !!! } }
/* * Copyright 2014-2023 JKOOL, LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jkoolcloud.jesl.net.ssl; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyStore; import java.security.Security; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import com.jkoolcloud.jesl.net.security.AuthUtils; /** * Implements a factory for generating client- and server-side SSL Contexts. * * @version $Revision: 1 $ */ public class SSLContextFactory { protected static final String KEYSTORE_TYPE = "JKS"; // default to javax.net.ssl.keyStoreType/trustStoreType protected SSLContext serverContext = null; protected SSLContext clientContext = null; protected SSLContext dfltContext = null; /** * Create default SSL context factory * * @throws SecurityException * if error initializing context factory using default context */ public SSLContextFactory() throws SecurityException { init(); } /** * Create SSL context factory with given attributes * * @param keyStoreFileName * key store file name * @param keyStorePassword * key store password * @param keyPassword * key password * @throws SecurityException * if error initializing context factory using specified keystore */ public SSLContextFactory(String keyStoreFileName, String keyStorePassword, String keyPassword) throws SecurityException { if (keyStoreFileName == null) { init(); } else { init(keyStoreFileName, keyStorePassword, keyPassword); } } /** * Initialize default SSL context * * @throws SecurityException * if error initializing context factory using default context */ protected void init() throws SecurityException { try { dfltContext = SSLContext.getDefault(); } catch (Exception e) { throw new SecurityException("Failed to initialize the default SSLContext", e); } } /** * Initialize SSL context factory with given attributes * * @param keyStoreFileName * key store file name * @param keyStorePassword * key store password * @param keyPassword * key password * @throws SecurityException * if error initializing context factory using specified keystore */ protected void init(String keyStoreFileName, String keyStorePassword, String keyPassword) throws SecurityException { String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } KeyManagerFactory kmf = null; TrustManagerFactory tmf = null; try { // Load keystore KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE); try (InputStream fis = Files.newInputStream(Paths.get(keyStoreFileName))) { ks.load(fis, keyStorePassword.toCharArray()); } // Set up key manager factory to use our keystore kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(ks, keyPassword.toCharArray()); // Set up trust manager factory to use our keystore tmf = TrustManagerFactory.getInstance(algorithm); tmf.init(ks); } catch (Exception e) { throw new SecurityException("Failed to initialize key manager", e); } try { // Initialize the server SSLContext to work with our key managers. serverContext = SSLContext.getInstance(AuthUtils.SSL_PROTOCOL); serverContext.init(kmf.getKeyManagers(), null, null); } catch (Exception e) { throw new SecurityException("Failed to initialize the server-side SSLContext", e); } try { // Initialize the client SSLContext to work with our trust manager clientContext = SSLContext.getInstance(AuthUtils.SSL_PROTOCOL); clientContext.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { throw new SecurityException("Failed to initialize the client-side SSLContext", e); } } /** * Obtain {@link javax.net.ssl.SSLContext} instance * * @param isClient * is client * @return SSL context instance */ public SSLContext getSslContext(boolean isClient) { if (dfltContext != null) { return dfltContext; } if (isClient) { return clientContext; } return serverContext; } }
package uk.ac.qub.eeecs.gage.playerTests; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.internal.matchers.Null; import org.mockito.runners.MockitoJUnitRunner; import uk.ac.qub.eeecs.gage.Game; import uk.ac.qub.eeecs.gage.engine.AssetManager; import uk.ac.qub.eeecs.game.CardDemo.Card; import uk.ac.qub.eeecs.game.matchAttax.player.Deck; import uk.ac.qub.eeecs.game.matchAttax.player.PlayerAI; import uk.ac.qub.eeecs.game.matchAttax.screens.MatchGameScreen; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class PlayerAITest { @Mock private MatchGameScreen gameScreen = mock(MatchGameScreen.class); @Mock private Game game = mock(Game.class); @Mock private AssetManager assetManager = mock(AssetManager.class); @Mock private Deck deck = mock(Deck.class); @Before public void setup() { } @Test public void constructPlayerAIObject() { PlayerAI player = new PlayerAI("Adam", deck, gameScreen); assertTrue(player.getName().equals("Adam")); assertTrue(player.getDeck() == deck); } @Test public void playerAINameGetAndSet() { PlayerAI playerAI= new PlayerAI("Adam", deck, gameScreen); playerAI.setName("Aaron"); assertTrue(playerAI.getName().equals("Aaron")); } @Test public void playerAIDeckGetAndSet() { PlayerAI playerAI = new PlayerAI("Adam", deck, gameScreen); Deck newDeck = mock(Deck.class); playerAI.setDeck(newDeck); assertTrue(playerAI.getDeck().equals(newDeck)); } @Test public void playerAIScoreGetAndSet() { PlayerAI playerAI = new PlayerAI("Adam", deck, gameScreen); playerAI.setScore(1); assertTrue(playerAI.getScore() == 1); } @Test public void playerAIEndTurnGetAndSet() { PlayerAI playerAI = new PlayerAI("Adam", deck, gameScreen); playerAI.setEndTurn(false); assertTrue(playerAI.getEndTurn() == false); } public void playerAIselectCardToPlay_returnsCard(){ PlayerAI playerAI = new PlayerAI("Adam", deck, gameScreen); int playerScore = 10, aiScore = 5, roundNum = 1; Card card = mock(Card.class); assertTrue(playerAI.selectCardToPlay(playerScore, aiScore, roundNum).equals(card)); } }
package practico13.E2.test; import practico13.E2.ColeccionEnteros; public class testColeccionEnteros { public static void main(String[] args) { ColeccionEnteros coleccion1=new ColeccionEnteros(10); coleccion1.desplegarColeccion(); coleccion1.existeValor(10); coleccion1.maximoValor(); coleccion1.desplegarPosicionesMultiplo(5); coleccion1.promedioValores(); coleccion1.invertir(); coleccion1.hayRepetidos(); coleccion1.duplicarCeldasMultiplo(5); coleccion1.desplegarColeccion(); } }
package com.example.practice.service; import com.example.practice.model.Author; public interface AuthorService { }
package com.git.cloud.resmgt.compute.model.comparator; import java.util.Comparator; import com.git.cloud.resmgt.compute.model.vo.ScanVmResultVo; public class ScanVmResultVoComparator implements Comparator<ScanVmResultVo>{ @Override public int compare(ScanVmResultVo o1, ScanVmResultVo o2) { int flag = o1.getVmName().compareToIgnoreCase(o2.getVmName()); if(flag == 0){ return o1.getAddDuName().compareToIgnoreCase(o2.getAddDuName()); } return flag; } }
package com.cbsystematics.edu.eshop.entities; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.List; @Data @EqualsAndHashCode(callSuper = true) @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "shop_users") public class User extends AbstractEntity { @Column(name = "username", unique = true, nullable = false) private String username; @Column(nullable = false) private String password; @Column(nullable = false) private String firstName; @Column(nullable = false) private String lastName; @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "user_details_id") private UserDetails userDetails; @OneToOne @JoinColumn(name = "roles_id") private Role role; @OneToMany @JoinColumn(name = "orders_id") private List<Order> orders; }
package demo; public class TestRandomCharacter { public static void main(String[] args) { final int NUMBER_OF_CHARS = 100; final int CHARS_PER_LINE = 25; for( int i = 0 ; i < NUMBER_OF_CHARS ; i++ ) { char ch = RandomCharacter.getRandomCharacter(); if( (i+1) % CHARS_PER_LINE ==0 ) { System.out.printf("%5c\n", ch); } else System.out.printf("%5c", ch); } } }
public interface BetterBehavior { public void comIs(); }
package controller; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.UserBean; import model.dao.UserBeanDAOHibernate; import model.misc.HibernateUtil; import model.service.UserBeanService; @WebServlet( urlPatterns={"/pages/customer.controller"} ) public class CustomerServlet extends HttpServlet { private SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd"); private UserBeanService service; @Override public void init() throws ServletException { service = new UserBeanService( new UserBeanDAOHibernate(HibernateUtil.getSessionFactory())); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收資料 request.setCharacterEncoding("UTF-8"); String temp1 = request.getParameter("id"); System.out.println("temp1:"+temp1); String user_Name = request.getParameter("user_Name"); String password = request.getParameter("password"); String email = request.getParameter("email"); String address = request.getParameter("address"); System.out.println("address"+address); String temp2 = request.getParameter("birthday"); String prod_name= request.getParameter("prod_name"); String tel = request.getParameter("tel"); String mobile = request.getParameter("mobile"); String temp3 = request.getParameter("style"); System.out.println("style"+temp3); String brand_desc = request.getParameter("brand_desc"); System.out.println("brand_desc"+brand_desc); String prodaction = request.getParameter("prodaction"); //驗證資料 Map<String, String> errors = new HashMap<String, String>(); request.setAttribute("error", errors); if(prodaction!=null) { if(prodaction.equals("Insert") || prodaction.equals("Update") || prodaction.equals("Delete")) { if(temp1==null || temp1.length()==0) { errors.put("id", "Please enter Id for "+prodaction); } } } //轉換資料 int id = 0; if(temp1!=null && temp1.length()!=0) { try { id = Integer.parseInt(temp1); } catch (NumberFormatException e) { e.printStackTrace(); errors.put("id", "Id must be an integer"); } } int style = 0; if(temp3!=null && temp3.length()!=0) { try { style = Integer.parseInt(temp3); } catch (NumberFormatException e) { e.printStackTrace(); errors.put("style", "style must be an integer"); } } java.util.Date birthday = null; if(temp2!=null && temp2.length()!=0) { try { birthday = sFormat.parse(temp2); } catch (ParseException e) { e.printStackTrace(); errors.put("make", "Make must be a date of YYYY-MM-DD"); } } if(errors!=null && !errors.isEmpty()) { request.getRequestDispatcher( "/pages/Register.jsp").forward(request, response); return; } //呼叫Model UserBean bean = new UserBean(); bean.setId(id); bean.setUser_Name(user_Name); bean.setPassword(password); bean.setEmail(email); bean.setAddress(address); bean.setBirthday(birthday); bean.setProd_name(prod_name); bean.setTel(tel); bean.setMobile(mobile); bean.setStyle(style); bean.setBrand_desc(brand_desc); System.out.println("Insert :" +prodaction); //根據Model執行結果導向View if(prodaction!=null && prodaction.equals("Select")) { List<UserBean> result = service.select( ); // ProductBean result = service.select(bean); request.setAttribute("select", result); request.getRequestDispatcher( "/pages/display.jsp").forward(request, response); } else if(prodaction!=null && prodaction.equals("Insert")) { UserBean result = service.insert(bean); System.out.println("Insert"+result); if(result==null) { errors.put("action", "Insert fail"); } else { request.setAttribute("insert", result); } request.getRequestDispatcher( "/pages/Register.jsp").forward(request, response); } else if(prodaction!=null && prodaction.equals("Update")) { UserBean result = service.update(bean); if(result==null) { errors.put("action", "Update fail"); } else { request.setAttribute("update", result); } request.getRequestDispatcher( "/pages/Register.jsp").forward(request, response); } else if(prodaction!=null && prodaction.equals("Delete")) { boolean result = service.delete(bean.getId()); System.out.println("delete"+result); if(!result) { request.setAttribute("delete", 0); } else { request.setAttribute("delete", 1); } request.getRequestDispatcher( "/pages/Register.jsp").forward(request, response); } else { errors.put("action", "Unknown Action:"+prodaction); request.getRequestDispatcher( "/pages/Register.jsp").forward(request, response); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
package com.biz.servlet; import com.biz.service.StudentService; import org.omg.CORBA.Request; 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 java.io.IOException; /** * 删除学生 * Created by Administrator on 2017/4/18. */ @WebServlet("/delete") public class DeleteServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); StudentService studentService = new StudentService(); String id = request.getParameter("id"); studentService.deleteStudent(id); request.getRequestDispatcher("/studentlist?cur_page=1").forward(request, response); } }
package com.gasparetti.salestaxes.services; public interface Service { }
package lesson11.lesson; public class GenericException<T> /*extends Exception*/{ }
/* * 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 Business.StructuralHealthMonitor; import java.util.ArrayList; /** * * @author User */ public class StructuralHealthHistory { private ArrayList<SensorData> buildingHealthData; public StructuralHealthHistory(){ buildingHealthData=new ArrayList<>(); } /** * @return the buildingHealthData */ public ArrayList<SensorData> getBuildingHealthData() { return buildingHealthData; } /** * @param buildingHealthData the buildingHealthData to set */ public void setBuildingHealthData(ArrayList<SensorData> buildingHealthData) { this.buildingHealthData = buildingHealthData; } public SensorData addValue(){ SensorData shv=new SensorData(); buildingHealthData.add(shv); return shv; } }
/* * (C) Copyright IBM Corp. 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.ibm.cloud.cloudant.v1.model; import java.util.ArrayList; import java.util.List; import com.ibm.cloud.sdk.core.service.model.GenericModel; /** * The postAllDocsQueries options. */ public class PostAllDocsQueriesOptions extends GenericModel { protected String db; protected List<AllDocsQuery> queries; /** * Builder. */ public static class Builder { private String db; private List<AllDocsQuery> queries; private Builder(PostAllDocsQueriesOptions postAllDocsQueriesOptions) { this.db = postAllDocsQueriesOptions.db; this.queries = postAllDocsQueriesOptions.queries; } /** * Instantiates a new builder. */ public Builder() { } /** * Instantiates a new builder with required properties. * * @param db the db * @param queries the queries */ public Builder(String db, List<AllDocsQuery> queries) { this.db = db; this.queries = queries; } /** * Builds a PostAllDocsQueriesOptions. * * @return the new PostAllDocsQueriesOptions instance */ public PostAllDocsQueriesOptions build() { return new PostAllDocsQueriesOptions(this); } /** * Adds an queries to queries. * * @param queries the new queries * @return the PostAllDocsQueriesOptions builder */ public Builder addQueries(AllDocsQuery queries) { com.ibm.cloud.sdk.core.util.Validator.notNull(queries, "queries cannot be null"); if (this.queries == null) { this.queries = new ArrayList<AllDocsQuery>(); } this.queries.add(queries); return this; } /** * Set the db. * * @param db the db * @return the PostAllDocsQueriesOptions builder */ public Builder db(String db) { this.db = db; return this; } /** * Set the queries. * Existing queries will be replaced. * * @param queries the queries * @return the PostAllDocsQueriesOptions builder */ public Builder queries(List<AllDocsQuery> queries) { this.queries = queries; return this; } } protected PostAllDocsQueriesOptions(Builder builder) { com.ibm.cloud.sdk.core.util.Validator.notEmpty(builder.db, "db cannot be empty"); com.ibm.cloud.sdk.core.util.Validator.notNull(builder.queries, "queries cannot be null"); db = builder.db; queries = builder.queries; } /** * New builder. * * @return a PostAllDocsQueriesOptions builder */ public Builder newBuilder() { return new Builder(this); } /** * Gets the db. * * Path parameter to specify the database name. * * @return the db */ public String db() { return db; } /** * Gets the queries. * * An array of query objects with fields for the parameters of each individual view query to be executed. The field * names and their meaning are the same as the query parameters of a regular `/_all_docs` request. * * @return the queries */ public List<AllDocsQuery> queries() { return queries; } }
package vistas; import juego.Escenario; import ar.uba.fi.algo3.titiritero.vista.Imagen; /* * Vista del escenario (el fondo de la pantalla de juego) */ public class VistaEscenario extends Imagen { public VistaEscenario() { this.setPosicionable(Escenario.getInstance()); this.setNombreArchivoImagen("../images/agua/aguaGrande.jpg"); } }
package helloworld; import javax.enterprise.context.RequestScoped; import javax.inject.Named; import java.io.Serializable; @Named (value="helloworld") @RequestScoped public class MyBean implements Serializable { public String getHello() { return "Hello world from MyBean"; } }
package org.bellatrix.admin; import java.util.HashMap; import org.bellatrix.data.TransferTypes; import org.bellatrix.process.BaseRepository; import org.mule.module.http.internal.ParameterMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class TransferTypeDetail { @Autowired private BaseRepository baseRepository; public HashMap<String, String> getTransferTypeDetail(ParameterMap map) { Integer tid = Integer.valueOf(map.get("id")); HashMap<String, String> tmap = new HashMap<String, String>(); TransferTypes ttype = baseRepository.getTransferTypeRepository().findTransferTypeByID(tid); tmap.put("name", ttype.getName()); tmap.put("description", ttype.getDescription()); tmap.put("min", ttype.getMinAmount().toPlainString()); tmap.put("max", ttype.getMaxAmount().toPlainString()); return tmap; } }
import java.util.Scanner; public class week07 { public static void main(String[] args) { int s = 0; int b = 0; int c = 0; System.out.println("최대공약수 & 최소공배수 구하기"); Scanner sc = new Scanner(System.in); System.out.print("숫자 1 입력 : "); int i = sc.nextInt(); System.out.print("숫자 2 입력 : "); int j = sc.nextInt(); if(i > j) { for (int k = 2; k < i; k++) { if(i % k == 0 && j % k == 0) { c = (i*j)/k; System.out.println(String.format("최대공약수 : %d", k)); System.out.println(String.format("최소공배수 : %d", c)); } } } else { for (int k = 2; k < j; k++) { if(i % k == 0 && j % k == 0) { c = (i*j)/k; System.out.println(String.format("최대공약수 : %d", k)); System.out.println(String.format("최소공배수 : %d", c)); } } } } }
/* * SelectFromAvailableDialog */ package net.maizegenetics.gui; import net.maizegenetics.util.BitSet; import net.maizegenetics.util.OpenBitSet; import javax.swing.*; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import java.awt.*; import java.awt.event.ActionEvent; import java.util.Arrays; /** * * @author terry */ public class SelectFromAvailableDialog extends JDialog { private final static int LIST_ROW_COUNT = 20; private JList<String> myAvailable; private JList<String> mySelected; private AbstractAvailableListModel myAvailableListModel; private SelectedListModel mySelectedListModel; private boolean myIsCanceled = false; private boolean myIsCaptureSelected = true; public SelectFromAvailableDialog(Frame frame, String title, AbstractAvailableListModel availableModel) { super(frame, true); myAvailableListModel = availableModel; myAvailable = new JList(myAvailableListModel); myAvailable.setPrototypeCellValue("XXXXXXXXXXXXXXXXXXXX"); mySelectedListModel = new SelectedListModel(); mySelected = new JList(mySelectedListModel); mySelected.setPrototypeCellValue("XXXXXXXXXXXXXXXXXXXX"); setTitle(title); setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); setUndecorated(false); getRootPane().setWindowDecorationStyle(JRootPane.NONE); Container contentPane = getContentPane(); BoxLayout layout = new BoxLayout(contentPane, BoxLayout.Y_AXIS); contentPane.setLayout(layout); JPanel whole = new JPanel(new BorderLayout()); whole.add(getMain(), BorderLayout.CENTER); whole.add(getBottomPanel(), BorderLayout.SOUTH); contentPane.add(whole); pack(); validate(); setResizable(true); } private JPanel getMain() { JPanel result = new JPanel(); BoxLayout layout = new BoxLayout(result, BoxLayout.X_AXIS); result.setLayout(layout); result.add(Box.createRigidArea(new Dimension(15, 1))); JPanel available = getLabeledListWSearch("Available", myAvailable); result.add(available); result.add(Box.createRigidArea(new Dimension(15, 1))); result.add(getAddButton()); result.add(Box.createRigidArea(new Dimension(15, 1))); JPanel selected = getLabeledList("Selected", mySelected); result.add(selected); result.add(Box.createRigidArea(new Dimension(15, 1))); return result; } private JPanel getLabeledList(String label, JList list) { JPanel result = new JPanel(); result.setLayout(new BorderLayout()); result.setPreferredSize(new Dimension(150, 200)); result.add(new JLabel(label), BorderLayout.NORTH); list.setVisibleRowCount(LIST_ROW_COUNT); list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); JScrollPane scrollPane = new JScrollPane(list); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); result.add(scrollPane, BorderLayout.CENTER); return result; } private JPanel getLabeledListWSearch(String label, JList list) { JPanel result = new JPanel(); result.setLayout(new BorderLayout()); result.setPreferredSize(new Dimension(150, 200)); result.add(new JLabel(label), BorderLayout.NORTH); JTextField search = new JTextField(); CaretListener caret = new CaretListener() { @Override public void caretUpdate(CaretEvent e) { String text = ((JTextField) e.getSource()).getText(); myAvailableListModel.setShown(text); } }; search.addCaretListener(caret); result.add(search, BorderLayout.SOUTH); list.setVisibleRowCount(LIST_ROW_COUNT); list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); JScrollPane scrollPane = new JScrollPane(list); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); result.add(scrollPane, BorderLayout.CENTER); return result; } private JButton getAddButton() { JButton result = new JButton("Add ->"); result.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { int[] selected = myAvailable.getSelectedIndices(); selected = myAvailableListModel.translateToRealIndices(selected); for (int i = 0, n = selected.length; i < n; i++) { mySelectedListModel.add(selected[i]); } } }); return result; } private JPanel getBottomPanel() { JPanel result = new JPanel(new FlowLayout()); result.add(getSelectedButton()); result.add(Box.createRigidArea(new Dimension(15, 1))); result.add(getUnselectedButton()); result.add(Box.createRigidArea(new Dimension(15, 1))); result.add(getRemoveButton()); result.add(Box.createRigidArea(new Dimension(15, 1))); result.add(getCancelButton()); return result; } private JButton getSelectedButton() { JButton okButton = new JButton("Capture Selected"); okButton.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { setVisible(false); myIsCanceled = false; myIsCaptureSelected = true; } }); return okButton; } private JButton getUnselectedButton() { JButton okButton = new JButton("Capture Unselected"); okButton.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { setVisible(false); myIsCanceled = false; myIsCaptureSelected = false; } }); return okButton; } private JButton getCancelButton() { JButton okButton = new JButton("Cancel"); okButton.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { setVisible(false); myIsCanceled = true; } }); return okButton; } private JButton getRemoveButton() { JButton result = new JButton("Remove"); result.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { int[] indices = mySelected.getSelectedIndices(); Arrays.sort(indices); for (int i = indices.length - 1; i >= 0; i--) { mySelectedListModel.remove(indices[i]); mySelected.clearSelection(); } } }); return result; } public boolean isCanceled() { return myIsCanceled; } public int[] getDesiredIndices() { if (myIsCaptureSelected) { return mySelectedListModel.getBitSet().getIndicesOfSetBits(); } else { BitSet temp = mySelectedListModel.getBitSet(); temp.flip(0, myAvailableListModel.getRealSize()); return temp.getIndicesOfSetBits(); } } public class SelectedListModel extends AbstractListModel<String> { private BitSet mySelectedIndices; public SelectedListModel() { mySelectedIndices = new OpenBitSet(myAvailableListModel.getRealSize()); } @Override public int getSize() { return (int) mySelectedIndices.cardinality(); } @Override public String getElementAt(int index) { return myAvailableListModel.getRealElementAt(mySelectedIndices.indexOfNthSetBit(index + 1)); } public void add(int index) { mySelectedIndices.fastSet(index); fireContentsChanged(this, 0, getSize() - 1); } public void remove(int index) { mySelectedIndices.fastClear(mySelectedIndices.indexOfNthSetBit(index + 1)); fireContentsChanged(this, 0, getSize() - 1); } public BitSet getBitSet() { return mySelectedIndices; } } }
package com.GestiondesClub.services; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.GestiondesClub.dao.TypeClubRepository; import com.GestiondesClub.entities.TypeClub; @Service public class TypeClubService { @Autowired private TypeClubRepository typeRepo; public List<TypeClub> getAllType() { return typeRepo.findAll(); } public Optional<TypeClub> getType(Long id) { return typeRepo.findById(id); } public TypeClub save(TypeClub type) { return typeRepo.save(type); } public TypeClub updateClub(TypeClub type) { return typeRepo.save(type); } public boolean delete(long id) { typeRepo.deleteById(id); return true; } }
/** * */ package com.imooc.security.config; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import io.prometheus.client.Counter; import io.prometheus.client.Summary; /** * @author jojo * */ @Component public class PrometheusMetricsInterceptor extends HandlerInterceptorAdapter { @Autowired private Counter requestCounter; @Autowired private Summary requestLatency; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { request.setAttribute("startTime", new Date().getTime()); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { String service = request.getRequestURI(); requestCounter.labels(service, request.getMethod(), String.valueOf(response.getStatus())) .inc(); long duration = new Date().getTime() - (Long)request.getAttribute("startTime"); requestLatency.labels(service, request.getMethod(), String.valueOf(response.getStatus())) .observe(duration); } }
package com.blackflagbin.kcommondemowithjava.common.entity.net; import com.blackflagbin.kcommon.entity.net.IHttpResultEntity; import org.jetbrains.annotations.NotNull; /** * Created by blackflagbin on 2018/3/25. */ public class HttpResultEntity<T> implements IHttpResultEntity<T> { public boolean error; public int code; public String message; public T results; @Override public boolean isSuccess() { return !error; } @Override public int getErrorCode() { return 0; } @NotNull @Override public String getErrorMessage() { return message; } @Override public T getResult() { return results; } }