text
stringlengths
10
2.72M
/** * * @author jotaele */ package GUI; import java.util.ArrayList; import napakalaki.BadConsequence; import napakalaki.TreasureKind; public class BadConsequenceView extends javax.swing.JPanel { public BadConsequence badConsequenceModel; private String KindsToString(ArrayList<TreasureKind> a) { String out = " "; for (TreasureKind kind : a) { out += kind.toString(); out += " "; } return out; } void setBadConsequence(BadConsequence bc) { badConsequenceModel = bc; LText.setText(badConsequenceModel.getText()); //LNiveles.setText(Integer.toString(badConsequenceModel.getLevels())); //Lnvisibles.setText(Integer.toString(badConsequenceModel.getnVisible())); //Lnocultos.setText(Integer.toString(badConsequenceModel.getnHidden())); //LDeath.setText(Boolean.toString(badConsequenceModel.getDeath())); //LVisibleKind.setText( KindsToString( badConsequenceModel.getSpecificVisibleTreasures() ) ); //LOcultoKind.setText( KindsToString( badConsequenceModel.getSpecificVisibleTreasures() ) ); repaint(); } /** * Creates new form BadConsequenceView */ public BadConsequenceView() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { LText = new javax.swing.JLabel(); setLayout(null); LText.setFont(new java.awt.Font("Ubuntu", 0, 11)); // NOI18N LText.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); LText.setText("Texto Mal Rollo"); add(LText); LText.setBounds(10, 30, 440, 14); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel LText; // End of variables declaration//GEN-END:variables }
package presentation.customer.view; import businesslogic.creditbl.Credit; import businesslogicservice.creditblservice.CreditBLservice; import javafx.fxml.FXML; import javafx.scene.control.Label; import util.CustomerType; import vo.CustomerVO; /** * Created by 段梦洋 on 2016/11/28. */ public class CustomerInfoController { private presentation.customer.MainAPP mainAPP; private CustomerVO customerVO; @FXML private Label usernameField; @FXML private Label trueNameField; @FXML private Label customerTypeField; @FXML private Label idtentifyField; @FXML private Label idtentifyContextField; @FXML private Label contactField; @FXML private Label numCreditField; public void setMainAPP(presentation.customer.MainAPP mainAPP){ this.mainAPP=mainAPP; setUsernameField(); setTrueNameField(); setCustomerTypeField(); setIdtentifyContextField(); setIdtentifyField(); setContactField(); setNumCreditField(); } private void setUsernameField(){ usernameField.setText(customerVO.getUserName()); } private void setTrueNameField(){ trueNameField.setText(customerVO.getCustomerName()); } private void setCustomerTypeField(){ customerTypeField.setText(String.valueOf(customerVO.getCustomerType())); } private void setIdtentifyField(){ if(customerVO.getCustomerType().equals(CustomerType.PERSONAL)) idtentifyField.setText("生日"); else if(customerVO.getCustomerType().equals(CustomerType.COMPANY)) idtentifyField.setText("企业名"); } private void setIdtentifyContextField(){ idtentifyContextField.setText(customerVO.getUniqueInformation()); } private void setContactField(){ contactField.setText(customerVO.getPhoneNumber()); } private void setNumCreditField(){ CreditBLservice creditBLservice=new Credit(customerVO.getUserName()); numCreditField.setText(String.valueOf(creditBLservice.getNumCredit(customerVO.getUserName()))); } @FXML private void setDetailedCreditButton(){ mainAPP.showDetailedCreditField(customerVO); } @FXML private void setModifyButton(){ mainAPP.showCustomerInfoModifyView(customerVO); } public void setCustomerVO(CustomerVO customerVO) { this.customerVO=customerVO; } }
package io.chark.food.domain.article.photo; import io.chark.food.domain.BaseRepository; import org.springframework.stereotype.Repository; @Repository public interface ArticlePhotoRepository extends BaseRepository<ArticlePhoto> { }
package ch04; public class CalculatorApp { public static void main(String[] args) { Calculator c = new Calculator(); int a1 = c.add(10, 5); a1 = c.multi(a1, 20); a1 = c.divid(a1, 5); a1 = c.minus(a1, 100); System.out.println(a1); } }
package pers.mine.scratchpad.base.singleton; import static org.junit.Assert.*; import org.junit.Test; import pers.mine.scratchpad.singleton.EnumSingleton; public class EnumSingletonTest { /** * 验证枚举单例模式并不是懒加载 */ @Test public void test() { EnumSingleton.test(); System.out.println(EnumSingleton.instance); } }
package com.fhsoft.model; /** * @ClassName:com.fhsoft.model.Product * @Description: * * @Author:liyi * @Date:2015年11月6日下午2:45:54 * */ public class Product { private int id; private String name; private String propversion; private int subject; private String zsd; private String tx; private String nd; private String status; private int qstCount; private String created; private Integer creatorId; private String creator; private String lastmodified; private Integer lastmodifierId; private String lastmodifier; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPropversion() { return propversion; } public void setPropversion(String propversion) { this.propversion = propversion; } public int getSubject() { return subject; } public void setSubject(int subject) { this.subject = subject; } public String getZsd() { return zsd; } public void setZsd(String zsd) { this.zsd = zsd; } public String getTx() { return tx; } public void setTx(String tx) { this.tx = tx; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getQstCount() { return qstCount; } public void setQstCount(int qstCount) { this.qstCount = qstCount; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } public Integer getCreatorId() { return creatorId; } public void setCreatorId(Integer creatorId) { this.creatorId = creatorId; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public String getLastmodified() { return lastmodified; } public void setLastmodified(String lastmodified) { this.lastmodified = lastmodified; } public Integer getLastmodifierId() { return lastmodifierId; } public void setLastmodifierId(Integer lastmodifierId) { this.lastmodifierId = lastmodifierId; } public String getLastmodifier() { return lastmodifier; } public void setLastmodifier(String lastmodifier) { this.lastmodifier = lastmodifier; } public String getNd() { return nd; } public void setNd(String nd) { this.nd = nd; } }
package org.apidesign.gate.timing.shared; import static org.junit.Assert.assertEquals; import org.junit.Test; public class EventsTest { @Test public void shortWhenShowsCents() { Event ev1 = new Event().withWhen(1488855865759L).withType(Events.START); assertEquals("04'25:75", ev1.getShortWhen()); } @Test public void shortWhenShowsCents2() { Event ev2 = new Event().withWhen(1488855865973L).withType(Events.START); assertEquals("04'25:97", ev2.getShortWhen()); } @Test public void shortWhenShowsCents3() { Event ev3 = new Event().withWhen(1488855866759L).withType(Events.START); assertEquals("04'26:75", ev3.getShortWhen()); } }
package com.youdao.dic.comber; public interface IWordComber { void start(); }
package com.dambroski.services; import java.util.Optional; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort.Direction; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import com.dambroski.domain.Cidade; import com.dambroski.domain.Cliente; import com.dambroski.domain.Endereco; import com.dambroski.domain.dto.ClienteDTO; import com.dambroski.domain.dto.ClienteInsertDTO; import com.dambroski.domain.enuns.Perfil; import com.dambroski.repositories.ClienteRepository; import com.dambroski.repositories.EnderecoRepository; import com.dambroski.security.UserSS; import com.dambroski.services.exceptions.AuthorizationException; import com.dambroski.services.exceptions.DataIntegrityException; import com.dambroski.services.exceptions.EntitieNotFoundException; @Service public class ClienteService { @Autowired private ClienteRepository clienteRepository; @Autowired private EnderecoRepository enderecoRepository; @Autowired private BCryptPasswordEncoder BPC; public Cliente findById(Integer id) { UserSS user = UserService.authenticated(); if(user == null || !user.hasRole(Perfil.ADMIN) && !id.equals(user.getId())) { throw new AuthorizationException("Acesso negado"); } Optional<Cliente> cli = clienteRepository.findById(id); return cli.orElseThrow(() -> new EntitieNotFoundException("Cliente não encontrado")); } public Page<ClienteDTO> findAll(Integer page, Integer size, String direction, String orderBy) { Pageable pageble = PageRequest.of(page, size, Direction.fromString(direction), orderBy); Page<Cliente> clientes = clienteRepository.findAll(pageble); Page<ClienteDTO> clientesDTO = clientes.map(obj -> new ClienteDTO(obj)); return clientesDTO; } public void update(Integer id, ClienteDTO clienteDTO) { Cliente cliente = findById(id); if (clienteDTO.getNome() != null) { cliente.setNome(clienteDTO.getNome()); } if (clienteDTO.getEmail() != null) { cliente.setEmail(clienteDTO.getEmail()); } clienteRepository.save(cliente); } @Transactional public Cliente insert(ClienteInsertDTO clienteInsertDTO) { clienteInsertDTO.setSenha(BPC.encode(clienteInsertDTO.getSenha())); Cliente cliente = new Cliente(clienteInsertDTO); if (clienteInsertDTO.getTelefone1() != null) { cliente.getTelefones().add(clienteInsertDTO.getTelefone1()); } if (clienteInsertDTO.getTelefone2() != null) { cliente.getTelefones().add(clienteInsertDTO.getTelefone2()); } if (clienteInsertDTO.getTelefone3() != null) { cliente.getTelefones().add(clienteInsertDTO.getTelefone3()); } cliente = clienteRepository.save(cliente); Cidade cidade = new Cidade(); cidade.setId(clienteInsertDTO.getCidadeId()); Endereco endereco = new Endereco(clienteInsertDTO.getLogradouro(), clienteInsertDTO.getNumero(), clienteInsertDTO.getComplemento(), clienteInsertDTO.getBairro(), clienteInsertDTO.getCep(), cliente, cidade); endereco = enderecoRepository.save(endereco); cliente.getEnderecos().add(endereco); return cliente; } public void delete(Integer id) { Cliente cliente = findById(id); try { clienteRepository.delete(cliente); } catch (DataIntegrityViolationException e) { throw new DataIntegrityException("Cliente vinculado a pedidos não pode ser deletado"); } } }
package iit.android.language; import iit.android.swarachakra.KeyAttr; import java.util.ArrayList; import java.util.HashMap; public class Language { public String name; public String symbol; public int nKeys; public String[] defaultChakra; public ArrayList<KeyAttr> myKey; public boolean halantExists; public int halantEnd; public HashMap<Integer, KeyAttr> hashThis(){ return null; } }
package com.coder.model; // Generated Jan 23, 2020 8:11:18 PM by Hibernate Tools 5.0.6.Final import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * IngredientJoinItemResturant generated by hbm2java */ @Entity @Table(name = "ingredient_join_item_resturant", catalog = "traveldb") public class IngredientJoinItemResturant implements java.io.Serializable { private IngredientJoinItemResturantId id; private Ingredient ingredient; private ItemJoinStore itemJoinStore; private double addionalPrice; public IngredientJoinItemResturant() { } public IngredientJoinItemResturant(IngredientJoinItemResturantId id, Ingredient ingredient, ItemJoinStore itemJoinStore, double addionalPrice) { this.id = id; this.ingredient = ingredient; this.itemJoinStore = itemJoinStore; this.addionalPrice = addionalPrice; } @EmbeddedId @AttributeOverrides({ @AttributeOverride(name = "ingredientId", column = @Column(name = "ingredient_id", nullable = false)), @AttributeOverride(name = "itemJoinStoreId", column = @Column(name = "item_join_store_id", nullable = false)) }) public IngredientJoinItemResturantId getId() { return this.id; } public void setId(IngredientJoinItemResturantId id) { this.id = id; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "ingredient_id", nullable = false, insertable = false, updatable = false) public Ingredient getIngredient() { return this.ingredient; } public void setIngredient(Ingredient ingredient) { this.ingredient = ingredient; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "item_join_store_id", nullable = false, insertable = false, updatable = false) public ItemJoinStore getItemJoinStore() { return this.itemJoinStore; } public void setItemJoinStore(ItemJoinStore itemJoinStore) { this.itemJoinStore = itemJoinStore; } @Column(name = "addional_price", nullable = false, precision = 22, scale = 0) public double getAddionalPrice() { return this.addionalPrice; } public void setAddionalPrice(double addionalPrice) { this.addionalPrice = addionalPrice; } }
package com.alex.patterns.abstractfactory.example.fordfactory; import com.alex.patterns.abstractfactory.example.Jeep; /* this is a specific implementation of car's interface */ public class FordJeep implements Jeep { }
package io.github.satr.aws.lambda.bookstore.test; // Copyright © 2020, github.com/satr, MIT License import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded; import com.amazonaws.services.dynamodbv2.local.shared.access.AmazonDynamoDBLocal; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.satr.aws.lambda.bookstore.constants.IntentSlotName; import io.github.satr.aws.lambda.bookstore.entity.Book; import io.github.satr.aws.lambda.bookstore.repositories.database.tableentity.BasketItem; import io.github.satr.aws.lambda.bookstore.repositories.database.tableentity.BookSearchResultItem; import io.github.satr.aws.lambda.bookstore.request.Request; import io.github.satr.aws.lambda.bookstore.request.RequestFactory; import java.io.File; import java.io.IOException; import java.util.*; public final class ObjectMother { private static ObjectMapper jsonObjectMapper; private static Random random = new Random(); public static Map<String, Object> createMapFromJson(String jsonFileName){ ClassLoader classLoader = ObjectMother.class.getClassLoader(); File jsonFile = new File(classLoader.getResource(jsonFileName).getFile()); if(!jsonFile.exists()) { System.out.println("File not found: " + jsonFileName); return new HashMap<>(); } jsonObjectMapper = new ObjectMapper(); try { Map<String, Object> dataMap = jsonObjectMapper.readValue(jsonFile, new TypeReference<Map<String, Object>>() { }); return dataMap; } catch (IOException e) { e.printStackTrace(); return new HashMap<>(); } } public static Request createLexRequestForOrderBook(String bookTitle, String bookAuthor) { Request request = new Request(); request.getSlots().put(IntentSlotName.BookTitle, bookTitle); request.getSlots().put(IntentSlotName.BookAuthor, bookAuthor); return request; } public static Request createLexRequestForSelectBook(String chooseFromListAction, String itemNumber, String positionInSequence) { Request request = new Request(); request.getSlots().put(IntentSlotName.ItemNumber, itemNumber); request.getSlots().put(IntentSlotName.PositionInSequence, positionInSequence); request.getSlots().put(IntentSlotName.ChooseFromListAction, chooseFromListAction); return request; } public static Request createLexRequestFromJson(String jsonFileName) { return RequestFactory.createFrom(ObjectMother.createMapFromJson(jsonFileName)); } public static String getRandomString() { return UUID.randomUUID().toString(); } public static List<Book> getRandomBookList(int amount) { LinkedList<Book> books = new LinkedList<>(); for (int i = 0; i < amount; i++) books.add(getRandomBook()); return books; } public static Book getRandomBook() { return getRandomlyPopulatedBook(new Book()); } public static List<BasketItem> getRandomBasketItemList(int amount) { LinkedList<BasketItem> books = new LinkedList<>(); for (int i = 0; i < amount; i++) books.add(getRandomBasketItem()); return books; } public static List<BookSearchResultItem> getRandomBookSearchResultItemList(int amount) { LinkedList<BookSearchResultItem> books = new LinkedList<>(); for (int i = 0; i < amount; i++) books.add(getRandomBookSearchResultItem()); return books; } public static BasketItem getRandomBasketItem() { return (BasketItem) getRandomlyPopulatedBook(new BasketItem()); } public static BookSearchResultItem getRandomBookSearchResultItem() { return (BookSearchResultItem) getRandomlyPopulatedBook(new BookSearchResultItem()); } private static Book getRandomlyPopulatedBook(Book book) { book.setTitle("Title-" + getRandomString()); book.setAuthor("Author-" + getRandomString()); book.setIssueYear(getRandomInt(1900, 2020)); book.setPrice(getRandomFloat(1.5f, 50.9f)); return book; } public static int getRandomInt(int min, int max) { return min + random.nextInt(max - min); } public static float getRandomFloat(float min, float max) { int minFloat = (int)(min * 100); int maxFloat = (int)(max * 100); return ((float)(minFloat + random.nextInt(maxFloat - minFloat)))/100; } public static AmazonDynamoDB createInMemoryDb() { AmazonDynamoDB dynamodb = null; try { // Create an in-memory and in-process instance of DynamoDB Local AmazonDynamoDBLocal amazonDynamoDBLocal = DynamoDBEmbedded.create(); dynamodb = amazonDynamoDBLocal.amazonDynamoDB(); return dynamodb; } catch (Exception e){ if(dynamodb != null) dynamodb.shutdown();// Shutdown the thread pools in DynamoDB Local / Embedded } return dynamodb; } }
package com.arthur.bishi.tengxun0822; import java.util.ArrayList; import java.util.Arrays; /** * @description: * @author: arthurji * @date: 2021/8/22 20:23 * @modifiedBy: * @version: 1.0 */ public class No1 { public static class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public ListNode[] solve (int m, ListNode a) { // write code here ArrayList<ListNode> arrayLists[] = new ArrayList[m]; for (int i = 0; i < arrayLists.length; i++) { arrayLists[i] = new ArrayList<ListNode>(); } while (a != null) { arrayLists[a.val % m].add(a); a = a.next; } for (ArrayList<ListNode> arrayList : arrayLists) { arrayList.sort(((o1, o2) -> { return o2.val - o1.val; })); } ListNode[] ans = new ListNode[m]; ListNode pre = null; for (int i = 0; i < arrayLists.length; i++) { for (ListNode listNode : arrayLists[i]) { listNode.next = pre; pre = listNode; } ans[i] = pre; pre = null; } return ans; } public static void main(String[] args) { ListNode listNode = new ListNode(0); ListNode listNode1 = new ListNode(1); ListNode listNode2 = new ListNode(3); ListNode listNode3 = new ListNode(4); ListNode listNode4 = new ListNode(5); ListNode listNode5 = new ListNode(11); ListNode listNode6 = new ListNode(6); listNode.next = listNode1; listNode1.next = listNode2; listNode2.next = listNode3; listNode3.next = listNode4; listNode4.next = listNode5; listNode5.next = listNode6; new No1().solve(5, listNode); } }
package com.toda.consultant.model; import android.app.Activity; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.TextUtils; import com.toda.consultant.util.GsonUtil; import com.toda.consultant.util.HouseUtil; import com.toda.consultant.util.LogUtils; import com.toda.consultant.util.StringUtils; import org.json.JSONObject; import java.io.IOException; import java.lang.reflect.Type; import java.net.ConnectException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by Zhao Haibin on 2016/1/27. */ public class HouseHandler extends BaseHandler implements Callback { private static final int REFRESH = 0x001; private Type type; protected static Handler handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { switch (msg.what) { case REFRESH: Map map = (Map) msg.obj; ResponseListener listener = (ResponseListener) map.get("listener"); int tag = (int) map.get("tag"); ResultData data = (ResultData) map.get("data"); Call call= (Call) map.get("call"); listener.onRefresh(call,tag,data); } } }; public HouseHandler(Context context, Type type) { super(context); this.type = type; } @Override public void onFailure(Call call, IOException e) { LogUtils.e(e); if (isCancel()) { dissDialog(); return; } ResultData data = new ResultData(); data.setCode(getErrCode(e)); onData(data); } @Override public void onResponse(Call call, Response response) throws IOException { if (isCancel()) { dissDialog(); return; } String resultStr = response.body().string(); LogUtils.e("加密数据="+resultStr); // String realResult= AESCrypt.getInstance().decrypt(resultStr); ResultData data = new ResultData(); try { // if(StringUtils.isEmpty(resultStr)){ // showSessionErrDialog(); // return; // } JSONObject resJson = new JSONObject(resultStr); String resStr=resJson.optString("response"); // String realResult= AESCrypt.getInstance().decrypt(URLDecoder.decode(resStr,"utf-8")); // LogUtils.e("解密数据="+realResult); // JSONObject json = new JSONObject(realResult); String code = resJson.optString("errorCode"); String msg=resJson.optString("errorMsg"); if(ErrorCode.SESSION_ERR.equals(code)&&!StringUtils.isEmpty(msg)&&msg.contains("token")){ showSessionErrDialog(); return; } data.setCode(TextUtils.isEmpty(code) ? "" : code); data.setMsg(msg); if(TextUtils.isEmpty(data.getMsg())||data.getMsg().equals("null")){ data.setMsg(""); } if (type != null&&resJson.has("data")&&!resJson.getString("data").equals("[]")) { data.setData(GsonUtil.fromJson(resJson.getString("data"), type)); } } catch (Exception e) { e.printStackTrace(); data.setCode(ErrorCode.JSON_ERR); } onData(data); } protected void onData(final ResultData data) { dissDialog(); if(context==null){ return; } if((context instanceof Activity)&&((Activity) context).isFinishing()){ return; } if (listener != null) { Map map = new HashMap(); map.put("listener", listener); map.put("tag", tag); map.put("data", data); map.put("call",call); handler.sendMessage(handler.obtainMessage(REFRESH, map)); } } /*** * 获取错误码 * * @param e * @return */ public String getErrCode(Throwable e) { String code = ""; if (e instanceof SocketTimeoutException) { //服务器连接超时 code = ErrorCode.SOCKET_TIME_OUT; } else if (e instanceof UnknownHostException) { //域名解析错误 code = ErrorCode.UNKNOW_HOST_ERR; } else if (e instanceof ConnectException) { code = ErrorCode.CONNECT_ERR; } else if (e instanceof SocketException) { //网络连接失败 code = ErrorCode.CONNECT_ERR; } else { code = ErrorCode.SYSTEM_ERR; } return code; } private void showSessionErrDialog(){ handler.post(new Runnable() { @Override public void run() { HouseUtil.showLoginErrDialog(context); } }); } }
package com.rk; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; public class TableCell_ComboBox extends JFrame { JTable table; JScrollPane scroll; DefaultTableModel model; String header[] = {"Nama", "Jurusan", "Angkatan", "Lulus"}; Object data[][] = { {"Rizky Khapidsyah", "Sistem Komputer", "2009", null}, {"Muhammad Riyan", "Sistem Komputer", "2009", null}, {"Nazar Ilham", "Sistem Komputer", "2009", null}, {"Zulfikar Baharuddin", "Sistem Komputer", "2009", null}, {"Kebetulan Manusia", "Sistem Komputer", "2009", null} }; public TableCell_ComboBox() { super("ComboBox Di Dalam Tabel"); Inisialisasi_Komponen(); } private void Inisialisasi_Komponen() { aturTabel(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); } private void aturTabel() { model = new DefaultTableModel(data, header); table = new JTable(); table.setModel(model); JComboBox comboBox = new JComboBox(); comboBox.addItem("Ya"); comboBox.addItem("Tidak"); table.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(comboBox)); scroll = new JScrollPane(table); scroll.setPreferredSize(new Dimension(400, 200)); add(scroll, BorderLayout.CENTER); } }
package oo.shopping; import java.util.Scanner; public class GoldenCustomer extends SilverCustomer { String level = "金級"; float returnRate = 0.05f; public GoldenCustomer(){ } public GoldenCustomer(int amount) { this.amount = amount; } @Override public void print1() { System.out.print("客戶級別:"+level+"\t"); Scanner scanner = new Scanner(System.in); System.out.print("消費金額:"); String price = scanner.nextLine(); int p = Integer.parseInt(price); System.out.println("折扣後金額:"+(int)(p*0.9)+"\t"+"還元金:"+(int)(p*0.05)); } @Override public void print2(){ System.out.println(level+"\t"+amount+"\t"+(int)(amount*discount)+ "\t"+(int)(amount*returnRate)); } // @Override // public void printWay(){ // Scanner scanner = new Scanner(System.in); // System.out.println("請輸入您欲列印的格式(1.每一項目為一行 2.多項目為一行):"); // String way = scanner.nextLine(); // int w = Integer.parseInt(way); // if(w == 1){ // // }else{ // // } // } }
package br.com.candleanalyser.genetics.trainner; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Random; import br.com.candleanalyser.engine.CandleFactory; import br.com.candleanalyser.engine.Helper; import br.com.candleanalyser.engine.StockPeriod; import br.com.candleanalyser.genetics.GeneticAdvisor; public class GeneticTrainnerRunner { private static Random random = new Random(); public static void performTrainning(GeneticTrainner trainner, List<String> stockNames, Date fromDate, Date toDate, float percentTranningDaysForEachStock, int numberOfNewRandomAdvisors, File advisorsFile) throws IOException, ClassNotFoundException, NumberFormatException, ParseException { List<StockPeriod> stockPeriods = new ArrayList<StockPeriod>(); //distribute total days to stock periods int daysPeriod = (int)((toDate.getTime()-fromDate.getTime())/(1000*60*60*24)); int daysEachPeriod = (int)(percentTranningDaysForEachStock*daysPeriod); for (String stock : stockNames) { //define beginning date Calendar c1 = GregorianCalendar.getInstance(); c1.setTime(fromDate); int dayBegin = (int)((daysPeriod-daysEachPeriod)*random.nextFloat()); c1.add(Calendar.DAY_OF_MONTH, dayBegin); //define end date Calendar c2 = GregorianCalendar.getInstance(); c2.setTime(c1.getTime()); c2.add(Calendar.DAY_OF_YEAR, daysEachPeriod); if(c2.getTime().after(toDate)) { throw new IllegalStateException("End stock date cannot be after " + toDate); } //get stocks StockPeriod stockPeriod = CandleFactory.getStockHistoryFromYahoo(stock, c1.getTime(), c2.getTime()); stockPeriods.add(stockPeriod); } if(advisorsFile!=null) { //load advisors from disk List<GeneticAdvisor> advisors = null; try { advisors = (List<GeneticAdvisor>)Helper.loadObject(advisorsFile); } catch (Exception e) { System.out.println("Skipping advisors loading: " + e); } if(advisors!=null) { //evolve loaded advisors System.out.println("Found " + advisors.size() + " advisors in disk"); if(advisors.size()>200) { advisors = advisors.subList(0, 199); System.out.println("Too many advisors in disk. Using only 200."); } trainner.evolveAdvisors(stockPeriods, numberOfNewRandomAdvisors, advisors); } else { //evolve random advisors trainner.evolveAdvisors(stockPeriods, numberOfNewRandomAdvisors); } } else { //evolve random advisors trainner.evolveAdvisors(stockPeriods, numberOfNewRandomAdvisors); } //save advisors to disk if(advisorsFile!=null) { ArrayList<GeneticAdvisor> advisors = new ArrayList<GeneticAdvisor>(); for (AdvisorResult ar : trainner.getAdvisorResults()) { if(ar.getAdvisor() instanceof Serializable) { advisors.add(ar.getAdvisor()); } } try { Helper.saveObject(advisorsFile, advisors); } catch (Exception e) { System.out.println("Skipping advisors saving: " + e); } } } //EVOLUI CADA PAPEL // public static void performTrainning(GeneticTrainner trainner, List<String> stockNames, Date fromDate, Date toDate, int numberOfNewRandomAdvisors, File advisorsFile) throws IOException, ClassNotFoundException, NumberFormatException, ParseException { // boolean first = true; // for (String stock : stockNames) { // StockPeriod stockPeriod = CandleFactory.getStockHistoryFromYahoo(stock, fromDate, toDate); // if(first) { // if(advisorsFile!=null) { // Object obj = Helper.loadObject(advisorsFile); // trainner.evolveAdvisorResults(stockPeriod, (List<GeneticAdvisor>)obj); // } else { // trainner.evolveAdvisorResults(stockPeriod, numberOfNewRandomAdvisors); // } // } else { // trainner.evolveAdvisorResults(stockPeriod, 0); // } // } // if(advisorsFile!=null) { // ArrayList<AdvisorResult> results = new ArrayList<AdvisorResult>(trainner.getAdvisorResults()); // Helper.saveObject(advisorsFile, results); // } // } }
package com.youthlin.example.compiler.linscript.semantic; import com.youthlin.example.compiler.linscript.YourLangParserBaseListener; import org.antlr.v4.runtime.ParserRuleContext; import org.slf4j.Logger; /** * @author youthlin.chen * @date 2019-09-03 17:15 */ public class BaseListener extends YourLangParserBaseListener { protected AnnotatedTree at; BaseListener(AnnotatedTree at) { this.at = at; } protected void error(Logger log, ParserRuleContext ctx, String msg) { at.getErrorMap().put(ctx, msg); log.warn(msg); } }
/* * 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.core; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.List; import kotlin.reflect.KFunction; import kotlin.reflect.KParameter; import kotlin.reflect.jvm.ReflectJvmMapping; import org.springframework.lang.Nullable; /** * {@link ParameterNameDiscoverer} implementation which uses Kotlin's reflection facilities * for introspecting parameter names. * * <p>Compared to {@link StandardReflectionParameterNameDiscoverer}, it allows in addition to * determine interface parameter names without requiring Java 8 -parameters compiler flag. * * @author Sebastien Deleuze * @since 5.0 * @see StandardReflectionParameterNameDiscoverer * @see DefaultParameterNameDiscoverer */ public class KotlinReflectionParameterNameDiscoverer implements ParameterNameDiscoverer { @Override @Nullable public String[] getParameterNames(Method method) { if (!KotlinDetector.isKotlinType(method.getDeclaringClass())) { return null; } try { KFunction<?> function = ReflectJvmMapping.getKotlinFunction(method); return (function != null ? getParameterNames(function.getParameters()) : null); } catch (UnsupportedOperationException ex) { return null; } } @Override @Nullable public String[] getParameterNames(Constructor<?> ctor) { if (ctor.getDeclaringClass().isEnum() || !KotlinDetector.isKotlinType(ctor.getDeclaringClass())) { return null; } try { KFunction<?> function = ReflectJvmMapping.getKotlinFunction(ctor); return (function != null ? getParameterNames(function.getParameters()) : null); } catch (UnsupportedOperationException ex) { return null; } } @Nullable private String[] getParameterNames(List<KParameter> parameters) { String[] parameterNames = parameters.stream() // Extension receivers of extension methods must be included as they appear as normal method parameters in Java .filter(p -> KParameter.Kind.VALUE.equals(p.getKind()) || KParameter.Kind.EXTENSION_RECEIVER.equals(p.getKind())) // extension receivers are not explicitly named, but require a name for Java interoperability // $receiver is not a valid Kotlin identifier, but valid in Java, so it can be used here .map(p -> KParameter.Kind.EXTENSION_RECEIVER.equals(p.getKind()) ? "$receiver" : p.getName()) .toArray(String[]::new); for (String parameterName : parameterNames) { if (parameterName == null) { return null; } } return parameterNames; } }
package com.paragon.sensonic.ui.fragments.upcoming; import com.paragon.brdata.dto.ResidentsRelationRoot; public interface UpcomingNavigator { void init(); void setResidentsList(ResidentsRelationRoot relationRoot); }
package uz.pdp.lesson5task1.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.GenericGenerator; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import uz.pdp.lesson5task1.entity.enums.TurniketStatus; import javax.persistence.*; import java.sql.Timestamp; import java.util.UUID; @Data @AllArgsConstructor @NoArgsConstructor @Entity public class TurnikitHistory { @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2",strategy = "org.hibernate.id.UUIDGenerator") private UUID id; @ManyToOne private Turnikit turnikit; @Enumerated(EnumType.STRING) private TurniketStatus turniketStatus; @CreationTimestamp private Timestamp timestamp; }
package server; import java.net.MalformedURLException; import java.nio.channels.AlreadyBoundException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import dao.SelfLease; public class Coordinator { public static void main(String args[]) throws InterruptedException{ SelfLease selfLease=null; try{ //调用远程对象,注意RMI路径与接口必须与服务器配置一致 /* * 在这里得到主节点失效的消息以后,再通知其余的备节点开始选主的过程 */ System.out.println("这里是协调器!!!"); ILeaseService iLeaseService=(ILeaseService)Naming.lookup("rmi://219.228.147.113:7700/iLeaseService"); selfLease=iLeaseService.getLease();//约定的时间为6s int i=0; while(true){ iLeaseService.isFlag(); Thread.sleep(3000);//每隔3秒调用一次远程对象 System.out.println(i++); } }catch (RemoteException e) { System.out.println("创建远程对象发生异常!"); /* * 开始和其余的备节点通信,通知可以开始选主的流程,在这里可以写一个循环 */ try { //在这里休眠约定的时间 Thread.sleep(selfLease.getDuration()); System.out.println("发生异常以后,经过租约时间6s以后开始调用备节点进行选主流程"); ILeaseService iLeaseService2=(ILeaseService)Naming.lookup("rmi://219.228.147.113:6600/iLeaseService"); iLeaseService2.setFlag(true); ILeaseService iLeaseService3=(ILeaseService)Naming.lookup("rmi://219.228.147.113:6601/iLeaseService"); iLeaseService3.setFlag(true); ILeaseService iLeaseService4=(ILeaseService)Naming.lookup("rmi://219.228.147.113:6602/iLeaseService"); iLeaseService4.setFlag(true); } catch (MalformedURLException | RemoteException | NotBoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } catch (AlreadyBoundException e) { System.out.println("发生重复绑定对象异常!"); e.printStackTrace(); } catch (MalformedURLException e) { System.out.println("发生URL畸形异常!"); e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotBoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void informStandBy() { } }
package com.Carousell.android.page; import com.Carousell.android.ElementOP; import com.Carousell.android.GeneralOP; import com.Carousell.util.Log; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileBy; /** Page object for the landing page **/ public abstract class ProductPage { public static void buyNow(AppiumDriver driver) throws Exception { try { loaded(driver); //Tap buy button //If it's bought before, cancel it if (!ElementOP.isElementPresent(driver, MobileBy.xpath("//android.widget.TextView[@text='Buy Now']"),2)) { if (ElementOP.isElementPresent(driver, MobileBy.xpath("//android.widget.TextView[@text='View Offer']"),2)) { Log.info("Bought. Cancel it."); driver.findElementById("com.thecarousell.Carousell:id/button_buy").click(); driver.findElementById("com.thecarousell.Carousell:id/button_chat_left").click(); driver.findElementByXPath("//android.widget.Button[@text='Yes']").click(); driver.findElementById("com.thecarousell.Carousell:id/button_chat_offer").click(); } else { Log.info("--->Cannot find buy button. Please check"); GeneralOP.takeScreenShot(driver); throw new AssertionError("--->Fail to find buy button"); } } else { driver.findElementByXPath("//android.widget.TextView[@text='Buy Now']").click(); } OfferPage.loaded(driver); } catch(Exception e) { Log.infoTitle("--->Buy now Fails. Please check!"); GeneralOP.takeScreenShot(driver); //Log.info(e.getMessage()); throw new AssertionError("--->Buy now fails."); } } public static void checkGuide(AppiumDriver driver) throws Exception { if (ElementOP.isElementPresent(driver, MobileBy.xpath("//android.widget.TextView[@text='Make an offer to buy this item!']"),2)) { driver.findElementByXPath("//android.widget.TextView[@text='OK, Got it!']").click(); } if (ElementOP.isElementPresent(driver, MobileBy.xpath("//android.widget.TextView[@text='Got questions? Ask the seller!']"),2)) { driver.findElementByXPath("//android.widget.TextView[@text='OK, Got it!']").click(); } } public static String printProductTitle(AppiumDriver driver) { return driver.findElementById("com.thecarousell.Carousell:id/text_product_title").getText(); } public static boolean inProductPage(AppiumDriver driver) { if (ElementOP.isElementPresent(driver, MobileBy.id("com.thecarousell.Carousell:id/text_product_title"), 2)) return true; else return false; } /** Verify the product page has loaded **/ public static void loaded(AppiumDriver driver) { if (!inProductPage(driver)) { Log.infoTitle("--->Not in product page. Please check!"); GeneralOP.takeScreenShot(driver); //Log.info(e.getMessage()); throw new AssertionError("--->Go to product page fails."); } } }
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.recovery.internal.service.impl.password; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.application.common.model.User; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.event.IdentityEventException; import org.wso2.carbon.identity.governance.service.notification.NotificationChannels; import org.wso2.carbon.identity.recovery.ChallengeQuestionManager; import org.wso2.carbon.identity.recovery.IdentityRecoveryClientException; import org.wso2.carbon.identity.recovery.IdentityRecoveryConstants; import org.wso2.carbon.identity.recovery.IdentityRecoveryException; import org.wso2.carbon.identity.recovery.IdentityRecoveryServerException; import org.wso2.carbon.identity.recovery.RecoveryScenarios; import org.wso2.carbon.identity.recovery.RecoverySteps; import org.wso2.carbon.identity.recovery.bean.NotificationResponseBean; import org.wso2.carbon.identity.recovery.confirmation.ResendConfirmationManager; import org.wso2.carbon.identity.recovery.dto.PasswordRecoverDTO; import org.wso2.carbon.identity.recovery.dto.PasswordResetCodeDTO; import org.wso2.carbon.identity.recovery.dto.RecoveryChannelInfoDTO; import org.wso2.carbon.identity.recovery.dto.RecoveryInformationDTO; import org.wso2.carbon.identity.recovery.dto.ResendConfirmationDTO; import org.wso2.carbon.identity.recovery.dto.SuccessfulPasswordResetDTO; import org.wso2.carbon.identity.recovery.internal.IdentityRecoveryServiceDataHolder; import org.wso2.carbon.identity.recovery.internal.service.impl.UserAccountRecoveryManager; import org.wso2.carbon.identity.recovery.model.Property; import org.wso2.carbon.identity.recovery.model.UserRecoveryData; import org.wso2.carbon.identity.recovery.password.NotificationPasswordRecoveryManager; import org.wso2.carbon.identity.recovery.services.password.PasswordRecoveryManager; import org.wso2.carbon.identity.recovery.store.JDBCRecoveryDataStore; import org.wso2.carbon.identity.recovery.store.UserRecoveryDataStore; import org.wso2.carbon.identity.recovery.util.Utils; import org.wso2.carbon.identity.user.functionality.mgt.UserFunctionalityManager; import org.wso2.carbon.identity.user.functionality.mgt.exception.UserFunctionalityManagementException; import org.wso2.carbon.identity.user.functionality.mgt.model.FunctionalityLockStatus; import java.util.ArrayList; import java.util.Map; import java.util.UUID; /** * Class that implements the PasswordRecoveryManager. */ public class PasswordRecoveryManagerImpl implements PasswordRecoveryManager { private static final Log log = LogFactory.getLog(PasswordRecoveryManagerImpl.class); private static final boolean isSkipRecoveryWithChallengeQuestionsForInsufficientAnswersEnabled = Utils.isSkipRecoveryWithChallengeQuestionsForInsufficientAnswersEnabled(); private static final boolean isPerUserFunctionalityLockingEnabled = Utils.isPerUserFunctionalityLockingEnabled(); private static final boolean isDetailedErrorMessagesEnabled = Utils.isDetailedErrorResponseEnabled(); /** * Get the username recovery information with available verified channel details. * * @param claims User Claims * @param tenantDomain Tenant domain * @param properties Meta properties * @return RecoveryInformationDTO {@link RecoveryInformationDTO} object that contains * recovery information of a verified user * @throws IdentityRecoveryException Error while initiating password recovery */ @Override public RecoveryInformationDTO initiate(Map<String, String> claims, String tenantDomain, Map<String, String> properties) throws IdentityRecoveryException { validateTenantDomain(tenantDomain); UserAccountRecoveryManager userAccountRecoveryManager = UserAccountRecoveryManager.getInstance(); boolean isQuestionBasedRecoveryEnabled = isQuestionBasedRecoveryEnabled(tenantDomain); boolean isNotificationBasedRecoveryEnabled = isNotificationBasedRecoveryEnabled(tenantDomain); if (!isNotificationBasedRecoveryEnabled && !isQuestionBasedRecoveryEnabled) { if (log.isDebugEnabled()) { log.debug("User password recovery is not enabled for the tenant: " + tenantDomain); } throw Utils.handleClientException( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_PASSWORD_RECOVERY_NOT_ENABLED, null); } // Get recovery channel information. RecoveryChannelInfoDTO recoveryChannelInfoDTO = userAccountRecoveryManager .retrieveUserRecoveryInformation(claims, tenantDomain, RecoveryScenarios.NOTIFICATION_BASED_PW_RECOVERY, properties); RecoveryInformationDTO recoveryInformationDTO = new RecoveryInformationDTO(); String username = recoveryChannelInfoDTO.getUsername(); recoveryInformationDTO.setUsername(username); // Do not add recovery channel information if Notification based recovery is not enabled. recoveryInformationDTO.setNotificationBasedRecoveryEnabled(isNotificationBasedRecoveryEnabled); if (isNotificationBasedRecoveryEnabled) { recoveryInformationDTO.setRecoveryChannelInfoDTO(recoveryChannelInfoDTO); } if (isSkipRecoveryWithChallengeQuestionsForInsufficientAnswersEnabled) { recoveryInformationDTO.setQuestionBasedRecoveryAllowedForUser(isQuestionBasedRecoveryEnabled && isMinNoOfRecoveryQuestionsAnswered(username, tenantDomain)); } else { recoveryInformationDTO.setQuestionBasedRecoveryAllowedForUser(isQuestionBasedRecoveryEnabled); } // Check if question based password recovery is unlocked in per-user functionality locking mode. if (isPerUserFunctionalityLockingEnabled) { boolean isQuestionBasedRecoveryLocked = getFunctionalityStatusOfUser(tenantDomain, recoveryChannelInfoDTO.getUsername(), IdentityRecoveryConstants.FunctionalityTypes.FUNCTIONALITY_SECURITY_QUESTION_PW_RECOVERY .getFunctionalityIdentifier()).getLockStatus(); recoveryInformationDTO.setQuestionBasedRecoveryEnabled(!isQuestionBasedRecoveryLocked); } else { recoveryInformationDTO.setQuestionBasedRecoveryEnabled(isQuestionBasedRecoveryEnabled); } recoveryInformationDTO.setNotificationBasedRecoveryEnabled(isNotificationBasedRecoveryEnabled); return recoveryInformationDTO; } /** * Verify the recovery code and send recovery information via channel which matches the given channel id. * * @param recoveryCode RecoveryId of the user * @param channelId Channel Id of the user * @param tenantDomain Tenant Domain * @param properties Meta properties in the recovery request * @return UsernameRecoverDTO {@link PasswordRecoverDTO} object that contains notified * channel details and success status code * @throws IdentityRecoveryException Error while notifying user */ @Override public PasswordRecoverDTO notify(String recoveryCode, String channelId, String tenantDomain, Map<String, String> properties) throws IdentityRecoveryException { validateTenantDomain(tenantDomain); validateConfigurations(tenantDomain); int channelIDCode = validateChannelID(channelId); UserAccountRecoveryManager userAccountRecoveryManager = UserAccountRecoveryManager.getInstance(); // Get Recovery data. UserRecoveryData userRecoveryData = userAccountRecoveryManager .getUserRecoveryData(recoveryCode, RecoverySteps.SEND_RECOVERY_INFORMATION); String notificationChannel = extractNotificationChannelDetails(userRecoveryData.getRemainingSetIds(), channelIDCode); // Resolve notify status according to the notification channel of the user. boolean manageNotificationsInternally = true; if (NotificationChannels.EXTERNAL_CHANNEL.getChannelType().equals(notificationChannel)) { manageNotificationsInternally = false; } NotificationResponseBean notificationResponseBean = notifyUser(userRecoveryData.getUser(), notificationChannel, manageNotificationsInternally, properties); String secretKey = notificationResponseBean.getKey(); String resendCode = generateResendCode(notificationChannel, userRecoveryData); return buildPasswordRecoveryResponseDTO(notificationChannel, secretKey, resendCode); } /** * Validate the confirmation code given for password recovery and return the password reset code. * * @param confirmationCode Confirmation code * @param tenantDomain Tenant domain * @param properties Meta properties in the confirmation request * @return PasswordResetCodeDTO {@link PasswordResetCodeDTO} object which contains password reset code * @throws IdentityRecoveryException Error while confirming password recovery */ @Override public PasswordResetCodeDTO confirm(String confirmationCode, String tenantDomain, Map<String, String> properties) throws IdentityRecoveryException { validateTenantDomain(tenantDomain); UserAccountRecoveryManager userAccountRecoveryManager = UserAccountRecoveryManager.getInstance(); // Get Recovery data. UserRecoveryData userRecoveryData = userAccountRecoveryManager .getUserRecoveryData(confirmationCode, RecoverySteps.UPDATE_PASSWORD); if (!tenantDomain.equals(userRecoveryData.getUser().getTenantDomain())) { throw Utils.handleClientException( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_USER_TENANT_DOMAIN_MISS_MATCH_WITH_CONTEXT, tenantDomain); } String domainQualifiedName = IdentityUtil.addDomainToName(userRecoveryData.getUser().getUserName(), userRecoveryData.getUser().getUserStoreDomain()); if (log.isDebugEnabled()) { log.debug("Valid confirmation code for user: " + domainQualifiedName); } return buildPasswordResetCodeDTO(confirmationCode); } /** * Reset the password for password recovery, if the password reset code is valid. * * @param resetCode Password reset code * @param password New password * @param properties Properties * @return SuccessfulPasswordResetDTO {@link SuccessfulPasswordResetDTO} object which contain the information * for a successful password update * @throws IdentityRecoveryException Error while resetting the password */ @Override public SuccessfulPasswordResetDTO reset(String resetCode, char[] password, Map<String, String> properties) throws IdentityRecoveryException { // Validate the password. if (ArrayUtils.isEmpty(password)) { throw Utils.handleClientException( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_NO_PASSWORD_IN_REQUEST.getCode(), IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_NO_PASSWORD_IN_REQUEST.getMessage(), null); } String newPassword = String.valueOf(password); NotificationPasswordRecoveryManager notificationPasswordRecoveryManager = NotificationPasswordRecoveryManager .getInstance(); Property[] metaProperties = buildPropertyList(null, properties); try { notificationPasswordRecoveryManager.updatePassword(resetCode, newPassword, metaProperties); } catch (IdentityRecoveryServerException e) { String errorCode = Utils.prependOperationScenarioToErrorCode(e.getErrorCode(), IdentityRecoveryConstants.PASSWORD_RECOVERY_SCENARIO); throw Utils.handleServerException(errorCode, e.getMessage(), null); } catch (IdentityRecoveryClientException e) { throw mapClientExceptionWithImprovedErrorCodes(e); } catch (IdentityEventException e) { if (log.isDebugEnabled()) { log.debug("PasswordRecoveryManagerImpl: Error while resetting password ", e); } throw Utils.handleServerException( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED_ERROR_PASSWORD_RESET.getCode(), IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED_ERROR_PASSWORD_RESET.getMessage(), null); } return buildSuccessfulPasswordUpdateDTO(); } /** * Resend the password recovery information to the user via user specified channel. * * @param tenantDomain Tenant Domain * @param resendCode Resend code * @param properties Meta properties * @return ResendConfirmationDTO {@link ResendConfirmationDTO} which wraps the information for a successful * recovery information resend * @throws IdentityRecoveryException Error while sending recovery information */ @Override public ResendConfirmationDTO resend(String tenantDomain, String resendCode, Map<String, String> properties) throws IdentityRecoveryException { validateTenantDomain(tenantDomain); Property[] metaProperties = buildPropertyList(null, properties); ResendConfirmationManager resendConfirmationManager = ResendConfirmationManager.getInstance(); try { return resendConfirmationManager.resendConfirmation(tenantDomain, resendCode, RecoveryScenarios.NOTIFICATION_BASED_PW_RECOVERY.name(), RecoverySteps.UPDATE_PASSWORD.name(), IdentityRecoveryConstants.NOTIFICATION_TYPE_RESEND_PASSWORD_RESET, metaProperties); } catch (IdentityRecoveryException e) { e.setErrorCode(Utils.prependOperationScenarioToErrorCode(e.getErrorCode(), IdentityRecoveryConstants.PASSWORD_RECOVERY_SCENARIO)); throw e; } } /** * Map the client exceptions with the new API error codes and the scenarios. * * @param exception IdentityRecoveryClientException * @return IdentityRecoveryClientException */ private IdentityRecoveryClientException mapClientExceptionWithImprovedErrorCodes( IdentityRecoveryClientException exception) { if (IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_INVALID_CODE.getCode() .equals(exception.getErrorCode())) { exception.setErrorCode(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_INVALID_RECOVERY_CODE.getCode()); } else if (IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_EXPIRED_CODE.getCode() .equals(exception.getErrorCode())) { exception.setErrorCode(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_EXPIRED_RECOVERY_CODE.getCode()); } else if (IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_HISTORY_VIOLATE.getCode() .equals(exception.getErrorCode())) { exception.setErrorCode( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_PASSWORD_HISTORY_VIOLATION.getCode()); } else if (IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_POLICY_VIOLATION.getCode() .equals(exception.getErrorCode())) { exception.setErrorCode( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_PASSWORD_POLICY_VIOLATION.getCode()); } else { exception.setErrorCode(Utils.prependOperationScenarioToErrorCode(exception.getErrorCode(), IdentityRecoveryConstants.PASSWORD_RECOVERY_SCENARIO)); } return Utils.handleClientException(exception.getErrorCode(), exception.getMessage(), null); } /** * Send recovery information to the user. * * @param user User * @param notificationChannel Notification Channel * @param manageNotificationInternally Manage notifications internally * @param properties Meta properties * @return NotificationResponseBean * @throws IdentityRecoveryException Error while sending notifications */ private NotificationResponseBean notifyUser(User user, String notificationChannel, boolean manageNotificationInternally, Map<String, String> properties) throws IdentityRecoveryException { Property[] metaProperties = buildPropertyList(notificationChannel, properties); NotificationResponseBean notificationResponseBean; try { notificationResponseBean = NotificationPasswordRecoveryManager .getInstance(). sendRecoveryNotification(user, null, manageNotificationInternally, metaProperties); } catch (IdentityRecoveryException exception) { if (StringUtils.isNotEmpty(exception.getErrorCode())) { String errorCode = exception.getErrorCode(); if (IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_CALLBACK_URL_NOT_VALID.getCode() .equals(errorCode)) { exception.setErrorCode( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_INVALID_CALLBACK_PASSWORD_RESET .getCode()); } else if (IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED.getCode() .equals(errorCode)) { exception.setErrorCode( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED_ERROR_PASSWORD_RESET .getCode()); } exception.setErrorCode(Utils.prependOperationScenarioToErrorCode(exception.getErrorCode(), IdentityRecoveryConstants.PASSWORD_RECOVERY_SCENARIO)); } throw exception; } if (notificationResponseBean == null) { if (log.isDebugEnabled()) { log.debug("Empty Response while notifying password recovery information for user : " + user .getUserName()); } throw Utils .handleServerException( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED_ERROR_PASSWORD_RESET, null); } return notificationResponseBean; } /** * Build Property list using the meta properties map. * * @param notificationChannel Notification channel * @param properties Map of properties * @return List of properties */ private Property[] buildPropertyList(String notificationChannel, Map<String, String> properties) { ArrayList<Property> propertyArrayList = new ArrayList<>(); // Add already existing meta properties. if (MapUtils.isNotEmpty(properties)) { for (String key : properties.keySet()) { if (StringUtils.isNotEmpty(key)) { propertyArrayList.add(buildProperty(key, properties.get(key))); } } } // Add the notification channel property. if (StringUtils.isNotEmpty(notificationChannel)) { propertyArrayList.add(buildProperty(IdentityRecoveryConstants.NOTIFICATION_CHANNEL_PROPERTY_KEY, notificationChannel)); } // Add the verified user property since the user is already verified and no need to validate the existence // again. propertyArrayList .add(buildProperty(IdentityRecoveryConstants.VERIFIED_USER_PROPERTY_KEY, Boolean.toString(true))); return propertyArrayList.toArray(new Property[0]); } /** * Build a property object. * * @param key Key * @param value Value * @return Property object */ private Property buildProperty(String key, String value) { Property property = new Property(); property.setKey(key); property.setValue(value); return property; } /** * Build SuccessfulPasswordResetDTO response for a successful password update. * * @return SuccessfulPasswordResetDTO object */ private SuccessfulPasswordResetDTO buildSuccessfulPasswordUpdateDTO() { SuccessfulPasswordResetDTO successfulPasswordResetDTO = new SuccessfulPasswordResetDTO(); successfulPasswordResetDTO.setSuccessCode( IdentityRecoveryConstants.SuccessEvents.SUCCESS_STATUS_CODE_SUCCESSFUL_PASSWORD_UPDATE.getCode()); successfulPasswordResetDTO.setMessage( IdentityRecoveryConstants.SuccessEvents.SUCCESS_STATUS_CODE_SUCCESSFUL_PASSWORD_UPDATE.getMessage()); return successfulPasswordResetDTO; } /** * Validate the channel Id given in the request. * * @param channelId Channel Id in the request. * @return Channel Id * @throws IdentityRecoveryClientException Invalid channel Id */ private int validateChannelID(String channelId) throws IdentityRecoveryClientException { int id; try { id = Integer.parseInt(channelId); } catch (NumberFormatException e) { throw Utils .handleClientException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_INVALID_CHANNEL_ID, null); } // Channel id needs to be larger than 0. if (id < 1) { throw Utils .handleClientException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_INVALID_CHANNEL_ID, null); } return id; } /** * Build the PasswordResetCodeDTO for successful verification. * * @param resetCode Password reset code * @return PasswordResetCodeDTO */ private PasswordResetCodeDTO buildPasswordResetCodeDTO(String resetCode) { PasswordResetCodeDTO passwordResetCodeDTO = new PasswordResetCodeDTO(); passwordResetCodeDTO.setPasswordResetCode(resetCode); return passwordResetCodeDTO; } /** * Build PasswordRecoverDTO for notifying password recovery details successfully. * * @param notificationChannel Notified channel * @param confirmationCode Confirmation code for confirm recovery * @param resendCode Code to resend recovery confirmation code * @return PasswordRecoverDTO object */ private PasswordRecoverDTO buildPasswordRecoveryResponseDTO(String notificationChannel, String confirmationCode, String resendCode) { PasswordRecoverDTO passwordRecoverDTO = new PasswordRecoverDTO(); passwordRecoverDTO.setNotificationChannel(notificationChannel); if (NotificationChannels.EXTERNAL_CHANNEL.getChannelType().equals(notificationChannel)) { passwordRecoverDTO.setConfirmationCode(confirmationCode); } passwordRecoverDTO.setResendCode(resendCode); passwordRecoverDTO.setCode( IdentityRecoveryConstants.SuccessEvents.SUCCESS_STATUS_CODE_PASSWORD_RECOVERY_INTERNALLY_NOTIFIED .getCode()); passwordRecoverDTO.setMessage( IdentityRecoveryConstants.SuccessEvents.SUCCESS_STATUS_CODE_PASSWORD_RECOVERY_INTERNALLY_NOTIFIED .getMessage()); return passwordRecoverDTO; } /** * Extract the channel that matches the channelId from the channels stored in recovery data. * * @param recoveryChannels All available recovery channels * @param channelId User preferred channelId * @throws IdentityRecoveryException Invalid channelId */ private String extractNotificationChannelDetails(String recoveryChannels, int channelId) throws IdentityRecoveryException { String[] channels = recoveryChannels.split(IdentityRecoveryConstants.NOTIFY_CHANNEL_LIST_SEPARATOR); if (channels.length < channelId) { throw Utils .handleClientException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_INVALID_CHANNEL_ID, null); } String notificationChannel = channels[channelId - 1]; String[] channelDetails = notificationChannel.split(IdentityRecoveryConstants.CHANNEL_ATTRIBUTE_SEPARATOR); return channelDetails[0]; } /** * Check whether recovery is enabled. * * @param tenantDomain Tenant domain * @throws IdentityRecoveryException Error with the configurations */ private void validateConfigurations(String tenantDomain) throws IdentityRecoveryException { boolean isRecoveryEnable = Boolean.parseBoolean( Utils.getRecoveryConfigs(IdentityRecoveryConstants.ConnectorConfig.NOTIFICATION_BASED_PW_RECOVERY, tenantDomain)); if (!isRecoveryEnable) { throw Utils.handleClientException( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_PASSWORD_RECOVERY_WITH_NOTIFICATIONS_NOT_ENABLED, null); } } /** * Check whether challenge question based recovery is enabled for the tenant. * * @param tenantDomain Tenant domain * @return True if challenge question based recovery is enabled * @throws IdentityRecoveryServerException Error reading configs for the tenant */ private boolean isQuestionBasedRecoveryEnabled(String tenantDomain) throws IdentityRecoveryServerException { // Check whether the challenge question based recovery is enabled. try { return Boolean.parseBoolean( Utils.getRecoveryConfigs(IdentityRecoveryConstants.ConnectorConfig.QUESTION_BASED_PW_RECOVERY, tenantDomain)); } catch (IdentityRecoveryServerException e) { // Prepend scenario to the thrown exception. String errorCode = Utils .prependOperationScenarioToErrorCode(IdentityRecoveryConstants.PASSWORD_RECOVERY_SCENARIO, e.getErrorCode()); throw Utils.handleServerException(errorCode, e.getMessage(), null); } } /** * Check whether notification based recovery is enabled for the tenant. * * @param tenantDomain Tenant domain * @return True if challenge question based recovery is enabled * @throws IdentityRecoveryServerException Error reading configs for the tenant */ private boolean isNotificationBasedRecoveryEnabled(String tenantDomain) throws IdentityRecoveryServerException { // Check whether the challenge question based recovery is enabled. try { return Boolean.parseBoolean( Utils.getRecoveryConfigs(IdentityRecoveryConstants.ConnectorConfig.NOTIFICATION_BASED_PW_RECOVERY, tenantDomain)); } catch (IdentityRecoveryServerException e) { // Prepend scenario to the thrown exception. String errorCode = Utils .prependOperationScenarioToErrorCode(IdentityRecoveryConstants.PASSWORD_RECOVERY_SCENARIO, e.getErrorCode()); throw Utils.handleServerException(errorCode, e.getMessage(), null); } } /** * Get the resend code. * * @param notificationChannel Notification channel * @param userRecoveryData User Recovery data * @return Resend code * @throws IdentityRecoveryServerException Error while adding the resend code */ private String generateResendCode(String notificationChannel, UserRecoveryData userRecoveryData) throws IdentityRecoveryServerException { String resendCode = UUID.randomUUID().toString(); /* Checking whether the existing confirmation code can be used based on the email confirmation code tolerance and the existing recovery details. If so this code updates the existing SEND_RECOVERY_INFORMATION code with the new RESEND_CONFIRMATION_CODE by not changing the TIME_CREATED. */ if (Utils.reIssueExistingConfirmationCode(getSendRecoveryCodeData(userRecoveryData), notificationChannel)){ invalidateRecoveryInfoSendCode(resendCode, notificationChannel, userRecoveryData); return resendCode; } addRecoveryDataObject(resendCode, notificationChannel, userRecoveryData.getUser()); return resendCode; } /** * Retrieves the send recovery information code details. * * @param userRecoveryData Recovery details of the corresponding user. * @return Existing send recovery information code details. * @throws IdentityRecoveryServerException Will be thrown when an error occurred. */ private UserRecoveryData getSendRecoveryCodeData(UserRecoveryData userRecoveryData) throws IdentityRecoveryServerException { UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance(); try { return userRecoveryDataStore.loadWithoutCodeExpiryValidation( userRecoveryData.getUser(), RecoveryScenarios.NOTIFICATION_BASED_PW_RECOVERY, RecoverySteps.SEND_RECOVERY_INFORMATION); } catch (IdentityRecoveryException e) { throw Utils.handleServerException( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_ERROR_STORING_RECOVERY_DATA, "Error Storing Recovery Data", e); } } /** * Invalidates the existing send recovery code and add the new resend code by not changing the existing code's * time created. * * @param resendCode New resend code that needs to be sent. * @param notificationChannel Channel that needs to send the recovery information. * @param userRecoveryData Existing resend code details. * @throws IdentityRecoveryServerException Will be thrown if there is any error. */ private void invalidateRecoveryInfoSendCode(String resendCode, String notificationChannel, UserRecoveryData userRecoveryData) throws IdentityRecoveryServerException { UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance(); try { userRecoveryDataStore.invalidateWithoutChangeTimeCreated(userRecoveryData.getSecret(), resendCode, RecoverySteps.RESEND_CONFIRMATION_CODE, notificationChannel); } catch (IdentityRecoveryException e) { throw Utils.handleServerException( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_ERROR_UPDATING_RECOVERY_DATA, "Error Updating Recovery Data : RESEND_CONFIRMATION_CODE", e); } } /** * Add the notification channel recovery data to the store. * * @param secretKey RecoveryId * @param recoveryData Data to be stored as mata which are needed to evaluate the recovery data object * @throws IdentityRecoveryServerException Error storing recovery data */ private void addRecoveryDataObject(String secretKey, String recoveryData, User user) throws IdentityRecoveryServerException { UserRecoveryData recoveryDataDO = new UserRecoveryData(user, secretKey, RecoveryScenarios.NOTIFICATION_BASED_PW_RECOVERY, RecoverySteps.RESEND_CONFIRMATION_CODE); // Store available channels in remaining setIDs. recoveryDataDO.setRemainingSetIds(recoveryData); try { UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance(); userRecoveryDataStore.store(recoveryDataDO); } catch (IdentityRecoveryException e) { throw Utils.handleServerException( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_ERROR_STORING_RECOVERY_DATA, "Error Storing Recovery Data", e); } } /** * Validates the tenant domain in the request. * * @param tenantDomain Tenant domain * @throws IdentityRecoveryClientException Empty tenant domain in the request */ private void validateTenantDomain(String tenantDomain) throws IdentityRecoveryClientException { if (StringUtils.isBlank(tenantDomain)) { throw Utils.handleClientException( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_PASSWORD_RECOVERY_EMPTY_TENANT_DOMAIN.getCode(), IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_PASSWORD_RECOVERY_EMPTY_TENANT_DOMAIN .getMessage(), null); } } /** * Get the lock status of a functionality given the tenant domain, user name and the functionality type. * * @param tenantDomain Tenant domain of the user. * @param userName Username of the user. * @param functionalityIdentifier Identifier of the the functionality. * @return The status of the functionality, {@link FunctionalityLockStatus}. */ private FunctionalityLockStatus getFunctionalityStatusOfUser(String tenantDomain, String userName, String functionalityIdentifier) throws IdentityRecoveryServerException { int tenantId = IdentityTenantUtil.getTenantId(tenantDomain); String userId = Utils.getUserId(userName, tenantId); UserFunctionalityManager userFunctionalityManager = IdentityRecoveryServiceDataHolder.getInstance().getUserFunctionalityManagerService(); try { return userFunctionalityManager.getLockStatus(userId, tenantId, functionalityIdentifier); } catch (UserFunctionalityManagementException e) { String mappedErrorCode = Utils.prependOperationScenarioToErrorCode( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_FAILED_TO_GET_LOCK_STATUS_FOR_FUNCTIONALITY .getCode(), IdentityRecoveryConstants.PASSWORD_RECOVERY_SCENARIO); StringBuilder message = new StringBuilder( IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_FAILED_TO_GET_LOCK_STATUS_FOR_FUNCTIONALITY .getMessage()); if (isDetailedErrorMessagesEnabled) { message.append(String.format("functionality: %s for %s.", IdentityRecoveryConstants.FunctionalityTypes.FUNCTIONALITY_SECURITY_QUESTION_PW_RECOVERY .getFunctionalityIdentifier(), userName)); } throw Utils.handleServerException(mappedErrorCode, message.toString(), null); } } /** * Checks if user has set answers for at least the minimum number of questions with answers required for password * recovery. * * @param username The username of the user. * @param tenantDomain The tenant domain of the user. * @return True if expected number of challenge question answers have been set for the user. * @throws IdentityRecoveryException Error while retrieving challenge question Ids for user. */ private boolean isMinNoOfRecoveryQuestionsAnswered(String username, String tenantDomain) throws IdentityRecoveryException { User user = Utils.buildUser(username, tenantDomain); ChallengeQuestionManager challengeQuestionManager = ChallengeQuestionManager.getInstance(); String[] ids = challengeQuestionManager.getUserChallengeQuestionIds(user); boolean isMinNoOfRecoveryQuestionsAnswered = false; if (ids != null) { int minNoOfQuestionsToAnswer = Integer.parseInt(Utils.getRecoveryConfigs(IdentityRecoveryConstants .ConnectorConfig.QUESTION_MIN_NO_ANSWER, tenantDomain)); isMinNoOfRecoveryQuestionsAnswered = ids.length >= minNoOfQuestionsToAnswer; if (isMinNoOfRecoveryQuestionsAnswered && log.isDebugEnabled()) { log.debug(String.format("User: %s in tenant domain %s has set answers for at least the minimum number" + " of questions with answers required for password recovery.", username, tenantDomain)); } } return isMinNoOfRecoveryQuestionsAnswered; } }
package com.yg.vo; import java.io.Serializable; public class PaymentVo implements Serializable { private static final long serialVersionUID = 48L; private String payMonth; private double amount; public PaymentVo() { } public PaymentVo(String payMonth, double amount) { this.payMonth = payMonth; this.amount = amount; } public String getPayMonth() { return payMonth; } public void setPayMonth(String payMonth) { this.payMonth = payMonth; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.webadmin.preferences; import java.util.HashSet; import java.util.List; import java.util.Set; import pl.edu.icm.unity.exceptions.EngineException; import pl.edu.icm.unity.server.api.EndpointManagement; import pl.edu.icm.unity.server.api.PreferencesManagement; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.types.endpoint.EndpointDescription; import pl.edu.icm.unity.webui.common.preferences.PreferencesHandlerRegistry; import com.vaadin.ui.TabSheet; import com.vaadin.ui.VerticalLayout; /** * Allows for viewing and editing of preferences of the logged user. * @author K. Benedyczak */ public class PreferencesComponent extends VerticalLayout { private UnityMessageSource msg; private PreferencesHandlerRegistry registry; private PreferencesManagement prefMan; private EndpointManagement endpMan; public PreferencesComponent(UnityMessageSource msg, PreferencesHandlerRegistry registry, PreferencesManagement prefMan, EndpointManagement endpMan) { super(); this.msg = msg; this.registry = registry; this.prefMan = prefMan; this.endpMan = endpMan; init(); } private void init() { TabSheet tabs = new TabSheet(); Set<String> deployedTypes = null; try { List<EndpointDescription> deployed = endpMan.getEndpoints(); deployedTypes = new HashSet<String>(); for (EndpointDescription desc: deployed) deployedTypes.add(desc.getType().getName()); } catch (EngineException e) { //no authz - no problem, just add all preferences } Set<String> types = registry.getSupportedPreferenceTypes(deployedTypes); for (String type: types) { PreferenceViewTab tab = new PreferenceViewTab(msg, registry.getHandler(type), prefMan); tabs.addTab(tab); } tabs.setSizeFull(); addComponent(tabs); } }
package pl.weakpoint.library.service; import java.util.List; import java.util.Optional; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.weakpoint.library.model.User; import pl.weakpoint.library.repository.UserRepository; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override public void createUser(String name) { User user = new User(); user.setFirstName(name); user.setLastName(name); user.setEmail(name+"@"+name+".pl"); user.setPhone("510 510 510"); userRepository.save(user); } @Override public List<User> getAllUsers() { return userRepository.findAll(); } @Override public Optional<User> getUserById(String id) { return userRepository.findById(Long.parseLong(id)); } }
package ru.job4j.convertlist; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /** * Класс ConvertListTest тестирует класс ConvertList. * * @author Goureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2018-12-06 * @since 2017-05-10 */ public class ConvertListTest { /** * Тестирует public List<Integer> toList(int[][] array). */ @Test public void testToList() { List<Integer> expected = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 0, 0)); int[][] array = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 0, 0}}; ConvertList cl = new ConvertList(); List actual = cl.toList(array); assertEquals(expected, actual); } /** * Тестирует public int[][] toArray(List<Integer> list, int rows). */ @Test public void testToArray() { int[][] expected = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 0, 0}}; List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7)); ConvertList cl = new ConvertList(); int[][] actual = cl.toArray(list, 3); assertArrayEquals(expected, actual); } /** * Тестирует public List<Integer> convert(List<int[]> list). */ @Test public void testConvert() { List<Integer> expected = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6)); List<int[]> list = new ArrayList<>(); list.add(new int[]{1, 2}); list.add(new int[]{3, 4, 5, 6}); ConvertList cl = new ConvertList(); List<Integer> actual = cl.convert(list); assertEquals(expected, actual); } }
package firstfactor.model; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; @Entity @NoArgsConstructor @Getter @Setter public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; @Column(name = "phone_number") private String phoneNumber; }
package com.zhongyp.advanced.pattern.observer.jdkobserver; import java.util.Observable; /** * project: demo * author: zhongyp * date: 2018/3/26 * mail: zhongyp001@163.com */ public class ObserverTest{ public static void main(String[] args) { SpecialRepoter repoter = new SpecialRepoter(); PeopleDaily n2 = new PeopleDaily(repoter); repoter.getNewNews("new news!"); n2.remove(); repoter.getNewNews("another new news!"); } }
package br.edu.com.dados.repositories; import java.util.List; import br.edu.com.dados.dao.Dao; import br.edu.com.entities.Aluno; public class RepositoryAluno implements IRepositoryAluno { @Override public boolean salvarAluno(Aluno aluno) { return Dao.getInstance().save(aluno); } @Override public boolean atualizarAluno(Aluno aluno) { return Dao.getInstance().update(aluno); } @Override public boolean inativarAluno(Aluno aluno) { return Dao.getInstance().delete(aluno); } @Override public List<Aluno> listarAluno() { return (List<Aluno>) Dao.getInstance().list(Aluno.class); } @Override public List<Aluno> procurarAluno(String query) { return (List<Aluno>) Dao.getInstance().createQuery(query); } }
package pt.uminho.sdc.cs; public class ErrorReply extends Reply { private final RemoteInvocationException exception; public ErrorReply(RemoteInvocationException exception) { this.exception = exception; } public RemoteInvocationException getException() { return exception; } public String toString() { return "Exception: "+ exception.getMessage(); } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.drivemanager; import java.util.ArrayList; import java.util.Collection; import net.datacrow.core.data.DataFilter; import net.datacrow.core.data.DataFilterEntry; import net.datacrow.core.data.DataManager; import net.datacrow.core.data.Operator; import net.datacrow.core.modules.DcModule; import net.datacrow.core.modules.DcModules; import net.datacrow.core.objects.DcObject; import net.datacrow.core.objects.ValidationException; import net.datacrow.core.resources.DcResources; import org.apache.log4j.Logger; public class FileSynchronizer { private static Logger logger = Logger.getLogger(FileSynchronizer.class.getName()); private Task task; private Collection<DcModule> modules = new ArrayList<DcModule>(); protected FileSynchronizer() { for (DcModule module : DcModules.getModules()) { if (module.isFileBacked()) modules.add(module); } } public boolean start(int precision) { if (task == null || !task.isAlive()) { task = new Task(this, precision); task.start(); return true; } return false; } public boolean isRunning() { return task != null && task.isAlive(); } public void cancel() { if (task != null) task.cancel(); } protected Collection<DcModule> getModules() { return modules; } private static class Task extends Thread { private boolean keepOnRunning = true; private FileSynchronizer fs; private int precision; public Task(FileSynchronizer fs, int precision) { this.fs = fs; this.precision = precision; setPriority(Thread.MIN_PRIORITY); } public void cancel() { keepOnRunning = false; } @Override public void run() { DriveManager dm = DriveManager.getInstance(); dm.notifyJobStarted(dm.getSynchronizerListeners()); int[] fields; DataFilter df; String filename; String hash; Long size; String message; FileInfo currentFI; FileInfo fi; while (keepOnRunning) { for (DcModule module : fs.getModules()) { Collection<Integer> c = new ArrayList<Integer>(); c.add(Integer.valueOf(DcObject._SYS_FILEHASH)); c.add(Integer.valueOf(DcObject._SYS_FILESIZE)); c.add(Integer.valueOf(DcObject._SYS_FILENAME)); fields = module.getMinimalFields(c); if (!keepOnRunning) break; df = new DataFilter(module.getIndex()); df.addEntry(new DataFilterEntry(DataFilterEntry._AND, module.getIndex(), DcObject._SYS_FILENAME, Operator.IS_FILLED, null)); if (precision >= DriveManager._PRECISION_MEDIUM) df.addEntry(new DataFilterEntry(DataFilterEntry._AND, module.getIndex(), DcObject._SYS_FILESIZE, Operator.IS_FILLED, null)); if (precision == DriveManager._PRECISION_HIGHEST) df.addEntry(new DataFilterEntry(DataFilterEntry._AND, module.getIndex(), DcObject._SYS_FILEHASH, Operator.IS_FILLED, null)); for (DcObject dco : DataManager.get(df, fields)) { if (!keepOnRunning) break; filename = (String) dco.getValue(DcObject._SYS_FILENAME); hash = (String) dco.getValue(DcObject._SYS_FILEHASH); size = (Long) dco.getValue(DcObject._SYS_FILESIZE); currentFI = new FileInfo(hash, filename, size); fi = dm.find(currentFI, precision); // A result means a match was found. // No longer check whether the filename is different; found = found. if (fi != null) { dco.setValue(DcObject._SYS_FILENAME, fi.getFilename()); dco.setValue(DcObject._SYS_FILESIZE, fi.getSize()); dco.setValue(DcObject._SYS_FILEHASH, fi.getHash()); try { dco.setUpdateGUI(false); dco.saveUpdate(true); message = DcResources.getText("msgSynchronizedFile", new String[] {dco.toString(), fi.getFilename()}); dm.sendMessage(dm.getSynchronizerListeners(), message); } catch (ValidationException ve) { dm.sendMessage(dm.getSynchronizerListeners(), DcResources.getText("msgSynchronizerCouldNotSave", dco.toString())); } } currentFI.clear(); if (fi != null) fi.clear(); try { sleep(2000); } catch (Exception e) { logger.error(e, e); } } } try { sleep(60000); } catch (Exception e) { logger.error(e, e); } } fs = null; dm.notifyJobStopped(dm.getSynchronizerListeners()); } } }
/* 3.b.- Escribe una clase Película que herede de la clase Multimedia anterior. * La clase Película tiene, además de los atributos heredados, un actor principal y una actriz principal. * Se permite que uno de los dos sea nulo, pero no los dos. * La clase debe tener dos métodos para obtener los dos nuevos atributos y debe sobrescribir el método toString() * para que devuelva, además de la información heredada, la nueva información. */ package HERENCIA; public class PELICULA extends MULTIMEDIA { private String actorPrincipal, actrizPrincipal; public PELICULA(String titulo, String autor, format formato, String duracion, String actorPrincipal, String actrizPrincipal) throws Exception { super(titulo, autor, formato, duracion); if ((actorPrincipal == null && actrizPrincipal == null) || (actorPrincipal.isEmpty() &&actrizPrincipal.length()==0)) { throw new Exception("Datos incorrectos. cuenta no creada"); } else { this.actorPrincipal = actorPrincipal; this.actrizPrincipal = actrizPrincipal; } } public String getActorPrincipal() { return actorPrincipal; } public void setActorPrincipal(String actorPrincipal) { this.actorPrincipal = actorPrincipal; } public String getActrizPrincipal() { return actrizPrincipal; } public void setActrizPrincipal(String actrizPrincipal) { this.actrizPrincipal = actrizPrincipal; } public String toString() { return super.toString()+ "\nActor Principal: " + actorPrincipal + "\nActriz Principal: " + actrizPrincipal; } }
package net.awesomekorean.podo.reading.readings; import net.awesomekorean.podo.R; import net.awesomekorean.podo.reading.Reading; import java.io.Serializable; public class Reading07 extends ReadingInit implements Reading, Serializable { String readingId = "R_07"; int readingLevel = 1; final String title = "감사합니다 vs. 고맙습니다"; final String[] article = { "", "여러분", "은 ‘감사합니다’와 ‘고맙습니다’ 중 어떤 말을 더 많이 사용하나요? \n두 말은 어떻게 다를까요? \n\n‘감사합니다’는 ‘감사’(感謝)라는 한자에서 온 말이고 ‘고맙습니다’는 ", "순수한", " 한국어입니다.\n의미는 ", "완전히", " 같습니다. \n어떤 사람들은 ‘감사합니다’가 더 ", "공손한", " 표현이라고 하는데 이것은 잘못된 생각입니다. \n\n두 말은 100% 같은 의미이고 모두 공손한 표현이므로 쓰고 싶은 말을 사용하면 됩니다.\n\n" }; final String[] popUpFront = {"여러분", "순수하다", "완전히", "공손하다"}; final String[] popUpBack = {"everyone", "pure", "totally", "polite"}; private int readingImage = R.drawable.thankyou; @Override public String getReadingId() { return readingId; } @Override public String getTitle() { return title; } @Override public String[] getArticle() { return article; } @Override public String[] getPopUpFront() { return popUpFront; } @Override public String[] getPopUpBack() { return popUpBack; } @Override public int getReadingImage() { return this.readingImage; } @Override public int getReadingLevel() { return this.readingLevel; } }
import com.sun.org.apache.xerces.internal.xs.XSTerm; import java.util.Map; public class Main { public static void main(String[] args) { MyStream<Person> stream = MyStream.of( new Person("Ivan", 55), new Person("Oleg", 15), new Person("Anton", 30)) .filter(p -> p.getAge() > 30) .transform(p -> new Person(p.getAge() + 30)); System.out.println(stream); Map map = stream.toMap(); System.out.println("--------------------------------------------------"); MyStream<Person> stream1 = stream .filter(p -> p.getAge() > 30) .transform(p -> new Person(p.getAge() + 30)); System.out.println(stream1); } }
package com.pwc.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * Created with IntelliJ IDEA. * User: Jason ZX Lin * Date: 30/06/13 * Time: 15:20 * To change this template use File | Settings | File Templates. */ public class File { public static String readFileAsString(String filePath) throws IOException { StringBuffer fileData = new StringBuffer(); BufferedReader reader = new BufferedReader( new FileReader(filePath)); char[] buf = new char[1024]; int numRead=0; while((numRead=reader.read(buf)) != -1){ String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); } reader.close(); return fileData.toString(); } }
package com.zeal.smartdo.base; import com.zeal.smartdo.http.HttpService; import com.zeal.smartdo.http.ServiceGenerator; import com.zeal.smartdo.mvp.IModel; /** * @作者 廖伟健 * @创建时间 2017/3/27 15:44 * @描述 ${TODO} */ public abstract class BaseModel<T> implements IModel<T> { protected static HttpService sHttpService; //初始化 HttpService static { sHttpService = ServiceGenerator.createService(); } // @Override // public T getDataFromNetwork() throws Exception { // if(NetworkUtil.isNetworkAvailable(SmartDoApplication.getContext())) { // throw new ApiException(ApiException.NET_WORK_AVAILABLE); // } // return getDataFromNetworkInternal(); // } // // protected abstract T getDataFromNetworkInternal(); }
package at.fhv.itm14.fhvgis.webservice.app.services; import at.fhv.itm14.fhvgis.domain.Device; import at.fhv.itm14.fhvgis.domain.MotionValues; import at.fhv.itm14.fhvgis.domain.Track; import at.fhv.itm14.fhvgis.domain.Waypoint; import at.fhv.itm14.fhvgis.domain.raw.RawMotionValue; import at.fhv.itm14.fhvgis.domain.raw.RawWaypoint; import at.fhv.itm14.fhvgis.persistence.DatabaseController; import at.fhv.itm14.fhvgis.persistence.exceptions.PersistenceException; import at.fhv.itm14.fhvgis.webservice.app.exceptions.ServiceException; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; import java.time.Instant; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; /** * Author: Tobias * Date: 15.01.2016 * Time: 15:26 */ public class ConversionService { private static final String PREF = "ConversionService"; public void convertTrackData() throws ServiceException { Waypoint w; // First, reset tracks that failed resetTrackData(); try { List<Track> tracks2Convert = DatabaseController.getInstance().findTracksToConvert(); for (Track t : tracks2Convert) { convertTrackData(t); } } catch (PersistenceException e) { e.printStackTrace(); throw new ServiceException("Failed to convert Tracks" + e.getMessage()); } } private void resetTrackData() { Logger.getLogger(PREF).log(Level.ALL, "Try to reset track data"); try { List<Track> failedTracks = DatabaseController.getInstance().findFailedTracks(); if (failedTracks.size() > 0) Logger.getLogger(PREF).log(Level.ALL, "Found " + failedTracks.size() + " to reset"); for (Track t : failedTracks) { // Delete all Waypoints while (t.getWaypoints().size() > 0) { // for (Waypoint w : t.getWaypoints()) { Waypoint w = t.getWaypoints().get(0); // Delete all MotionValues while (w.getMotionValues().size() > 0) { MotionValues mv = w.getMotionValues().get(0); w.removeMotionValue(mv); DatabaseController.getInstance().deleteMotionValue(mv); } t.removeWaypoint(w); DatabaseController.getInstance().deleteWaypoint(w); } // Mark track as 'fresh' t.setStatus(0); DatabaseController.getInstance().updateTrack(t); Logger.getLogger(PREF).log(Level.INFO, "Succeeded resetting track with id " + t.getId()); } } catch (PersistenceException e) { // on error, no problem to just log because track is failed anyway e.printStackTrace(); } } public void convertTrackData(UUID trackid) throws ServiceException { try { Track t = DatabaseController.getInstance().findTrack(trackid); convertTrackData(t); } catch (PersistenceException e) { e.printStackTrace(); throw new ServiceException("Failed to convert Track: " + e.getMessage()); } } private void convertTrackData(Track t) throws PersistenceException { Logger.getLogger(PREF).log(Level.ALL, "Try to convert track with id " + t.getId()); // Mark track as currently 'inWork' t.setStatus(1200); DatabaseController.getInstance().updateTrack(t); if (t.getStatus() == 1200) { convertTrackWaypoints(t); convertTrackMotions(t); t = DatabaseController.getInstance().findTrack(t.getId()); t.setStatus(1); DatabaseController.getInstance().updateTrack(t); } else { Logger.getLogger(PREF).log(Level.WARNING, "Could not convert track with " + t.getId() + " as it has an incorrect status"); } } private void convertTrackWaypoints(Track t) throws PersistenceException { List<RawWaypoint> listWaypoints = null; try { listWaypoints = DatabaseController.getInstance().findRawWaypointsOfTrack(t.getId()); for (RawWaypoint rWp : listWaypoints) { Waypoint w = fromRaw(rWp); t.addWaypoint(w); // And directly insert DatabaseController.getInstance().persistWaypoint(w); } } catch (PersistenceException e) { e.printStackTrace(); throw e; } } public void convertTrackMotions(Track track) { List<RawMotionValue> listRaw = null; Device d = null; try { d = track.getDevice(); // foreach waypoint, find the MotionValues that where a bit erlier and a bit later than the waypoint for (Waypoint wp : track.getWaypoints()) { listRaw = DatabaseController.getInstance().findRawMotionValuesInRangeOfDevice( d.getId(), wp.getRecordTime().toEpochMilli() - 3000, wp.getRecordTime().toEpochMilli() + 3000 ); for (RawMotionValue r : listRaw) { MotionValues m = fromRaw(r); wp.addMotionValue(m); DatabaseController.getInstance().persistMotionValues(m); } DatabaseController.getInstance().updateWaypoint(wp); } } catch (Exception e) { e.printStackTrace(); } } private Waypoint fromRaw(RawWaypoint raw) { Waypoint waypoint = new Waypoint(); GeometryFactory geometryFactory = new GeometryFactory(); Point p = geometryFactory.createPoint(new Coordinate(raw.getLongitude(), raw.getLatitude())); Date input = new Date(raw.getTimestamp()); Instant instant = input.toInstant(); waypoint.setPosition(p); waypoint.setSpeed(raw.getSpeed()); waypoint.setAccuracy(raw.getAccuracy()); waypoint.setTrack(raw.getTrack()); waypoint.setNrOfSatellites(raw.getNrOfnSatellites()); waypoint.setRecordTime(instant); waypoint.setId(UUID.randomUUID()); waypoint.setValid(true); // no filtering per default if (raw.getVehicle() != null) { waypoint.setTransportation(raw.getVehicle()); } // DB does not allow value < 0 if (waypoint.getNrOfSatellites() < 0) waypoint.setNrOfSatellites(0); // Other provider that GPS can not have nrOfSattelites if (!"gps".equals(raw.getProvider())) waypoint.setNrOfSatellites(0); return waypoint; } private MotionValues fromRaw(RawMotionValue raw) { MotionValues mv = new MotionValues(); Date input = new Date(raw.getTimestamp()); Instant instant = input.toInstant(); mv.setId(UUID.randomUUID()); mv.setDevice(raw.getDevice()); mv.setMotionType(raw.getMotionType()); mv.setX(raw.getX()); mv.setY(raw.getY()); mv.setZ(raw.getZ()); mv.setTimestamp(instant); return mv; } }
package cqut.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * 读取源文件 * * @author Cheng * */ public class SourceReader { public static String sourcePath = "src/sample.jom"; public static String currentPath; public static List<String> read(String path) { currentPath = path; List<String> source = new ArrayList<String>(); FileReader fr = null; BufferedReader br = null; try { fr = new FileReader(path); br = new BufferedReader(fr); String strLine = ""; StringBuffer sb = new StringBuffer(); while ((strLine = br.readLine()) != null) { sb.append(strLine).append('\n'); source.add(strLine + '\n'); } sb = null; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fr != null) fr.close(); if (br != null) br.close(); } catch (IOException e) { e.printStackTrace(); } } return source; } public static void write(String source) { FileWriter fw; try { fw = new FileWriter(currentPath); fw.write(source); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } public static void write(String path, String source) { File f = new File(path); System.out.println(path); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } FileWriter fw; try { fw = new FileWriter(f); fw.write(source); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 获取当前源文件路径 * * @return */ public static String getAbsoluteFilePath() { return currentPath; } public static String getFileName() { String[] s = currentPath.split("\\\\"); return s[s.length - 1]; } }
package epfl.sweng.test; import java.util.Arrays; import java.util.HashSet; import org.apache.http.HttpStatus; import org.json.JSONException; import android.util.Log; import epfl.sweng.authentication.UserCredentials; import epfl.sweng.authentication.UserCredentials.AuthenticationState; import epfl.sweng.entry.MainActivity; import epfl.sweng.quizquestions.QuizQuestion; import epfl.sweng.searchquestions.QuestionIterator; import epfl.sweng.servercomm.SwengHttpClientFactory; import epfl.sweng.test.framework.QuizActivityTestCase; import epfl.sweng.test.minimalmock.MockHttpClient; import epfl.sweng.testing.TestCoordinator.TTChecks; import epfl.sweng.utils.JSONUtilities; /** * @author kokaku * */ public class QuestionIteratorTest extends QuizActivityTestCase<MainActivity> { private final MockHttpClient mockHttpClient = new MockHttpClient(); private final QuizQuestion[] questions = new QuizQuestion[] { new QuizQuestion( "question 1", Arrays.asList(new String[]{"1", "2", "3", "4"}), 0, new HashSet<String>(Arrays.asList(new String[] {"test"}))), new QuizQuestion( "question 2", Arrays.asList(new String[]{"a", "b", "c", "d"}), 1, new HashSet<String>(Arrays.asList(new String[] {"test"}))), new QuizQuestion( "question 3", Arrays.asList(new String[]{"A", "B", "C", "D"}), 2, new HashSet<String>(Arrays.asList(new String[] {"test"}))), new QuizQuestion( "question 4", Arrays.asList(new String[]{"4", "3", "2", "1"}), 3, new HashSet<String>(Arrays.asList(new String[] {"test"})))}; private final QuizQuestion[] newQuestions = new QuizQuestion[] { new QuizQuestion( "question 5", Arrays.asList(new String[]{"a1", "a2", "a3", "a4"}), 0, new HashSet<String>(Arrays.asList(new String[] {"test2"})), 0, "me"), new QuizQuestion( "question 6", Arrays.asList(new String[]{"a1", "b2", "c3", "d4"}), 1, new HashSet<String>(Arrays.asList(new String[] {"test2"})), 0, "me"), new QuizQuestion( "question 7", Arrays.asList(new String[]{"A.1", "B.2", "C.3", "D.4"}), 2, new HashSet<String>(Arrays.asList(new String[] {"test2"})), 0, "me"), new QuizQuestion( "question 8", Arrays.asList(new String[]{"q", "w", "e", "r"}), 3, new HashSet<String>(Arrays.asList(new String[] {"test2"})), 0, "me")}; private static final String LOG_TAG = QuestionIteratorTest.class.getName(); public QuestionIteratorTest() { super(MainActivity.class); } protected void setUp() throws Exception { super.setUp(); getActivityAndWaitFor(TTChecks.MAIN_ACTIVITY_SHOWN); UserCredentials.INSTANCE.setState(AuthenticationState.AUTHENTICATED); UserCredentials.INSTANCE.saveUserCredentials("test"); SwengHttpClientFactory.setInstance(mockHttpClient); mockHttpClient.pushCannedResponse( "GET (?:https?://[^/]+|[^/]+)?/+quizquestions/random\\b", HttpStatus.SC_OK, "", "application/json"); } @Override protected void tearDown() throws Exception { mockHttpClient.clearCannedResponses(); super.tearDown(); } public void testCannotConstructWithoutQuestion() { try { QuizQuestion[] question = null; new QuestionIterator(question); fail("QuestionIterator constructed without any questions"); } catch (IllegalArgumentException e) { Log.v(LOG_TAG, "IllegalArgumentException in testCannotConstructWithoutQuestion()", e); } try { new QuestionIterator(null, null, null); fail("QuestionIterator constructed without any questions"); } catch (IllegalArgumentException e) { Log.v(LOG_TAG, "IllegalArgumentException in testCannotConstructWithoutQuestion()", e); } } public void testCannotConstructWithoutQueryIfNextSetted() { try { new QuestionIterator(questions, null, "next"); fail("QuestionIterator constructed without any questions"); } catch (IllegalArgumentException e) { Log.v(LOG_TAG, "IllegalArgumentException in testCannotConstructWithoutQueryIfNextSetted()", e); } } public void testHasTheCorrectNumberOfQuestion() { QuestionIterator iterator = new QuestionIterator(questions); int counter = 0; while (iterator.hasNext()) { try { iterator.next(); } catch (Exception e) { Log.v(LOG_TAG, "Exception in testHasTheCorrectNumberOfQuestion()", e); fail("Unexpected exception"); } counter++; } assertTrue(counter == questions.length); } public void testNextReturnQuestionInCorrectOrder() { QuestionIterator iterator = new QuestionIterator(questions); int counter = 0; while (counter < questions.length && iterator.hasNext()) { try { assertTrue(questions[counter] == iterator.next()); } catch (Exception e) { Log.v(LOG_TAG, "Exception in testNextReturnQuestionInCorrectOrder()", e); fail("Unexpected exception"); } counter++; } } public void testGetLocalQuestionsReturnCorrectArrayOfQuestions() { QuestionIterator iterator = new QuestionIterator(questions); QuizQuestion[] retArray = iterator.getLocalQuestions(); assertTrue(retArray.length == questions.length); for (int i = 0; i < retArray.length; i++) { assertTrue(retArray[i] == questions[i]); } } private void pushNextQuestions() throws JSONException { String JSONQuestion = "{\"questions\": [ "; StringBuffer buf = new StringBuffer(); for(QuizQuestion question: newQuestions) { buf.append(JSONUtilities.getJSONString(question)+", "); } JSONQuestion += buf.toString(); JSONQuestion = JSONQuestion.substring(0, JSONQuestion.length()-2)+ " ]}"; mockHttpClient.clearCannedResponses(); mockHttpClient.pushCannedResponse( "POST [^/]+", HttpStatus.SC_OK, JSONQuestion, null); } private boolean questionsEquals(QuizQuestion q1, QuizQuestion q2) { return q1.getId()==q2.getId() && q1.getOwner().equals(q2.getOwner()) && q1.getQuestion().equals(q2.getQuestion()) && q1.getSolutionIndex() == q2.getSolutionIndex() && q1.getAnswers().equals(q2.getAnswers()) && q1.getTags().equals(q2.getTags()); } public void testWhenNextQuestionsFetchCorrectNumberOfQuestion() { try { pushNextQuestions(); } catch (JSONException e1) { Log.v(LOG_TAG, "JSONException in testWhenNextQuestionsFetchCorrectNumberOfQuestion()", e1); fail("Problem with mock"); } QuestionIterator iterator = new QuestionIterator(questions, "banana + patatos", "42"); for (int i = 0; i < questions.length; i++) { try { iterator.next(); } catch (Exception e) { Log.v(LOG_TAG, "Exception in testWhenNextQuestionsFetchCorrectNumberOfQuestion()", e); fail("Unexpected exception"); } } int counter = 0; while (iterator.hasNext()) { try { iterator.next(); } catch (Exception e) { Log.v(LOG_TAG, "Exception in testWhenNextQuestionsFetchCorrectNumberOfQuestion()", e); fail("Problem with mock"); } counter++; } assertTrue(counter == newQuestions.length); } public void testNextQuestionsFetchCorrectly() { try { pushNextQuestions(); } catch (JSONException e1) { Log.v(LOG_TAG, "JSONException in testNextQuestionsFetchCorrectly()", e1); fail("Problem with mock"); } QuestionIterator iterator = new QuestionIterator(questions, "banana + patatos", "42"); for (int i = 0; i < questions.length; i++) { try { iterator.next(); } catch (Exception e) { Log.v(LOG_TAG, "Exception in testNextQuestionsFetchCorrectly()", e); fail("Unexpected exception"); } } int counter = 0; while (counter < newQuestions.length && iterator.hasNext()) { try { assertTrue(questionsEquals(newQuestions[counter], iterator.next())); } catch (Exception e) { Log.v(LOG_TAG, "Exception in testNextQuestionsFetchCorrectly()", e); fail("Problem with mock"); } counter++; } } public void testWhenNextQuestionsFetchReturnCorrectArrayOfQuestions() { try { pushNextQuestions(); } catch (JSONException e1) { Log.v(LOG_TAG, "JSONException in testWhenNextQuestionsFetchReturnCorrectArrayOfQuestions()", e1); fail("Problem with mock"); } QuestionIterator iterator = new QuestionIterator(questions, "banana + patatos", "42"); for (int i = 0; i <= questions.length; i++) { try { iterator.next(); } catch (Exception e) { Log.v(LOG_TAG, "Exception in testWhenNextQuestionsFetchReturnCorrectArrayOfQuestions()", e); fail("Unexpected exception"); } } QuizQuestion[] retArray = iterator.getLocalQuestions(); assertTrue(retArray.length == newQuestions.length); for (int i = 0; i < retArray.length; i++) { assertTrue(questionsEquals(retArray[i], newQuestions[i])); } } }
package mk.finki.ukim.dians.surveygenerator.surveygeneratorcore.domain.jpamodels; import lombok.*; import javax.persistence.*; /** Definicija na model i negovo mapiranje so JPA anotacii*/ @Getter @Setter @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode @Entity @Table(schema = "surveys", name = "question_answers") public class QuestionAnswers { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "answer") private int answer; @ManyToOne @JoinColumn(name = "question_id") private SurveyQuestion surveyQuestion; }
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int[] values = new int[n]; int[] weights = new int[n]; for(int i=0; i<n;i++){ values[i] = scn.nextInt(); } for(int i=0; i<n;i++){ weights[i] = scn.nextInt(); } int capacity = scn.nextInt(); System.out.println(knapsack(n, values, weights, capacity)); } public static int knapsack(int n, int[]values, int[]weights,int cap){ int[]dp = new int[cap + 1]; dp[0]= 0; for(int i=0; i<n; i++){ int w = weights[i]; int v = values[i]; for(int j = w; j <= cap ; j++){ dp[j] = Math.max(dp[j -w]+v, dp[j]); } } return dp[cap]; } }
package com.example.cubomagicoranking2.Domain; public class Tempo { private int minutos; private int segundos; public Tempo() { } public Tempo(int minutos, int segundos) { this.minutos = minutos; this.segundos = segundos; } public Integer getMinutos() { return minutos; } public void setMinutos(Integer minutos) { this.minutos = minutos; } public Integer getSegundos() { return segundos; } public void setSegundos(Integer segundos) { this.segundos = segundos; } public Integer toSeconds() { return minutos*60 + segundos; } public String ofSeconds() { int minutosFinais = segundos/60; int segundosFinais = (segundos%60); Tempo tempoFinal = new Tempo(); tempoFinal.setMinutos(minutosFinais); tempoFinal.setSegundos(segundosFinais); return tempoFinal.toString(); } public String toString() { if(minutos == 1000){ return "DNF"; } if(String.valueOf(segundos).length() == 1 && String.valueOf(minutos).length() == 1) { return "0" + minutos + ":0" + segundos; } if(String.valueOf(minutos).length() == 1 && String.valueOf(segundos).length() == 2 ){ return "0"+minutos + ":" + segundos; } if(String.valueOf(minutos).length() == 2 && String.valueOf(segundos).length() == 1){ return minutos + ":0" + segundos; } else{ return minutos + ":" + segundos; } } }
package com.example.asus.myapp.Teacher; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.asus.myapp.R; import com.example.asus.myapp.Student.StudentLoginActivity; import com.example.asus.myapp.Student.StudentRegistrationActivity; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.Calendar; public class Add_info extends AppCompatActivity { EditText type,link; Button submit; FirebaseAuth firebaseAuth; DatabaseReference mdatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_info); type=(EditText)findViewById(R.id.type); link=(EditText)findViewById(R.id.link); submit=(Button)findViewById(R.id.submit); final String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()); firebaseAuth=FirebaseAuth.getInstance(); mdatabase = FirebaseDatabase.getInstance().getReference().child("Info"); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DatabaseReference infodb=mdatabase.push(); infodb.child("teacher").setValue(firebaseAuth.getCurrentUser().getUid()); infodb.child("info").setValue(link.getText().toString()); infodb.child("type").setValue(type.getText().toString()); infodb.child("id").setValue(infodb.getKey()); infodb.child("time").setValue(mydate); Toast.makeText(Add_info.this,"Information added",Toast.LENGTH_SHORT).show(); startActivity(new Intent(Add_info.this, TeacherAreaActivity.class)); finish(); } }); } }
package com.hdy.myhxc.mapper; import com.hdy.myhxc.model.Menu; import com.hdy.myhxc.model.MenuExample; import java.util.List; import org.apache.ibatis.annotations.*; import org.apache.ibatis.type.JdbcType; import org.springframework.stereotype.Repository; @Repository @Mapper public interface MenuMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_menu * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @SelectProvider(type=MenuSqlProvider.class, method="countByExample") long countByExample(MenuExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_menu * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @DeleteProvider(type=MenuSqlProvider.class, method="deleteByExample") int deleteByExample(MenuExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_menu * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @Delete({ "delete from m_menu", "where UUID = #{uuid,jdbcType=VARCHAR}" }) int deleteByPrimaryKey(String uuid); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_menu * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @Insert({ "insert into m_menu (UUID, Menu_ID, ", "Menu_Name, Menu_URL, ", "Parent_ID, Menu_ICO, ", "Leavel_ID, SORT, ", "Create_User, Create_Date, ", "Update_User, Update_Date, ", "DelFg, Beizhu)", "values (#{uuid,jdbcType=VARCHAR}, #{menuId,jdbcType=VARCHAR}, ", "#{menuName,jdbcType=VARCHAR}, #{menuUrl,jdbcType=VARCHAR}, ", "#{parentId,jdbcType=VARCHAR}, #{menuIco,jdbcType=VARCHAR}, ", "#{leavelId,jdbcType=INTEGER}, #{sort,jdbcType=INTEGER}, ", "#{createUser,jdbcType=VARCHAR}, #{createDate,jdbcType=TIMESTAMP}, ", "#{updateUser,jdbcType=VARCHAR}, #{updateDate,jdbcType=TIMESTAMP}, ", "#{delfg,jdbcType=VARCHAR}, #{beizhu,jdbcType=VARCHAR})" }) int insert(Menu record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_menu * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @InsertProvider(type=MenuSqlProvider.class, method="insertSelective") int insertSelective(Menu record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_menu * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @SelectProvider(type=MenuSqlProvider.class, method="selectByExample") @Results({ @Result(column="UUID", property="uuid", jdbcType=JdbcType.VARCHAR, id=true), @Result(column="Menu_ID", property="menuId", jdbcType=JdbcType.VARCHAR), @Result(column="Menu_Name", property="menuName", jdbcType=JdbcType.VARCHAR), @Result(column="Menu_URL", property="menuUrl", jdbcType=JdbcType.VARCHAR), @Result(column="Parent_ID", property="parentId", jdbcType=JdbcType.VARCHAR), @Result(column="Menu_ICO", property="menuIco", jdbcType=JdbcType.VARCHAR), @Result(column="Leavel_ID", property="leavelId", jdbcType=JdbcType.INTEGER), @Result(column="SORT", property="sort", jdbcType=JdbcType.INTEGER), @Result(column="Create_User", property="createUser", jdbcType=JdbcType.VARCHAR), @Result(column="Create_Date", property="createDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="Update_User", property="updateUser", jdbcType=JdbcType.VARCHAR), @Result(column="Update_Date", property="updateDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="DelFg", property="delfg", jdbcType=JdbcType.VARCHAR), @Result(column="Beizhu", property="beizhu", jdbcType=JdbcType.VARCHAR) }) List<Menu> selectByExample(MenuExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_menu * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @Select({ "select", "UUID, Menu_ID, Menu_Name, Menu_URL, Parent_ID, Menu_ICO, Leavel_ID, SORT, Create_User, ", "Create_Date, Update_User, Update_Date, DelFg, Beizhu", "from m_menu", "where UUID = #{uuid,jdbcType=VARCHAR}" }) @Results({ @Result(column="UUID", property="uuid", jdbcType=JdbcType.VARCHAR, id=true), @Result(column="Menu_ID", property="menuId", jdbcType=JdbcType.VARCHAR), @Result(column="Menu_Name", property="menuName", jdbcType=JdbcType.VARCHAR), @Result(column="Menu_URL", property="menuUrl", jdbcType=JdbcType.VARCHAR), @Result(column="Parent_ID", property="parentId", jdbcType=JdbcType.VARCHAR), @Result(column="Menu_ICO", property="menuIco", jdbcType=JdbcType.VARCHAR), @Result(column="Leavel_ID", property="leavelId", jdbcType=JdbcType.INTEGER), @Result(column="SORT", property="sort", jdbcType=JdbcType.INTEGER), @Result(column="Create_User", property="createUser", jdbcType=JdbcType.VARCHAR), @Result(column="Create_Date", property="createDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="Update_User", property="updateUser", jdbcType=JdbcType.VARCHAR), @Result(column="Update_Date", property="updateDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="DelFg", property="delfg", jdbcType=JdbcType.VARCHAR), @Result(column="Beizhu", property="beizhu", jdbcType=JdbcType.VARCHAR) }) Menu selectByPrimaryKey(String uuid); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_menu * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @UpdateProvider(type=MenuSqlProvider.class, method="updateByExampleSelective") int updateByExampleSelective(@Param("record") Menu record, @Param("example") MenuExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_menu * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @UpdateProvider(type=MenuSqlProvider.class, method="updateByExample") int updateByExample(@Param("record") Menu record, @Param("example") MenuExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_menu * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @UpdateProvider(type=MenuSqlProvider.class, method="updateByPrimaryKeySelective") int updateByPrimaryKeySelective(Menu record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_menu * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @Update({ "update m_menu", "set Menu_ID = #{menuId,jdbcType=VARCHAR},", "Menu_Name = #{menuName,jdbcType=VARCHAR},", "Menu_URL = #{menuUrl,jdbcType=VARCHAR},", "Parent_ID = #{parentId,jdbcType=VARCHAR},", "Menu_ICO = #{menuIco,jdbcType=VARCHAR},", "Leavel_ID = #{leavelId,jdbcType=INTEGER},", "SORT = #{sort,jdbcType=INTEGER},", "Create_User = #{createUser,jdbcType=VARCHAR},", "Create_Date = #{createDate,jdbcType=TIMESTAMP},", "Update_User = #{updateUser,jdbcType=VARCHAR},", "Update_Date = #{updateDate,jdbcType=TIMESTAMP},", "DelFg = #{delfg,jdbcType=VARCHAR},", "Beizhu = #{beizhu,jdbcType=VARCHAR}", "where UUID = #{uuid,jdbcType=VARCHAR}" }) int updateByPrimaryKey(Menu record); }
package com.example.ahmadrizaldi.traveloka_retrofit; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.example.ahmadrizaldi.traveloka_retrofit.Adapter.RegisterUser; public class MainMenu extends AppCompatActivity { Button user, maskapai, datapenerbangan; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_menu); user = (Button)findViewById(R.id.btn_user); maskapai = (Button)findViewById(R.id.btn_maskapai); datapenerbangan = (Button)findViewById(R.id.btn_DataPenerbangan); user.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(MainMenu.this, User_.class); startActivity(i); } }); maskapai.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(MainMenu.this, MaskapaiActivity.class); startActivity(i); } }); datapenerbangan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(MainMenu.this, InsertDataPenerbangan.class); startActivity(i); } }); } }
/* * Copyright 2003-2005 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 * * 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.jdon.jivejdon.service.imp.account; import javax.transaction.TransactionManager; import com.jdon.container.visitor.data.SessionContext; import com.jdon.container.visitor.data.SessionContextAcceptable; import com.jdon.controller.events.EventModel; import com.jdon.controller.model.PageIterator; import com.jdon.controller.service.Stateful; import com.jdon.jivejdon.Constants; import com.jdon.jivejdon.auth.ResourceAuthorization; import com.jdon.jivejdon.dao.AccountDao; import com.jdon.jivejdon.dao.SequenceDao; import com.jdon.jivejdon.dao.util.OldUpdateNewUtil; import com.jdon.jivejdon.model.Account; import com.jdon.jivejdon.model.auth.Role; import com.jdon.jivejdon.service.AccountService; import com.jdon.jivejdon.service.util.JtaTransactionUtil; import com.jdon.jivejdon.service.util.SessionContextUtil; import com.jdon.jivejdon.util.ToolsUtil; import com.jdon.util.Debug; import com.jdon.util.StringUtil; import com.jdon.util.task.TaskEngine; /** * @author <a href="mailto:banqiao@jdon.com">banq</a> * */ public class AccountServiceImp implements AccountService, Stateful, SessionContextAcceptable { private final static String module = AccountServiceImp.class.getName(); private AccountDao accountDao; private SequenceDao sequenceDao; protected SessionContext sessionContext; protected SessionContextUtil sessionContextUtil; protected JtaTransactionUtil jtaTransactionUtil; protected ResourceAuthorization resourceAuthorization; private OldUpdateNewUtil oldUpdateNewUtil; private EmailHelper emailHelper; public AccountServiceImp(AccountDao accountDao, SequenceDao sequenceDao, SessionContextUtil sessionContextUtil, JtaTransactionUtil jtaTransactionUtil, ResourceAuthorization resourceAuthorization, OldUpdateNewUtil oldUpdateNewUtil, EmailHelper emailHelper) { this.accountDao = accountDao; this.sequenceDao = sequenceDao; this.sessionContextUtil = sessionContextUtil; this.jtaTransactionUtil = jtaTransactionUtil; this.resourceAuthorization = resourceAuthorization; this.oldUpdateNewUtil = oldUpdateNewUtil; this.emailHelper = emailHelper; } public Account getloginAccount(){ return sessionContextUtil.getLoginAccount(sessionContext); } public Account getAccountByName(String username){ Account account = getloginAccount(); if (resourceAuthorization.isAdmin(account))// if now is Admin return accountDao.getAccountByName(username); else return account; } public Account getAccount(Long userId) { return accountDao.getAccount(userId.toString()); } /** * init the account */ public Account initAccount(EventModel em) { return new Account(); } /* (non-Javadoc) * @see com.jdon.framework.samples.jpetstore.service.AccountService#insertAccount(com.jdon.framework.samples.jpetstore.domain.Account) */ public void createAccount(EventModel em) { Account account = (Account) em.getModelIF(); Debug.logVerbose("createAccount username=" + account.getUsername(), module); TransactionManager tx = jtaTransactionUtil.getTransactionManager(); try { if (accountDao.getAccountByEmail(account.getEmail()) != null) { em.setErrors(Constants.EMAIL_EXISTED); return; } if (accountDao.getAccountByName(account.getUsername()) != null) { em.setErrors(Constants.USERNAME_EXISTED); return; } tx.begin(); Long userIDInt = sequenceDao.getNextId(Constants.USER); Debug.logVerbose("new userIDInt =" + userIDInt, module); account.setUserId(userIDInt.toString().trim()); //setup the role is User account.setRoleName(Role.USER); account.setPassword(ToolsUtil.hash(account.getPassword())); accountDao.createAccount(account); tx.commit(); } catch (Exception e) { Debug.logError(" createAccount error : " + e, module); em.setErrors(Constants.ERRORS); jtaTransactionUtil.rollback(tx); } } /* (non-Javadoc) * @see com.jdon.framework.samples.jpetstore.service.AccountService#updateAccount(com.jdon.framework.samples.jpetstore.domain.Account) */ public void updateAccount(EventModel em) { Debug.logVerbose("enter updateAccount", module); Account accountInput = (Account) em.getModelIF(); TransactionManager tx = jtaTransactionUtil.getTransactionManager(); try { Account account = getloginAccount(); if (account == null) { Debug.logError("this user not login", module); return; } tx.begin(); if (resourceAuthorization.isOwner(account, accountInput)) { accountInput.setPassword(ToolsUtil.hash(accountInput.getPassword())); accountDao.updateAccount(accountInput); } tx.commit(); } catch (Exception daoe) { Debug.logError(" updateAccount error : " + daoe, module); em.setErrors(Constants.ERRORS); jtaTransactionUtil.rollback(tx); } } public void deleteAccount(EventModel em) { Account account = (Account) em.getModelIF(); TransactionManager tx = jtaTransactionUtil.getTransactionManager(); try { tx.begin(); accountDao.deleteAccount(account); tx.commit(); } catch (Exception e) { em.setErrors(Constants.ERRORS); jtaTransactionUtil.rollback(tx); } } /* (non-Javadoc) * @see com.jdon.jivejdon.service.AccountService#getAccounts(int, int) */ public PageIterator getAccounts(int start, int count) { return accountDao.getAccounts(start, count); } public void forgetPasswd(EventModel em){ Account accountParam = (Account) em.getModelIF(); Account account = null; TransactionManager tx = jtaTransactionUtil.getTransactionManager(); try { account = accountDao.getAccountByEmail(accountParam.getEmail()); if (account == null) { em.setErrors(Constants.NOT_FOUND); return; } if ((account.getPasswdanswer().equalsIgnoreCase(accountParam.getPasswdanswer())) && (account.getPasswdtype().equalsIgnoreCase(accountParam.getPasswdtype()))){ tx.begin(); String newpasswd = StringUtil.getPassword(8); account.setPassword(ToolsUtil.hash(newpasswd)); accountDao.updateAccount(account); emailHelper.send(account, newpasswd); tx.commit(); }else{ em.setErrors(Constants.NOT_FOUND); return; } } catch (Exception e) { em.setErrors(Constants.ERRORS); jtaTransactionUtil.rollback(tx); } } /** * @return Returns the sessionContext. */ public SessionContext getSessionContext() { return sessionContext; } /** * @param sessionContext The sessionContext to set. */ public void setSessionContext(SessionContext sessionContext) { this.sessionContext = sessionContext; } public void update(){ TaskEngine.addTask(oldUpdateNewUtil); Debug.logVerbose("work is over", module); Debug.logVerbose("work is over", module); } }
package com.em.service; import java.io.Serializable; import com.em.dto.EmployeeDto; public interface EmployeeServiceInterface { /* * public Long saveEmployee(EmployeeDto employee); public int * deleteEmployee(EmployeeDto employee); public EmployeeDto getEmployee(Long * id); public EmployeeDto updateEmployee(EmployeeDto employee); */ public EmployeeDto getEmpByLoginId(String loginId ); public void deleteAccount(EmployeeDto emp); public void udpateEmp(EmployeeDto empFromJspp); public Serializable saveEmpInDb(EmployeeDto employee); }
/** * 会议用户类型基类 * Created by wangy on 2017/1/16. */ public class BaseUser { private static final int LOCAL_USER_PRIORITY = 100; private static final int MAIN_SPEAKER_PRIORITY = 99; private static final int TELEPHONE_USER_PRIORITY = -100; protected RoomUserInfo userInfo; /** * 构造器 * */ public BaseUser(RoomUserInfo userInfo) { this.userInfo = userInfo; } public void setRoomInfo(RoomUserInfo roomUserInfo) { userInfo = roomUserInfo; } /** * 检查是否有广播音频的权限 */ public boolean checkAudioPermission() { return !isListener(); } /** * 检查是否有广播音频的权限 */ public boolean checkVideoPermission() { return !isListener() && !MeetingModel.getInstance().isAudioMeeting(); } /** * 检查是否有申请主讲的权限 */ public boolean checkMainSpeakPermission() { return !isListener(); } /** * 检查音频频权限 */ public boolean checkAVPermission() { return checkVideoPermission() && checkAudioPermission(); } /** * 检查是否具有公聊权限 */ public boolean checkPubChatPermission() { MeetingModel roomInfoModel = MeetingModel.getInstance(); return roomInfoModel.chatEnable() && roomInfoModel.pubChatEnable() && isChatEnable(); } /** * 检查是否具有私聊权限 */ public boolean checkP2pChatPermission() { MeetingModel roomInfoModel = MeetingModel.getInstance(); return roomInfoModel.chatEnable() && roomInfoModel.p2pChatEnable() && isChatEnable(); } /** * 检查是否有控制远程用户的权限,如发言,视频广播,其实际就是当前用户是主讲或者主席与{@checkHighestPermission()}方法返回一致 */ public boolean checkControlRemotePermission() { return checkHighestPermission(); } /** * @return 请出会议室权限:只有主席才有权限 */ public boolean checkRemoveUserPermission() { return userInfo.userRight == RoomUserInfo.USERRIGHT_CHAIR; } /** * 检查是否有共享文档的权限 * * @return 只有非旁听用户才具有共享文档的权限 */ public boolean checkSharePermission() { return checkMainSpeakPermission(); } /** * 用户是否具有最高权限,即是主席或者主讲 */ public boolean checkHighestPermission() { return isChair() || isMainSpeakerDone(); } public boolean isMainSpeakerDone() { return userInfo.dataState == RoomUserInfo.STATE_DONE; } public boolean isMainSpeakerWait() { return userInfo.dataState == RoomUserInfo.STATE_WAITING; } /** * 不在主讲状态,不包含申请主讲中状态 */ public boolean isMainSpeakerNone() { return userInfo.dataState == RoomUserInfo.STATE_NONE; } /** * 是否在主讲或者申请主讲状态中 */ public boolean isMainSpeakerDoneOrWait() { return !isMainSpeakerNone(); } /** * 是否在共享 */ public boolean isVncDone() { return userInfo.vncState == RoomUserInfo.STATE_DONE; } public boolean isMediaShareDone() { return (userInfo.audioShareID != 0 || userInfo.videoShareID != 0) && userInfo.mediaShareState != RoomUserInfo.MEDIA_SHARE_PAUSE; } public boolean isMediaSharePause() { return userInfo.mediaShareState == RoomUserInfo.MEDIA_SHARE_PAUSE; } public boolean isMediaShareNone() { return (userInfo.audioShareID == 0 && userInfo.videoShareID == 0); } /** * 是否是电话接入用户 */ public boolean isTelephoneUser() { return userInfo.terminalType == RoomUserInfo.TERMINAL_TELEPHONE; } /** * 是否有接入的视屏设备 */ public boolean isVideoDeviceConnected() { if (userInfo.vclmgr == null) { return false; } return userInfo.vclmgr.getChannelCount() > 0; } /** * 是否有音频设备接入 */ public boolean isAudioDeviceConnected() { return userInfo.audioChannel.hasAudio == RoomUserInfo.STATE_BOOL_TRUE; } public boolean isVncNone() { return userInfo.vncState == RoomUserInfo.STATE_NONE; } /** * 是否是本地用户 */ public final boolean isLocalUser() { return UserManager.getInstance().getLocalUserID() == userInfo.userID; } public VideoChannelManager getVideoManager() { return userInfo.vclmgr; } public long getUserID() { return this.userInfo.userID; } /** * 获取用户昵称,如果昵称为空,则返回用户名称 */ public String getNickName() { if (userInfo.strNickName == null) { return userInfo.strUserName; } return userInfo.strNickName; } /** * 获取已经接入的视频设备列表 */ public ArrayList<VideoChannel> getVideoChannelList() { if (userInfo.vclmgr == null) { return new ArrayList<>(); } return userInfo.vclmgr.getChannelList(); } /** * 是否是主席用户 */ public boolean isChair() { return userInfo.userRight == RoomUserInfo.USERRIGHT_CHAIR; } /** * 是否是旁听用户 */ public boolean isListener() { return userInfo.userRight == RoomUserInfo.USERRIGHT_LISTENER; } /** * 是否是出席用户 */ public boolean isAttender() { return userInfo.userRight == RoomUserInfo.USERRIGHT_ATTENDER; } /** * 是否正在发言中 */ public boolean isSpeechDone() { return userInfo.audioChannel.state == AudioChannel.AUDIO_STATE_DONE; } /** * 是否正在申请发言 */ public boolean isSpeechWait() { return userInfo.audioChannel.state == AudioChannel.AUDIO_STATE_WAITING; } /** * 未发言状态,不包含申请中状态 */ public boolean isSpeechNone() { return userInfo.audioChannel.state == AudioChannel.AUDIO_STATE_NONE; } /** * 是否在广播视频,只要有一路视频在广播,则返回true */ public boolean isVideoDone() { return userInfo.vclmgr != null && userInfo.vclmgr.hasStateDone(); } /** * 没有视频在广播 */ public boolean isVideoNone() { return userInfo.vclmgr == null || !userInfo.vclmgr.hasStateDone(); } /** * 是否有白板标注权限 */ public boolean isWBMarkDone() { return userInfo.wbMarkState == RoomUserInfo.STATE_DONE; } /** * 获取用户优先级Id, * 用于排序,本地用户 > 主讲 > 主席 > 出席 > 旁听 > 电话用户 */ public int getUserPriority() { if (isTelephoneUser()) { return TELEPHONE_USER_PRIORITY; } else if (isLocalUser()) { return LOCAL_USER_PRIORITY; } else if (isMainSpeakerDone()) { return MAIN_SPEAKER_PRIORITY; } else { return userInfo.userRight; } } /** * 用户本身是否具有聊天的权限 */ private boolean isChatEnable() { return userInfo.enableChat == RoomInfo.STATE_DONE; } /** * 指定的视频channelId的视频是否在广播 * */ public boolean isVideoChannelDone(byte channelId) { return userInfo.vclmgr != null && userInfo.vclmgr.getChannelState(channelId) == RoomUserInfo.STATE_DONE; } }
package com.jaiaxn.design.pattern.behavioral.visitor; /** * @author: wang.jiaxin * @date: 2019年08月27日 * @description: **/ public interface ComputerPartVisitor { /** * 访问电脑各个部分 * @param computer 电脑 */ void visit(Computer computer); /** * 访问电脑各个部分 * @param mouse 鼠标 */ void visit(Mouse mouse); /** * 访问电脑各个部分 * @param keyboard 键盘 */ void visit(Keyboard keyboard); /** * 访问电脑各个部分 * @param monitor 显示器 */ void visit(Monitor monitor); }
package org.typhon.client.model.dto; import java.util.*; import java.sql.Timestamp; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class CustomerDetailsDTO { private String oid; private String name; private String surname; private String city; public void setOid (String oid){ this.oid = oid; } public String getOid(){ return oid; } public void setName (String name){ this.name = name; } public String getName(){ return name; } public void setSurname (String surname){ this.surname = surname; } public String getSurname(){ return surname; } public void setCity (String city){ this.city = city; } public String getCity(){ return city; } }
package com.notthemostcommon.creditcardpayoff.Calculator; import org.junit.Test; import org.junit.jupiter.api.DisplayName; import java.util.Map; import static org.junit.Assert.assertEquals; public class InterestCalculatorTest { private InterestCalculator iCalc = new InterestCalculator(); @Test public void calculatesInterest(){ double apr = 10.00; double balance = 100.00; String interest = iCalc.calculateInterest(apr, balance); assertEquals("0.83", interest); } @Test @DisplayName("Return 1 month of interest") public void calculatesNoInterest(){ double monthlyPayment = 100.00; Map<String, Object> interestCalc = iCalc.calculateTotalAccruedInterest(10, 100, monthlyPayment); String interestPaid = interestCalc.get("accruedInterest").toString(); assertEquals("0.83", interestPaid ); } @Test @DisplayName("Calculates 2 months of interest") public void calculates2MonthsInterest(){ double monthlyPayment = 50.00; Map<String, Object> interestCalc = iCalc.calculateTotalAccruedInterest(10, 100, monthlyPayment); String interestPaid = interestCalc.get("accruedInterest").toString(); assertEquals("1.66", interestPaid ); } @Test @DisplayName("Counts number of months of payments") public void returns3Months(){ String monthsTilPayoff = "3"; double monthlyPayment = 50.00; Map<String, Object> interestCalc = iCalc.calculateTotalAccruedInterest(10, 100, monthlyPayment); String months = interestCalc.get("monthsOfPayments").toString(); assertEquals(monthsTilPayoff, months ); } @Test @DisplayName("Returns 1 month of payment") public void returns1Month(){ String monthsTilPayoff = "1"; double monthlyPayment = 100.83; Map<String, Object> interestCalc = iCalc.calculateTotalAccruedInterest(10, 100, monthlyPayment); String months = interestCalc.get("monthsOfPayments").toString(); assertEquals(monthsTilPayoff, months ); } }
package serializer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Serializer { private final ObjectMapper objectMapper; public Serializer() { this.objectMapper = new ObjectMapper(); } public String fromObjectTotString(Object o) throws JsonProcessingException { return objectMapper.writeValueAsString(o); } }
package com.pdd.pop.sdk.http.api.request; import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty; import com.pdd.pop.sdk.http.api.response.PddSmsTemplateQueryResponse; import com.pdd.pop.sdk.http.HttpMethod; import com.pdd.pop.sdk.http.PopBaseHttpRequest; import com.pdd.pop.sdk.common.util.JsonUtil; import java.util.Map; import java.util.TreeMap; public class PddSmsTemplateQueryRequest extends PopBaseHttpRequest<PddSmsTemplateQueryResponse>{ /** * 0, "优惠券", 1, "提醒付款", 2, "活动营销", 3, "召唤买家成团", 4, "新客转化", 5, "老客召回", 6, "流失唤醒", 7, "用户自定义", 8, "个性化营销", 9, "精准客户推送" */ @JsonProperty("scene") private Integer scene; @Override public String getVersion() { return "V1"; } @Override public String getDataType() { return "JSON"; } @Override public String getType() { return "pdd.sms.template.query"; } @Override public HttpMethod getHttpMethod() { return HttpMethod.POST; } @Override public Class<PddSmsTemplateQueryResponse> getResponseClass() { return PddSmsTemplateQueryResponse.class; } @Override public Map<String, String> getParamsMap() { Map<String, String> paramsMap = new TreeMap<String, String>(); paramsMap.put("version", getVersion()); paramsMap.put("data_type", getDataType()); paramsMap.put("type", getType()); paramsMap.put("timestamp", getTimestamp().toString()); if(scene != null) { paramsMap.put("scene", scene.toString()); } return paramsMap; } public void setScene(Integer scene) { this.scene = scene; } }
package download.service.impl; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import berkeley.service.BerkeleyService; import berkeley.service.impl.BerkeleyServiceImpl; import csv.service.CsvService; import csv.service.impl.CsvServiceImpl; import download.service.DownLoadService; import download.util.ThunderDownLoad; import quartz.job.DownLoadJob; import quartz.util.JobUtil; import util.ConstantUtil; import util.DateUtil; public class DownLoadServiceImpl implements DownLoadService { private static String _ssPath; private static String _szPath; private static Map<String, String> compMap; private static List<String> fileNameList; private static DownLoadServiceImpl INSTANCE; public static synchronized DownLoadServiceImpl getInstance() { if (null == INSTANCE) { INSTANCE = new DownLoadServiceImpl(); } return INSTANCE; } private DownLoadServiceImpl() { _ssPath = ConstantUtil.CSV_PATH + ConstantUtil.SS_PATH; _szPath = ConstantUtil.CSV_PATH + ConstantUtil.SZ_PATH; // 获取编码信息 BerkeleyService berkeleyService = BerkeleyServiceImpl.getInstance(); compMap = berkeleyService.queryDatabaseByKey(ConstantUtil.STOCK_DB, ConstantUtil.STOCK_KEY); // 获取上海文件的文件名 fileNameList = new ArrayList<>(); File ssFile = new File(_ssPath); File[] ssFiles = ssFile.listFiles(); if (ssFiles.length > 0) { for (File _file : ssFiles) { fileNameList.add(_file.getName()); } } // 获取深圳文件的文件名 File szFile = new File(_szPath); File[] szFiles = szFile.listFiles(); if (szFiles.length > 0) { for (File _file : szFiles) { fileNameList.add(_file.getName()); } } } /** * 获取所有股票历史数据 */ @Override public void getYahooFinanceStockData() { String today = DateUtil.getToday(); String tmpFileName; String downLoadPath = null; for (String fileName : fileNameList) { tmpFileName = fileName.substring(0, fileName.indexOf("_") - 1); compMap.remove(tmpFileName); } // 若所有编码还有没下载完成的,就按照名字重新下载 if (!compMap.isEmpty()) { for (Map.Entry<String, String> entry : compMap.entrySet()) { String compCode = entry.getKey(); String type = compCode.substring(0, 2); if ("sh".equals(type)) { downLoadPath = _ssPath; } else if ("sz".equals(type)) { downLoadPath = _szPath; } String code = compCode.substring(2); new ThunderDownLoad().httpDown( "http://table.finance.yahoo.com/table.csv?s=" + code + "." + type + "&g=d&ignore=.csv", downLoadPath, entry.getKey() + "_" + today + ".csv", 5); } // 所有的csv文档下载完成后立刻开始解析csv文档 CsvService csvService = CsvServiceImpl.getInstance(); csvService.storageAllCSVInToday(); } } /** * 定时器下载csv文档 每天凌晨15分 */ @Override public void startDownLoadJobThread() { Map<String, String> paramMap = new HashMap<>(); paramMap.put("type", "cron"); paramMap.put("cron", "0 15 00 * * ?"); try { JobUtil.initJob(DownLoadJob.class, "DownLoadCSV", paramMap); } catch (Exception e) { e.printStackTrace(); } } }
package other.shortestpath; import java.util.Scanner; /** * 五行代码解决求任意两点最短的路径,因为两点之间的最短路径可以通过第三点,第四点或者第五点等等中转。 * 比如:上海可以到杭州,但是上海可以通过湖南,湖北然后到杭州。 * 上海+杭州 > 上海+湖南+杭州 的距离,则上海+湖南+杭州是最短的距离,则更新路径Map(通过湖南中转) * 上海+杭州 > 上海+湖北+杭州 的距离,上海+湖南+杭州>上海+湖北+杭州 则上海+湖北+杭州是最短的距离,则更新路径Map (通过湖北中转) * 但是有可能: * 上海+杭州>上海 + 湖南 + 湖北 + 杭州的距离, 则上海 + 湖南 + 湖北 + 杭州 是最短的距离,更新路径Map(通过湖南,湖北中转) * * @author 丹丘生 */ public class FloydWarshall { static int[][] map; static int n; public static void main(String[] args) { Scanner read = new Scanner(System.in); //几个点 n = read.nextInt(); //几条边 int m = read.nextInt(); map = new int[n + 1][n + 1]; initMap(); for (int index = 0; index < m; index++) { int row = read.nextInt(); int col = read.nextInt(); int distance = read.nextInt(); map[row][col] = distance; } // 核心代码 //第一层循环为中间点,中转的城市 ,可能中转1,3或者1,2 for (int center = 1; center <= n; center++) { // 第二,三层是当前的城市到另一个城市的直接距离 for (int row = 1; row <= n; row++) { for (int col = 1; col <= n; col++) { if (map[row][center] < Integer.MAX_VALUE && map[center][col] < Integer.MAX_VALUE && map[row][col] > map[row][center] + map[center][col]) { map[row][col] = map[row][center] + map[center][col]; } } } } for (int row = 1; row <= n; row++) { for (int col = 1; col <= n; col++) { System.out.printf("%10d", map[row][col]); } System.out.println(); } } private static void initMap() { for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) { map[i][j] = Integer.MAX_VALUE; // 无法到达 if (i == j) map[i][j] = 0; } } } } //4 8 //1 2 2 //1 3 6 //1 4 4 //2 3 3 //3 1 7 //3 4 1 //4 1 5 //4 3 12
package com.junzhao.shanfen.fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.junzhao.base.base.APPCache; import com.junzhao.base.base.BaseFrag; import com.junzhao.base.http.IHttpResultSuccess; import com.junzhao.base.http.MLHttpRequestMessage; import com.junzhao.base.http.MLHttpType; import com.junzhao.base.http.MLRequestParams; import com.junzhao.base.utils.ImageUtils; import com.junzhao.shanfen.EventBusContant; import com.junzhao.shanfen.R; import com.junzhao.shanfen.activity.MyBusinessCardAty; import com.junzhao.shanfen.activity.MyCompanyAty; import com.junzhao.shanfen.activity.MyMoneyAty; import com.junzhao.shanfen.activity.SettingAty; import com.junzhao.shanfen.activity.UserInfoAty; import com.junzhao.shanfen.model.LZMeData; import com.junzhao.shanfen.service.CommService; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.lidroid.xutils.view.annotation.event.OnClick; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; /** * Created by Administrator on 2018/3/22. */ public class LZmeFrag extends BaseFrag { private View view; @ViewInject(R.id.tv_comeput) TextView tv_comeput; @ViewInject(R.id.tv_comeput1) TextView tv_comeput1; @ViewInject(R.id.tv_comzigongsi) TextView tv_comzigongsi; @ViewInject(R.id.rel_busstion_orange) RelativeLayout rel_busstion_orange; @ViewInject(R.id.ll_bussion_white) LinearLayout ll_bussion_white; @ViewInject(R.id.tv_job) TextView tv_job; @ViewInject(R.id.tv_tel) TextView tv_tel; @ViewInject(R.id.tv_phone1) TextView tv_phone1; @ViewInject(R.id.tv_address) TextView tv_address; @ViewInject(R.id.tv_address1) TextView tv_address1; @ViewInject(R.id.tv_job1) TextView tv_job1; @ViewInject(R.id.tv_name) TextView tv_name; @ViewInject(R.id.tv_name1) TextView tv_name1; @ViewInject(R.id.tv_email) TextView tv_email; @ViewInject(R.id.tv_email1) TextView tv_email1; @ViewInject(R.id.iv_topic) ImageView iv_topic; @ViewInject(R.id.iv_topic1) ImageView iv_topic1; LZMeData lzMeData; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (view == null) { view = inflater.inflate(R.layout.aty_personcenter, null); ViewUtils.inject(this, view); EventBus.getDefault().register(this); } return view; } @Override public void onDestroyView() { super.onDestroyView(); EventBus.getDefault().unregister(this); } @Override public void onResume() { super.onResume(); showCustom(); getPersonData(); } private void showCustom() { String backColor = APPCache.getBussitionBackgroup(); String show = APPCache.getBussitionShow(); if("white".equals(backColor)){ ll_bussion_white.setVisibility(View.VISIBLE); rel_busstion_orange.setVisibility(View.GONE); }else { ll_bussion_white.setVisibility(View.GONE); rel_busstion_orange.setVisibility(View.VISIBLE); } if(show.contains("phone")){ tv_tel.setVisibility(View.VISIBLE); tv_phone1.setVisibility(View.VISIBLE); }else { tv_tel.setVisibility(View.INVISIBLE); tv_phone1.setVisibility(View.INVISIBLE); } if (show.contains("email")){ tv_email.setVisibility(View.VISIBLE); tv_email1.setVisibility(View.VISIBLE); }else { tv_email.setVisibility(View.INVISIBLE); tv_email1.setVisibility(View.INVISIBLE); } if (show.contains("job")){ tv_job.setVisibility(View.VISIBLE); tv_job1.setVisibility(View.VISIBLE); }else { tv_job.setVisibility(View.INVISIBLE); tv_job1.setVisibility(View.INVISIBLE); } } @OnClick({R.id.rel_busstion,R.id.rel_company,R.id.rel_money,R.id.rel_welfare,R.id.rel_setting,R.id.ll_bussion_white,R.id.rel_busstion_orange}) public void onClick(View view){ switch (view.getId()){ case R.id.rel_busstion: //我的名片 startAct(this, MyBusinessCardAty.class); break; case R.id.rel_company: //我的公司 startAct(this,MyCompanyAty.class); break; case R.id.rel_money: //我的钱包 startAct(this,MyMoneyAty.class); break; case R.id.rel_welfare: //我的福利 break; case R.id.rel_setting: //设置 startAct(this,SettingAty.class); break; case R.id.ll_bussion_white: //头像(用户信息) startAct(this,UserInfoAty.class); break; case R.id.rel_busstion_orange: startAct(this,UserInfoAty.class); break; } } public void getPersonData() { MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("token", APPCache.getToken()); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.GETCARDINFO, mlHttpParam, LZMeData.class, CommService.getInstance(), true); loadData2(getActivity(), message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { lzMeData = (LZMeData) obj; tv_comeput.setText(lzMeData.headCompanyName); tv_comzigongsi.setText(lzMeData.branchCompanyName); tv_name.setText(lzMeData.userName); tv_job.setText("职位:"+(lzMeData.position == null ? "" : lzMeData.position) ); tv_tel.setText("手机:"+(lzMeData.tel == null ? "" : lzMeData.tel) ); tv_email.setText("邮箱:"+(lzMeData.email == null ? "" : lzMeData.email)); tv_address.setText("地址:"+(lzMeData.address == null ? "" : lzMeData.address)); ImageUtils.dispatchImage(lzMeData.photo,iv_topic); tv_comeput1.setText(lzMeData.headCompanyName); tv_name1.setText(lzMeData.userName); tv_phone1.setText("手机:"+(lzMeData.tel == null ? "" : lzMeData.tel) ); tv_email1.setText("邮箱:"+(lzMeData.email == null ? "" : lzMeData.email)); tv_address1.setText("地址:"+(lzMeData.address == null ? "" : lzMeData.address)); tv_job1.setText("职位:"+(lzMeData.position == null ? "" : lzMeData.position) ); ImageUtils.dispatchImage(lzMeData.photo,iv_topic1); } } ); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMessage(EventBusContant contant){ if (contant.getFlag() == EventBusContant.RESH_BUSINESS){ showCustom(); } } }
package com.lucasirc.servercatalog.resources; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lucasirc.servercatalog.model.Application; import com.lucasirc.servercatalog.model.Server; import com.lucasirc.servercatalog.service.ApplicationResourceService; import com.lucasirc.servercatalog.service.ServerResourceService; import com.lucasirc.servercatalog.service.v1.ApplicationV1Transformer; import com.lucasirc.servercatalog.service.v1.ServerV1Transformer; import org.junit.Test; import org.mockito.Mockito; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ApplicationResourceTests { @Test public void testGet() { Application app = new Application(13l, "game 123", "lucas"); Map appMap = new ApplicationV1Transformer().entityToMap(app); ApplicationResourceService appspy = Mockito.spy(new ApplicationResourceService(null,null)); Mockito.doReturn(appMap).when(appspy).get(13l); ApplicationResource resource = new ApplicationResource(); ApplicationResource resourceS = Mockito.spy(resource); Mockito.doReturn(appspy).when(resourceS).getAppResourceService(); Response response = resourceS.get(13l); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals(MediaType.APPLICATION_JSON, response.getMediaType().toString()); Object obj = response.getEntity(); assertTrue(obj instanceof String); JsonObject objJson = new JsonParser().parse((String) obj).getAsJsonObject(); assertEquals(13l, objJson.get("id").getAsLong()); assertEquals("game 123", objJson.get("name").getAsString()); assertEquals("lucas", objJson.get("owner").getAsString()); } @Test public void testGet_not_found() { ApplicationResourceService appspy = Mockito.spy(new ApplicationResourceService(null,null)); Mockito.doReturn(null).when(appspy).get(13l); ApplicationResource resource = new ApplicationResource(); ApplicationResource resourceS = Mockito.spy(resource); Mockito.doReturn(appspy).when(resourceS).getAppResourceService(); Response response = resourceS.get(13l); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); assertEquals(MediaType.APPLICATION_JSON, response.getMediaType().toString()); } /** * POST Tests */ @Test public void testPost() throws URISyntaxException { Application app = new Application(13l, "teste", "teste2"); ApplicationResourceService appSpy = Mockito.spy(new ApplicationResourceService(null, null)); Mockito.doReturn(app).when(appSpy).create("{\"name\": \"teste\"}"); ApplicationResource resourceS = Mockito.spy( new ApplicationResource()); Mockito.doReturn(appSpy).when(resourceS).getAppResourceService(); UriInfo uriInfo = Mockito.mock(UriInfo.class); Mockito.when(uriInfo.getRequestUri()).thenReturn(new URI("path_get")); resourceS.uriInfo = uriInfo; Response response = resourceS.post("{\"name\": \"teste\"}"); assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); assertEquals("path_get/13", response.getHeaders().get("Location").get(0).toString()); } /** * PUT Tests */ @Test public void testPut() throws URISyntaxException { Application app = new Application(145l, "teste", "teste2"); ApplicationResourceService appSpy = Mockito.spy(new ApplicationResourceService(null, null)); Mockito.doReturn(app).when(appSpy).update(145l, "{\"name\": \"teste\"}"); ApplicationResource resourceS = Mockito.spy( new ApplicationResource()); Mockito.doReturn(appSpy).when(resourceS).getAppResourceService(); Response response = resourceS.put("{\"name\": \"teste\"}", 145); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } @Test public void testPut_not_found() { ApplicationResourceService appSpy = Mockito.spy(new ApplicationResourceService(null, null)); Mockito.doReturn(null).when(appSpy).update(145l, "{\"name\": \"teste\"}"); ApplicationResource resourceS = Mockito.spy( new ApplicationResource()); Mockito.doReturn(appSpy).when(resourceS).getAppResourceService(); Response response = resourceS.put("{\"name\": \"teste\"}", 145); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); } @Test public void testList() { List<Map> servers = new ArrayList<Map>(); Map appMap = new ApplicationV1Transformer().entityToMap(new Application(13l, "game 1","lucas")); servers.add(appMap); appMap = new ApplicationV1Transformer().entityToMap(new Application(11l, "game 2", "jose")); servers.add(appMap); ApplicationResourceService appSpy = Mockito.spy(new ApplicationResourceService(null, null)); Mockito.doReturn(servers).when(appSpy).list(0l, 10l); ApplicationResource resourceS = Mockito.spy( new ApplicationResource()); Mockito.doReturn(appSpy).when(resourceS).getAppResourceService(); Response response = resourceS.list(0l, 10l); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals(MediaType.APPLICATION_JSON, response.getMediaType().toString()); Object obj = response.getEntity(); assertTrue(obj instanceof String); JsonArray objJson = new JsonParser().parse((String) obj).getAsJsonArray(); assertEquals(2, objJson.size()); assertEquals(13l, objJson.get(0).getAsJsonObject().get("id").getAsLong()); assertEquals("game 1", objJson.get(0).getAsJsonObject().get("name").getAsString()); assertEquals("lucas", objJson.get(0).getAsJsonObject().get("owner").getAsString()); assertEquals(11l, objJson.get(1).getAsJsonObject().get("id").getAsLong()); assertEquals("game 2", objJson.get(1).getAsJsonObject().get("name").getAsString()); assertEquals("jose", objJson.get(1).getAsJsonObject().get("owner").getAsString()); } @Test public void testDelete() { Application app = new Application(1l, "a","b"); ApplicationResourceService appSpy = Mockito.spy(new ApplicationResourceService(null, null)); Mockito.doReturn(app).when(appSpy).delete(1l); ApplicationResource resourceS = Mockito.spy( new ApplicationResource()); Mockito.doReturn(appSpy).when(resourceS).getAppResourceService(); Response response = resourceS.delete(1); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } @Test public void testDelete_not_found() { ApplicationResourceService appSpy = Mockito.spy(new ApplicationResourceService(null, null)); Mockito.doReturn(null).when(appSpy).delete(145l); ApplicationResource resourceS = Mockito.spy( new ApplicationResource()); Mockito.doReturn(appSpy).when(resourceS).getAppResourceService(); Response response = resourceS.delete(145); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); } }
package engine.managers.general; import views.GraphicsHelper; import views.screens.GameScreen; import views.screens.ScreenHandler; import views.screens.ScreenType; import views.screens.GameScreen.LocalGameListener; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Image; import engine.Values; import engine.managers.GameScrollManager; /** * Logic Helper. A class that takes care of the logical part in the game. * @author David Lasry * */ public class LogicManager { private final String[] CRYSTALS_COLORS = {"green", "blue", "grey", "orange", "pink", "yellow"}; private int index = 1; private int limitCoolText, limitCrystal; private int difficulty; private PlayerDataManager dataManager; private GameScrollManager gameScrollManager; private LocalGameListener listener; public LogicManager(GameScrollManager gameScrollManager, PlayerDataManager dataManager) { limitCoolText = 50; limitCrystal = 60; difficulty = 1; this.gameScrollManager = gameScrollManager; this.dataManager = dataManager; } public void pointsLogic(int score, int points, Vector2 position) { if(score/15 >= difficulty) { difficulty++; gameScrollManager.increaseDifficulty(); showMessage(points, position); } if(score >= limitCoolText) { showCoolText(false); showParticles(position, true); } else { showParticles(position, false); } if(score >= limitCrystal) { changeCrystal(CRYSTALS_COLORS[index]); scaleCrystal(1.5f); } } public void strikesLogic() { if (listener.getPlayerStrikes() == 0) listener.notifiyGameOver(); else if(listener.getPlayerStrikes() == 1) listener.setSlowMotionOn(3f); } public void determineBestScore() { if (dataManager.getBestScore() < dataManager.getPlayerScore()) listener.setBestScore(dataManager.getPlayerScore()); } public void setListener(LocalGameListener listener) { this.listener = listener; } // Helper methods private void showMessage(int points, Vector2 position) { ((GameScreen) ScreenHandler.getInstance().getScreen(ScreenType.GAME)) .getHudManager().showMessage("+"+points, position, Color.GREEN); } private void changeCrystal(String color) { limitCrystal += 60; ((GameScreen) ScreenHandler.getInstance().getScreen(ScreenType.GAME)) .getHudManager().changeCrystal(color); index++; if(index >= 5) index = 0; } private void scaleCrystal(float duration) { ((GameScreen) ScreenHandler.getInstance().getScreen(ScreenType.GAME)) .getHudManager().scaleCrystal(1f); } private void showCoolText(boolean special) { limitCoolText += 50; Image image = GraphicsHelper.createCoolText(); ((GameScreen) ScreenHandler.getInstance().getScreen(ScreenType.GAME)) .getHudManager().slideFromLeft(image, new Vector2(0 - image.getWidth(), Values.SCREEN_HEIGHT / 3 - image.getHeight() / 2), new Vector2(Values.SCREEN_WIDTH, image.getY()), 3f, true); } private void showParticles(Vector2 position, boolean special) { ((GameScreen) ScreenHandler.getInstance().getScreen(ScreenType.GAME)) .getHudManager().showParticles(position, special); } }
package ru.petrovich.algorithms.book.printing; import javax.validation.constraints.NotNull; /** * Интерфейс для вывода элементов на экран */ public interface Printable { @NotNull default String print(int[] array) { if (array.length == 0) { return "Not enough data in array to print"; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; i++) { sb.append("Elements in array under ") .append(i) .append(" position is ") .append(array[i]) .append("\r\n"); } return sb.toString(); } }
package service; import dao.UserDAO; import entities.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import javax.transaction.Transactional; /** * Created by linhtran on 14/07/17. */ @Transactional @Repository public class UserService implements IUserService { @Autowired UserDAO userDAO; @Override public User getUserByName(String name) { return userDAO.getUserByName(name); } }
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.neuron.mytelkom.model; import java.io.Serializable; public class ComplaitLevel implements Serializable { private static final long serialVersionUID = 1L; String level; String name; public ComplaitLevel() { } public String getLevel() { return level; } public String getName() { return name; } public void setLevel(String s) { level = s; } public void setName(String s) { name = s; } }
// ********************************************************** // 1. 제 목: COMMUNITY ADMIN BEAN // 2. 프로그램명: CommunityAdminBean.java // 3. 개 요: 커뮤니티 관리자 bean // 4. 환 경: JDK 1.3 // 5. 버 젼: 1.0 // 6. 작 성: 2004.02.12 mscho // 7. 수 정: // ********************************************************** package com.ziaan.community; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Enumeration; import java.util.Vector; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.DataBox; import com.ziaan.library.ErrorManager; import com.ziaan.library.FormMail; import com.ziaan.library.FormatDate; import com.ziaan.library.ListSet; import com.ziaan.library.MailSet; import com.ziaan.library.RequestBox; import com.ziaan.library.SQLString; import com.ziaan.library.StringManager; public class CommunityAdminBean { public CommunityAdminBean() { } /** community 승인 리스트 @param box receive from the form object and session @return ArrayList */ public ArrayList selectPermitList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; String sql = ""; DataBox dbox = null; String v_search = box.getString("p_search"); String v_select = box.getString("p_select"); try { connMgr = new DBConnectionManager(); list = new ArrayList(); // select commId, sdesc, categoryId, intros, usercnt, isPublic, permittedStatus sql = "select commId, sdesc, categoryId, intros, usercnt, isPublic, permittedStatus "; sql += "from TZ_COMMUNITY where commId > 0 "; if ( !v_search.equals("") ) { // 검색어(커뮤니티명)가 있는 경우 sql += " and sdesc like " + StringManager.makeSQL("%" + v_search + "%") + " "; } if ( !v_select.equals("") ) { // 검색항목(카테고리 아이디)이 있는 경우 sql += " and categoryId like " + StringManager.makeSQL("%" + v_select + "%") + " "; } sql += " order by permittedStatus desc,commId desc"; ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); list.add(dbox); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** community 승인 조회 @param box receive from the form object and session @return CommunityData */ public DataBox selectPermit(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; DataBox dbox = null; String v_commId = box.getString("p_commId"); try { connMgr = new DBConnectionManager(); // select grcode,sdesc,categoryId,master,userCnt,requestDate,intros,topics,permittedStatus,permittedDate,rejectedDate,rejectedReason sql = "select grcode,sdesc,categoryId,master,usercnt,requestDate,intros,topics,permittedstatus,permitteddate,"; sql += "rejecteddate,rejectedreason "; sql += "from TZ_COMMUNITY where commId = '" +v_commId + "'"; ls = connMgr.executeQuery(sql); if ( ls.next() ) { dbox= ls.getDataBox(); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return dbox; } /** community 승인 처리 @param box receive from the form object and session @return int */ public int handlingPermit(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; String sql = ""; int isOk = 0; String v_commId = box.getString("p_commId"); String v_permittedStatus= box.getString("p_permittedStatus"); String v_rejectedReason = box.getString("p_rejectedReason"); try { connMgr = new DBConnectionManager(); // update TZ_COMMUNITY table sql = "update TZ_COMMUNITY set permittedStatus = ?, rejectedReason = ?, permittedDate = ?, rejectedDate = ? "; sql += "where commId = '" +v_commId + "'"; pstmt = connMgr.prepareStatement(sql); pstmt.setString(1, v_permittedStatus); if ( v_permittedStatus.equals("01") ) { // 승인 pstmt.setString(2, ""); pstmt.setString(3, FormatDate.getDate("yyyyMMdd") ); pstmt.setString(4,""); // == == == == 폼메일 발송 isOk = this.sendFormMail(box); } else if ( v_permittedStatus.equals("02") ) { // 폐쇄 pstmt.setString(2, v_rejectedReason); pstmt.setString(3,""); pstmt.setString(4,FormatDate.getDate("yyyyMMdd") ); // == == == == 폼메일 발송 isOk = this.sendFormMail2(box); } isOk = pstmt.executeUpdate(); if ( pstmt != null ) { pstmt.close(); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** 폼메일 발송(승인) @param box receive from the form object and session @return int */ public int sendFormMail(RequestBox box) throws Exception { DBConnectionManager connMgr = null; // Connection conn = null; ListSet ls = null; String sql = ""; String v_commId = box.getString("p_commId"); int cnt = 0; // 메일발송이 성공한 사람수 try { connMgr = new DBConnectionManager(); //// //// //// //// //// 폼메일 발송 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// // String v_sendhtml = "mail6.html"; FormMail fmail = new FormMail(v_sendhtml); // 폼메일발송인 경우 MailSet mset = new MailSet(box); // 메일 세팅 및 발송 String v_mailTitle = "안녕하세요? e-Academy 운영자입니다."; //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// / // select sdesc,master,name,email,ismailing,cono sql = "select A.sdesc,A.master,B.name,B.email,B.ismailing,B.cono "; sql += " from TZ_COMMUNITY A,TZ_MEMBER B "; sql += " where A.commid = " +SQLString.Format(v_commId); sql += " and A.master=B.userid "; ls = connMgr.executeQuery(sql); while ( ls.next() ) { String v_toEmail = ls.getString("email"); String v_toCono = ls.getString("cono"); String v_ismailing= ls.getString("ismailing"); // String v_toEmail = "jj1004@dreamwiz.com"; mset.setSender(fmail); // 메일보내는 사람 세팅 fmail.setVariable("sdesc", ls.getString("sdesc") ); fmail.setVariable("toname", ls.getString("name") ); String v_mailContent = fmail.getNewMailContent(); boolean isMailed = mset.sendMail(v_toCono, v_toEmail, v_mailTitle, v_mailContent,v_ismailing, v_sendhtml); if ( isMailed) cnt++; // 메일발송에 성공하면 } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return cnt; } /** 폼메일 발송(폐쇄) @param box receive from the form object and session @return int */ public int sendFormMail2(RequestBox box) throws Exception { DBConnectionManager connMgr = null; // Connection conn = null; ListSet ls = null; String sql = ""; String v_commId = box.getString("p_commId"); int cnt = 0; // 메일발송이 성공한 사람수 try { connMgr = new DBConnectionManager(); //// //// //// //// //// 폼메일 발송 //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// // String v_sendhtml = "mail61.html"; FormMail fmail = new FormMail(v_sendhtml); // 폼메일발송인 경우 MailSet mset = new MailSet(box); // 메일 세팅 및 발송 String v_mailTitle = "안녕하세요? e-Academy 운영자입니다."; //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// //// / // select sdesc,master,name,email,ismailing,cono sql = "select A.sdesc,A.master,B.name,B.email,B.ismailing,B.cono "; sql += " from TZ_COMMUNITY A,TZ_MEMBER B "; sql += " where A.commid = " +SQLString.Format(v_commId); sql += " and A.master=B.userid "; ls = connMgr.executeQuery(sql); while ( ls.next() ) { String v_toEmail = ls.getString("email"); String v_toCono = ls.getString("cono"); String v_ismailing= ls.getString("ismailing"); mset.setSender(fmail); // 메일보내는 사람 세팅 fmail.setVariable("sdesc", ls.getString("sdesc") ); fmail.setVariable("toname", ls.getString("name") ); String v_mailContent = fmail.getNewMailContent(); boolean isMailed = mset.sendMail(v_toCono, v_toEmail, v_mailTitle, v_mailContent,v_ismailing, v_sendhtml); if ( isMailed) cnt++; // 메일발송에 성공하면 } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return cnt; } /** 우수 community 리스트 @param box receive from the form object and session @return ArrayList */ public ArrayList selectSuperiorList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; String sql = ""; DataBox dbox = null; String v_search = box.getString("p_search"); String v_select = box.getString("p_select"); // String ss_year = box.getStringDefault("s_year","ALL"); // String ss_month = box.getStringDefault("s_month","ALL"); try { connMgr = new DBConnectionManager(); list = new ArrayList(); // select commId, sdesc, categoryId, intros, usercnt, isPublic, isSuperior sql = "select commId, sdesc, categoryId, intros, usercnt, isPublic, isSuperior "; sql += "from TZ_COMMUNITY where permittedStatus = '01' "; if ( !v_search.equals("") ) { // 검색어(커뮤니티명)가 있는 경우 sql += " and sdesc like " + StringManager.makeSQL("%" + v_search + "%") + ""; } if ( !v_select.equals("") ) { // 검색항목(카테고리 아이디)이 있는 경우 sql += " and categoryId like " + StringManager.makeSQL("%" + v_select + "%") + ""; } sql += " order by isSuperior, commId desc"; ls = connMgr.executeQuery(sql); ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox=ls.getDataBox(); list.add(dbox); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** 우수 community 승인 처리 @param box receive from the form object and session @return int */ public int handlingSuperior(RequestBox box) throws Exception { DBConnectionManager connMgr = null; String sql = ""; int isOk = 0; // p_supcheck로 넘어온 다수의 value를 처리하기 위해 vector로 구현 Vector v_supcheck = new Vector(); v_supcheck = box.getVector("p_supcheck"); Enumeration em = v_supcheck.elements(); String v_str = ""; // 실제 넘어온 각각의 value String v_yn = ""; // v_str중에서 Y/N부분 String v_commId = ""; // v_str중에서 community ID부분 try { connMgr = new DBConnectionManager(); while ( em.hasMoreElements() ) { v_str = (String)em.nextElement(); v_yn = StringManager.substring(v_str,0,1); v_commId= StringManager.substring(v_str,2); // update TZ_COMMUNITY table sql = "update TZ_COMMUNITY set isSuperior = '" +v_yn + "' "; sql += "where commId = '" +Integer.parseInt(v_commId) + "'"; isOk = connMgr.executeUpdate(sql); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { // if ( stmt != null ) { try { stmt.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** ActionLearning 리스트 @param box receive from the form object and session @return ArrayList */ public ArrayList selectActionLearningList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt2 = null; PreparedStatement pstmt3 = null; PreparedStatement pstmt4 = null; ListSet ls = null; ResultSet rs2 = null; ResultSet rs3 = null; ResultSet rs4 = null; ArrayList list = null; String sql1 = ""; String sql2 = ""; String sql3 = ""; String sql4 = ""; String v_subj = ""; // 과목아이디 String v_year = ""; // 과목년도 String v_subjseq= ""; // 과목기수 String v_sdesc = ""; // 동호회명 int v_cntpropose= 0; // 총수강자수 int v_cntstold= 0; // 총수료자수 int v_commid = 0; // 동호회ID DataBox dbox = null; String v_search = box.getString("p_search"); try { connMgr = new DBConnectionManager(); list = new ArrayList(); // select B.grcode,A.subj,A.subjnm,B.subjseq,B.edustart,B,eduend,B.isClosed sql1 = "select B.grcode,A.subj,A.subjnm,B.year,B.subjseq,B.edustart,B.eduend,B.isClosed "; sql1 += "from TZ_SUBJ A,TZ_SUBJSEQ B where A.subj=B.subj and A.isonoff='OFF' "; if ( !v_search.equals("") ) { // 검색어(과목명)가 있는 경우 sql1 += "and A.subjnm like " + StringManager.makeSQL("%" + v_search + "%") + " "; } sql1 += "order by B.eduend desc,B.isclosed"; ls = connMgr.executeQuery(sql1); // select commId,sdesc sql2 = "select commId,sdesc from TZ_SUBJ_ASSOCIATION "; sql2 += "where subj=? and year=? and subjseq=?"; pstmt2 = connMgr.prepareStatement(sql2); // select count propose sql3 = "select count(subj) cntpropose from TZ_STUDENT "; sql3 += "where subj=? and year=? and subjseq=?"; pstmt3 = connMgr.prepareStatement(sql3); // select count graduate sql4 = "select count(subj) cntstold from TZ_STOLD "; sql4 += "where subj=? and year=? and subjseq=? and isgraduate = 'Y'"; pstmt4 = connMgr.prepareStatement(sql4); while ( ls.next() ) { dbox=ls.getDataBox(); v_subj = dbox.getString("d_subj"); v_year = dbox.getString("d_year"); v_subjseq = dbox.getString("d_subjseq"); /* data = new CommunityData(); data.setGrcode( ls.getString("grcode") ); data.setSubjnm( ls.getString("subjnm") ); v_subj = ls.getString("subj"); v_year = ls.getString("year"); v_subjseq = ls.getString("subjseq"); data.setSubj(v_subj); data.setYear(v_year); data.setSubjseq(v_subjseq); data.setEdustart( ls.getString("edustart") ); data.setEduend( ls.getString("eduend") ); data.setIsclosed( ls.getString("isclosed") ); */ // TZ_SUBJ_ASSOCIATION table에서 select pstmt2.setString(1,v_subj); pstmt2.setString(2,v_year); pstmt2.setString(3,v_subjseq); try { rs2 = pstmt2.executeQuery(); if ( rs2.next() ) { v_commid = rs2.getInt("commId"); v_sdesc = rs2.getString("sdesc"); } else { v_commid = 0; v_sdesc = ""; } } catch ( Exception ex ) { } finally{ if ( rs2 != null ) { try { rs2.close(); } catch ( Exception e ) { } } } // TZ_PROPOSE table에서 select pstmt3.setString(1,v_subj); pstmt3.setString(2,v_year); pstmt3.setString(3,v_subjseq); try { rs3 = pstmt3.executeQuery(); if ( rs3.next() ) { v_cntpropose= rs3.getInt("cntPropose"); } else { v_cntpropose= 0; } } catch ( Exception ex ) { } finally{ if ( rs3 != null ) { try { rs3.close(); } catch ( Exception e ) { } } } // TZ_STOLD table에서 select pstmt4.setString(1,v_subj); pstmt4.setString(2,v_year); pstmt4.setString(3,v_subjseq); try { rs4 = pstmt4.executeQuery(); if ( rs4.next() ) { v_cntstold= rs4.getInt("cntstold"); } else { v_cntstold= 0; } } catch ( Exception ex ) { } finally{ if ( rs4 != null ) { try { rs4.close(); } catch ( Exception e ) { } } } /* data.setCommId(v_commid); data.setSdesc(v_sdesc); data.setCntpropose(v_cntpropose); data.setCntstold(v_cntstold); list.add(data); */ dbox.put("d_commid",new Integer(v_commid)); dbox.put("d_sdesc", v_sdesc); dbox.put("d_cntpropose", new Integer(v_cntpropose)); dbox.put("d_cntstold", new Integer(v_cntstold)); list.add(dbox); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql4); throw new Exception("sql4 = " + sql4 + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e ) { } } if ( pstmt3 != null ) { try { pstmt3.close(); } catch ( Exception e ) { } } if ( pstmt4 != null ) { try { pstmt4.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** ActionLearning community 생성 @param box receive from the form object and session @return int */ public int insertActionLearning(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; PreparedStatement pstmt2 = null; PreparedStatement pstmt3 = null; String sql1 = ""; String sql2 = ""; String sql3 = ""; // int isOk1 = 0; int isOk2 = 0; int isOk3 = 0; int isOk4 = 0; // int p_commId= 1; int v_result= 0; int v_max = 1; String v_id = box.getString("p_masterID"); // String v_name = box.getString("p_masterName"); int v_commId = 1; String v_sdesc = box.getString("p_sdesc"); String v_categoryId = box.getString("p_categoryId"); String v_intros = box.getString("p_intros"); String v_topics = box.getString("p_topics"); String v_isPublic = box.getString("p_isPublic"); String v_subj = box.getString("p_subj"); String v_grcode = box.getString("p_grcode"); String v_year = box.getString("p_year"); String v_subjseq = box.getString("p_subjseq"); int v_cntpropose = box.getInt("p_cntpropose"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // 커뮤니티의 중복여부 조회 v_result = overlapping(v_sdesc,v_id); if ( v_result == 1) { return 0; } // select max(commId) sql1 = "select max(commId) from TZ_COMMUNITY"; ls = connMgr.executeQuery(sql1); if ( ls.next() ) { v_max = ls.getInt(1); if ( v_max != 0) { v_commId = v_max + 1; } } // insert TZ_COMMUNITY table sql2 = "insert into TZ_COMMUNITY(grcode,commId,sdesc,categoryId,requestDate,permittedStatus,permitteddate,master,"; sql2 += "intros,topics,isPublic,isPermit,usercnt)"; sql2 += " values (?, ?, ?, ?, dbo.to_date(getdate(),'YYYYMMDD'),'01', dbo.to_date(getdate(),'YYYYMMDD'),?, ?, ?, ? ,'N',?)"; pstmt2 = connMgr.prepareStatement(sql2); // insert TZ_COMMUNITY_MEMBER table // sql3 = "insert into TZ_COMMUNITY_MEMBER(grcode,commId,userid,name,requestDate,"; // sql3 += "permittedStatus,permittedDate,isLeader) "; // sql3 += "values(?, ?, ?, ?, dbo.to_date(getdate(),'YYYYMMDD'), '01', dbo.to_date(getdate(),'YYYYMMDD'),'Y')"; // pstmt3 = connMgr.prepareStatement(sql3); // insert TZ_SUBJ_ASSOCIATION table sql3 = "insert into TZ_SUBJ_ASSOCIATION(subj,year,subjseq,grcode,commId,sdesc) "; sql3 += "values(?,?,?,?,?,?)"; pstmt3 = connMgr.prepareStatement(sql3); pstmt2.setString(1, v_grcode); pstmt2.setInt(2, v_commId); pstmt2.setString(3, v_sdesc); pstmt2.setString(4, v_categoryId); pstmt2.setString(5, v_id); pstmt2.setString(6, v_intros); pstmt2.setString(7, v_topics); pstmt2.setString(8, v_isPublic); pstmt2.setInt(9, v_cntpropose); isOk2 = pstmt2.executeUpdate(); // Action Learning 등록 if ( pstmt2 != null ) { pstmt2.close(); } // pstmt3.setString(1, v_grcode); // pstmt3.setInt(2, v_commId); // pstmt3.setString(3, v_id); // pstmt3.setString(4, v_name); // isOk3 = pstmt3.executeUpdate(); // ACtion Learning 시샵등록 pstmt3.setString(1,v_subj); pstmt3.setString(2,v_year); pstmt3.setString(3,v_subjseq); pstmt3.setString(4, v_grcode); pstmt3.setInt(5,v_commId); pstmt3.setString(6,v_sdesc); isOk3 = pstmt3.executeUpdate(); // Action Learning mapping table 등록 if ( pstmt3 != null ) { pstmt3.close(); } isOk4 = insertActionLearningMember(connMgr, v_grcode,v_commId, v_subj, v_year, v_subjseq, v_id); // Action Learning 회원등록 if ( isOk2 > 0 && isOk3 > 0 && isOk4 > 0) { connMgr.commit(); } else { connMgr.rollback(); } } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql2); throw new Exception("sql2 = " + sql2 + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e1 ) { } } if ( pstmt3 != null ) { try { pstmt3.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk2*isOk3*isOk4; } /** 입력한 커뮤니티의 중복여부 조회 @param v_sdesc 커뮤니티명 @param v_master 시샵ID @return v_result 1:중복됨 ,0:중복되지 않음 */ public int overlapping(String v_sdesc,String v_master) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; int v_result = 0; try { connMgr = new DBConnectionManager(); sql = "select commId from TZ_COMMUNITY where sdesc ='" +v_sdesc + "'"; sql += " and master='" +v_master + "'"; ls = connMgr.executeQuery(sql); // 중복된 경우 1을 return한다 if ( ls.next() ) { v_result = 1; } } catch ( Exception ex ) { throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return v_result; } /** ActionLearning community member insert @param box receive from the form object and session @return int */ public int insertActionLearningMember(DBConnectionManager connMgr, String v_grcode,int v_commId,String v_subj,String v_year,String v_subjseq, String v_masterId) throws Exception { ListSet ls = null; PreparedStatement pstmt2 = null; String sql1 = ""; String sql2 = ""; int isOk = 0; String v_id = ""; String v_name = ""; String v_isLeader = "N"; try { connMgr = new DBConnectionManager(); sql1 = "select userid,(select name from TZ_MEMBER where userid=A.userid) name "; sql1 += "from TZ_STUDENT A "; sql1 += "where subj='" +v_subj + "' and year='" +v_year + "' and subjseq='" +v_subjseq + "'"; ls = connMgr.executeQuery(sql1); sql2 = "insert into TZ_COMMUNITY_MEMBER(commId,grcode,userid,name,requestDate,permittedStatus,permittedDate, isLeader) "; sql2 += "values(?, ?, ?, ?, dbo.to_date(getdate(),'YYYYMMDD'), '01', dbo.to_date(getdate(),'YYYYMMDD'), ?)"; pstmt2 = connMgr.prepareStatement(sql2); while ( ls.next() ) { v_id = ls.getString("userid"); v_name = ls.getString("name"); if ( v_id.equals(v_masterId)) { v_isLeader = "Y"; } // 시삽일경우 pstmt2.setInt (1,v_commId); pstmt2.setString(2,v_grcode); pstmt2.setString(3,v_id); pstmt2.setString(4,v_name); pstmt2.setString(5,v_isLeader); isOk = pstmt2.executeUpdate(); } if ( pstmt2 != null ) { pstmt2.close(); } } catch ( Exception ex ) { throw new Exception("sql1 = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** 선택된 Action Learning Community 상세내용 select(수정 page) @param box receive from the form object and session @return CommunityData 선택한 커뮤니티 내용 */ public DataBox selectActionLearning(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; String v_commId = box.getString("p_commId"); DataBox dbox = null; try { connMgr = new DBConnectionManager(); // select grcode,sdesc,categoryId,master,nickname,intros,targets,topics,isPublic,isPermit sql = "select grcode,sdesc,categoryid,master,nickname,intros,targets,topics,isPublic,isPermit "; sql += "from TZ_COMMUNITY where commId = '" +v_commId + "'"; ls = connMgr.executeQuery(sql); if ( ls.next() ) { dbox = ls.getDataBox(); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return dbox; } /** ActionLearning community 수정 @param box receive from the form object and session @return int */ public int updateActionLearning(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; PreparedStatement pstmt1 = null; PreparedStatement pstmt2 = null; PreparedStatement pstmt3 = null; PreparedStatement pstmt4 = null; String sql1 = ""; String sql2 = ""; String sql3 = ""; String sql4 = ""; int isOk1 = 0; int isOk2 = 0; int isOk3 = 0; int isOk4 = 0; String v_id = box.getString("p_masterID"); String v_name = box.getString("p_masterName"); int v_commId = box.getInt("p_commId"); String v_sdesc = box.getString("p_sdesc"); String v_categoryId = box.getString("p_categoryId"); String v_intros = box.getString("p_intros"); String v_topics = box.getString("p_topics"); String v_isPublic = box.getString("p_isPublic"); // String v_isPermit = box.getString("p_isPermit"); String v_subj = box.getString("p_subj"); String v_year = box.getString("p_year"); String v_subjseq = box.getString("p_subjseq"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // update TZ_COMMUNITY table sql1 = "update TZ_COMMUNITY set sdesc=? , categoryId=? , master=? , "; sql1 += "intros=? , topics=? , isPublic=? "; sql1 += "where commid='" +v_commId + "'"; pstmt1 = connMgr.prepareStatement(sql1); // update TZ_COMMUNITY_MEMBER table sql2 = "update TZ_COMMUNITY_MEMBER set isLeader='N' "; sql2 += "where commid=? "; pstmt2 = connMgr.prepareStatement(sql2); // update TZ_COMMUNITY_MEMBER table sql3 = "update TZ_COMMUNITY_MEMBER set isLeader='Y' "; sql3 += "where commid=? and userid=? and name=? "; pstmt3 = connMgr.prepareStatement(sql3); // update TZ_SUBJ_ASSOCIATION table sql4 = "update TZ_SUBJ_ASSOCIATION set sdesc=? "; sql4 += "where subj=? and year=? and subjseq=? and commid=?"; pstmt4 = connMgr.prepareStatement(sql4); pstmt1.setString(1, v_sdesc); pstmt1.setString(2, v_categoryId); pstmt1.setString(3, v_id); pstmt1.setString(4, v_intros); pstmt1.setString(5, v_topics); pstmt1.setString(6, v_isPublic); isOk1 = pstmt1.executeUpdate(); // Action Learning 수정 if ( pstmt1 != null ) { pstmt1.close(); } if ( !v_name.equals("")) // 시샵을 수정한 경우 { pstmt2.setInt(1, v_commId); isOk2 = pstmt2.executeUpdate(); // ACtion Learning 멤버 수정 if ( pstmt2 != null ) { pstmt2.close(); } pstmt3.setInt(1, v_commId); pstmt3.setString(2, v_id); pstmt3.setString(3, v_name); isOk3 = pstmt3.executeUpdate(); // ACtion Learning 시샵 수정 if ( pstmt3 != null ) { pstmt3.close(); } } else { isOk2 = 1; isOk3 = 1; } pstmt4.setString(1,v_sdesc); pstmt4.setString(2,v_subj); pstmt4.setString(3,v_year); pstmt4.setString(4,v_subjseq); pstmt4.setInt(5,v_commId); isOk4 = pstmt4.executeUpdate(); // Action Learning mapping table 수정 if ( pstmt4 != null ) { pstmt4.close(); } if ( isOk1 > 0 && isOk2 > 0 && isOk3 > 0 && isOk4 > 0) { connMgr.commit(); } else { connMgr.rollback(); } } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql3); throw new Exception("sql3 = " + sql3 + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e1 ) { } } if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e1 ) { } } if ( pstmt3 != null ) { try { pstmt3.close(); } catch ( Exception e1 ) { } } if ( pstmt4 != null ) { try { pstmt4.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk1*isOk2*isOk3; } /** * 시샵 조회 @param box receive from the form object and session @return ArrayList */ public static ArrayList selectSearchMaster(RequestBox box) throws Exception { DBConnectionManager connMgr = null; // Connection conn = null; ListSet ls = null; ArrayList list = null; String sql = ""; // MemberData data = null; DataBox dbox = null; String v_subj = box.getString("p_subj"); String v_year = box.getString("p_year"); String v_subjseq = box.getString("p_subjseq"); int v_pageno = box.getInt("p_pageno"); try { connMgr = new DBConnectionManager(); list = new ArrayList(); sql = "select a.userid userid, a.name name, a.jikwi jikwi, a.jikwinm jikwinm, b.companynm companynm,"; sql += "b.gpmnm gpmnm,b.deptnm deptnm, (b.companynm + '/' + b.gpmnm + '/' + b.deptnm) compnm,a.cono cono "; sql += "from TZ_MEMBER a, TZ_COMP b, TZ_STUDENT c "; sql += "where a.comp = b.comp and a.userid = c.userid and c.subj='" + v_subj + "' and c.year='" + v_year + "' and c.subjseq='" + v_subjseq + "' "; sql += "order by a.comp asc, a.jikwi asc"; ls = connMgr.executeQuery(sql); ls.setPageSize(10); // 페이지당 row 갯수를 세팅한다 ls.setCurrentPage(v_pageno); // 현재페이지번호를 세팅한다. int total_page_count = ls.getTotalPage(); // 전체 페이지 수를 반환한다 int total_row_count = ls.getTotalCount(); // 전체 row 수를 반환한다 while ( ls.next() ) { dbox = ls.getDataBox(); dbox.put("d_dispnum", new Integer(total_row_count - ls.getRowNum() + 1)); dbox.put("d_totalpagecount", new Integer(total_page_count)); list.add(dbox); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } public boolean isSuperior(DBConnectionManager connMgr, String p_commid, String p_year, String p_month) throws Exception { ListSet ls = null; String sql = ""; String v_commid = ""; try { sql = "select commid "; sql += " from tz_community_superior "; sql += " where commid = " + SQLString.Format(p_commid); sql += " and year = " + SQLString.Format(p_year); sql += " and month = " + SQLString.Format(p_month); ls = connMgr.executeQuery(sql); while ( ls.next() ) { v_commid = ls.getString("commid"); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, null, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } } return v_commid.equals(p_commid); } /* Community 우수동호회 선정 년도 select box */ public ArrayList getCyear(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; String sql = ""; DataBox dbox = null; try { connMgr = new DBConnectionManager(); list = new ArrayList(); sql = "select distinct year"; sql += " from tz_community_superior"; sql += " order by year desc"; ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); list.add(dbox); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } }
package com.trump.auction.activity.domain; import lombok.Data; import lombok.ToString; import java.util.Date; /** * 抽奖记录实体类 * @author wangbo 2018/1/8. */ @Data @ToString public class LotteryRecord { private Integer id; private String prizeNo; private String prizeName; private String prizePic; private Integer prizeType; private Integer prizeTypeSub; private Integer amount; private Integer userId; private String userName; private String userPhone; private String orderNo; private Date addTime; private Integer buyCoinType; private Integer productId; private String productName; private String productPic; }
package com.example.g0294.tutorial.multithread; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.g0294.tutorial.NetworkUtils; import com.example.g0294.tutorial.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class VolleyActivity extends AppCompatActivity { private static final String TAG = "MyTag"; // Instantiate the RequestQueue. RequestQueue mRequestQueue; private ImageView imageView; private TextView textView; // json object response url private String urlJsonObj = "http://api.androidhive.info/volley/person_object.json"; // json array response url private String urlJsonArry = "http://api.androidhive.info/volley/person_array.json"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_async_task); Button button = (Button) findViewById(R.id.button); imageView = (ImageView) findViewById(R.id.imageView); textView = (TextView) findViewById(R.id.tvContent); mRequestQueue = Volley.newRequestQueue(this); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (NetworkUtils.isNetworkAvailable(getApplicationContext())) { // VolleyString(); /* Use Singleton*/ //simpleStringRequest(); makeJsonArrayRequest(); } } }); } @Override protected void onStop() { super.onStop(); if (mRequestQueue != null) { mRequestQueue.cancelAll(TAG); } MyRequestQueueSingleton.getInstance(getApplicationContext()).cancelPendingRequests(TAG); } protected void VolleyString() { String url = "http://httpbin.org/get"; // Instantiate the cache Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap // Set up the network to use HttpURLConnection as the HTTP client. Network network = new BasicNetwork(new HurlStack()); // Instantiate the RequestQueue with the cache and network. mRequestQueue = new RequestQueue(cache, network); // Start the queue mRequestQueue.start(); StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { textView.setText(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); // Set the tag on the request. stringRequest.setTag(TAG); // Add the request to the RequestQueue. mRequestQueue.add(stringRequest); } private void simpleStringRequest() { StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://httpbin.org/post", new Response.Listener<String>() { @Override public void onResponse(String response) { textView.setText(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("name", "Android"); params.put("password", "password123"); return params; } }; MyRequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest, TAG); } private void makeJsonObjectRequest() { JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, urlJsonObj, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); try { // Parsing json object response // response will be a json object String name = response.getString("name"); String email = response.getString("email"); JSONObject phone = response.getJSONObject("phone"); String home = phone.getString("home"); String mobile = phone.getString("mobile"); String jsonResponse = ""; jsonResponse += "Name: " + name + "\n\n"; jsonResponse += "Email: " + email + "\n\n"; jsonResponse += "Home: " + home + "\n\n"; jsonResponse += "Mobile: " + mobile + "\n\n"; textView.setText(jsonResponse); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); // Adding request to request queue MyRequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjReq, TAG); } private void makeJsonArrayRequest() { JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); try { // Parsing json array response // loop through each json object String jsonResponse = ""; for (int i = 0; i < response.length(); i++) { JSONObject person = (JSONObject) response .get(i); String name = person.getString("name"); String email = person.getString("email"); JSONObject phone = person .getJSONObject("phone"); String home = phone.getString("home"); String mobile = phone.getString("mobile"); jsonResponse += "Name: " + name + "\n\n"; jsonResponse += "Email: " + email + "\n\n"; jsonResponse += "Home: " + home + "\n\n"; jsonResponse += "Mobile: " + mobile + "\n\n\n"; } textView.setText(jsonResponse); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); // Adding request to request queue MyRequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(req, TAG); } }
package fh.ooe.mcm.accelerometerdatagatherer; import android.app.Service; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.PowerManager; import android.os.Process; import android.preference.PreferenceManager; public class SensorService extends Service implements SensorEventListener { int READING_RATE = 50000; private SensorManager sensorManager; private Sensor sensor; HandlerThread sensorThread; Handler sensorHandler; MainActivity parent; PowerManager.WakeLock wakeLock; public SensorService(MainActivity parent) { this.parent = parent; sensorManager = (SensorManager) parent.getSystemService(Context.SENSOR_SERVICE); sensor = this.sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); sensorThread = new HandlerThread("Sensor thread", Process.THREAD_PRIORITY_BACKGROUND); sensorThread.start(); sensorHandler = new Handler(sensorThread.getLooper()); sensorManager.registerListener(this, sensor, READING_RATE, sensorHandler); PowerManager pm = (PowerManager) parent.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "myApp:myWakeTag"); wakeLock.acquire(); } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER && parent.isActivityOn()) { double x = event.values[0]; double y = event.values[1]; double z = event.values[2]; parent.addData(x, y, z); } } public void sleep(int time) { try { sensorThread.sleep(time); //why does this block UI thread?! } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void onDestroy() { super.onDestroy(); wakeLock.release(); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Do nothing here. } //@androidx.annotation.Nullable @Override public IBinder onBind(Intent intent) { return null; } }
package uz.zako.example.service; import org.springframework.core.io.InputStreamResource; import org.springframework.data.domain.Page; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; import uz.zako.example.entity.Attachment; import uz.zako.example.model.Result; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.MalformedURLException; public interface AttachmentService { public Attachment save(MultipartFile multipartFile); public Attachment findByHashId(String hashids); public Result delete(String hashids); public Page<Attachment> findAllWithPage(int page, int size); public ResponseEntity<InputStreamResource> downloadToServer(String id, HttpServletResponse response) throws IOException; }
package be.odisee.se4.hetnest.dao; import be.odisee.se4.hetnest.domain.Brouwsel; import org.springframework.data.repository.CrudRepository; public interface BrouwselRepository extends CrudRepository<Brouwsel, Long> { }
package LIR; public class StmtLabel { public final String stmtName; public final int stmtNum; private static int numberOfStmtLabels = 1; public StmtLabel(String name) { this.stmtName = name; stmtNum = numberOfStmtLabels; numberOfStmtLabels++; } public String toString() { return "_"+stmtName+"_"+stmtNum; } public String toStringEnd() { return "_"+stmtName+"_"+stmtNum+"_end"; } }
package net.tecgurus.service.assembler; import org.springframework.stereotype.Component; import net.tecgurus.dto.ClienteDTO; import net.tecgurus.entities.Banco; import net.tecgurus.entities.Cliente; @Component public class ClienteAssembler extends Assembler<ClienteDTO, Cliente> { @Override public ClienteDTO getDTOTransform(Cliente mapping) { if (mapping == null) { return null; } ClienteDTO dto = new ClienteDTO(); dto.setAmaterno(mapping.getAmaterno()); dto.setApaterno(mapping.getApaterno()); dto.setEdad(mapping.getEdad()); dto.setIdBanco(mapping.getBanco().getIdBanco()); dto.setIdCliente(mapping.getIdCliente()); dto.setNombre(mapping.getNombre()); return dto; } @Override public Cliente getMappingTransform(ClienteDTO dto) { if (dto == null) { return null; } Cliente cliente = new Cliente(); cliente.setAmaterno(dto.getAmaterno()); cliente.setApaterno(dto.getApaterno()); cliente.setEdad(dto.getEdad()); cliente.setNombre(dto.getNombre()); if (dto.getIdBanco() != null) { Banco banco = new Banco(); banco.setIdBanco(dto.getIdBanco()); cliente.setBanco(banco); } if (dto.getIdCliente() != null) { cliente.setIdCliente(dto.getIdCliente()); } return cliente; } }
package org.giddap.dreamfactory.leetcode.onlinejudge; import java.util.List; /** * <a href="http://oj.leetcode.com/problems/subsets/">Subsets</a> * <p/> * Copyright 2013 LeetCode * <p/> * Given a set of distinct integers, S, return all possible subsets. * <p/> * Note: * <p/> * Elements in a subset must be in non-descending order. * The solution set must not contain duplicate subsets. * <pre> * For example, * If S = [1,2,3], a solution is: * * [ * [3], * [1], * [2], * [1,2,3], * [1,3], * [2,3], * [1,2], * [] * ] * </pre> * <p/> * * @see <a href="http://discuss.leetcode.com/questions/253/subsets">Leetcode discussion</a> * @see <a href="http://gongxuns.blogspot.ca/2012/12/leetcodesubsets.html">gongxuns blog</a> * @see <a href="https://github.com/logicmd/leetcode/blob/master/Subsets.java">lgicmd @ github</a> * @see <a href="http://compprog.wordpress.com/2007/10/10/generating-subsets/">compprog blog</a> * @see <a href="http://www.stefan-pochmann.info/spots/tutorials/sets_subsets/">Another online tutorial</a> */ public interface Subsets { List<List<Integer>> subsets(int[] S); }
import java.util.*; public class Ch12_07 { //searches a 2D array for a given key - takes O(m+n) time complexity and O(1) space complexity public static boolean search2D(List<List<Integer>> matrix, int key) { // starts at top right of matrix int col = matrix.get(0).size() - 1; int row = 0; while (col >= 0 && row < matrix.size()){ int curr = matrix.get(row).get(col); if (curr > key) { col--; } else if (curr < key) { row++; } else { return true; } } return false; } public static void main(String []args) { int key = 12; List<List<Integer>> matrix = new ArrayList<List<Integer>>(); matrix.add(new ArrayList<Integer>(Arrays.asList(-1, 2, 4, 4, 6))); matrix.add(new ArrayList<Integer>(Arrays.asList(1, 5, 5, 9, 21))); matrix.add(new ArrayList<Integer>(Arrays.asList(3, 6, 6, 9, 22))); matrix.add(new ArrayList<Integer>(Arrays.asList(3, 6, 8, 10, 24))); matrix.add(new ArrayList<Integer>(Arrays.asList(6, 8, 9, 12, 25))); matrix.add(new ArrayList<Integer>(Arrays.asList(8, 10, 12, 13, 40))); System.out.print(search2D(matrix, key)); } }
package common.environment; import common.environment.DriverProvider.Driver; import common.environment.driver.Browser; import org.apache.log4j.Logger; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.openqa.selenium.WebDriver; import java.io.IOException; public class TestEnvironment extends TestWatcher { private static final Logger LOGGER = Logger.getLogger(TestEnvironment.class); private static final ThreadLocal<Driver> DRIVER_THREAD_LOCAL = new ThreadLocal<>(); private final Browser fBrowser; private final boolean fEnableCookies; TestEnvironment(Browser browser, boolean enableCookies) { fBrowser = browser; fEnableCookies = enableCookies; } @Override protected void starting(Description description) { try { Driver driver = DriverProvider.getDriver(fBrowser, fEnableCookies); DRIVER_THREAD_LOCAL.set(driver); } catch (IOException e) { LOGGER.error("Error while initiating driver", e); } super.starting(description); } @Override protected void finished(Description description) { DRIVER_THREAD_LOCAL.get().quitDriver(); super.finished(description); } public static WebDriver getDriver() { return DRIVER_THREAD_LOCAL.get().getWebDriver(); } }
package com.cinema.sys.dao; import java.util.List; import java.util.Map; import com.cinema.sys.model.RoleUser; import com.cinema.sys.model.base.TRoleUser; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; public interface RoleUserMapper extends Mapper<TRoleUser>,MySqlMapper<TRoleUser> { RoleUser getDetail(String id); List<RoleUser> getList(Map<String, Object> paraMap); void remove(Map<String, Object> paraMap); }
package com.tomcat; import java.io.File; import java.lang.management.ManagementFactory; import java.net.URI; import java.net.URISyntaxException; import java.security.CodeSource; import java.security.ProtectionDomain; /** * Created by wangwr on 2016/5/25. */ public class TestLoad { @org.junit.Test public void test() throws URISyntaxException { System.out.println(getClass().getCanonicalName()); ProtectionDomain domain = getClass().getProtectionDomain(); CodeSource codeSource = domain.getCodeSource(); URI location = codeSource == null?null:codeSource.getLocation().toURI(); String path = location ==null?null:location.getSchemeSpecificPart(); if(path == null){ throw new IllegalStateException("unable to determine code resource archive"); } File root = new File(path); if(!root.exists()){ throw new IllegalStateException(String.format("unable to determine code resource archive from %s",path)); } System.out.println(ManagementFactory.getRuntimeMXBean().getName()); } }
package com.phicomm.account.service; import com.phicomm.account.operator.GetMapOperation; import com.phicomm.account.operator.UploadContactOperation; import com.phicomm.account.requestmanager.PoCRequestFactory; public class PoCRequestService extends RequestService { @Override protected int getMaxNumberOfThreads() { return 5; } @Override public Operation getOperationType(int requestType) { switch(requestType){ case PoCRequestFactory.REQUEST_TYPE_INIT_CHECK: //return new InitCheckOperation2(); case PoCRequestFactory.REQUEST_TYPE_GET_MAP: return new GetMapOperation(); case PoCRequestFactory.REQUEST_TYPE_CONTACT_UPLOAD: return new UploadContactOperation(); } return null; } }
/* * @(#) EbmsRoutingSearchOrderService.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ebms.ebmsroutingsearchorder.service.impl; import com.esum.appframework.exception.ApplicationException; import com.esum.appframework.service.impl.BaseService; import com.esum.wp.ebms.ebmsroutingsearchorder.service.IEbmsRoutingSearchOrderService; import com.esum.wp.ebms.ebmsroutingsearchorder.dao.IEbmsRoutingSearchOrderDAO; import com.esum.wp.ebms.ebmsroutingsearchorder.EbmsRoutingSearchOrder; import java.util.List; /** * * @author heowon@esumtech.com * @version $Revision: 1.1 $ $Date: 2007/06/20 00:46:52 $ */ public class EbmsRoutingSearchOrderService extends BaseService implements IEbmsRoutingSearchOrderService { /** * Default constructor. Can be used in place of getInstance() */ public EbmsRoutingSearchOrderService () {} public Object removeEbmsRoutingSearchOrderList(Object object) { List list = (List) object; for (int i = 0; i < list.size(); i++) { EbmsRoutingSearchOrder ebmsRoutingSearchOrder = (EbmsRoutingSearchOrder) (list.get(i)); super.delete(ebmsRoutingSearchOrder); } return list; } public Object selectPageList(Object object) { try { IEbmsRoutingSearchOrderDAO iEbmsRoutingSearchOrderDAO = (IEbmsRoutingSearchOrderDAO)iBaseDAO; return iEbmsRoutingSearchOrderDAO.selectPageList(object); } catch (ApplicationException e) { e.setMouduleName(moduleName); e.printException(""); return e; } catch (Exception e) { ApplicationException ae = new ApplicationException(e); ae.setMouduleName(moduleName); return ae; } } }
package com.blog.dusk.utils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; public class GetCurrentUser { public String getCookies(HttpServletRequest request){ // 获取request里面的cookie cookie里面存值方式也是 键值对的方式  Cookie[] cookie = request.getCookies(); Cookie cook = null; for (int i = 0; i < cookie.length; i++) { cook = cookie[i]; if(cook.getName().equalsIgnoreCase("eredg4.login.account")){ //获取键  System.out.println("account:"+cook.getValue().toString()); //获取值  } } return cook.getValue().toString(); } }
package com.gestion.entity; import java.io.Serializable; import javax.persistence.*; import java.util.Date; import java.util.List; /** * The persistent class for the commande_client database table. * */ @Entity @Table(name="commande_client") public class CommandeClient implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="id_commande_client") private int idCommandeClient; private String article; @Temporal( TemporalType.DATE) @Column(name="date_commande") private Date dateCommande; private String designation; @Column(name="n_serie") private String nSerie; private int quantite; //bi-directional many-to-one association to Client @ManyToOne @JoinColumn(name="id_client") private Client client; //bi-directional many-to-one association to Livraison /*@OneToMany(mappedBy="commandeClient") private List<Livraison> livraisons;*/ public CommandeClient() { } public int getIdCommandeClient() { return this.idCommandeClient; } public void setIdCommandeClient(int idCommandeClient) { this.idCommandeClient = idCommandeClient; } public String getArticle() { return this.article; } public void setArticle(String article) { this.article = article; } public Date getDateCommande() { return this.dateCommande; } public void setDateCommande(Date dateCommande) { this.dateCommande = dateCommande; } public String getDesignation() { return this.designation; } public void setDesignation(String designation) { this.designation = designation; } public String getNSerie() { return this.nSerie; } public void setNSerie(String nSerie) { this.nSerie = nSerie; } public int getQuantite() { return this.quantite; } public void setQuantite(int quantite) { this.quantite = quantite; } public Client getClient() { return this.client; } public void setClient(Client client) { this.client = client; } /*public List<Livraison> getLivraisons() { return this.livraisons; }*/ /*public void setLivraisons(List<Livraison> livraisons) { this.livraisons = livraisons; }*/ }
package com.bcq.oklib; import android.os.Environment; import java.io.File; /** * @author: BaiCQ * @ClassName: NetConstant * @date: 2018/8/17 * @Description: NetConstant 公共常量值 */ public class Constant { public final static String ACTION_APP_EXIT = "_org_app_exit"; /*****************存储路径 path*****************/ public final static String ROOT_NAME = "oklib"; public final static String ROOT = Environment.getExternalStorageDirectory() + File.separator; public final static String BASE_PATH = ROOT + ROOT_NAME + File.separator; /***************** Intent key *****************/ public final static String KEY_BASE = "key_basis"; public final static String KEY_OBJ = "key_obj"; }
package com.capstone.kidinvest.models; import com.capstone.kidinvest.repositories.AddonRepo; import javax.persistence.*; import java.util.List; @Entity @Table(name = "addons") public class Addon { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(nullable = false, unique = true) private String name; @Column(name = "popularity_bonus", nullable = false) private int popularityBonus; private double price; @ManyToMany(mappedBy = "addons") private List<Business> businessList; //blank constructor public Addon() { } //constructor public Addon(long id, String name, int popularityBonus, double price) { this.id = id; this.name = name; this.popularityBonus = popularityBonus; this.price = price; } //getters and setters public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPopularityBonus() { return popularityBonus; } public void setPopularityBonus(int popularityBonus) { this.popularityBonus = popularityBonus; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public List<Business> getBusinessList() { return businessList; } public void setBusinessList(List<Business> businessList) { this.businessList = businessList; } }
public class CPUSimulator { public static void main(String[] args) { // creating a gui interface for simulation with the GuiBuilder class GuiBuilder newGui = new GuiBuilder(); } }
package com.b.test.security; import com.b.test.common.CorsConfig; import com.b.test.common.SessionUtil; import com.b.test.common.StringUtils; import com.b.test.util.JsonResult; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 登录失败处理器 * * @author hjl * @date 2018/6/8/008 9:48 **/ @Component public class LoginFailHandler implements AuthenticationFailureHandler { /** * 前端服务器地址 */ @Value("${web.host.url}") public String WEB_HOST_URL; /** * 前端访问地址白名单 */ @Value("${web.host.white}") public String WHITE_LIST; @Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { CorsConfig.setCors(httpServletRequest, httpServletResponse,WHITE_LIST,WEB_HOST_URL); httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true"); String result = (String) SessionUtil.get("login"); if (StringUtils.isEmpty(result)) { result = "密码错误"; } JsonResult.err(result); } }
package Utilities; import java.applet.Applet; import java.applet.AudioClip; import java.io.FileInputStream; import java.io.InputStream; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.swing.JApplet; import sun.audio.AudioPlayer; import sun.audio.AudioStream; public class SoundUtilities extends JApplet{ public void init(){ AudioClip testClip = getAudioClip(getCodeBase(), ""); testClip.loop(); } public static void playSound(String fileName){ try{ //AudioClip clip = Applet.newAudioClip(getClass().getResource(fileName)); //InputStream in = new FileInputStream(fileName); ClassLoader cl = ClassLoader.getSystemClassLoader(); InputStream resourceAsStream = cl.getResourceAsStream(fileName); AudioStream as = new AudioStream(resourceAsStream); AudioPlayer.player.start(as); } catch (Exception e){ System.out.println("Sound Error: "+fileName); e.printStackTrace(); } } public static void loopSound(String fileName){ try{ //AudioClip clip = Applet.newAudioClip(getClass().getResource(fileName)); //InputStream in = new FileInputStream(fileName); //System.out.println("1"); //AudioStream as = new AudioStream(in); //System.out.println("2"); //AudioPlayer.player.start(as); //System.out.println("3"); //clip.loop(); } catch (Exception e){ System.out.println("Sound Error"); e.printStackTrace(); } } }
/* charAt:这个就是获取str字符串中的那个字符 */ class Trim { public static void sop(String str) { System.out.println(str); } public static void StringMyTrim(String str) { int start=0; int end=str.length()-1; //开始位置要小于结束的文职,同时要在字符串str中寻找为空的字符 //双引号和单引号的区别,单引号代表的就是一个字符一个字符 //双引号是字符串,如果这时候使用双引号会造成类型不匹配 while(start<=end &&str.charAt(start)==' ') { start++; while(start<=end && str.charAt(end)==' ') { end--; } } //subString:拼接字符串,1,4,会拼接从1开始但是不包括4的字符串 //注意书写的格式 System.out.println(str.substring(start,end+1)); } } class StringTrim { public static void main(String[] args) { String str=" a,b,c, "; Trim.StringMyTrim(str); } }
/* * HuskyList App * Authors: Vladimir Smirnov and Shelema Bekele */ package tcss450.uw.edu.huskylist; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * The AddBookActivity is responsible for holding the AdsAddFragment which * is used to create new ads. * * @author Shelema Bekele * @author Vladimir Smirnov * @version 1.0 */ public class AddItemActivity extends AppCompatActivity implements AdsAddFragment.ItemAddListener{ /** * This method is called when the activity is created. * * @param savedInstanceState is a bundle holding the saved state. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_book); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); AdsAddFragment addFragment = new AdsAddFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_add_container,addFragment) .addToBackStack(null) .commit(); } /** * The AddBookTask is used to add books to the database. * * @author Shelema Bekele * @author Vladimir Smirnov * @version 1.0 */ private class AddBookTask extends AsyncTask<String, Void, String> { /** * This method starts before the task is exectued. */ @Override protected void onPreExecute() { super.onPreExecute(); } /** * This method runs in the background. * * @param urls is the given URL. * @return is a String representing the response. */ @Override protected String doInBackground(String... urls) { String response = ""; HttpURLConnection urlConnection = null; for (String url : urls) { try { URL urlObject = new URL(url); urlConnection = (HttpURLConnection) urlObject.openConnection(); InputStream content = urlConnection.getInputStream(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { response = "Unable to add course, Reason: " + e.getMessage(); } finally { if (urlConnection != null) urlConnection.disconnect(); } } return response; } /** * This method checks to see if there was a problem with the URL(Network) which is when an * exception is caught. It tries to call the parse Method and checks to see if it was successful. * If not, it displays the exception. * * @param result is the JSON String. */ @Override protected void onPostExecute(String result) { // Something wrong with the network or the URL. try { JSONObject jsonObject = new JSONObject(result); String status = (String) jsonObject.get("result"); if (status.equals("success")) { Toast.makeText(getApplicationContext(), "Item successfully added!" , Toast.LENGTH_LONG) .show(); } else { Toast.makeText(getApplicationContext(), "Failed to add: " + jsonObject.get("error") , Toast.LENGTH_LONG) .show(); } } catch (JSONException e) { Toast.makeText(getApplicationContext(), "Something wrong with the data" + e.getMessage(), Toast.LENGTH_LONG).show(); } } } /** * This method is used to add books. * * @param url is the given URL. */ public void addItems(String url){ AddBookTask task = new AddBookTask(); task.execute(new String[]{url.toString()}); // Takes you back to the previous fragment by popping the current fragment out. getSupportFragmentManager().popBackStackImmediate(); } }
import java.awt.Color; public class TwoSquares{ public static void main(String[] args){ StdDraw.setXscale(-20,20); StdDraw.setYscale(-20,20); final int R = Integer.parseInt(args[0]); final int G = Integer.parseInt(args[1]); final int B = Integer.parseInt(args[2]); final int R2 = Integer.parseInt(args[3]); final int G2 = Integer.parseInt(args[4]); final int B2 = Integer.parseInt(args[5]); Color c = new Color(R,G,B); Color c2 = new Color(R2,G2,B2); StdDraw.setPenColor(c); StdDraw.filledSquare(-10,0,6); StdDraw.setPenColor(c2); StdDraw.filledSquare(-10,0,3); StdDraw.filledSquare(10,0,6); StdDraw.setPenColor(c); StdDraw.filledSquare(10,0,3); } }
package com.ngocdt.tttn.specification; import com.ngocdt.tttn.entity.Product; import org.springframework.data.jpa.domain.Specification; public final class ProductSpecification { public static Specification<Product> getFilter(String q, Integer originID, Integer categoryID, Integer brandID , Integer skinID, Integer toneID, Integer ingredientID, Integer characteristicID, Integer sizeID) { Specification<Product> specification = Specification.where(null); if (!q.isEmpty()) specification = specification.and(nameLike(q)); if (originID > 0) specification = specification.and(belongToOrigin(originID)); if (categoryID > 0) specification = specification.and(belongToCategory(categoryID)); if (brandID > 0) specification = specification.and(belongToBrand(brandID)); if (skinID > 0) specification = specification.and(belongToSkin(skinID)); if (toneID > 0) specification = specification.and(belongToTone(toneID)); if (ingredientID > 0) specification = specification.and(belongToIngredient(ingredientID)); if (characteristicID > 0) specification = specification.and(belongToCharacteristic(characteristicID)); if (sizeID > 0) specification = specification.and(belongToSize(sizeID)); return specification; } static Specification<Product> nameLike(String q) { return (product, cq, cb) -> cb.like(product.get("otherName"), "%" + q + "%"); } static Specification<Product> belongToOrigin(Integer originID) { return (product, cq, cb) -> cb.equal(product.get("origin").get("id"), originID); } static Specification<Product> belongToCategory(Integer categoryID) { return (product, cq, cb) -> cb.equal(product.get("category").get("categoryID"), categoryID); } static Specification<Product> belongToBrand(Integer brandID) { return (product, cq, cb) -> cb.equal(product.get("brand").get("id"), brandID); } static Specification<Product> belongToSkin(Integer skinID) { return (product, cq, cb) -> cb.equal(product.get("skinType").get("id"), skinID); } static Specification<Product> belongToTone(Integer toneID) { return (product, cq, cb) -> cb.equal(product.get("tone").get("id"), toneID); } static Specification<Product> belongToIngredient(Integer ingredientID) { return (product, cq, cb) -> cb.equal(product.get("ingredient").get("id"), ingredientID); } static Specification<Product> belongToCharacteristic(Integer characteristicID) { return (product, cq, cb) -> cb.equal(product.get("characteristic").get("id"), characteristicID); } static Specification<Product> belongToSize(Integer sizeID) { return (product, cq, cb) -> cb.equal(product.get("size").get("id"), sizeID); } }
/** * Copyright 2016 Shyam Bhimani */ package day8_DictionaryAndMaps; import java.util.*; import java.io.*; public class DictionaryExample { // Complete this code or write your own from scratch public static void main(String[] argh) { Scanner in = new Scanner(System.in); int n = in.nextInt(); Map<String, Integer> phoneDictionary = new HashMap<String, Integer>(); for (int i = 0; i < n; i++) { String name = in.next(); int phone = in.nextInt(); // getting input in dictionary phoneDictionary.put(name, phone); } while (in.hasNext()) { String s = in.next(); // Querying by user for (String key : phoneDictionary.keySet()) { key = s; if (phoneDictionary.get(key) != null) { System.out.println(key + "=" + phoneDictionary.get(key)); } else { System.out.println("Not found"); } break; } } in.close(); } }
package com.example.netflix_project.src.main.home; public class homeServiece { }
package com.ankit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; public class Main { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf); job.setJarByClass(Main.class); job.setMapperClass(WordCountMap.class); job.setReducerClass(WordCountReduce.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.setInputPaths(job, new Path("/user/ankitb/input/")); FileOutputFormat.setOutputPath(job, new Path("/user/ankitb/phase1/")); job.setNumReduceTasks(25); if(job.waitForCompletion(true)) System.out.println("Job completed successfully"); else System.out.println("Job Failed"); } }
package com.meizu.scriptkeeper.utils.performance; import android.app.ActivityManager; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.net.TrafficStats; import android.os.AsyncTask; import android.util.Log; import com.meizu.scriptkeeper.db.ScheduleDataBase; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Author: liyong1 * Date: 2015/5/28 */ public class PerformanceAsync extends AsyncTask<Long, Void, Void> { private Context context; public PerformanceAsync(Context context) { this.context = context; } @Override protected Void doInBackground(Long... params) { Log.i("FPS Start", "Start log record"); long taskId = params[0]; getUidRxBytes(); PerformanceTools.startWatchingCpu(context, taskId); return null; } private void getUidRxBytes() { final ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); Map<Integer, Long> map = new HashMap<>(); List<ActivityManager.RunningAppProcessInfo> infos = am.getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo info : infos) { map.put(info.uid, TrafficStats.getUidRxBytes(info.uid)); } PerformanceTools.TRAFFIC.putAll(map); } }
package com.throle.throle; import android.content.Context; import android.content.SharedPreferences; /** * Created by TEST on 11/12/2017. */ public class PrefMan { SharedPreferences pref; SharedPreferences.Editor editor; Context _context; // shared pref mode int PRIVATE_MODE = 0; // Shared preferences file name private static final String PREF_NAME = "throle-username"; private static final String IS_SESSION_START_USERNAME = ""; private static final String BLOCKED_USER = "nothing"; private static final String NUMBER_OF_TIMES_OPENED = "0"; public PrefMan(Context context) { this._context = context; pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); editor = pref.edit(); } public void setUSerNAme(String Username) { editor.putString(IS_SESSION_START_USERNAME, Username); editor.commit(); } public void setNumberOfTimesOpened(int numberOfTimesOpened) { editor.putInt(NUMBER_OF_TIMES_OPENED, numberOfTimesOpened); editor.commit(); } public int getNumberOfTimesOpened() { return pref.getInt(NUMBER_OF_TIMES_OPENED, 0); } public String getUserName() { return pref.getString(IS_SESSION_START_USERNAME, "none"); } }
package com.tu.rocketmq.action; import com.tu.mysql.model.User; import com.tu.mysql.service.UserService; import org.apache.rocketmq.client.exception.MQBrokerException; import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.client.producer.TransactionMQProducer; import org.apache.rocketmq.client.producer.TransactionSendResult; import org.apache.rocketmq.common.message.Message; import org.apache.rocketmq.remoting.exception.RemotingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.UUID; /** * @Auther: tuyongjian * @Date: 2020/4/20 17:24 * @Description: */ @RestController @RequestMapping(value = "rocketMqTrans") public class RocketTransAction { private static final Logger logger = LoggerFactory.getLogger(RocketTransAction.class); @Autowired private TransactionMQProducer transactionMQProducer; @GetMapping(value = "test") public void Test() throws MQClientException { String msg = "11";//UUID.randomUUID().toString(); logger.info("开始发送消息:"+msg); Message sendMsg = new Message("DemoTopic","DemoTag",msg.getBytes()); //默认3秒超时 TransactionSendResult transactionSendResult = transactionMQProducer.sendMessageInTransaction(sendMsg,10000); logger.info("消息发送响应信息:"+transactionSendResult.toString()); } }
//*Vladimir Ventura // 00301144 // CIS 252 - Data Structures // Problem Set 7: Word Frequency Main Tester // // This program aims to find a file passed as a string to the load(String) function. // I will provide a file, but you can use any text file to be honest. Extensions are required.*// public class WordFrequencyTester { public static void main(String[] args) { WordFrequency wf = new WordFrequency(); wf.load("Lyrics"); wf.start(); wf.printWordsByFrequency(); } }
package usc.cs310.ProEvento.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import usc.cs310.ProEvento.dao.EventDao; import usc.cs310.ProEvento.dao.EventNotificationDao; import usc.cs310.ProEvento.dao.UserDao; import usc.cs310.ProEvento.model.EventNotification; import usc.cs310.ProEvento.model.User; import java.util.List; import java.util.Set; @Service public class EventNotificationService { @Autowired private EventNotificationDao eventNotificationDao; @Autowired private UserDao userDao; @Autowired private EventDao eventDao; public boolean sendEventNotification(EventNotification notification) { if (notification == null || notification.getSender() == null || notification.getReceivers() == null || notification.getReceivers().size() == 0 || notification.getEvent() == null || userDao.selectUserById(notification.getSender().getId()) == null || eventDao.selectEventById(notification.getEvent().getId()) == null) { return false; } else { return eventNotificationDao.createEventNotification(notification); } } public List<EventNotification> getEventNotificationByReceiverId(long id) { return eventNotificationDao.selectEventNotificationByReceiverId(id); } public boolean deleteEventNotification(EventNotification notification) { return eventNotificationDao.deleteEventNotification(notification); } public EventNotification getEventNotificationById(long id){ return eventNotificationDao.selectEventNotificationById(id); } public boolean removeEventNotificationReceiver(long userId, long notificationId) { User user = userDao.selectUserById(userId); EventNotification notification = eventNotificationDao.selectEventNotificationById(notificationId); if (user == null || notification == null || !notification.getReceivers().contains(user)) { return false; } Set<User> receivers = notification.getReceivers(); receivers.remove(user); notification.setReceivers(receivers); return eventNotificationDao.updateEventNotification(notification); } }
package com.platform.au.dao.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.platform.au.dao.UserDao; import com.platform.au.entity.User; @Repository("userDaoImpl") public class UserDaoImpl implements UserDao { @Override public String getUserIdByName(String userName) { return null; } @Override public String getUserNameById(String userId) { return null; } @Override public User getUserByName(String userName) { return null; } @Override public String getUserEmpNameById(String userId) { return null; } public HashMap<String,Object> getUsers(List<String> users) throws Exception { return null; } public User getUserById(String userId)throws Exception { return null; } @Override public List<Map> getEmpIdByEmpCode(String empCode) { return null; } @Override public List<Map> getUserByEmpId(String empId) { return null; } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#selectForPage(java.util.Map) */ @Override public List<User> selectForPage(Map<String, Object> param) throws Exception { // TODO return null; } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#selectCount(java.util.Map) */ @Override public Integer selectCount(Map<String, Object> param) throws Exception { // TODO return null; } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#selectByPK(java.util.Map) */ @Override public User selectByPK(Map<String, Object> params) throws Exception { // TODO return null; } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#selectByPropertys(java.util.Map) */ @Override public User selectByPropertys(Map<String, Object> params) throws Exception { // TODO return null; } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#checkData(java.lang.Object) */ @Override public void checkData(User entity) throws Exception { // TODO } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#checkDataBeforeDalete(java.lang.Object) */ @Override public void checkDataBeforeDalete(User entity) throws Exception { // TODO } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#insert(java.lang.Object) */ @Override public void insert(User entity) throws Exception { // TODO } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#update(java.lang.Object) */ @Override public void update(User entity) throws Exception { // TODO } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#delete(java.lang.Object) */ @Override public void delete(User entity) throws Exception { // TODO } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#deleteByParam(java.util.Map) */ @Override public void deleteByParam(Map<String, Object> param) throws Exception { // TODO } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#delete(java.util.List) */ @Override public void delete(List<User> entity) throws Exception { // TODO } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#findAll(java.util.Map) */ @Override public List<User> findAll(Map<String, Object> param) throws Exception { // TODO return null; } /* (非 Javadoc) * @see com.platform.common.dao.BaseDao#checkDataBeforeDalete(java.util.Map) */ @Override public void checkDataBeforeDalete(Map<String, Object> params) throws Exception { // TODO } }
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.accept; import java.util.Map; import jakarta.servlet.ServletContext; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.context.request.NativeWebRequest; /** * Extends {@code PathExtensionContentNegotiationStrategy} that also uses * {@link ServletContext#getMimeType(String)} to resolve file extensions. * * @author Rossen Stoyanchev * @since 3.2 * @deprecated as of 5.2.4. See class-level note in * {@link ContentNegotiationManagerFactoryBean} on the deprecation of path * extension config options. */ @Deprecated public class ServletPathExtensionContentNegotiationStrategy extends PathExtensionContentNegotiationStrategy { private final ServletContext servletContext; /** * Create an instance without any mappings to start with. Mappings may be * added later when extensions are resolved through * {@link ServletContext#getMimeType(String)} or via * {@link org.springframework.http.MediaTypeFactory}. */ public ServletPathExtensionContentNegotiationStrategy(ServletContext context) { this(context, null); } /** * Create an instance with the given extension-to-MediaType lookup. */ public ServletPathExtensionContentNegotiationStrategy( ServletContext servletContext, @Nullable Map<String, MediaType> mediaTypes) { super(mediaTypes); Assert.notNull(servletContext, "ServletContext is required"); this.servletContext = servletContext; } /** * Resolve file extension via {@link ServletContext#getMimeType(String)} * and also delegate to base class for a potential * {@link org.springframework.http.MediaTypeFactory} lookup. */ @Override @Nullable protected MediaType handleNoMatch(NativeWebRequest webRequest, String extension) throws HttpMediaTypeNotAcceptableException { MediaType mediaType = null; String mimeType = this.servletContext.getMimeType("file." + extension); if (StringUtils.hasText(mimeType)) { mediaType = MediaType.parseMediaType(mimeType); } if (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) { MediaType superMediaType = super.handleNoMatch(webRequest, extension); if (superMediaType != null) { mediaType = superMediaType; } } return mediaType; } /** * Extends the base class * {@link PathExtensionContentNegotiationStrategy#getMediaTypeForResource} * with the ability to also look up through the ServletContext. * @param resource the resource to look up * @return the MediaType for the extension, or {@code null} if none found * @since 4.3 */ @Override public MediaType getMediaTypeForResource(Resource resource) { MediaType mediaType = null; String mimeType = this.servletContext.getMimeType(resource.getFilename()); if (StringUtils.hasText(mimeType)) { mediaType = MediaType.parseMediaType(mimeType); } if (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) { MediaType superMediaType = super.getMediaTypeForResource(resource); if (superMediaType != null) { mediaType = superMediaType; } } return mediaType; } }