text
stringlengths
10
2.72M
package com.kun.security.web.filter; import javax.servlet.*; import java.io.IOException; /** * @author CaoZiye * @version 1.0 2017/11/12 14:53 */ public class TimeFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("time filter init"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { long start = System.currentTimeMillis(); System.out.println("enter time filter"); filterChain.doFilter(servletRequest, servletResponse); System.out.println("exit time filter, consumed:" + (System.currentTimeMillis() - start)); } @Override public void destroy() { System.out.println("time filter destroy"); } }
package game; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import java.awt.Point; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static game.GameOfLife.CellState.*; public class GameOfLifeTest { @Test public void Canary(){ assertTrue(true); } @Test public void testDeadCellBehaviors() { assertAll( () -> assertEquals(DEAD, GameOfLife.nextState(DEAD, 0)), () -> assertEquals(DEAD, GameOfLife.nextState(DEAD, 1)), () -> assertEquals(DEAD, GameOfLife.nextState(DEAD, 2)), () -> assertEquals(DEAD, GameOfLife.nextState(DEAD, 5)), () -> assertEquals(DEAD, GameOfLife.nextState(DEAD, 8)), () -> assertEquals(ALIVE, GameOfLife.nextState(DEAD, 3)) ); } @Test public void testLiveCellBehaviors() { assertAll( () -> assertEquals(DEAD, GameOfLife.nextState(ALIVE, 1)), () -> assertEquals(DEAD, GameOfLife.nextState(ALIVE, 4)), () -> assertEquals(DEAD, GameOfLife.nextState(ALIVE, 8)), () -> assertEquals(ALIVE, GameOfLife.nextState(ALIVE, 2)), () -> assertEquals(ALIVE, GameOfLife.nextState(ALIVE, 3)) ); } @Test public void testGenerateSignalsForOnePosition() { List<Point> points = List.of(new Point(2, 2), new Point(3, 2), new Point(4, 2), new Point(2, 3), new Point(4, 3), new Point(2, 4), new Point(3, 4), new Point(4, 4)); assertEquals(points, GameOfLife.generateSignalForPositions(List.of(new Point(3, 3)))); } @Test public void testGenerateSignalsForAnotherPosition() { List<Point> points = List.of(new Point(1, 3), new Point(2, 3), new Point(3, 3), new Point(1, 4), new Point(3, 4), new Point(1, 5), new Point(2, 5), new Point(3, 5)); assertEquals(points, GameOfLife.generateSignalForPositions(List.of(new Point(2, 4)))); } @Test public void testGenerateSignalsForPosition00() { List<Point> points = List.of(new Point(-1, -1), new Point(0, -1), new Point(1, -1), new Point(-1, 0), new Point(1, 0), new Point(-1, 1), new Point(0, 1), new Point(1, 1)); assertEquals(points, GameOfLife.generateSignalForPositions(List.of(new Point(0, 0)))); } @Test public void testGenerateSignalsForNumberInList() { assertAll( () -> assertEquals(0, GameOfLife.generateSignalForPositions(List.of()).size()), () -> assertEquals(8, GameOfLife.generateSignalForPositions(List.of(new Point(3, 3))).size()), () -> assertEquals(16, GameOfLife.generateSignalForPositions(List.of(new Point(3, 3), new Point(2, 4))).size()), () -> assertEquals(24, GameOfLife.generateSignalForPositions(List.of(new Point(3, 3), new Point(2, 4), new Point(0, 0))).size()) ); } @Test public void testCountSignals() { assertAll( () -> assertEquals(Map.of(), GameOfLife.countSignals(List.of())), () -> assertEquals(Map.of(new Point(3, 3), 1), GameOfLife.countSignals(List.of(new Point(3, 3)))), () -> assertEquals(Map.of(new Point(3, 3), 2), GameOfLife.countSignals(List.of(new Point(3, 3), new Point(3, 3)))), () -> assertEquals(Map.of(new Point(3, 3), 2, new Point(2, 4), 1), GameOfLife.countSignals(List.of(new Point(3, 3), new Point(2, 4), new Point(3, 3)))) ); } public class PointsComparator implements Comparator<Point> { @Override public int compare(Point a, Point b) { return Integer.compare(a.x, b.x); } } @Test public void testNextGeneration() { assertAll( () -> assertEquals(List.of(), GameOfLife.nextGeneration(List.of())), () -> assertEquals(List.of(), GameOfLife.nextGeneration(List.of(new Point(3, 3)))), () -> assertEquals(List.of(), GameOfLife.nextGeneration(List.of(new Point(2, 3), new Point(2, 4)))), () -> assertEquals(List.of(new Point(2, 1)), GameOfLife.nextGeneration(List.of(new Point(1, 1), new Point(1, 2), new Point(3, 0)))), () -> assertEquals(List.of(new Point(1, 1), new Point(1, 2), new Point(2, 1), new Point(2, 2)) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList()), GameOfLife.nextGeneration(List.of(new Point(1, 1), new Point(1, 2), new Point(2, 2))) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList())) ); } @Test public void testPatterns() { assertAll( // block () -> assertEquals(List.of(new Point(2,2), new Point(3,2), new Point(2,3), new Point(3,3)) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList()), GameOfLife.nextGeneration(List.of(new Point(2,2), new Point(3,2), new Point(2,3), new Point(3,3))) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList())), // beehive () -> assertEquals(List.of(new Point(4,4), new Point(5,3), new Point(5,5), new Point(6,3), new Point(6,5), new Point(7,4)) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList()), GameOfLife.nextGeneration(List.of(new Point(4,4), new Point(5,3), new Point(5,5), new Point(6,3), new Point(6,5), new Point(7,4))) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList())), // horizontal blinker () -> assertEquals(List.of(new Point(4, 2), new Point(4, 3), new Point(4, 4)) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList()), GameOfLife.nextGeneration(List.of(new Point(3, 3), new Point(4, 3), new Point(5, 3))) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList())), // vertical blinker () -> assertEquals(List.of(new Point(3, 3), new Point(4, 3), new Point(5, 3)) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList()), GameOfLife.nextGeneration(List.of(new Point(4, 2), new Point(4, 3), new Point(4, 4))) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList())), // glider () -> assertEquals(List.of(new Point(4, 3), new Point(4, 4), new Point(5, 3), new Point(5, 2), new Point(3, 2)) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList()), GameOfLife.nextGeneration(List.of(new Point(3, 3), new Point(4, 3), new Point(5, 3), new Point(5, 2), new Point(4, 1))) .stream().sorted(Comparator.comparing(Point::getX).thenComparing(Point::getY)).collect(Collectors.toList())) ); } }
package rocks.zipcode.stringsgalore; import java.util.Arrays; import java.util.HashSet; public class ArraysTheory { // // public static void main(String[] args) { // // String[] arrayStr = { "Java", "Python", "PHP", "C#", "C Programming", "C++" }; // // int[] arrayInt = {1789, 2035, 1899, 1456, 2013, 1458, 2458, 1254, 1472, 2365,1456, 2165, 1457, 2456}; // // } /** * 1. Write a Java program to sort a numeric array and a string array. * tsmallest positive integer NOT present in an array. */ public static int Exercise1(int[] a) { HashSet<Integer> hashSet = new HashSet<>(); int smallestInt = 1; for (int i = 0; i < a.length; i++) { hashSet.add(a[i]); } while (hashSet.contains(smallestInt)) { ; smallestInt++; } return smallestInt; } // // public static void main(String[] args) throws Exception { // String time1 = "12:00:00"; // String time2 = "12:01:00"; // // SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); // Date date1 = format.parse(time1); // Date date2 = format.parse(time2); // long difference = date2.getTime() - date1.getTime(); // System.out.println(difference / 1000); // } public class MyMap <K, V>{ private MyMap<K, V> myMap; private K key; private V value; public void set (K key, V value) { this.key = key; this.value = value; } public MyMap() { myMap = new MyMap<>(); } public int size() { return myMap.size(); } public boolean isEmpty() { return myMap.isEmpty(); } public boolean containsKey(K key){ if (myMap.getKey() == key) { return true; }else return false; } public boolean containsValue(K value){ if(myMap.getValue() == value) { return true; }else return false; } public void put(K key, K value){ if (myMap.getKey() != key) { myMap.put(key, value); } } public void remove(K key) { myMap.remove(key); } public void clear() { myMap.clear(); } public void values(){ } public void equals(){ } public int hashCode(){ return myMap.hashCode(); } //Getters & Setters for Key & Value public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } public class MySet <K> { private MyArrayList<K> mySet; public MySet() { mySet = new MyArrayList<>(); } public void add(K obj){ if (!mySet.contains(obj)) { mySet.add(obj); } } public void remove(int index) { mySet.remove(index); } public K get(int index) { return mySet.get(index); } public void set(int index, K obj){ mySet.set(index, obj); } public int size() { return mySet.size(); } public boolean contains (K obj){ return mySet.contains(obj); } public void clear() { mySet.clear(); } public boolean isEmpty() { return mySet.isEmpty(); } // public K[] toArray(K[] values) { // return (K[]) Arrays.copyOf(mySet, inputArray.length, newArray.getClass()); // // } } } public class MyArrayList <K>{ private K[] inputArray; public MyArrayList(){ inputArray = (K[]) new Object[0]; } public MyArrayList(int size){ inputArray = (K[]) new Object[size]; } public <K> K[] toArray(K[] newArray){ return (K[]) Arrays.copyOf(inputArray, inputArray.length, newArray.getClass()); } public void set(int index, K element){ inputArray[index] = element; } public K get(int index){ return inputArray[index]; } public int size(){ return inputArray.length; } public void add(K obj){ K[] addArray = Arrays.copyOf(inputArray, inputArray.length + 1); addArray[addArray.length - 1] = obj; inputArray = addArray; } public void add(int index, K obj) { inputArray = Arrays.copyOf(inputArray, inputArray.length + 1); for (int i = inputArray.length - 1; i > index; i--){ inputArray[i] = inputArray[i-1]; } inputArray[index]= obj; } public void remove(int index){ for (int i = index; i < inputArray.length - 1; i++){ inputArray[i] = inputArray[i + 1] ; } inputArray = Arrays.copyOf(inputArray, inputArray.length - 1); } public void clear() { //reassigned it to an empty array inputArray = (K[]) new Object[0]; } public boolean isEmpty(){ if (inputArray.length == 0) { return true; }else return false; } public boolean contains(K value) { for (int i = 0; i < inputArray.length; i++) { if (value.equals(inputArray[i])) { return true; } } return false; } } }
package cn.sabotage.util; import org.omg.CORBA.Object; import java.util.Map; /** * Created by yxjr-jwh on 2016/5/16. */ public class Command { private Map state; public Object execute() { System.out.println("execute Command : " + this); return null; } public Map getState() { return state; } public void setState(Map state) { this.state = state; } }
package com.examples.io.strings; public class SubstringTest { public static void main(String[] args) { String s = "abba"; int start = 0; int end = 4; System.out.println(s.substring(start,start+end)); } }
package com.game4u.arwinebottle.bean; /** * Created by walke.Z on 2017/11/11. */ public class RegisterResult { /** * result : {"func":"register","servertime":"2017-11-11 17:13:48","status":1} * userInfo : {} * code : 1 * desc : 注册成功! */ private ResultBean result; private UserInfoBean userInfo; private int code; private String desc; public ResultBean getResult() { return result; } public void setResult(ResultBean result) { this.result = result; } public UserInfoBean getUserInfo() { return userInfo; } public void setUserInfo(UserInfoBean userInfo) { this.userInfo = userInfo; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public static class ResultBean { /** * func : register * servertime : 2017-11-11 17:13:48 * status : 1 */ private String func; private String servertime; private int status; public String getFunc() { return func; } public void setFunc(String func) { this.func = func; } public String getServertime() { return servertime; } public void setServertime(String servertime) { this.servertime = servertime; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } } public static class UserInfoBean { } }
package com.gxtc.huchuan.pop; import android.app.Activity; import android.support.v7.widget.LinearLayoutManager; import android.view.View; import com.gxtc.commlibrary.base.BasePopupWindow; import com.gxtc.commlibrary.recyclerview.RecyclerView; import com.gxtc.commlibrary.utils.EventBusUtil; import com.gxtc.commlibrary.utils.WindowUtil; import com.gxtc.huchuan.R; import com.gxtc.huchuan.adapter.PopListTypeAdapter; import com.gxtc.huchuan.bean.DealTypeBean; import com.gxtc.huchuan.bean.event.EventClickBean; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * 来自 伍玉南 的装逼小尾巴 on 17/5/26. */ public class PopDealType extends BasePopupWindow { @BindView(R.id.recyclerview) RecyclerView mRecyclerView; private View footView; private View btnFinish; private PopListTypeAdapter mAdapter; public PopDealType(Activity activity, int resId) { super(activity, resId); } @Override public void init(View layoutView) { ButterKnife.bind(this, layoutView); footView = View.inflate(getActivity(),R.layout.item_type_finish,null); btnFinish = footView.findViewById(R.id.tv_finish); mRecyclerView.addFootView(footView,RecyclerView.DEFAULT_FOOTVIEW); mAdapter = new PopListTypeAdapter(getActivity(),new ArrayList<DealTypeBean>(),new int[]{R.layout.item_list_deal_type_edit, R.layout.item_list_deal_type_btn,R.layout.item_list_deal_type}); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),1,false)); mRecyclerView.setAdapter(mAdapter); } @Override public void initListener() { btnFinish.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EventBusUtil.post(new EventClickBean("-1",v)); WindowUtil.closeInputMethod(getActivity()); closePop(); } }); } public void changeData(List<DealTypeBean> datas){ mRecyclerView.notifyChangeData(datas,mAdapter); } }
package edu.uha.miage.core.service; import edu.uha.miage.core.entity.Services; import edu.uha.miage.core.entity.Categorie; import java.util.List; import java.util.Optional; /** * * @author victo */ public interface ServiceService { Services save(Services entity); void delete(Long id); List<Services> findAll(); Optional<Services> findById(Long id); Services findByLibelle(String libelle); Services getOne(Long id); public List<Services> findByCategorie(Categorie categorie); }
package com.hlx.view.option; import com.hlx.model.Setting; import com.hlx.service.SettingService; import com.hlx.service.RouteService; import com.hlx.service.SoundService; import com.hlx.view.common.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * The option frame of bo game * @author hlx * @version 1.0 2018-3-17 */ @Component public class OptionFrame extends RenewableFrame{ private BackgroundLabel backgroundLabel; private TranslucentPanel mainPanel; private WordsLabel titleLabel; private List<WordsLabel> attentionLabelList; private List<TabPanel> tabPanelList; private List<GeneralButton> selButtonList; private static final float mainPanelTransparency = (float) 0.4; private RouteService routeService; private SettingService settingService; private SoundService soundService; @Autowired public OptionFrame(RouteService routeService,SettingService optionService,SoundService soundService) { super(true); this.routeService = routeService; this.settingService = optionService; this.soundService = soundService; routeService.addUrl("/option",this); initBackground(); initMainPanel(); } public void refresh() { Setting option = settingService.get(); tabPanelList.get(0).setNumber(option.getNum()); tabPanelList.get(1).setNumber(option.getNum2()); tabPanelList.get(2).setNumber(option.getNum3()); tabPanelList.get(3).setNumber(option.getNum4()); tabPanelList.get(4).setNumber(option.getNum5()); tabPanelList.get(5).setNumber(option.getNum6()); tabPanelList.get(6).setNumber(option.getNum7()); } private void initMainPanel() { //init the mainPanel mainPanel =new TranslucentPanel(); mainPanel.setSize(600, 500); mainPanel.setTransparency(mainPanelTransparency); PositionUtil.setCenter(mainPanel,backgroundLabel); //init the title titleLabel = new WordsLabel("OPTION",30,false); titleLabel.setForeground(new Color(31, 89,240)); titleLabel.setSize(180,30); titleLabel.setLocation(0,0); mainPanel.add(titleLabel); //init the attention attentionLabelList = new ArrayList<>(Arrays.asList( new WordsLabel("一秀", 25, false, SwingConstants.CENTER), new WordsLabel("二举", 25, false, SwingConstants.CENTER), new WordsLabel("四进", 25, false, SwingConstants.CENTER), new WordsLabel("三红", 25, false, SwingConstants.CENTER), new WordsLabel("对堂", 25, false, SwingConstants.CENTER), new WordsLabel("状元", 25, false, SwingConstants.CENTER), new WordsLabel("玩家", 25, false, SwingConstants.CENTER) )); int initY = 80; for (WordsLabel attentionLabel : attentionLabelList) { attentionLabel.setForeground(new Color(100, 71,240)); attentionLabel.setSize(100, 40); attentionLabel.setLocation(100,initY); attentionLabel.setBackground(new Color(240, 175, 211)); attentionLabel.setOpaque(true); mainPanel.add(attentionLabel); initY = initY + 50; } //init the tab tabPanelList = new ArrayList<>(Arrays.asList( new TabPanel(-1,0,soundService), new TabPanel(-1,0,soundService), new TabPanel(-1,0,soundService), new TabPanel(-1,0,soundService), new TabPanel(-1,0,soundService), new TabPanel(-1,0,soundService), new TabPanel(-1,1,soundService) )); initY = 80; for (TabPanel tabPanel : tabPanelList) { tabPanel.setLocation(200,initY); mainPanel.add(tabPanel); initY = initY + 50; } //init the sel button selButtonList = new ArrayList<>(Arrays.asList( new GeneralButton("保存", 22), new GeneralButton("取消", 22), new GeneralButton("重置", 22) )); initY = 120; for (GeneralButton selButton :selButtonList) { selButton.setBackground(new Color(240, 175, 211)); selButton.setBounds(450, initY, 80, 60); mainPanel.add(selButton); initY = initY + 100; } GeneralButton saveButton = selButtonList.get(0); saveButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Setting setting = new Setting( tabPanelList.get(0).getNumber(), tabPanelList.get(1).getNumber(), tabPanelList.get(2).getNumber(), tabPanelList.get(3).getNumber(), tabPanelList.get(4).getNumber(), tabPanelList.get(5).getNumber(), tabPanelList.get(6).getNumber() ); settingService.save(setting); routeService.redirect("/entry"); } }); GeneralButton cancelButton = selButtonList.get(1); cancelButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { routeService.redirect("/entry"); } }); GeneralButton resetButton = selButtonList.get(2); resetButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { for (TabPanel tabPanel : tabPanelList) { tabPanel.setNumber(0); } tabPanelList.get(6).setNumber(1); } }); } private void initBackground() { backgroundLabel = new BackgroundLabel("view/image/background/back2.jpg"); this.add(backgroundLabel); } }
/* * Ara - Capture Species and Specimen Data * * Copyright © 2009 INBio (Instituto Nacional de Biodiversidad). * Heredia, Costa Rica. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.inbio.ara.facade.transaction.impl; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.ejb.EJB; import org.inbio.ara.dto.agent.InstitutionDTO; import org.inbio.ara.facade.transaction.*; import javax.ejb.Stateless; import org.inbio.ara.dto.agent.InstitutionDTOFactory; import org.inbio.ara.dto.inventory.PersonDTO; import org.inbio.ara.dto.inventory.PersonDTOFactory; import org.inbio.ara.dto.inventory.SelectionListDTOFactory; import org.inbio.ara.dto.transaction.TransactedSpecimenDTO; import org.inbio.ara.dto.transaction.TransactedSpecimenDTOFactory; import org.inbio.ara.dto.transaction.TransactionDTO; import org.inbio.ara.dto.transaction.TransactionDTOFactory; import org.inbio.ara.eao.agent.InstitutionEAOLocal; import org.inbio.ara.eao.agent.PersonEAOLocal; import org.inbio.ara.eao.collection.CollectionEAOLocal; import org.inbio.ara.eao.identification.IdentificationEAOLocal; import org.inbio.ara.eao.selectionlist.SelectionListValueLocalEAO; import org.inbio.ara.eao.specimen.SpecimenEAOLocal; import org.inbio.ara.eao.transaction.TransactedSpecimenEAOLocal; import org.inbio.ara.eao.transaction.TransactedSpecimenStatusEAOLocal; import org.inbio.ara.eao.transaction.TransactionEAOLocal; import org.inbio.ara.eao.transaction.TransactionTypeEAOLocal; import org.inbio.ara.persistence.collection.Collection; import org.inbio.ara.persistence.identification.Identification; import org.inbio.ara.persistence.institution.Institution; import org.inbio.ara.persistence.person.Person; import org.inbio.ara.persistence.specimen.Specimen; import org.inbio.ara.persistence.transaction.TransactedSpecimen; import org.inbio.ara.persistence.transaction.TransactedSpecimenPK; import org.inbio.ara.persistence.transaction.TransactedSpecimenStatus; import org.inbio.ara.persistence.transaction.Transaction; import org.inbio.ara.persistence.transaction.TransactionType; /** * * @author echinchilla */ @Stateless public class TransactionFacadeImpl implements TransactionFacadeRemote { @EJB private TransactionEAOLocal transactionEAOImpl; @EJB private TransactedSpecimenEAOLocal transactedSpecimenEAOImpl; @EJB private PersonEAOLocal personEAOImpl; @EJB private InstitutionEAOLocal insitutionEAOImpl; @EJB private CollectionEAOLocal collectionEAOImpl; @EJB private TransactionTypeEAOLocal transactionTypeEAOImpl; @EJB private TransactedSpecimenStatusEAOLocal transactedSpecimenStatusEAOImpl; @EJB private SpecimenEAOLocal specimenEAOImpl; /*@EJB private SelectionListValueLocalEAO selectionListValueEAOImpl;*/ @EJB private IdentificationEAOLocal identificationEAOImpl; private TransactionDTOFactory transactionDTOFactory = new TransactionDTOFactory(); private TransactedSpecimenDTOFactory transactedSpecimenDTOFactory = new TransactedSpecimenDTOFactory(); private PersonDTOFactory personDTOFactory = new PersonDTOFactory(); private InstitutionDTOFactory institutionDTOFactory = new InstitutionDTOFactory(); /*private SelectionListDTOFactory selecionListDTOFactory = new SelectionListDTOFactory();*/ /** * Cuenta las transacciones asociadas a una colección * @param collectionId * @return */ public Long countTransaction(Long collectionId) { return this.transactionEAOImpl.countTransactionByCollecionId(collectionId); } /** * Cuenta los especímenes transados asociados a una transacción * @param transactionId * @return */ public Long countTransactedSpecimen(Long transactionId) { return this.transactedSpecimenEAOImpl.countTransactedSpecimenByTransactionId(transactionId); } /** * Retrive all transactions paginated * @return */ public List<TransactionDTO> getAllTransactionPaginated(int firstResult, int maxResults, Long collectionId) { String[] orderByFields = {"transactionId"}; List<TransactionDTO> result = transactionDTOFactory.createDTOList(transactionEAOImpl. findAllPaginatedFilterAndOrderBy(Transaction.class, firstResult, maxResults, orderByFields,collectionId)); if (result == null) { return null; } List<TransactionDTO> update = updateNames(result); return update; } /** * Retrive all transacted specimens paginated * @return */ public List<TransactedSpecimenDTO> getAllTransactedSpecimenPaginated(int firstResult, int maxResults, Long transactionId) { List<TransactedSpecimenDTO> result = transactedSpecimenDTOFactory.createDTOList(transactedSpecimenEAOImpl. getTransactedSpecimenByTransactionIdPaginated(firstResult, maxResults, transactionId)); if (result == null) { return null; } return getReadOnlyFields(result); } /** * Función que llena los campos read-only para cada espécimen transado * @param tsDTOList * @return */ public List<TransactedSpecimenDTO> getReadOnlyFields(List<TransactedSpecimenDTO> tsDTOList) { List<TransactedSpecimenDTO> resultTransactedSpecimenDTOList = new ArrayList<TransactedSpecimenDTO>(); TransactedSpecimenDTO auxDTO; for (TransactedSpecimenDTO tsDTO : tsDTOList) { auxDTO = getCatalogNumber(tsDTO); auxDTO = getSpecimenTaxon(auxDTO); auxDTO = getTransactedSpecimenStatus(auxDTO); resultTransactedSpecimenDTOList.add(auxDTO); } return resultTransactedSpecimenDTOList; } /** * Función que trae el nombre del taxón asociado a un SpecimenId * @param tsDTO * @return */ public TransactedSpecimenDTO getSpecimenTaxon(TransactedSpecimenDTO tsDTO) { String taxones = ""; List<Identification> identificaciones = this.identificationEAOImpl. findBySpecimenId(tsDTO.getTransactedSpecimenPK().getSpecimenId()); for (int i = 1; i <= identificaciones.size(); i++) { Identification aux = identificaciones.get(i - 1); if (i == identificaciones.size()) { taxones += aux.getTaxon().getDefaultName(); } else { taxones += aux.getTaxon().getDefaultName() + " , "; } } tsDTO.setTaxonName(taxones); return tsDTO; } /** * Función que trae el CatalogNumber asociado a un SpecimenId * @param transactedSpecimenDTO * @return */ public TransactedSpecimenDTO getCatalogNumber(TransactedSpecimenDTO transactedSpecimenDTO) { Specimen specimen; specimen = this.specimenEAOImpl.findById(Specimen.class, transactedSpecimenDTO.getTransactedSpecimenPK().getSpecimenId()); transactedSpecimenDTO.setCatalogNumber(specimen.getCatalogNumber()); return transactedSpecimenDTO; } /** * Función que trae el nombre asociado a un id de TransactedSpecimenStatus * @param transactedSpecimenDTO * @return */ public TransactedSpecimenDTO getTransactedSpecimenStatus(TransactedSpecimenDTO transactedSpecimenDTO) { TransactedSpecimenStatus transactedSpecimenStatus; transactedSpecimenStatus = this.transactedSpecimenStatusEAOImpl.findById(TransactedSpecimenStatus.class, transactedSpecimenDTO.getTransactedSpecimenStatusId()); transactedSpecimenDTO.setTransactedSpecimenStatus(transactedSpecimenStatus.getName()); return transactedSpecimenDTO; } /** * Metodo para eliminar Transacciones por su id * @param Id */ public void deleteTransaction(Long transactionId) { Transaction aux = this.transactionEAOImpl.findById(Transaction.class, transactionId); if (aux != null) { this.transactionEAOImpl.delete(aux); } } /** * Método para eliminar una lista de especímenes transados * @param selectedTransactedSpecimens */ public void deleteTransactedSpecimens(ArrayList<TransactedSpecimenDTO> selectedTransactedSpecimens) { Long transactionId; Long specimenId; for (TransactedSpecimenDTO tsDTO: selectedTransactedSpecimens) { transactionId = tsDTO.getTransactedSpecimenPK().getTransactionId(); specimenId = tsDTO.getTransactedSpecimenPK().getSpecimenId(); this.transactedSpecimenEAOImpl.deleteTransactedSpecimen(transactionId, specimenId); } } /** * Método para editar una lista de especímenes transados. * @param selectedTransactedSpecimens * @param tDTO */ public void editTransactedSpecimens(ArrayList<TransactedSpecimenDTO> selectedTransactedSpecimens, TransactedSpecimenDTO tDTO) { Long transactionId; Long specimenId; for (TransactedSpecimenDTO tsDTO: selectedTransactedSpecimens) { transactionId = tsDTO.getTransactedSpecimenPK().getTransactionId(); specimenId = tsDTO.getTransactedSpecimenPK().getSpecimenId(); tDTO.setTransactedSpecimenPK(new TransactedSpecimenPK(specimenId, transactionId)); tDTO.setCrationDateAndTime(tsDTO.getCrationDateAndTime()); tDTO.setWaitingForReturn(tsDTO.getWaitingForReturn()); TransactedSpecimen transactedSpecimenEntity = this.transactedSpecimenEAOImpl.getTransactedSpecimenById(transactionId, specimenId).get(0); transactedSpecimenEntity = this.transactedSpecimenDTOFactory.updateEntityWithPlainValues(tDTO, transactedSpecimenEntity); this.transactedSpecimenEAOImpl.update(transactedSpecimenEntity); } } /** * Método para la devolución de un espécimen * @param catalogNumber * @param receivingDate * @param transactedSpecimenStatusId */ public void returnTransactedSpecimen (String catalogNumber, Calendar receivingDate, Long transactedSpecimenStatusId) { Long specimenId = getSpecimenIdByCatalogNumber(catalogNumber); // traer el id de la última transacción que registró el espécimen a devolver TransactedSpecimen transactedSpecimenEntity = this.transactedSpecimenEAOImpl.getWaitingForReturnTransactionId(specimenId); TransactedSpecimenDTO tsDTO = this.transactedSpecimenDTOFactory.createDTO(transactedSpecimenEntity); tsDTO.setReceivingDate(receivingDate); tsDTO.setTransactedSpecimenStatusId(transactedSpecimenStatusId); tsDTO.setWaitingForReturn(false); transactedSpecimenEntity = this.transactedSpecimenDTOFactory.updateEntityWithPlainValues(tsDTO, transactedSpecimenEntity); this.transactedSpecimenEAOImpl.update(transactedSpecimenEntity); } /** * Método que setea campos read-only de una transacción * @param transactionDTO * @return */ public TransactionDTO updateNames(TransactionDTO transactionDTO) { Person senderPerson, receiverPerson; Institution senderInstitution, receiverInstitution; Collection collection; TransactionType transactionType; senderPerson = this.personEAOImpl.findById(Person.class, transactionDTO.getSenderPersonId()); transactionDTO.setSenderPersonName(senderPerson.getNaturalLongName()); if (transactionDTO.getReceiverPersonId() != null) { receiverPerson = this.personEAOImpl.findById(Person.class, transactionDTO.getReceiverPersonId()); transactionDTO.setReceiverPersonName(receiverPerson.getNaturalLongName()); } if (transactionDTO.getSenderInstitutionId() != null) { senderInstitution = this.insitutionEAOImpl. findById(Institution.class, transactionDTO.getSenderInstitutionId()); transactionDTO.setSenderInstitutionName(senderInstitution.getInstitutionCode()); } else { // PARA EL CASO DE 'SIN INSTITUCION ASOCIADA' transactionDTO.setSenderInstitutionId(new Long(-1)); } if (transactionDTO.getReceiverInstitutionId() != null) { receiverInstitution = this.insitutionEAOImpl. findById(Institution.class, transactionDTO.getReceiverInstitutionId()); transactionDTO.setReceiverInstitutionName(receiverInstitution.getInstitutionCode()); } else { if (transactionDTO.getReceiverPersonId() != null) { // PARA EL CASO DE 'SIN INSTITUCION ASOCIADA' transactionDTO.setReceiverInstitutionId(new Long(-1)); } } collection = this.collectionEAOImpl.findById(Collection.class, transactionDTO.getCollectionId()); transactionDTO.setCollectionName(collection.getName()); transactionType = this.transactionTypeEAOImpl. findById(TransactionType.class, transactionDTO.getTransactionTypeId()); transactionDTO.setTransactionType(transactionType.getName()); return transactionDTO; } /** * Método que recorre lista de transacciones para setear campos read-only * @param tDTOList * @return */ public List<TransactionDTO> updateNames(List<TransactionDTO> tDTOList) { List<TransactionDTO> resultTransactionDTOList = new ArrayList<TransactionDTO>(); for (TransactionDTO tDTO : tDTOList) { resultTransactionDTOList.add(updateNames(tDTO)); } return resultTransactionDTOList; } /** * Metodo para auctualizar una transaccion * @param tDTO * @return */ public void updateTransaction(TransactionDTO tDTO) { //En caso de "Institución no Asociada" if(tDTO.getSenderInstitutionId() != null && tDTO.getSenderInstitutionId() == -1) tDTO.setSenderInstitutionId(null); //En caso de "Institución no Asociada" if(tDTO.getReceiverInstitutionId() != null && tDTO.getReceiverInstitutionId() == -1) tDTO.setReceiverInstitutionId(null); Transaction transactionEntity = this.transactionEAOImpl.findById(Transaction.class, tDTO. getTransactionId()); transactionEntity = this.transactionDTOFactory.updatePlainEntity(tDTO, transactionEntity); this.transactionEAOImpl.update(transactionEntity); } /** * Método para crear una transacción * @param transactionDTO * @return */ public TransactionDTO saveTransaction(TransactionDTO transactionDTO) { if(transactionDTO.getSenderInstitutionId() != null && transactionDTO.getSenderInstitutionId() == -1) transactionDTO.setSenderInstitutionId(null); if(transactionDTO.getReceiverInstitutionId() != null && transactionDTO.getReceiverInstitutionId() == -1) transactionDTO.setReceiverInstitutionId(null); Transaction entity = this.transactionDTOFactory.createPlainEntity(transactionDTO); this.transactionEAOImpl.create(entity); TransactionDTO aux = this.transactionDTOFactory.createDTO(entity); // PARA EL CASO DE 'SIN INSTITUCION ASOCIADA' if(aux.getSenderInstitutionId() == null) aux.setSenderInstitutionId(new Long(-1)); if(aux.getReceiverInstitutionId() == null && aux.getReceiverPersonId() != null) aux.setReceiverInstitutionId(new Long(-1)); return aux; } /** * Método * @param transactionDTO * @param transactedSpecimenDTO * @return */ public TransactedSpecimenDTO saveTransactedSpecimen(TransactionDTO transactionDTO, TransactedSpecimenDTO transactedSpecimenDTO) { Long specimenId = getSpecimenIdByCatalogNumber(transactedSpecimenDTO.getCatalogNumber()); TransactedSpecimen transactedSpecimenEntity = this.transactedSpecimenEAOImpl.getWaitingForReturnTransactionId(specimenId); if (transactedSpecimenEntity == null) { transactedSpecimenDTO.setTransactedSpecimenPK(new TransactedSpecimenPK(specimenId, transactionDTO.getTransactionId())); transactedSpecimenDTO.setTransactionTypeId(transactionDTO.getTransactionTypeId()); Calendar currentDateAndTime = Calendar.getInstance(); transactedSpecimenDTO.setCrationDateAndTime(currentDateAndTime); TransactedSpecimen entity = this.transactedSpecimenDTOFactory.createPlainEntity(transactedSpecimenDTO); this.transactedSpecimenEAOImpl.create(entity); return this.transactedSpecimenDTOFactory.createDTO(entity); } else { return null; } } /** * Método que obtiene la lista de personas asociadas a una institución * @param institutionId * @return */ public List<PersonDTO> getPersonsByInstitutionId(Long institutionId) { if (institutionId == null || institutionId != -1) return personDTOFactory.createDTOList(transactionEAOImpl. getPersonsByInstitution(institutionId)); else return personDTOFactory.createDTOList(transactionEAOImpl. getPersonsWithoutInstitution()); } /** * * @return Lista de todas las instituciones registradas en el sistema */ public List<InstitutionDTO> getAllInstitutions() { return institutionDTOFactory.createDTOList(transactionEAOImpl.getAllInstitutions()); } /** * Trae la lista de personas sin institución asociada * @return */ public List<PersonDTO> getPersonsWithoutInstitution() { return personDTOFactory.createDTOList(transactionEAOImpl. getPersonsWithoutInstitution()); } /** * Método que obtiene el specimenId asociado a un número de catálogo * @param catalogNumber * @return */ public Long getSpecimenIdByCatalogNumber (String catalogNumber) { return specimenEAOImpl.findByCatalogNumber(catalogNumber); } }
/* * Created by Angel Leon (@gubatron), Alden Torres (aldenml) * Copyright (c) 2011-2014, FrostWire(R). All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.frostwire.gui.library; import java.io.File; import com.frostwire.alexandria.InternetRadioStation; import com.limegroup.gnutella.gui.tables.HashBasedDataLineModel; /** * Library specific DataLineModel. * Uses HashBasedDataLineModel instead of BasicDataLineModel * for quicker access to row's based on the file. */ final class LibraryInternetRadioTableModel extends HashBasedDataLineModel<LibraryInternetRadioTableDataLine, InternetRadioStation> { /** * */ private static final long serialVersionUID = 3332011897003403390L; LibraryInternetRadioTableModel() { super(LibraryInternetRadioTableDataLine.class); } /** * Creates a new LibraryTableDataLine */ public LibraryInternetRadioTableDataLine createDataLine() { return new LibraryInternetRadioTableDataLine(); } /** * Override the normal refresh. * Because the DataLine's don't cache any data, * we can just call update & they'll show the correct info * now. */ public Object refresh() { fireTableRowsUpdated(0, getRowCount()); return null; } /** * OVerride default so new ones get added to the end */ @Override public int add(LibraryInternetRadioTableDataLine o) { return add(o, getRowCount()); } /** * Reinitializes a dataline that is using the given initialize object. */ void reinitialize(File f) { if(contains(f)) { // int row = getRow(f); // get(row).initialize(f); // fireTableRowsUpdated(row, row); } } /** * Reinitializes a dataline from using one file to use another. */ void reinitialize(File old, File now) { if(contains(old)) { // int row = getRow(old); // get(row).initialize(now); // initializeObjectChanged(old, now); // fireTableRowsUpdated(row, row); } } /** * Returns the file object stored in the given row. * * @param row The row of the file * * @return The <code>File</code> object stored at the specified row */ File getFile(int row) { return null;//new File(get(row).getInitializeObject().getFilePath()); } /** * Returns a boolean specifying whether or not specific cell in the table * is editable. * * @param row the row of the table to access * * @param col the column of the table to access * * @return <code>true</code> if the specified cell is editable, * <code>false</code> otherwise */ public boolean isCellEditable(int row, int col) { return col == LibraryInternetRadioTableDataLine.WEBSITE_IDX || col == LibraryInternetRadioTableDataLine.BOOKMARKED_IDX || col == LibraryInternetRadioTableDataLine.ACTIONS_IDX; } }
package com.git.cloud.resmgt.compute.model.vo; import java.util.List; /** * * @author git * jqGrid返回信息Vo * */ public class JqGridJsonVo { private Integer page; private Integer total; private Integer record; private String sord; private String sidx; private String search; private List <ScanVmResultVo> rowss; public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public Integer getRecord() { return record; } public void setRecord(Integer record) { this.record = record; } public String getSord() { return sord; } public void setSord(String sord) { this.sord = sord; } public String getSidx() { return sidx; } public void setSidx(String sidx) { this.sidx = sidx; } public String getSearch() { return search; } public void setSearch(String search) { this.search = search; } public List<ScanVmResultVo> getrows() { return rowss; } public void setrows(List<ScanVmResultVo> list) { this.rowss = list; } }
package com.zaxxer.sansorm.internal; import org.junit.Test; import javax.persistence.Column; import javax.persistence.Table; import static org.junit.Assert.*; /** * @author Holger Thurow (thurow.h@gmail.com) * @since 17.04.18 */ public class FieldColumnInfoTest { @Test public void getFullyQualifiedTableNameFromColumnAnnotation() { @Table class TestClass { @Column(table = "TEST_CLASS") String field; } Introspected introspected = new Introspected(TestClass.class); FieldColumnInfo[] fcInfos = introspected.getSelectableFcInfos(); String fqn = fcInfos[0].getFullyQualifiedDelimitedFieldName(); assertEquals("TEST_CLASS.field", fqn); } // @Test // public void getFullyQualifiedTableNameFromClassName() { // @Table // class TestClass { // @Column // String field; // } // Introspected introspected = new Introspected(TestClass.class); // FieldColumnInfo[] fcInfos = introspected.getSelectableFcInfos(); // String fqn = fcInfos[0].getFullyQualifiedDelimitedFieldName(); // assertEquals("TestClass.field", fqn); // } // @Test // public void getFullyQualifiedTableNameFromTableAnnotation() { // @Table(name = "TEST_CLASS") // class TestClass { // @Column // String field; // } // Introspected introspected = new Introspected(TestClass.class); // FieldColumnInfo[] fcInfos = introspected.getSelectableFcInfos(); // String fqn = fcInfos[0].getFullyQualifiedDelimitedFieldName(); // assertEquals("TEST_CLASS.field", fqn); // } }
package algorithms.graph.practice.weighted.digraph; import java.util.BitSet; import java.util.Deque; import java.util.LinkedList; import algorithms.graph.DirectedEdge; import algorithms.graph.EdgeWeightedDigraph; /** * Created by Chen Li on 2018/5/23. */ public class DepthFirstWeightedDigraphCycleDetection { private BitSet marked; private boolean hasCycle; private Deque<Integer> cycleVertices; //can not use int[] edge to record cycle path private Deque<Integer> stack; public void init(EdgeWeightedDigraph graph) { stack = new LinkedList<>(); marked = new BitSet(graph.verticesCount()); for (Integer vertex : graph.getVertices()) { //another connected component if (!marked.get(vertex)) { visit(graph, vertex); } //if found cycle, don't bother to try another connected component if (hasCycle) { break; } } } private void visit(EdgeWeightedDigraph graph, Integer v) { stack.push(v); marked.set(v); for (DirectedEdge directedEdge : graph.adjacent(v)) { //attention, use marked is bug, only test this connected component Integer adjacentV = directedEdge.to(); if (stack.contains(adjacentV)) { //cycle detected! cycleVertices = new LinkedList<>(); Integer current = stack.pop(); while (current != adjacentV && !stack.isEmpty()) { cycleVertices.push(current); current = stack.pop(); } cycleVertices.push(adjacentV); cycleVertices.push(v); hasCycle = true; return; } else { visit(graph, adjacentV); } if (hasCycle) { return; } } stack.pop(); } public boolean hasCycle() { return hasCycle; } public Iterable<Integer> cycle() { return cycleVertices; } }
package com.github.egnaf.springHibernateExample.models.manyToOne; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Table(name = "cars") @Data @NoArgsConstructor public class Car { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String model; @ManyToOne @JoinColumn(name = "driver_id") private Driver driver; }
package com.example.user.airport2; import java.util.Calendar; public class Absen { private String waktu; private String tag; public Absen() { } public String getWaktu() { return waktu; } public void setWaktu(String waktu) { this.waktu = waktu; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } @Override public String toString() { return "Absen{" + "waktu='" + waktu + '\'' + ", tag='" + tag + '\'' + '}'; } }
package com.brainacademy.singleton; public class Main { public static void main(String[] args) { SingleObject singleObject1 = SingleObject.getInstance(); SingleObject singleObject2 = SingleObject.getInstance(); // Оба объекта равны, то есть ссылаются на один и тот же исходный объект System.out.println(singleObject1 == singleObject2); } }
/* * 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.web.server; import java.security.Principal; import java.time.Instant; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import reactor.core.publisher.Mono; import org.springframework.context.ApplicationContext; import org.springframework.context.i18n.LocaleContext; import org.springframework.http.codec.multipart.Part; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.MultiValueMap; /** * Contract for an HTTP request-response interaction. Provides access to the HTTP * request and response and also exposes additional server-side processing * related properties and features such as request attributes. * * @author Rossen Stoyanchev * @since 5.0 */ public interface ServerWebExchange { /** * Name of {@link #getAttributes() attribute} whose value can be used to * correlate log messages for this exchange. Use {@link #getLogPrefix()} to * obtain a consistently formatted prefix based on this attribute. * @since 5.1 * @see #getLogPrefix() */ String LOG_ID_ATTRIBUTE = ServerWebExchange.class.getName() + ".LOG_ID"; /** * Return the current HTTP request. */ ServerHttpRequest getRequest(); /** * Return the current HTTP response. */ ServerHttpResponse getResponse(); /** * Return a mutable map of request attributes for the current exchange. */ Map<String, Object> getAttributes(); /** * Return the request attribute value if present. * @param name the attribute name * @param <T> the attribute type * @return the attribute value */ @SuppressWarnings("unchecked") @Nullable default <T> T getAttribute(String name) { return (T) getAttributes().get(name); } /** * Return the request attribute value or if not present raise an * {@link IllegalArgumentException}. * @param name the attribute name * @param <T> the attribute type * @return the attribute value */ @SuppressWarnings("unchecked") default <T> T getRequiredAttribute(String name) { T value = getAttribute(name); Assert.notNull(value, () -> "Required attribute '" + name + "' is missing"); return value; } /** * Return the request attribute value, or a default, fallback value. * @param name the attribute name * @param defaultValue a default value to return instead * @param <T> the attribute type * @return the attribute value */ @SuppressWarnings("unchecked") default <T> T getAttributeOrDefault(String name, T defaultValue) { return (T) getAttributes().getOrDefault(name, defaultValue); } /** * Return the web session for the current request. Always guaranteed to * return an instance either matching to the session id requested by the * client, or with a new session id either because the client did not * specify one or because the underlying session had expired. Use of this * method does not automatically create a session. See {@link WebSession} * for more details. */ Mono<WebSession> getSession(); /** * Return the authenticated user for the request, if any. */ <T extends Principal> Mono<T> getPrincipal(); /** * Return the form data from the body of the request if the Content-Type is * {@code "application/x-www-form-urlencoded"} or an empty map otherwise. * <p><strong>Note:</strong> calling this method causes the request body to * be read and parsed in full and the resulting {@code MultiValueMap} is * cached so that this method is safe to call more than once. */ Mono<MultiValueMap<String, String>> getFormData(); /** * Return the parts of a multipart request if the Content-Type is * {@code "multipart/form-data"} or an empty map otherwise. * <p><strong>Note:</strong> calling this method causes the request body to * be read and parsed in full and the resulting {@code MultiValueMap} is * cached so that this method is safe to call more than once. * <p><strong>Note:</strong>the {@linkplain Part#content() contents} of each * part is not cached, and can only be read once. */ Mono<MultiValueMap<String, Part>> getMultipartData(); /** * Cleans up any storage used for multipart handling. * @since 6.0.10 * @see Part#delete() */ default Mono<Void> cleanupMultipart() { return getMultipartData() .onErrorResume(t -> Mono.empty()) // ignore errors reading multipart data .flatMapIterable(Map::values) .flatMapIterable(Function.identity()) .flatMap(part -> part.delete().onErrorResume(ex -> Mono.empty())) .then(); } /** * Return the {@link LocaleContext} using the configured * {@link org.springframework.web.server.i18n.LocaleContextResolver}. */ LocaleContext getLocaleContext(); /** * Return the {@link ApplicationContext} associated with the web application, * if it was initialized with one via * {@link org.springframework.web.server.adapter.WebHttpHandlerBuilder#applicationContext(ApplicationContext)}. * @since 5.0.3 * @see org.springframework.web.server.adapter.WebHttpHandlerBuilder#applicationContext(ApplicationContext) */ @Nullable ApplicationContext getApplicationContext(); /** * Returns {@code true} if the one of the {@code checkNotModified} methods * in this contract were used and they returned true. */ boolean isNotModified(); /** * An overloaded variant of {@link #checkNotModified(String, Instant)} with * a last-modified timestamp only. * @param lastModified the last-modified time * @return whether the request qualifies as not modified */ boolean checkNotModified(Instant lastModified); /** * An overloaded variant of {@link #checkNotModified(String, Instant)} with * an {@code ETag} (entity tag) value only. * @param etag the entity tag for the underlying resource. * @return true if the request does not require further processing. */ boolean checkNotModified(String etag); /** * Check whether the requested resource has been modified given the supplied * {@code ETag} (entity tag) and last-modified timestamp as determined by * the application. Also transparently prepares the response, setting HTTP * status, and adding "ETag" and "Last-Modified" headers when applicable. * This method works with conditional GET/HEAD requests as well as with * conditional POST/PUT/DELETE requests. * <p><strong>Note:</strong> The HTTP specification recommends setting both * ETag and Last-Modified values, but you can also use * {@code #checkNotModified(String)} or * {@link #checkNotModified(Instant)}. * @param etag the entity tag that the application determined for the * underlying resource. This parameter will be padded with quotes (") * if necessary. * @param lastModified the last-modified timestamp that the application * determined for the underlying resource * @return true if the request does not require further processing. */ boolean checkNotModified(@Nullable String etag, Instant lastModified); /** * Transform the given url according to the registered transformation function(s). * By default, this method returns the given {@code url}, though additional * transformation functions can be registered with {@link #addUrlTransformer} * @param url the URL to transform * @return the transformed URL */ String transformUrl(String url); /** * Register an additional URL transformation function for use with {@link #transformUrl}. * The given function can be used to insert an id for authentication, a nonce for CSRF * protection, etc. * <p>Note that the given function is applied after any previously registered functions. * @param transformer a URL transformation function to add */ void addUrlTransformer(Function<String, String> transformer); /** * Return a log message prefix to use to correlate messages for this exchange. * The prefix is based on the value of the attribute {@link #LOG_ID_ATTRIBUTE} * along with some extra formatting so that the prefix can be conveniently * prepended with no further formatting no separators required. * @return the log message prefix or an empty String if the * {@link #LOG_ID_ATTRIBUTE} is not set. * @since 5.1 */ String getLogPrefix(); /** * Return a builder to mutate properties of this exchange by wrapping it * with {@link ServerWebExchangeDecorator} and returning either mutated * values or delegating back to this instance. */ default Builder mutate() { return new DefaultServerWebExchangeBuilder(this); } /** * Builder for mutating an existing {@link ServerWebExchange}. * Removes the need */ interface Builder { /** * Configure a consumer to modify the current request using a builder. * <p>Effectively this: * <pre> * exchange.mutate().request(builder -&gt; builder.method(HttpMethod.PUT)); * * // vs... * * ServerHttpRequest request = exchange.getRequest().mutate() * .method(HttpMethod.PUT) * .build(); * * exchange.mutate().request(request); * </pre> * @see ServerHttpRequest#mutate() */ Builder request(Consumer<ServerHttpRequest.Builder> requestBuilderConsumer); /** * Set the request to use especially when there is a need to override * {@link ServerHttpRequest} methods. To simply mutate request properties * see {@link #request(Consumer)} instead. * @see org.springframework.http.server.reactive.ServerHttpRequestDecorator */ Builder request(ServerHttpRequest request); /** * Set the response to use. * @see org.springframework.http.server.reactive.ServerHttpResponseDecorator */ Builder response(ServerHttpResponse response); /** * Set the {@code Mono<Principal>} to return for this exchange. */ Builder principal(Mono<Principal> principalMono); /** * Build a {@link ServerWebExchange} decorator with the mutated properties. */ ServerWebExchange build(); } }
package com.liyang.gys.service; import com.liyang.commons.Factory; import com.liyang.gys.entity.City; import com.liyang.gys.entity.Gys; import com.liyang.gys.entity.GysExample; import com.liyang.gys.entity.Province; import com.liyang.gys.mapper.CityMapper; import com.liyang.gys.mapper.GysMapper; import com.liyang.gys.mapper.ProvinceMapper; import org.apache.ibatis.session.SqlSession; import java.util.HashMap; import java.util.List; import java.util.Map; /* *@author:李洋 *@date:2019/7/29 9:35 */ public class GysService { public void addSupplier(Gys gys) { SqlSession session = null; try{ session = Factory.getSession(); GysMapper dao = session.getMapper(GysMapper.class); dao.insert(gys); session.commit(); }catch(Exception e){ e.printStackTrace(); if (session != null){ session.rollback(); } }finally{ if (session != null){ session.close(); } } } public int queryCount(Map<String,Object> map) { SqlSession session = null; try{ session = Factory.getSession(); GysMapper dao = session.getMapper(GysMapper.class); int count = dao.queryCount(map); session.commit(); return count; }catch(Exception e){ e.printStackTrace(); if (session != null){ session.rollback(); return 0; } }finally{ if (session != null){ session.close(); } } return 0; } public List<Gys> querySomeSupplier(Map<String,Object> map, int start, int pageSize) { SqlSession session = null; try{ session = Factory.getSession(); GysMapper dao = session.getMapper(GysMapper.class); map.put("start",start); map.put("end",pageSize+start); List<Gys> data = dao.querySome(map); session.commit(); return data; }catch(Exception e){ e.printStackTrace(); if (session != null){ session.rollback(); return null; } }finally{ if (session != null){ session.close(); } } return null; } public List<Gys> querySupplier(String name) { SqlSession session = null; try{ session = Factory.getSession(); GysMapper dao = session.getMapper(GysMapper.class); GysExample example = new GysExample(); GysExample.Criteria cri = example.createCriteria(); cri.andNameEqualTo(name); List<Gys> gys = dao.selectByExample(example); session.commit(); return gys; }catch(Exception e){ e.printStackTrace(); if (session != null){ session.rollback(); return null; } }finally{ if (session != null){ session.close(); } } return null; } public List<Gys> queryAllSupplier() { SqlSession session = null; try{ session = Factory.getSession(); GysMapper dao = session.getMapper(GysMapper.class); List<Gys> gys = dao.selectByExample(null); session.commit(); return gys; }catch(Exception e){ e.printStackTrace(); if (session != null){ session.rollback(); return null; } }finally{ if (session != null){ session.close(); } } return null; } }
package com.eu.front.dao; import java.util.List; import java.util.Map; public interface AllFrontDao { /** * 查询创课点击次数 * */ List<Map<String,String>> tronClass(); List<Map<String,String>> queryStudentInfo(); }
package com.debugger.car.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import com.debugger.car.domain.Cars; import com.debugger.car.model.CarsModel; import com.debugger.car.repository.CarsRepository; @Service public class CarService { @Autowired CarsRepository carsRepository; private static final String CARS = "/cars"; private static final String SLASH = "/"; @Value("${cars.rental.service.url}") private String carServiceUrl; private final RestTemplate restTemplate = new RestTemplate(); @Autowired public CarService(CarsRepository carsRepository) { this.carsRepository = carsRepository; } public Cars createCar(long carId, String model, String make, int rentalPrice, int year) { return carsRepository.findById(carId) .orElse(carsRepository.save(new Cars(carId, model, make, rentalPrice, year))); } public Iterable<Cars> lookup() { return carsRepository.findAll(); } public long total() { return carsRepository.count(); } public Cars add(Cars aCar) { Cars newCar = null; if (aCar.getModel() != null) { newCar = carsRepository.save(aCar); } return newCar; } // URL MAPPINGS public List<Cars> getAllCars(){ String url = carServiceUrl + CARS; HttpEntity<String> request = new HttpEntity<>(null, null); return this.restTemplate.exchange(url, HttpMethod.GET, request, new ParameterizedTypeReference<List<Cars>>() { }).getBody(); } public Cars addCar(CarsModel guestModel){ String url = carServiceUrl + CARS; HttpEntity<CarsModel> request = new HttpEntity<>(guestModel, null); return this.restTemplate.exchange(url, HttpMethod.POST, request, Cars.class).getBody(); } public Cars getCar(long id) { String url = carServiceUrl + CARS + SLASH + id; HttpEntity<String> request = new HttpEntity<>(null, null); return this.restTemplate.exchange(url, HttpMethod.GET, request, Cars.class).getBody(); } public Cars updateCar(long id, CarsModel guestModel) { System.out.println(guestModel); String url = carServiceUrl + CARS + SLASH + id; HttpEntity<CarsModel> request = new HttpEntity<>(guestModel, null); return this.restTemplate.exchange(url, HttpMethod.PUT, request, Cars.class).getBody(); } }
package com.seva.entity; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the printer_group_printers database table. * */ @Entity @Table(name="printer_group_printers") @NamedQuery(name="PrinterGroupPrinter.findAll", query="SELECT p FROM PrinterGroupPrinter p") public class PrinterGroupPrinter implements Serializable { private static final long serialVersionUID = 1L; private int id; private String printerName; private PrinterGroup printerGroup; public PrinterGroupPrinter() { } @Id @GeneratedValue(strategy=GenerationType.AUTO) public int getId() { return this.id; } public void setId(int id) { this.id = id; } @Column(name="PRINTER_NAME") public String getPrinterName() { return this.printerName; } public void setPrinterName(String printerName) { this.printerName = printerName; } //bi-directional many-to-one association to PrinterGroup @ManyToOne @JoinColumn(name="printer_id") public PrinterGroup getPrinterGroup() { return this.printerGroup; } public void setPrinterGroup(PrinterGroup printerGroup) { this.printerGroup = printerGroup; } }
package BuilderPattern06.exercise.controller; import BuilderPattern06.exercise.builder.VideoInterfaceBuilder; import BuilderPattern06.exercise.entity.VideoInterface; public class VideoInterfaceController { public VideoInterface construct(VideoInterfaceBuilder VID){ VID.buildCollectList(); VID.buildControlStrip(); VID.buildMainWindow(); VID.buildMenu(); VID.buildPlayList(); return VID.create(); } }
package org.dbdoclet.tidbit.perspective.docbook.wordml; import java.awt.Component; import java.io.IOException; import java.net.URL; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import org.dbdoclet.jive.Anchor; import org.dbdoclet.jive.Fill; import org.dbdoclet.jive.JiveFactory; import org.dbdoclet.jive.widget.GridPanel; import org.dbdoclet.service.ResourceServices; import org.dbdoclet.tidbit.application.Application; import org.dbdoclet.tidbit.common.Output; import org.dbdoclet.tidbit.medium.MediumService; import org.dbdoclet.tidbit.perspective.AbstractPerspective; import org.dbdoclet.tidbit.perspective.Perspective; import org.dbdoclet.tidbit.perspective.panel.InfoPanel; import org.dbdoclet.tidbit.perspective.panel.docbook.AbstractPanel; import org.dbdoclet.tidbit.project.Project; import org.osgi.service.component.ComponentContext; public class DocBookWordPerspective extends AbstractPerspective implements Perspective { private GridPanel registerPanel; private JTabbedPane tabbedPane; protected void activate(ComponentContext context) { } public Application getApplication() { return application; } public Icon getIcon() { Icon icon = null; URL iconUrl = ResourceServices.getResourceAsUrl("/images/dbdoclet.png", DocBookWordPerspective.class .getClassLoader()); if (iconUrl != null) { icon = new ImageIcon(iconUrl); } return icon; } public String getId() { return "docbook-wordml"; } public String getLocalizedName() { return "WordML (\u03b1)"; } public String getName() { return "WordML"; } public JPanel getPanel() { if (application == null) { throw new IllegalStateException("The argument application must not be null!"); } if (registerPanel == null) { JiveFactory wm = JiveFactory.getInstance(); tabbedPane = wm.createTabbedPane(); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane.setTopComponent(tabbedPane); InfoPanel infoPanel = new InfoPanel(); infoPanel.setConsole(getConsole()); infoPanel.createGui(); if (infoPanel != null) { splitPane.setBottomComponent(infoPanel); } registerPanel = new GridPanel(); registerPanel.addComponent(splitPane, Anchor.NORTHWEST, Fill.BOTH); } return registerPanel; } public Float getWeight() { return 0.0F; } public void syncView(Project project) { if (project != null && tabbedPane != null) { for (int i = 0; i < tabbedPane.getTabCount(); i++) { Component comp = tabbedPane.getComponentAt(i); if (comp instanceof AbstractPanel) { ((AbstractPanel) comp).syncView(project, project.getDriver(Output.wordml)); } } } } public void syncModel(Project project) { if (project != null && tabbedPane != null) { for (int i = 0; i < tabbedPane.getTabCount(); i++) { Component comp = tabbedPane.getComponentAt(i); if (comp instanceof AbstractPanel) { ((AbstractPanel) comp).syncModel(project,project.getDriver(Output.wordml)); } } } } public void onEnter() throws IOException { refresh(); } public void onLeave() { application.removeMenu(getId() + ".menu"); for (MediumService service : application.getMediumServiceList()) { application.removeToolBarButton(getId() + ".generate." + service.getId()); } } public void refresh() throws IOException { if (registerPanel == null) { getPanel(); } if (registerPanel != null && tabbedPane != null && isActive()) { for (MediumService service : application.getMediumServiceList("docbook-wordml")) { application.newGenerateAction(getConsole(), service, this); } } } public void reset() { } public boolean validate() { return true; } protected JSplitPane createBottomArea() { return null; } }
package flyingsaucer.demo; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; public class CommonUtils { public static String getAbsolutePathByClassLoader(String path) { URL url = ClassLoader.getSystemResource(path); URI uri; try { uri = url.toURI(); } catch (URISyntaxException ex) { ex.printStackTrace(); return null; } File file = new File(uri); String absolutePath = file.getAbsolutePath(); return absolutePath; } }
/* * 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.web.cors; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.springframework.http.HttpMethod; import org.springframework.lang.Nullable; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * A container for CORS configuration along with methods to check against the * actual origin, HTTP methods, and headers of a given request. * * <p>By default a newly created {@code CorsConfiguration} does not permit any * cross-origin requests and must be configured explicitly to indicate what * should be allowed. Use {@link #applyPermitDefaultValues()} to flip the * initialization model to start with open defaults that permit all cross-origin * requests for GET, HEAD, and POST requests. * * @author Sebastien Deleuze * @author Rossen Stoyanchev * @author Juergen Hoeller * @author Sam Brannen * @author Ruslan Akhundov * @since 4.2 * @see <a href="https://www.w3.org/TR/cors/">CORS spec</a> */ public class CorsConfiguration { /** Wildcard representing <em>all</em> origins, methods, or headers. */ public static final String ALL = "*"; private static final List<String> ALL_LIST = Collections.singletonList(ALL); private static final OriginPattern ALL_PATTERN = new OriginPattern("*"); private static final List<OriginPattern> ALL_PATTERN_LIST = Collections.singletonList(ALL_PATTERN); private static final List<String> DEFAULT_PERMIT_ALL = Collections.singletonList(ALL); private static final List<HttpMethod> DEFAULT_METHODS = List.of(HttpMethod.GET, HttpMethod.HEAD); private static final List<String> DEFAULT_PERMIT_METHODS = List.of(HttpMethod.GET.name(), HttpMethod.HEAD.name(), HttpMethod.POST.name()); @Nullable private List<String> allowedOrigins; @Nullable private List<OriginPattern> allowedOriginPatterns; @Nullable private List<String> allowedMethods; @Nullable private List<HttpMethod> resolvedMethods = DEFAULT_METHODS; @Nullable private List<String> allowedHeaders; @Nullable private List<String> exposedHeaders; @Nullable private Boolean allowCredentials; @Nullable private Long maxAge; /** * Construct a new {@code CorsConfiguration} instance with no cross-origin * requests allowed for any origin by default. * @see #applyPermitDefaultValues() */ public CorsConfiguration() { } /** * Construct a new {@code CorsConfiguration} instance by copying all * values from the supplied {@code CorsConfiguration}. */ public CorsConfiguration(CorsConfiguration other) { this.allowedOrigins = other.allowedOrigins; this.allowedOriginPatterns = other.allowedOriginPatterns; this.allowedMethods = other.allowedMethods; this.resolvedMethods = other.resolvedMethods; this.allowedHeaders = other.allowedHeaders; this.exposedHeaders = other.exposedHeaders; this.allowCredentials = other.allowCredentials; this.maxAge = other.maxAge; } /** * A list of origins for which cross-origin requests are allowed where each * value may be one of the following: * <ul> * <li>a specific domain, e.g. {@code "https://domain1.com"} * <li>comma-delimited list of specific domains, e.g. * {@code "https://a1.com,https://a2.com"}; this is convenient when a value * is resolved through a property placeholder, e.g. {@code "${origin}"}; * note that such placeholders must be resolved externally. * <li>the CORS defined special value {@code "*"} for all origins * </ul> * <p>For matched pre-flight and actual requests the * {@code Access-Control-Allow-Origin} response header is set either to the * matched domain value or to {@code "*"}. Keep in mind however that the * CORS spec does not allow {@code "*"} when {@link #setAllowCredentials * allowCredentials} is set to {@code true} and as of 5.3 that combination * is rejected in favor of using {@link #setAllowedOriginPatterns * allowedOriginPatterns} instead. * <p>By default this is not set which means that no origins are allowed. * However, an instance of this class is often initialized further, e.g. for * {@code @CrossOrigin}, via {@link #applyPermitDefaultValues()}. */ public void setAllowedOrigins(@Nullable List<String> origins) { if (origins == null) { this.allowedOrigins = null; } else { this.allowedOrigins = new ArrayList<>(origins.size()); for (String origin : origins) { addAllowedOrigin(origin); } } } private String trimTrailingSlash(String origin) { return (origin.endsWith("/") ? origin.substring(0, origin.length() - 1) : origin); } /** * Return the configured origins to allow, or {@code null} if none. */ @Nullable public List<String> getAllowedOrigins() { return this.allowedOrigins; } /** * Variant of {@link #setAllowedOrigins} for adding one origin at a time. */ public void addAllowedOrigin(@Nullable String origin) { if (origin == null) { return; } if (this.allowedOrigins == null) { this.allowedOrigins = new ArrayList<>(4); } else if (this.allowedOrigins == DEFAULT_PERMIT_ALL && CollectionUtils.isEmpty(this.allowedOriginPatterns)) { setAllowedOrigins(DEFAULT_PERMIT_ALL); } parseCommaDelimitedOrigin(origin, value -> { value = trimTrailingSlash(value); this.allowedOrigins.add(value); }); } /** * Alternative to {@link #setAllowedOrigins} that supports more flexible * origins patterns with "*" anywhere in the host name in addition to port * lists. Examples: * <ul> * <li>{@literal https://*.domain1.com} -- domains ending with domain1.com * <li>{@literal https://*.domain1.com:[8080,8081]} -- domains ending with * domain1.com on port 8080 or port 8081 * <li>{@literal https://*.domain1.com:[*]} -- domains ending with * domain1.com on any port, including the default port * <li>comma-delimited list of patters, e.g. * {@code "https://*.a1.com,https://*.a2.com"}; this is convenient when a * value is resolved through a property placeholder, e.g. {@code "${origin}"}; * note that such placeholders must be resolved externally. * </ul> * <p>In contrast to {@link #setAllowedOrigins(List) allowedOrigins} which * only supports "*" and cannot be used with {@code allowCredentials}, when * an allowedOriginPattern is matched, the {@code Access-Control-Allow-Origin} * response header is set to the matched origin and not to {@code "*"} nor * to the pattern. Therefore, allowedOriginPatterns can be used in combination * with {@link #setAllowCredentials} set to {@code true}. * <p>By default this is not set. * @since 5.3 */ public CorsConfiguration setAllowedOriginPatterns(@Nullable List<String> allowedOriginPatterns) { if (allowedOriginPatterns == null) { this.allowedOriginPatterns = null; } else { this.allowedOriginPatterns = new ArrayList<>(allowedOriginPatterns.size()); for (String patternValue : allowedOriginPatterns) { addAllowedOriginPattern(patternValue); } } return this; } /** * Return the configured origins patterns to allow, or {@code null} if none. * @since 5.3 */ @Nullable public List<String> getAllowedOriginPatterns() { if (this.allowedOriginPatterns == null) { return null; } return this.allowedOriginPatterns.stream() .map(OriginPattern::getDeclaredPattern) .toList(); } /** * Variant of {@link #setAllowedOriginPatterns} for adding one origin at a time. * @since 5.3 */ public void addAllowedOriginPattern(@Nullable String originPattern) { if (originPattern == null) { return; } if (this.allowedOriginPatterns == null) { this.allowedOriginPatterns = new ArrayList<>(4); } parseCommaDelimitedOrigin(originPattern, value -> { value = trimTrailingSlash(value); this.allowedOriginPatterns.add(new OriginPattern(value)); if (this.allowedOrigins == DEFAULT_PERMIT_ALL) { this.allowedOrigins = null; } }); } private static void parseCommaDelimitedOrigin(String rawValue, Consumer<String> valueConsumer) { if (rawValue.indexOf(',') == -1) { valueConsumer.accept(rawValue); return; } int start = 0; boolean withinPortRange = false; for (int current = 0; current < rawValue.length(); current++) { switch (rawValue.charAt(current)) { case '[' -> withinPortRange = true; case ']' -> withinPortRange = false; case ',' -> { if (!withinPortRange) { valueConsumer.accept(rawValue.substring(start, current).trim()); start = current + 1; } } } } if (start < rawValue.length()) { valueConsumer.accept(rawValue.substring(start)); } } /** * Set the HTTP methods to allow, e.g. {@code "GET"}, {@code "POST"}, * {@code "PUT"}, etc. * <p>The special value {@code "*"} allows all methods. * <p>If not set, only {@code "GET"} and {@code "HEAD"} are allowed. * <p>By default this is not set. * <p><strong>Note:</strong> CORS checks use values from "Forwarded" * (<a href="https://tools.ietf.org/html/rfc7239">RFC 7239</a>), * "X-Forwarded-Host", "X-Forwarded-Port", and "X-Forwarded-Proto" headers, * if present, in order to reflect the client-originated address. * Consider using the {@code ForwardedHeaderFilter} in order to choose from a * central place whether to extract and use, or to discard such headers. * See the Spring Framework reference for more on this filter. */ public void setAllowedMethods(@Nullable List<String> allowedMethods) { this.allowedMethods = (allowedMethods != null ? new ArrayList<>(allowedMethods) : null); if (!CollectionUtils.isEmpty(allowedMethods)) { this.resolvedMethods = new ArrayList<>(allowedMethods.size()); for (String method : allowedMethods) { if (ALL.equals(method)) { this.resolvedMethods = null; break; } this.resolvedMethods.add(HttpMethod.valueOf(method)); } } else { this.resolvedMethods = DEFAULT_METHODS; } } /** * Return the allowed HTTP methods, or {@code null} in which case * only {@code "GET"} and {@code "HEAD"} allowed. * @see #addAllowedMethod(HttpMethod) * @see #addAllowedMethod(String) * @see #setAllowedMethods(List) */ @Nullable public List<String> getAllowedMethods() { return this.allowedMethods; } /** * Add an HTTP method to allow. */ public void addAllowedMethod(HttpMethod method) { addAllowedMethod(method.name()); } /** * Add an HTTP method to allow. */ public void addAllowedMethod(String method) { if (StringUtils.hasText(method)) { if (this.allowedMethods == null) { this.allowedMethods = new ArrayList<>(4); this.resolvedMethods = new ArrayList<>(4); } else if (this.allowedMethods == DEFAULT_PERMIT_METHODS) { setAllowedMethods(DEFAULT_PERMIT_METHODS); } this.allowedMethods.add(method); if (ALL.equals(method)) { this.resolvedMethods = null; } else if (this.resolvedMethods != null) { this.resolvedMethods.add(HttpMethod.valueOf(method)); } } } /** * Set the list of headers that a pre-flight request can list as allowed * for use during an actual request. * <p>The special value {@code "*"} allows actual requests to send any * header. * <p>A header name is not required to be listed if it is one of: * {@code Cache-Control}, {@code Content-Language}, {@code Expires}, * {@code Last-Modified}, or {@code Pragma}. * <p>By default this is not set. */ public void setAllowedHeaders(@Nullable List<String> allowedHeaders) { this.allowedHeaders = (allowedHeaders != null ? new ArrayList<>(allowedHeaders) : null); } /** * Return the allowed actual request headers, or {@code null} if none. * @see #addAllowedHeader(String) * @see #setAllowedHeaders(List) */ @Nullable public List<String> getAllowedHeaders() { return this.allowedHeaders; } /** * Add an actual request header to allow. */ public void addAllowedHeader(String allowedHeader) { if (this.allowedHeaders == null) { this.allowedHeaders = new ArrayList<>(4); } else if (this.allowedHeaders == DEFAULT_PERMIT_ALL) { setAllowedHeaders(DEFAULT_PERMIT_ALL); } this.allowedHeaders.add(allowedHeader); } /** * Set the list of response headers other than simple headers (i.e. * {@code Cache-Control}, {@code Content-Language}, {@code Content-Type}, * {@code Expires}, {@code Last-Modified}, or {@code Pragma}) that an * actual response might have and can be exposed. * <p>The special value {@code "*"} allows all headers to be exposed for * non-credentialed requests. * <p>By default this is not set. */ public void setExposedHeaders(@Nullable List<String> exposedHeaders) { this.exposedHeaders = (exposedHeaders != null ? new ArrayList<>(exposedHeaders) : null); } /** * Return the configured response headers to expose, or {@code null} if none. * @see #addExposedHeader(String) * @see #setExposedHeaders(List) */ @Nullable public List<String> getExposedHeaders() { return this.exposedHeaders; } /** * Add a response header to expose. * <p>The special value {@code "*"} allows all headers to be exposed for * non-credentialed requests. */ public void addExposedHeader(String exposedHeader) { if (this.exposedHeaders == null) { this.exposedHeaders = new ArrayList<>(4); } this.exposedHeaders.add(exposedHeader); } /** * Whether user credentials are supported. * <p>By default this is not set (i.e. user credentials are not supported). */ public void setAllowCredentials(@Nullable Boolean allowCredentials) { this.allowCredentials = allowCredentials; } /** * Return the configured {@code allowCredentials} flag, or {@code null} if none. * @see #setAllowCredentials(Boolean) */ @Nullable public Boolean getAllowCredentials() { return this.allowCredentials; } /** * Configure how long, as a duration, the response from a pre-flight request * can be cached by clients. * @since 5.2 * @see #setMaxAge(Long) */ public void setMaxAge(Duration maxAge) { this.maxAge = maxAge.getSeconds(); } /** * Configure how long, in seconds, the response from a pre-flight request * can be cached by clients. * <p>By default this is not set. */ public void setMaxAge(@Nullable Long maxAge) { this.maxAge = maxAge; } /** * Return the configured {@code maxAge} value, or {@code null} if none. * @see #setMaxAge(Long) */ @Nullable public Long getMaxAge() { return this.maxAge; } /** * By default {@code CorsConfiguration} does not permit any cross-origin * requests and must be configured explicitly. Use this method to switch to * defaults that permit all cross-origin requests for GET, HEAD, and POST, * but not overriding any values that have already been set. * <p>The following defaults are applied for values that are not set: * <ul> * <li>Allow all origins with the special value {@code "*"} defined in the * CORS spec. This is set only if neither {@link #setAllowedOrigins origins} * nor {@link #setAllowedOriginPatterns originPatterns} are already set.</li> * <li>Allow "simple" methods {@code GET}, {@code HEAD} and {@code POST}.</li> * <li>Allow all headers.</li> * <li>Set max age to 1800 seconds (30 minutes).</li> * </ul> */ public CorsConfiguration applyPermitDefaultValues() { if (this.allowedOrigins == null && this.allowedOriginPatterns == null) { this.allowedOrigins = DEFAULT_PERMIT_ALL; } if (this.allowedMethods == null) { this.allowedMethods = DEFAULT_PERMIT_METHODS; this.resolvedMethods = DEFAULT_PERMIT_METHODS .stream().map(HttpMethod::valueOf).toList(); } if (this.allowedHeaders == null) { this.allowedHeaders = DEFAULT_PERMIT_ALL; } if (this.maxAge == null) { this.maxAge = 1800L; } return this; } /** * Validate that when {@link #setAllowCredentials allowCredentials} is {@code true}, * {@link #setAllowedOrigins allowedOrigins} does not contain the special * value {@code "*"} since in that case the "Access-Control-Allow-Origin" * cannot be set to {@code "*"}. * @throws IllegalArgumentException if the validation fails * @since 5.3 */ public void validateAllowCredentials() { if (this.allowCredentials == Boolean.TRUE && this.allowedOrigins != null && this.allowedOrigins.contains(ALL)) { throw new IllegalArgumentException( "When allowCredentials is true, allowedOrigins cannot contain the special value \"*\" " + "since that cannot be set on the \"Access-Control-Allow-Origin\" response header. " + "To allow credentials to a set of origins, list them explicitly " + "or consider using \"allowedOriginPatterns\" instead."); } } /** * Combine the non-null properties of the supplied * {@code CorsConfiguration} with this one. * <p>When combining single values like {@code allowCredentials} or * {@code maxAge}, {@code this} properties are overridden by non-null * {@code other} properties if any. * <p>Combining lists like {@code allowedOrigins}, {@code allowedMethods}, * {@code allowedHeaders} or {@code exposedHeaders} is done in an additive * way. For example, combining {@code ["GET", "POST"]} with * {@code ["PATCH"]} results in {@code ["GET", "POST", "PATCH"]}. However, * combining {@code ["GET", "POST"]} with {@code ["*"]} results in * {@code ["*"]}. Note also that default permit values set by * {@link CorsConfiguration#applyPermitDefaultValues()} are overridden by * any explicitly defined values. * @return the combined {@code CorsConfiguration}, or {@code this} * configuration if the supplied configuration is {@code null} */ public CorsConfiguration combine(@Nullable CorsConfiguration other) { if (other == null) { return this; } // Bypass setAllowedOrigins to avoid re-compiling patterns CorsConfiguration config = new CorsConfiguration(this); List<String> origins = combine(getAllowedOrigins(), other.getAllowedOrigins()); List<OriginPattern> patterns = combinePatterns(this.allowedOriginPatterns, other.allowedOriginPatterns); config.allowedOrigins = (origins == DEFAULT_PERMIT_ALL && !CollectionUtils.isEmpty(patterns) ? null : origins); config.allowedOriginPatterns = patterns; config.setAllowedMethods(combine(getAllowedMethods(), other.getAllowedMethods())); config.setAllowedHeaders(combine(getAllowedHeaders(), other.getAllowedHeaders())); config.setExposedHeaders(combine(getExposedHeaders(), other.getExposedHeaders())); Boolean allowCredentials = other.getAllowCredentials(); if (allowCredentials != null) { config.setAllowCredentials(allowCredentials); } Long maxAge = other.getMaxAge(); if (maxAge != null) { config.setMaxAge(maxAge); } return config; } private List<String> combine(@Nullable List<String> source, @Nullable List<String> other) { if (other == null) { return (source != null ? source : Collections.emptyList()); } if (source == null) { return other; } if (source == DEFAULT_PERMIT_ALL || source == DEFAULT_PERMIT_METHODS) { return other; } if (other == DEFAULT_PERMIT_ALL || other == DEFAULT_PERMIT_METHODS) { return source; } if (source.contains(ALL) || other.contains(ALL)) { return ALL_LIST; } Set<String> combined = new LinkedHashSet<>(source.size() + other.size()); combined.addAll(source); combined.addAll(other); return new ArrayList<>(combined); } private List<OriginPattern> combinePatterns( @Nullable List<OriginPattern> source, @Nullable List<OriginPattern> other) { if (other == null) { return (source != null ? source : Collections.emptyList()); } if (source == null) { return other; } if (source.contains(ALL_PATTERN) || other.contains(ALL_PATTERN)) { return ALL_PATTERN_LIST; } Set<OriginPattern> combined = new LinkedHashSet<>(source.size() + other.size()); combined.addAll(source); combined.addAll(other); return new ArrayList<>(combined); } /** * Check the origin of the request against the configured allowed origins. * @param origin the origin to check * @return the origin to use for the response, or {@code null} which * means the request origin is not allowed */ @Nullable public String checkOrigin(@Nullable String origin) { if (!StringUtils.hasText(origin)) { return null; } String originToCheck = trimTrailingSlash(origin); if (!ObjectUtils.isEmpty(this.allowedOrigins)) { if (this.allowedOrigins.contains(ALL)) { validateAllowCredentials(); return ALL; } for (String allowedOrigin : this.allowedOrigins) { if (originToCheck.equalsIgnoreCase(allowedOrigin)) { return origin; } } } if (!ObjectUtils.isEmpty(this.allowedOriginPatterns)) { for (OriginPattern p : this.allowedOriginPatterns) { if (p.getDeclaredPattern().equals(ALL) || p.getPattern().matcher(originToCheck).matches()) { return origin; } } } return null; } /** * Check the HTTP request method (or the method from the * {@code Access-Control-Request-Method} header on a pre-flight request) * against the configured allowed methods. * @param requestMethod the HTTP request method to check * @return the list of HTTP methods to list in the response of a pre-flight * request, or {@code null} if the supplied {@code requestMethod} is not allowed */ @Nullable public List<HttpMethod> checkHttpMethod(@Nullable HttpMethod requestMethod) { if (requestMethod == null) { return null; } if (this.resolvedMethods == null) { return Collections.singletonList(requestMethod); } return (this.resolvedMethods.contains(requestMethod) ? this.resolvedMethods : null); } /** * Check the supplied request headers (or the headers listed in the * {@code Access-Control-Request-Headers} of a pre-flight request) against * the configured allowed headers. * @param requestHeaders the request headers to check * @return the list of allowed headers to list in the response of a pre-flight * request, or {@code null} if none of the supplied request headers is allowed */ @Nullable public List<String> checkHeaders(@Nullable List<String> requestHeaders) { if (requestHeaders == null) { return null; } if (requestHeaders.isEmpty()) { return Collections.emptyList(); } if (ObjectUtils.isEmpty(this.allowedHeaders)) { return null; } boolean allowAnyHeader = this.allowedHeaders.contains(ALL); int maxResultSize = allowAnyHeader ? requestHeaders.size() : Math.min(requestHeaders.size(), this.allowedHeaders.size()); List<String> result = new ArrayList<>(maxResultSize); for (String requestHeader : requestHeaders) { if (StringUtils.hasText(requestHeader)) { requestHeader = requestHeader.trim(); if (allowAnyHeader) { result.add(requestHeader); } else { for (String allowedHeader : this.allowedHeaders) { if (requestHeader.equalsIgnoreCase(allowedHeader)) { result.add(requestHeader); break; } } } } } return (result.isEmpty() ? null : result); } /** * Contains both the user-declared pattern (e.g. "https://*.domain.com") and * the regex {@link Pattern} derived from it. */ private static class OriginPattern { private static final Pattern PORTS_PATTERN = Pattern.compile("(.*):\\[(\\*|\\d+(,\\d+)*)]"); private final String declaredPattern; private final Pattern pattern; OriginPattern(String declaredPattern) { this.declaredPattern = declaredPattern; this.pattern = initPattern(declaredPattern); } private static Pattern initPattern(String patternValue) { String portList = null; Matcher matcher = PORTS_PATTERN.matcher(patternValue); if (matcher.matches()) { patternValue = matcher.group(1); portList = matcher.group(2); } patternValue = "\\Q" + patternValue + "\\E"; patternValue = patternValue.replace("*", "\\E.*\\Q"); if (portList != null) { patternValue += (portList.equals(ALL) ? "(:\\d+)?" : ":(" + portList.replace(',', '|') + ")"); } return Pattern.compile(patternValue); } public String getDeclaredPattern() { return this.declaredPattern; } public Pattern getPattern() { return this.pattern; } @Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } if (other == null || !getClass().equals(other.getClass())) { return false; } return ObjectUtils.nullSafeEquals( this.declaredPattern, ((OriginPattern) other).declaredPattern); } @Override public int hashCode() { return this.declaredPattern.hashCode(); } @Override public String toString() { return this.declaredPattern; } } }
package com.citibank.ods.modules.client.customerprvt.form; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.form.BaseForm; import com.citibank.ods.common.util.ODSValidator; import com.citibank.ods.entity.pl.BaseTplCustomerPrvtEntity; import com.citibank.ods.modules.client.customerprvt.functionality.valueobject.BaseCustomerPrvtListFncVO; import com.citibank.ods.modules.client.customerprvtcmpl.form.CustomerPrvtCmplDetailable; import com.citibank.ods.modules.client.officer.form.OfficerSearchable; // //©2002-2007 Accenture. All rights reserved. // /** * @see package com.citibank.ods.modules.client.customerPrvt.form; * @version 1.0 * @author l.braga,14/03/2007 */ public class BaseCustomerPrvtListForm extends BaseForm implements CustomerPrvtDetailable, CustomerSearchable, OfficerSearchable, CustomerPrvtCmplDetailable { // Variável de controle de habilitação de botões de dados complementares private String cmplDataButtonControl; // Numero do Cliente private String m_custNbrSrc = ""; // Nome do cliente private String m_custFullNameTextSrc = ""; //Nome do Co-Titular private String m_custFullName2TextSrc = ""; //Nome do Co-Titular 2 private String m_custFullName3TextSrc = ""; //Nome do Co-Titular 3 private String m_custFullName4TextSrc = ""; // CFF ou CNPJ do cliente private String m_custCpfCnpjNbrSrc = ""; // Numero da conta corrente private String m_curAcctNbrSrc = ""; // Numero da conta Investimento private String m_invstCurAcctNbrSrc = ""; // numero do relacionamento private String m_reltnNbrSrc = ""; private String m_SelectedReltnNbr = ""; // DataSet como os resultados do banco. private DataSet m_results; private String m_SelectedCustNbr = ""; // Variáveis de Dados complementares de Cliente: private String m_clickedSearch; private String m_emNbrSrc; private String m_custTextSrc; private String m_prvtCustNbrSrc; private String m_prvtKeyNbrSrc; private String m_wealthPotnlCodeSrc; private String m_offcrNbrSrc; private String m_classCmplcCodeSrc; private String m_prvtCustTypeCodeSrc; private String m_offcrTextSrc; private String m_glbRevenSysOffcrNbrSrc; private DataSet m_wealthPotnlCodeDomain; private DataSet m_classCmplcCodeDomain; private DataSet m_prvtCustTypeCodeDomain; private String m_selectedEmNbr; //Status do cliente private String m_custPrvtStatCodeSrc = ""; //Status do cliente - Combo (Dataset) private DataSet m_custPrvtStatCodeDomain = null; //Lista de Customers private ArrayList m_custList = null; /** * @return Returns acctNbrSrc. */ public String getCurAcctNbrSrc() { return m_curAcctNbrSrc; } /** * @param acctNbrSrc_ Field acctNbrSrc to be setted. */ public void setCurAcctNbrSrc( String curAcctNbrSrc_ ) { m_curAcctNbrSrc = curAcctNbrSrc_; } /** * @return Returns reltnNbrSrc. */ public String getReltnNbrSrc() { return m_reltnNbrSrc; } /** * @param reltnNbrSrc_ Field reltnNbrSrc to be setted. */ public void setReltnNbrSrc( String reltnNbrSrc_ ) { m_reltnNbrSrc = reltnNbrSrc_; } /** * @return Returns custCpfCnpjNbrSrc. */ public String getCustCpfCnpjNbrSrc() { return m_custCpfCnpjNbrSrc; } /** * @param custCpfCnpjNbrSrc_ Field custCpfCnpjNbrSrc to be setted. */ public void setCustCpfCnpjNbrSrc( String custCpfCnpjNbrSrc_ ) { m_custCpfCnpjNbrSrc = removeMask( custCpfCnpjNbrSrc_ ); } /** * @return Returns custFullNameTextSrc. */ public String getCustFullNameTextSrc() { return m_custFullNameTextSrc; } /** * @param custFullNameTextSrc_ Field custFullNameTextSrc to be setted. */ public void setCustFullNameTextSrc( String custFullNameTextSrc_ ) { m_custFullNameTextSrc = custFullNameTextSrc_; } /** * @return Returns custNbrSrc. */ /** * @return Returns results. */ public DataSet getResults() { return m_results; } /** * @param results_ Field results to be setted. */ public void setResults( DataSet results_ ) { m_results = results_; } /** * @return Returns selectedCustomerPrvt. */ /** * @return Returns selectedCustNbr. */ public String getSelectedCustNbr() { return m_SelectedCustNbr; } /** * @param selectedCustNbr_ Field selectedCustNbr to be setted. */ public void setSelectedCustNbr( String selectedCustNbr_ ) { setCustNbrSrc( selectedCustNbr_ ); } public String getSelectedCustNbrList() { return m_SelectedCustNbr; } /** * @param selectedCustNbr_ Field selectedCustNbr to be setted. */ public void setSelectedCustNbrList( String selectedCustNbr_ ) { setCustNbrSrc( selectedCustNbr_ ); } /* * Realiza as validações de tipos e tamanhos */ /* * Realiza as validações de tipos e tamanhos */ public ActionErrors validate( ActionMapping actionMapping_, HttpServletRequest request_ ) { ActionErrors errors = new ActionErrors(); ODSValidator.validateBigInteger( BaseCustomerPrvtListFncVO.C_CUST_NBR_DESCRIPTION, m_custNbrSrc, BaseTplCustomerPrvtEntity.C_CUST_NBR_SIZE, errors ); ODSValidator.validateMaxLength( BaseCustomerPrvtListFncVO.C_CUST_FULL_NAME_TEXT_DESCRIPTION, m_custFullNameTextSrc, BaseTplCustomerPrvtEntity.C_CUST_FULL_NAME_TEXT_SIZE, errors ); ODSValidator.validateBigInteger( BaseCustomerPrvtListFncVO.C_CUST_CPF_CNPJ_NBR_DESCRIPTION, m_custCpfCnpjNbrSrc, BaseTplCustomerPrvtEntity.C_CUST_CPF_CNPJ_NBR_SIZE, errors ); ODSValidator.validateBigInteger( BaseCustomerPrvtListFncVO.C_CUR_ACCT_NBR_DESCRIPTION, m_curAcctNbrSrc, BaseTplCustomerPrvtEntity.C_CUR_ACCT_NBR_SIZE, errors ); ODSValidator.validateBigInteger( BaseCustomerPrvtListFncVO.C_RELTN_NBR_DESCRIPTION, m_reltnNbrSrc, BaseTplCustomerPrvtEntity.C_RELTN_NBR_SIZE, errors ); return errors; } /** * @return Returns custNbrSearch. */ public String getCustNbrSrc() { return m_custNbrSrc; } /** * @param custNbrSearch_ Field custNbrSearch to be setted. */ public void setCustNbrSrc( String custNbrSrc_ ) { m_custNbrSrc = custNbrSrc_; } // Getters e Setters de Dados complementares de Cliente: //Alteraçao GPTI /** * @return Returns PrvtCustTypeCodeSrc. */ public String getPrvtCustTypeCodeSrc() { return m_prvtCustTypeCodeSrc; } /** * @param PrvtCustTypeCodeSrc_ Field PrvtCustTypeCodeSrc to be setted. */ public void setPrvtCustTypeCodeSrc( String prvtCustTypeCodeSrc_ ) { m_prvtCustTypeCodeSrc = prvtCustTypeCodeSrc_; } /** * @return Returns prvtCustTypeCodeDomain. */ public DataSet getPrvtCustTypeCodeDomain() { return m_prvtCustTypeCodeDomain; } /** * @param prvtCustTypeCodeDomain_ Field prvtCustTypeCodeDomain to be setted. */ public void setPrvtCustTypeCodeDomain( DataSet prvtCustTypeCodeDomain_ ) { m_prvtCustTypeCodeDomain = prvtCustTypeCodeDomain_; } //Fim Alteração GPTI /** * @return Returns classCmplcCodeDomain. */ public DataSet getClassCmplcCodeDomain() { return m_classCmplcCodeDomain; } /** * @param classCmplcCodeDomain_ Field classCmplcCodeDomain to be setted. */ public void setClassCmplcCodeDomain( DataSet classCmplcCodeDomain_ ) { m_classCmplcCodeDomain = classCmplcCodeDomain_; } /** * @return Returns classCmplcCodeSrc. */ public String getClassCmplcCodeSrc() { return m_classCmplcCodeSrc; } /** * @param classCmplcCodeSrc_ Field classCmplcCodeSrc to be setted. */ public void setClassCmplcCodeSrc( String classCmplcCodeSrc_ ) { m_classCmplcCodeSrc = classCmplcCodeSrc_; } /** * @return Returns clickedSearch. */ public String getClickedSearch() { return m_clickedSearch; } /** * @param clickedSearch_ Field clickedSearch to be setted. */ public void setClickedSearch( String clickedSearch_ ) { m_clickedSearch = clickedSearch_; } /** * @return Returns custTextSrc. */ public String getCustTextSrc() { return m_custTextSrc; } /** * @param custTextSrc_ Field custTextSrc to be setted. */ public void setCustTextSrc( String custTextSrc_ ) { m_custTextSrc = custTextSrc_; } /** * @return Returns emNbrSrc. */ public String getEmNbrSrc() { return m_emNbrSrc; } /** * @param emNbrSrc_ Field emNbrSrc to be setted. */ public void setEmNbrSrc( String emNbrSrc_ ) { m_emNbrSrc = emNbrSrc_; } /** * @return Returns glbRevenSysOffcrNbrSrc. */ public String getGlbRevenSysOffcrNbrSrc() { return m_glbRevenSysOffcrNbrSrc; } /** * @param glbRevenSysOffcrNbrSrc_ Field glbRevenSysOffcrNbrSrc to be setted. */ public void setGlbRevenSysOffcrNbrSrc( String glbRevenSysOffcrNbrSrc_ ) { m_glbRevenSysOffcrNbrSrc = glbRevenSysOffcrNbrSrc_; } /** * @return Returns offcrNbrSrc. */ public String getOffcrNbrSrc() { return m_offcrNbrSrc; } /** * @param offcrNbrSrc_ Field offcrNbrSrc to be setted. */ public void setOffcrNbrSrc( String offcrNbrSrc_ ) { m_offcrNbrSrc = offcrNbrSrc_; } /** * @return Returns offcrTextSrc. */ public String getOffcrTextSrc() { return m_offcrTextSrc; } /** * @param offcrTextSrc_ Field offcrTextSrc to be setted. */ public void setOffcrTextSrc( String offcrTextSrc_ ) { m_offcrTextSrc = offcrTextSrc_; } /** * @return Returns prvtCustNbrSrc. */ public String getPrvtCustNbrSrc() { return m_prvtCustNbrSrc; } /** * @param prvtCustNbrSrc_ Field prvtCustNbrSrc to be setted. */ public void setPrvtCustNbrSrc( String prvtCustNbrSrc_ ) { m_prvtCustNbrSrc = prvtCustNbrSrc_; } /** * @return Returns prvtKeyNbrSrc. */ public String getPrvtKeyNbrSrc() { return m_prvtKeyNbrSrc; } /** * @param prvtKeyNbrSrc_ Field prvtKeyNbrSrc to be setted. */ public void setPrvtKeyNbrSrc( String prvtKeyNbrSrc_ ) { m_prvtKeyNbrSrc = prvtKeyNbrSrc_; } /** * @return Returns selectedEmNbr. */ public String getSelectedEmNbr() { return m_selectedEmNbr; } /** * @param selectedEmNbr_ Field selectedEmNbr to be setted. */ public void setSelectedEmNbr( String selectedEmNbr_ ) { m_selectedEmNbr = selectedEmNbr_; } /** * @return Returns wealthPotnlCodeDomain. */ public DataSet getWealthPotnlCodeDomain() { return m_wealthPotnlCodeDomain; } /** * @param wealthPotnlCodeDomain_ Field wealthPotnlCodeDomain to be setted. */ public void setWealthPotnlCodeDomain( DataSet wealthPotnlCodeDomain_ ) { m_wealthPotnlCodeDomain = wealthPotnlCodeDomain_; } /** * @return Returns wealthPotnlCodeSrc. */ public String getWealthPotnlCodeSrc() { return m_wealthPotnlCodeSrc; } /** * @param wealthPotnlCodeSrc_ Field wealthPotnlCodeSrc to be setted. */ public void setWealthPotnlCodeSrc( String wealthPotnlCodeSrc_ ) { m_wealthPotnlCodeSrc = wealthPotnlCodeSrc_; } /* * (non-Javadoc) * @see com.citibank.ods.modules.client.officer.form.OfficerSearcheable#getSelectedOffcrNbr() */ public String getSelectedOffcrNbr() { return null; } /* * (non-Javadoc) * @see com.citibank.ods.modules.client.officer.form.OfficerSearcheable#setSelectedOffcrNbr(java.lang.String) */ public void setSelectedOffcrNbr( String selectedOffcrNbr_ ) { this.setOffcrNbrSrc( selectedOffcrNbr_ ); } /** * @return Returns cmplDataButtonControl. */ public String getCmplDataButtonControl() { return cmplDataButtonControl; } /** * @param cmplDataButtonControl_ Field cmplDataButtonControl to be setted. */ public void setCmplDataButtonControl( String cmplDataButtonControl_ ) { cmplDataButtonControl = cmplDataButtonControl_; } /** * @return Returns custPrvtStatCodeDomain. */ public DataSet getCustPrvtStatCodeDomain() { return m_custPrvtStatCodeDomain; } /** * @param custPrvtStatCodeDomain_ Field custPrvtStatCodeDomain to be setted. */ public void setCustPrvtStatCodeDomain( DataSet custPrvtStatCodeDomain_ ) { m_custPrvtStatCodeDomain = custPrvtStatCodeDomain_; } /** * @return Returns custPrvtStatCodeSrc. */ public String getCustPrvtStatCodeSrc() { return m_custPrvtStatCodeSrc; } /** * @param custPrvtStatCodeSrc_ Field custPrvtStatCodeSrc to be setted. */ public void setCustPrvtStatCodeSrc( String custPrvtStatCodeSrc_ ) { m_custPrvtStatCodeSrc = custPrvtStatCodeSrc_; } //INICIO======================Alteraçao G&P //Tag para indicar se o cliente mudou e consequentemente limpar a tela private boolean clrScreen; /** * @return clrScreen */ public boolean getClrScreen() { return clrScreen; } /** * @param clrScreenParm */ public void setClrScreen(boolean clrScreenParm) { clrScreen = clrScreenParm; } //FIM=========================Alteraçao G&P /** * @return */ public ArrayList getCustList() { return m_custList; } /** * @param list */ public void setCustList(ArrayList m_custList_) { m_custList = m_custList_; } /** * @return */ public String getCustFullName2TextSrc() { return m_custFullName2TextSrc; } /** * @return */ public String getCustFullName3TextSrc() { return m_custFullName3TextSrc; } /** * @return */ public String getCustFullName4TextSrc() { return m_custFullName4TextSrc; } /** * @param string */ public void setCustFullName2TextSrc(String custFullName2TextSrc_) { m_custFullName2TextSrc = custFullName2TextSrc_; } /** * @param string */ public void setCustFullName3TextSrc(String custFullName3TextSrc_) { m_custFullName3TextSrc = custFullName3TextSrc_; } /** * @param string */ public void setCustFullName4TextSrc(String custFullName4TextSrc_) { m_custFullName4TextSrc = custFullName4TextSrc_; } /* (non-Javadoc) * @see com.citibank.ods.modules.client.customerprvt.form.CustomerSearchable#getReltnNbr() */ public String getReltnNbr() { return m_SelectedReltnNbr; } /* (non-Javadoc) * @see com.citibank.ods.modules.client.customerprvt.form.CustomerSearchable#setReltnNbr(java.lang.String) */ public void setReltnNbr(String reltnNbr_) { m_SelectedReltnNbr = reltnNbr_; } /** * @return */ public String getInvstCurAcctNbrSrc() { return m_invstCurAcctNbrSrc; } /** * @param string */ public void setInvstCurAcctNbrSrc(String invstCurAcctNbrSrc_) { m_invstCurAcctNbrSrc = invstCurAcctNbrSrc_; } }
package com.soa.dao; import com.soa.domain.Film; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.dao.BasicDAO; public class FilmDao extends BasicDAO<Film, Long> { public FilmDao(Datastore ds) { super(ds); } }
package com.gs.tablasco.spark; import com.gs.tablasco.VerifiableTable; import com.gs.tablasco.adapters.TableAdapters; import com.gs.tablasco.verify.*; import com.gs.tablasco.verify.indexmap.IndexMapTableVerifier; import org.apache.spark.api.java.Optional; import org.apache.spark.api.java.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; public class VerifyGroupFunction implements Function<Tuple2<Integer, Tuple2<Optional<Iterable<List<Object>>>, Optional<Iterable<List<Object>>>>>, SummaryResultTable> { private static final Logger LOGGER = LoggerFactory.getLogger(VerifyGroupFunction.class); private final Set<String> groupKeyColumns; private final List<String> actualColumns; private final List<String> expectedColumns; private final boolean ignoreSurplusColumns; private final ColumnComparators columnComparators; private final Set<String> columnsToIgnore; VerifyGroupFunction(Set<String> groupKeyColumns, List<String> actualColumns, List<String> expectedHeaders, boolean ignoreSurplusColumns, ColumnComparators columnComparators, Set<String> columnsToIgnore) { this.groupKeyColumns = groupKeyColumns; this.actualColumns = actualColumns; this.expectedColumns = expectedHeaders; this.ignoreSurplusColumns = ignoreSurplusColumns; this.columnComparators = columnComparators; this.columnsToIgnore = columnsToIgnore; } @Override public SummaryResultTable call(Tuple2<Integer, Tuple2<Optional<Iterable<List<Object>>>, Optional<Iterable<List<Object>>>>> v1) { Integer shardNumber = v1._1(); Optional<Iterable<List<Object>>> actualOptional = v1._2()._1(); Optional<Iterable<List<Object>>> expectedOptional = v1._2()._2(); Iterable<List<Object>> actualRows = actualOptional.isPresent() ? actualOptional.get() : Collections.emptyList(); Iterable<List<Object>> expectedRows = expectedOptional.isPresent() ? expectedOptional.get() : Collections.emptyList(); VerifiableTable actualTable = getVerifiableTable(actualRows, this.actualColumns); VerifiableTable expectedTable = getVerifiableTable(expectedRows, this.expectedColumns); IndexMapTableVerifier singleSingleTableVerifier = new IndexMapTableVerifier( this.columnComparators, false, IndexMapTableVerifier.DEFAULT_BEST_MATCH_THRESHOLD, false, false, this.ignoreSurplusColumns, false, 0); ResultTable resultTable = singleSingleTableVerifier.verify(actualTable, expectedTable); LOGGER.info("Verification of shard {} {}", shardNumber, resultTable.isSuccess() ? "PASSED" : "FAILED"); return new SummaryResultTable(resultTable); } private VerifiableTable getVerifiableTable(Iterable<List<Object>> data, List<String> headers) { List<List<Object>> dataList = new ArrayList<>(); data.forEach(dataList::add); VerifiableTable verifiableTable = new ListVerifiableTable(headers, dataList); if (this.columnsToIgnore != null) { verifiableTable = TableAdapters.withColumns(verifiableTable, (col) -> !VerifyGroupFunction.this.columnsToIgnore.contains(col)); } return this.groupKeyColumns.isEmpty() ? verifiableTable : new GroupKeyedVerifiableTable(verifiableTable, this.groupKeyColumns); } private static class GroupKeyedVerifiableTable extends DefaultVerifiableTableAdapter implements KeyedVerifiableTable { private final Set<String> groupKeyColumns; GroupKeyedVerifiableTable(VerifiableTable delegate, Set<String> groupKeyColumns) { super(delegate); this.groupKeyColumns = groupKeyColumns; } @Override public boolean isKeyColumn(int columnIndex) { return columnIndex >= 0 && this.groupKeyColumns.contains(this.getColumnName(columnIndex)); } } }
package pdp.uz.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import pdp.uz.entity.USSDCodes; import java.util.List; import java.util.Optional; @Repository public interface USSDRepo extends JpaRepository<USSDCodes, Long> { Optional<USSDCodes> findByCodeAndActiveTrue(String code); boolean existsByCode(String code); List<USSDCodes> findAllByActiveTrue(); boolean existsByCodeAndIdNot(String code, Long id); Optional<USSDCodes> findByIdAndActiveTrue(Long id); }
package ch.mitti.methoden_polymorphie; public class Operation { protected double result; protected double term1; protected double term2; public Operation(){ } public double getResult(){ return result; } public void setTerm1(double term){ this.term1 = term; } public void setTerm2(double term){ this.term2 = term; } public void doOperation(){ } }
package com.example.forcatapp.Main; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.example.forcatapp.R; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; /* Activity안에 Fragment로 화면을 그린 경우에는 View view = getView(); createQR = view.findViewById(R.id.createQR); 액티비티내에 부분페이지로 프래그먼트를 사용했을때 프래그먼트에서 액티비티의 버튼이나 콤포넌트를 접근할 때 사용할것. */ public class QRFragment extends Fragment { private Button scanQR = null; String qrContent = null;//네이티브앱 WebView wv_content = null;//네이티브앱-그안에 보여지는 콘텐츠는 웹앱이다. private static final String TAG = "QRFragment"; public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_qr, container, false); scanQR = view.findViewById(R.id.scanQR); scanQR.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator.forSupportFragment(QRFragment.this) .setDesiredBarcodeFormats(IntentIntegrator.QR_CODE) .setOrientationLocked(true) .setBeepEnabled(false) .setPrompt("QR코드에 맞추세요") .initiateScan(); } }); return view; }//onCreateView @Override public void onActivityResult(int requestCode, int resultCode, Intent data){ IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode,data); Log.d(TAG, "onActivityResult: result " + result); if(result !=null){ if(result.getContents() == null){//스캔한 결과가 없을 때 Toast.makeText(getActivity(),"결과가 없습니다", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(getActivity()," 스캔 성공! "+result.getContents(), Toast.LENGTH_LONG).show(); qrContent = result.getContents(); wv_content = getView().findViewById(R.id.wv_qr); WebSettings webSettings = wv_content.getSettings(); //자바스크립트를 사용할 수 있도록 설정하기 webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(true);//확대와 축소 webSettings.setBuiltInZoomControls(true);//안드로이드에서 제공되는 줌 아이콘설정 webSettings.setLoadsImagesAutomatically(true);//웹뷰가 앱에 등록된 이미지 리소스 인식 // 화면 비율 webSettings.setUseWideViewPort(true); // wide viewport를 사용하도록 설정 webSettings.setLoadWithOverviewMode(true); // 컨텐츠가 웹뷰보다 클 경우 스크린 크기에 맞게 조정 webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//웹뷰가 캐쉬를 사용하지 않도록 설정 wv_content.setWebViewClient(new WebViewClient()); wv_content.setWebChromeClient(new WebChromeClient()); wv_content.loadUrl(qrContent); } }else{ super.onActivityResult(requestCode,resultCode,data); } } }
package cn.fungo.service; import java.util.List; import java.util.Map; import cn.fungo.domain.W12WorkFlowSet; public interface WorkFlowService { /** * 查询 * @param map * @return */ public List<W12WorkFlowSet> findAllWorkFlow(Map<String,String> map); /** * 新增 * @param workflow * @return */ public int addWorkFlow(W12WorkFlowSet workflow); public int findMaxId(String type); /** * 删除 * @param id * @return */ public int removeWorkFlow(Integer id); public int editWorkFlow(W12WorkFlowSet workflow); }
package org.scoalaonline.api.service; import org.scoalaonline.api.model.Department; import org.scoalaonline.api.repo.DepartmentRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; @Service public class DepartmentService { @Autowired DepartmentRepo departmentRepo; /** * Getter for all departments * @return all department entities */ public List<Department> getAllDepartments () { return departmentRepo.findAll(); } /** * Getter for departments by id * @param id the id of the selected department * @return the department selected */ public Optional<Department> getDepartmentById ( long id ) { return departmentRepo.findById( id ); } /** * Deletes a department * @param id the id of the department to be deleted */ public void deleteDepartment ( long id ) { departmentRepo.deleteById( id ); } /** * Adds a department entity * @param department the department to be added * @return the new configuration with the department added */ public Department addDepartment ( Department department ) { Department departmentToAdd = new Department(); departmentToAdd.setDepartmentName( department.getDepartmentName() ); departmentToAdd.setSupervisor( department.getSupervisor() ); return departmentRepo.save( departmentToAdd ); } /** * Updates a department * @param id the id of the department to be changed * @param department the configuration of the new department * @return the configuration with the department changed */ public Department updateDepartment (long id, Department department ) { try { Department departmentToUpdate = departmentRepo.findById(id).get(); if (department.getDepartmentName() != null) { departmentToUpdate.setDepartmentName(department.getDepartmentName()); } if (department.getSupervisor() != null) { departmentToUpdate.setSupervisor(department.getSupervisor()); } return departmentRepo.save(departmentToUpdate); } catch (NoSuchElementException e) { System.out.println("The department to update doesn't exist"); return null; } } /** * Checks if a department exists * @param id the id of the department to be checked * @return if the department exists */ public boolean departmentExists( long id ) { return departmentRepo.existsById( id ); } }
package pl.coderslab.dice; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { System.out.println("The result is: " + dice(parseInfo())); } /** * store input value */ private static String input = null; /** * * @return value of index 'D' if exists */ private static int scanAndFindIndexD() { Scanner scan = new Scanner(System.in); System.out.println("Please enter info about dice: "); input = scan.nextLine(); return input.indexOf('D'); } /** * * @param indexD * @return amount of throws */ private static int checkValueBeforeD(int indexD) { Integer number = null; String beforeD = input.substring(0,indexD); if(beforeD.length() == 0) { number = 1; } else { try { number = Integer.parseInt(beforeD); } catch (NumberFormatException e) { System.out.println("Amount before letter D is not a value! Please enter correct value:"); Scanner scan = new Scanner(System.in); number = scan.nextInt(); checkValueBeforeD(number); } } return number; } /** * * @param indexD * @return array with two values. 1st - kind of dice. 2nd - additional value. */ private static int[] checkValueAfterD(int indexD) { String afterD = input.substring(indexD + 1); int[] results = new int[2]; int indexPlus = afterD.indexOf('+'); int indexMinus = afterD.indexOf('-'); if(indexPlus == indexMinus) { results[0] = Integer.parseInt(afterD); results[1] = 0; // if both index are equals -1, there is no sign '+' or '-' } else if(indexPlus > indexMinus) { results[0] = Integer.parseInt(afterD.substring(0, indexPlus)); results[1] = Integer.parseInt(afterD.substring(indexPlus + 1)); } else if(indexMinus > indexPlus) { results[0] = Integer.parseInt(afterD.substring(0, indexMinus)); results[1] -= Integer.parseInt(afterD.substring(indexMinus + 1)); } return results; } /** * * @return join all three values in one array * @throws NumberFormatException */ private static int[] parseInfo() throws NumberFormatException { int[] result = new int[3]; List<Integer> listDice = new ArrayList<>(); listDice.add(3); listDice.add(4); listDice.add(6); listDice.add(8); listDice.add(10); listDice.add(12); listDice.add(20); listDice.add(100); // input text and find index D Integer indexD = null; while(true) { indexD = scanAndFindIndexD(); if (indexD > -1) break; } // amount of throws result[0] = checkValueBeforeD(indexD); // kind of dice result[1] = checkValueAfterD(indexD)[0]; Scanner scan = new Scanner(System.in); while(true) { System.out.println("Please enter valid type of dice!"); try{ result[1] = scan.nextInt(); if(listDice.contains(result[1])) break; } catch(NumberFormatException e) { e.printStackTrace(); } } // additional value result[2] = checkValueAfterD(indexD)[1]; return result; } /** * * @param parameters * @return final result */ private static int dice(int[] parameters) { for(int i : parameters) { System.out.println(i); } return parameters[0] * parameters[1] + parameters[2]; } }
package com.test.proxy.statics; import com.test.proxy.dynamic.DynamicAgent; /** * Created with IntelliJ IDEA. * User: wuzbin * Date: 13-4-27 * Time: 下午11:18 * To change this template use File | Settings | File Templates. */ public class RentHouse { public static void main(String[] args) { HouseRenter lilei = new HouseRenter("李蕾"); Renter agent = DynamicAgent.createAgent(lilei); agent.rent(); } }
/** * Copyright 2017 伊永飞 * * 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.yea.remote.netty.codec; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import com.yea.core.compress.Compress; import com.yea.core.remote.constants.RemoteConstants; import com.yea.core.remote.struct.Message; import com.yea.core.serializer.ISerializer; import com.yea.core.serializer.pool.SerializePool; import com.yea.remote.netty.handle.NettyChannelHandler; /** * 消息处理,编码(FST) * @author yiyongfei * */ public final class NettyMessageEncoder extends MessageToByteEncoder<Message> implements NettyChannelHandler { private static final byte[] LENGTH_PLACEHOLDER = new byte[4]; private SerializePool serializePool; private RemoteConstants.CompressionAlgorithm compressionAlgorithm; public NettyMessageEncoder() { this(null); } public NettyMessageEncoder(RemoteConstants.CompressionAlgorithm compressionAlgorithm) { this.serializePool = new SerializePool(); this.compressionAlgorithm = compressionAlgorithm; } @Override protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf sendBuf) throws Exception { if (msg == null || msg.getHeader() == null) { throw new Exception("The encode message is null"); } ISerializer serializer = serializePool.borrow(); try { long basedate = new Date().getTime(); sendBuf.writeInt((msg.getHeader().getCrcCode()));// 长度4字节 sendBuf.writeInt((msg.getHeader().getLength()));// 长度4字节,存放Header+Body的长度,其中Header固定为18字节 sendBuf.writeBytes((msg.getHeader().getSessionID()));// 长度16字节 sendBuf.writeByte((msg.getHeader().getType()));// 长度1字节 sendBuf.writeByte((msg.getHeader().getPriority()));// 长度1字节 sendBuf.writeByte((msg.getHeader().getResult()));// 长度1字节 if (compressionAlgorithm != null && compressionAlgorithm.code() > 0) { // 设置压缩方法 serializer.setCompress(new Compress().setCompressionAlgorithm(compressionAlgorithm.algorithm())); sendBuf.writeByte(compressionAlgorithm.ordinal()); } else { sendBuf.writeByte(RemoteConstants.CompressionAlgorithm.NONE.ordinal()); } sendBuf.writeLong(basedate);// 长度为8字节,发送时间 if (msg.getHeader().getAttachment() != null && !msg.getHeader().getAttachment().isEmpty()) { sendBuf.writeByte(msg.getHeader().getAttachment().size()); Map<String, Number> mapDateType = new HashMap<String, Number>();// 存放Date类型 Map<String, String> mapStringType = new HashMap<String, String>();// 存放String类型 int lengthPos = sendBuf.writerIndex(); sendBuf.writeBytes(new byte[1]);// 长度1字节,存放非Date类型的参数个数 byte[] keyArray = null; byte[] valueArray = null; for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) { if (param.getValue() instanceof Date) { //Date类型的处理,按数字来存放,减少byte数 long time = basedate - ((Date) param.getValue()).getTime(); if (time > Integer.MAX_VALUE) { mapDateType.put(param.getKey(), new Long(time)); } else if (time > Short.MAX_VALUE) { mapDateType.put(param.getKey(), new Integer((int) time)); } else if (time > Byte.MAX_VALUE) { mapDateType.put(param.getKey(), new Short((short) time)); } else { mapDateType.put(param.getKey(), new Byte((byte) time)); } } else if (param.getValue() instanceof String) { //字符串类型的处理,一般情况,字符串的序列化会比getBytes()会占用更多空间 mapStringType.put(param.getKey(), (String) param.getValue()); } else { keyArray = param.getKey().getBytes("ISO-8859-1"); sendBuf.writeShort(keyArray.length); sendBuf.writeBytes(keyArray); valueArray = serializer.serialize(param.getValue()); sendBuf.writeShort(valueArray.length); sendBuf.writeBytes(valueArray); } } sendBuf.setByte(lengthPos, msg.getHeader().getAttachment().size() - mapDateType.size() - mapStringType.size()); if (mapDateType.isEmpty()) { sendBuf.writeByte(0);// 长度1字节,存放Date类型的参数个数,个数为0 } else { sendBuf.writeByte(mapDateType.size());// 长度1字节,存放Date类型的参数个数,个数为元素个数 for (Map.Entry<String, Number> param : mapDateType.entrySet()) { keyArray = param.getKey().getBytes("ISO-8859-1"); sendBuf.writeShort(keyArray.length); sendBuf.writeBytes(keyArray); if (param.getValue() instanceof Long) { sendBuf.writeByte(8); sendBuf.writeLong((Long) param.getValue()); } else if (param.getValue() instanceof Integer) { sendBuf.writeByte(4); sendBuf.writeInt((Integer) param.getValue()); } else if (param.getValue() instanceof Short) { sendBuf.writeByte(2); sendBuf.writeShort((Short) param.getValue()); } else { sendBuf.writeByte(1); sendBuf.writeByte((Byte) param.getValue()); } } } if (mapStringType.isEmpty()) { sendBuf.writeByte(0);// 长度1字节,存放String类型的参数个数,个数为0 } else { sendBuf.writeByte(mapStringType.size());// 长度1字节,存放String类型的参数个数,个数为元素个数 for (Map.Entry<String, String> param : mapStringType.entrySet()) { keyArray = param.getKey().getBytes("ISO-8859-1"); sendBuf.writeShort(keyArray.length); sendBuf.writeBytes(keyArray); valueArray = param.getValue().getBytes("ISO-8859-1"); sendBuf.writeShort(valueArray.length); sendBuf.writeBytes(valueArray); } } } else { sendBuf.writeByte(0);// 长度2字节,附属内容的数目为0 } if (msg.getBody() != null) { byte[] objArray = serializer.serialize(msg.getBody()); int lengthPos = sendBuf.writerIndex(); sendBuf.writeBytes(LENGTH_PLACEHOLDER);// 长度4字节,存放Body的长度 sendBuf.writeBytes(objArray); sendBuf.setInt(lengthPos, sendBuf.writerIndex() - lengthPos - 4);// 设置Body长度 } else { sendBuf.writeInt(0); } sendBuf.setInt(4, sendBuf.readableBytes() - 8);// 设置总长度,Header+Body的长度 } finally { serializePool.restore(serializer); } } public ChannelHandler clone() throws CloneNotSupportedException { NettyMessageEncoder obj = null; obj = (NettyMessageEncoder) super.clone(); return obj; } @SuppressWarnings("unused") private ApplicationContext context; /** * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) */ public void setApplicationContext(ApplicationContext arg0) throws BeansException { context = arg0; } }
package com.tvm.ImportAndMixConfiguration; public class UserService { public void createUser(){ System.out.println("Creating user in User Service"); } }
package com.shiyanlou.mybatis.mapper; import com.shiyanlou.mybatis.model.User; import jdk.nashorn.internal.runtime.ECMAException; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; public interface UserMapper { @Insert("insert into user(name,sex,age) values(#{name},#{sex},#{age})") @Options(useGeneratedKeys = true,keyProperty = "id") public int insertUser(User user) throws Exception; @Update("update user set age=#{age} where id=#{id}") public void updateUser(User user) throws Exception; @Delete("delete from user where id=#{user_id}") public int deleteUser(@Param("user_id") Integer id)throws Exception; @Select("select * from user where id=#{id}") @Results({ @Result(id=true,property = "id",column = "id"), @Result(property = "name",column = "name"), @Result(property = "sex",column = "sex"), @Result(property = "age",column = "age"), }) public User selectUserById(Integer id)throws Exception; @Select("select * from user") public List<User> selectAllUser()throws Exception; }
package arcs.android.demo.service; import android.content.ClipboardManager; import android.content.ClipboardManager.OnPrimaryClipChangedListener; import android.content.Context; import android.util.Log; import java.util.function.Consumer; import javax.inject.Inject; import arcs.android.api.Annotations.AppContext; import arcs.demo.services.ClipboardService; import static android.content.ClipDescription.MIMETYPE_TEXT_PLAIN; public class AndroidClipboardService implements ClipboardService { private Context ctx; private OnPrimaryClipChangedListener onPrimaryClipChangedListener; @Inject public AndroidClipboardService(@AppContext Context ctx) { this.ctx = ctx; } @Override public void listen(Consumer<String> pasted) { ClipboardManager clipboard = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE); if (onPrimaryClipChangedListener != null) { clipboard.removePrimaryClipChangedListener(onPrimaryClipChangedListener); } onPrimaryClipChangedListener = () -> { try { if (clipboard.hasPrimaryClip() && clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN) && clipboard.getPrimaryClip().getItemCount() > 0) { pasted.accept(clipboard.getPrimaryClip().getItemAt(0).getText().toString()); } } catch (Throwable t) { Log.e("Arcs", "Error in clipboard handling", t); } }; clipboard.addPrimaryClipChangedListener(onPrimaryClipChangedListener); } }
package com.arquitecturajava.aplicacion.dao; import com.arquitecturajava.aplicacion.bo.Categoria; import com.arquitecturajava.aplicacion.bo.Libro; import java.util.List; /** * Created by admuser on 16/04/17. */ public interface LibroDao extends GenericDao<Libro,String> { List<Libro> buscarPorCategoria(Categoria categoria); }
package com.melhamra.schoolAPI.repositories; import com.melhamra.schoolAPI.models.Groups; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface GroupsRepository extends JpaRepository<Groups, Long> { }
package introexception; import org.junit.Test; import static org.junit.Assert.assertEquals; public class PatientTest { @Test public void validSsn() { Patient patient = new Patient("John Doe", "123456788", 2000); assertEquals("John Doe", patient.getName()); assertEquals("123456788", patient.getSocialSecurityNumber()); assertEquals(2000, patient.getYearOfBirth()); } }
package com.example.demo.entity; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableField; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; /** * <p> * * </p> * * @author zjp * @since 2020-12-03 */ @Data @EqualsAndHashCode(callSuper = false) @TableName("order_contract_project") public class OrderContractProject implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 合同id */ @TableField("contract_id") private Integer contractId; /** * 项目编号 */ @TableField("projectNum") private String projectNum; /** * 项目金额 */ @TableField("project_money") private Double projectMoney; /** * 合计项目金额(累加增补合同金额) */ @TableField("sum_project_money") private Double sumProjectMoney; /** * 关联出版 */ @TableField("publishs") private String publishs; }
package com.oracle.curd.test; import com.oracle.curd.bean.Manager; import com.oracle.curd.dao.ManagerMapper; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) public class ManagerTest { @Autowired ManagerMapper managerMapper; @Autowired SqlSession sqlSession; @Test public void TestLogin(){ Manager admin = managerMapper.selectByPrimaryKey("admin"); System.out.println(admin); } }
package Es11; import prog.io.*; /** * Questo programma è un grado di parsare un numero intero * inserito dall'utente sotto forma di stringa. * Il numero può essere negativo e la stringa può avere * spazi in testa o in coda. */ public class String2Int { public static void main(String[] args) { ConsoleInputManager in = new ConsoleInputManager(); ConsoleOutputManager out = new ConsoleOutputManager(); // Prendiamo in input una stringa e la puliamo direttamente da // eventuali spazi a inizio o fine stringa con trim(); String num = in.readLine("Inserisci un numero: ").trim(); // Qui teniamo il risultato. int numInt = 0; // Qui teniamo l'esponente che moltiplica l'ultima cifra parsata. int currentEsp = 1; for (int i = num.length()-1; i >= 0; i--) { char current = num.charAt(i); int cifra = current - 48; if(cifra >= 0 && cifra <= 9) { numInt += cifra * currentEsp; } else { // Il carattere non è una cifra! // // Normalmente qui si da errore e si esce, gli unici casi // dove ciò non succede è se becchiamo il segno meno o il segno più // e se questo si trova rigorosamente a inizio stringa. // In questo caso lasciamo com'è (+) o invertiamo il numero (-). if(i == 0 && (current == '-' || current == '+')) { numInt = current == '-' ? numInt * -1: numInt; } else { out.println("Hai inserito una schifezza!"); return; } } // Moltiplichiamo il nostro esponente per il prossimo // (eventuale) passaggio. currentEsp *= 10; } // Stampo il risultato out.printf("La cifra inserita e' %d.\n", numInt); } }
package com.yevhenchmykhun.controller; import com.yevhenchmykhun.cart.ShoppingCart; import com.yevhenchmykhun.entity.Book; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @WebServlet("/deletefromcart") public class DeleteFromCartController extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String bookId = request.getParameter("bookId"); HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); Book book = new Book(); book.setId(Integer.parseInt(bookId)); cart.deleteItem(book); String url = "/cart"; request.getRequestDispatcher(url).forward(request, response); } }
package com.mybatis.service; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.mybatis.dao.TopicDao; import com.mybatis.util.MybatisUtil; import com.news.pojo.Topic; public class TopicServicesImpl implements TopicServices { @Override public List<Topic> getAllTopic() { SqlSession sqlSession = null; List<Topic> data4 = null; try { sqlSession = MybatisUtil.getsqlSession(); TopicDao dao = sqlSession.getMapper(TopicDao.class); data4 = dao.getAllTopic(); } catch (Exception e) { // TODO: handle exception }finally{ MybatisUtil.closeSqlSession(sqlSession); } return data4; } }
package com.loneless.controller; enum CommandName { ADD_TRANSACTION, AUTHORISE_USER, DELETE_TRANSACTION, UPDATE_TRANSACTION,WRONG_REQUEST, RECEIVE_ALL_TRANSACTION, CALCULATE_CURRENT_SUM, RECEIVE_PLANNED_TRANSACTION, FIND_OLL_TRANSACTION_TO_CURRENT_DATE, FIND_OLL_TRANSACTION_IN_INTERVAL, SAVE_TRANSACTIONS }
package com.lwc.user.service; import com.lwc.user.entity.Role; import com.baomidou.mybatisplus.core.metadata.IPage; import java.util.List; /** * <p> * 角色 服务类 * </p> * * @author Li * @since 2019-07-29 */ public interface RoleService { Role doQuery(Long id) throws Exception; int doRemove(Long id) throws Exception; int doPurge(Long id) throws Exception; List<Role> doQueryByIds(List<Long> ids) throws Exception; int doRemoveByIds(List<Long> ids) throws Exception; int doPurgeByIds(List<Long> ids) throws Exception; List<Role> doQuery(Role entity) throws Exception; Role doCreate(Role entity) throws Exception; List<Role> doUpdate(Role entity) throws Exception; int doRemove(Role entity) throws Exception; int doPurge(Role entity) throws Exception; int doCount(Role entity) throws Exception; List<Role> insertOrUpdateBatch(List<Role> entities) throws Exception; IPage<Role> page(Role entity, int current, int size) throws Exception; }
package br.com.zup.treinocasadocodigo.controllers; import br.com.zup.treinocasadocodigo.entities.estado.Estado; import br.com.zup.treinocasadocodigo.entities.estado.EstadoNovoRequest; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import javax.validation.Valid; /** * Contagem de carga intrínseca da classe: 2 */ @RestController @RequestMapping("/estados") public class EstadoConrtoller { @PersistenceContext private EntityManager manager; @PostMapping @Transactional @ResponseStatus(HttpStatus.CREATED) //1 public String cadastroEstado(@RequestBody @Valid EstadoNovoRequest novoEstado) { //1 Estado estado = novoEstado.toModel(manager); manager.persist(estado); return estado.toString(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DataObjects; import java.util.Date; /** * * @author Shivam Patel */ public class Project_Details_Object { private int Project_ID; private String Title,Functionality,Grade,Candidate_ID,year; public String getYear() { return year; } public void setYear(String year) { this.year = year; } public Project_Details_Object() { } public int getProject_ID() { return Project_ID; } public void setProject_ID(int Project_ID) { this.Project_ID = Project_ID; } public String getCandidate_ID() { return Candidate_ID; } public void setCandidate_ID(String Candidate_ID) { this.Candidate_ID = Candidate_ID; } public String getTitle() { return Title; } public void setTitle(String Title) { this.Title = Title; } public String getFunctionality() { return Functionality; } public void setFunctionality(String Functionality) { this.Functionality = Functionality; } public String getGrade() { return Grade; } public void setGrade(String Grade) { this.Grade = Grade; } @Override public String toString() { return "Project_Details_Object{" + "Project_ID=" + Project_ID + ", Title=" + Title + ", Functionality=" + Functionality + ", Grade=" + Grade + ", Candidate_ID=" + Candidate_ID + ", year=" + year + '}'; } }
package com.gaoshin.sorma.examples.addressbook; import com.gaoshin.sorma.annotation.Table; @Table( name="contact", keyColumn="id", autoId=true, create="create table if not exists contact (" + " id INTEGER primary key autoincrement" + ", firstName text" + ", lastName text" + ", married tinyint" + ")" ) public class Contact { private Integer id; private String firstName; private String lastName; private boolean married; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public boolean isMarried() { return married; } public void setMarried(boolean married) { this.married = married; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
package cn.jesse.extrasample; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.PixelFormat; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import java.util.List; public class RemoteToaster implements View.OnTouchListener { Context mContext; WindowManager.LayoutParams params; WindowManager mWM; View mView; private float mTouchStartX; private float mTouchStartY; private float x; private float y; public RemoteToaster(Context context){ this.mContext = context; params = new WindowManager.LayoutParams(); params.height = WindowManager.LayoutParams.WRAP_CONTENT; params.width = WindowManager.LayoutParams.WRAP_CONTENT; params.format = PixelFormat.TRANSLUCENT; params.windowAnimations = R.style.anim_view; params.type = WindowManager.LayoutParams.TYPE_TOAST; params.gravity = Gravity.CENTER; params.setTitle("Toast"); params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; mWM = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mView = inflate.inflate(R.layout.dialog_notify, null); mView.setOnTouchListener(this); } public void show(){ final TextView confirm = (TextView) mView.findViewById(R.id.tv_confirm); final TextView content = (TextView) mView.findViewById(R.id.tv_content); content.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hide(); startActivityByPackage("com.ppmoney.ppstock"); } }); confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { hide(); Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ComponentName cn = new ComponentName("cn.jesse.extrasample", "cn.jesse.extrasample.LoginActivity"); intent.setComponent(cn); mContext.startActivity(intent); } }); if (mView.getParent() != null) { mWM.removeView(mView); } mWM.addView(mView, params); } public void hide(){ if(mView!=null){ mWM.removeView(mView); } } private void updateViewPosition(){ //更新浮动窗口位置参数 params.x=(int) (x-mTouchStartX); params.y=(int) (y-mTouchStartY); mWM.updateViewLayout(mView, params); //刷新显示 } @Override public boolean onTouch(View v, MotionEvent event) { //获取相对屏幕的坐标,即以屏幕左上角为原点 // x = event.getRawX(); // y = event.getRawY(); // Log.i("currP", "currX"+x+"====currY"+y); // switch (event.getAction()) { // case MotionEvent.ACTION_DOWN: //捕获手指触摸按下动作 // //获取相对View的坐标,即以此View左上角为原点 // mTouchStartX = event.getX(); // mTouchStartY = event.getY(); // Log.i("startP","startX"+mTouchStartX+"====startY"+mTouchStartY); // break; // case MotionEvent.ACTION_MOVE: //捕获手指触摸移动动作 // updateViewPosition(); // break; // case MotionEvent.ACTION_UP: //捕获手指触摸离开动作 // updateViewPosition(); // break; // } return true; } private void startActivityByPackage(String appPackage) { PackageInfo pi = null; try { pi = mContext.getPackageManager().getPackageInfo(appPackage, 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null); resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER); resolveIntent.setPackage(pi.packageName); PackageManager pm= mContext.getPackageManager(); List<ResolveInfo> apps = pm.queryIntentActivities(resolveIntent, 0); ResolveInfo ri = apps.iterator().next(); if (ri != null ) { String packageName = ri.activityInfo.packageName; String className = ri.activityInfo.name; Intent intent = new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addCategory(Intent.CATEGORY_LAUNCHER); ComponentName cn = new ComponentName(packageName, className); intent.setComponent(cn); mContext.startActivity(intent); } } }
package com.jic.libin.leaderus.study006; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; /** * Created by andylee on 17/1/18. */ public class ReadThread implements Runnable{ Map<String,SalaryGroup> stringSalaryGroupMap; List<Salary> salaries; CountDownLatch countDownLatch; public ReadThread(List<Salary> salaries, Map<String,SalaryGroup> stringSalaryGroupMap, CountDownLatch countDownLatch) { this.salaries = salaries; this.stringSalaryGroupMap = stringSalaryGroupMap; this.countDownLatch = countDownLatch; } @Override public void run() { this.salaries.stream().parallel().forEachOrdered(salary -> { if(stringSalaryGroupMap.containsKey(salary.getName())) { SalaryGroup salaryGroup = stringSalaryGroupMap.get(salary.getName()); salaryGroup.setYearSalary(salaryGroup.getYearSalary()+salary.getYearSalary()); salaryGroup.setCount(salaryGroup.getCount()+1); } else { stringSalaryGroupMap.put(salary.getName(),new SalaryGroup(salary.getName(),1,salary.getYearSalary())); } }); this.countDownLatch.countDown(); } }
package com.youthlin.example.chat.protocol.request; import com.youthlin.example.chat.model.User; import com.youthlin.example.chat.protocol.Command; import com.youthlin.example.chat.protocol.Packet; import lombok.Data; import java.util.List; /** * 创建: youthlin.chen * 时间: 2018-11-14 10:10 */ @Data public class QuitGroupRequestPacket extends Packet { private static final long serialVersionUID = -8462923137864474577L; private long groupId; private User whoQuit; private List<User> userList; @Override public byte command() { return Command.QUIT_GROUP_REQUEST; } }
package com.yf.accountmanager.util; import android.content.SharedPreferences.Editor; public class SharePrefUtil { public static final String RESERVED_DIMEN="reserved_dimen"; public static boolean saveFileEditorTextsize(int textsize){ return putReservedDimen("fileEditorTextsize",textsize); } public static int getFileEditorTextsize(){ return getReservedDimen("fileEditorTextsize", 17); } public static boolean saveFileEditorPagesize(int pagesize){ return putReservedDimen("fileEditorPagesize",pagesize); } public static int getFileEditorPagesize(){ return getReservedDimen("fileEditorPagesize", 0); } public static boolean saveFileSystemGridColumnNum(int cnum){ return putReservedDimen("fileSystemGridColumnNum", cnum); } public static int getFileSystemGridColumnNum(){ return getReservedDimen("fileSystemGridColumnNum", 5); } public static boolean saveMaxFileSystemSearchResultCount(int count){ return putReservedDimen("maxFileSystemSearchResultCount", count); } public static int getMaxFileSystemSearchResultCount(){ return getReservedDimen("maxFileSystemSearchResultCount", 500); } public static boolean putReservedDimen(String key,int value){ Editor editor = CommonUtils.context.getSharedPreferences(RESERVED_DIMEN, 0).edit(); editor.putInt(key, value); return editor.commit(); } public static int getReservedDimen(String key,int defau){ return CommonUtils.context.getSharedPreferences(RESERVED_DIMEN, 0).getInt(key, defau); } }
package lab4; public class Vanilla extends IceCream { public Vanilla() { description= "Vanilla"; } @Override public double cost() { // TODO Auto-generated method stub return 0; } }
class InfluentableItem extends AbstractItem { public InfluentableItem(String name, int price) { super(name, price); } }
package programa2; /* Exemplo de programa onde uma variável é compartilhada entre duas Threads e o resultado final não é o esperado. Responder: Qual o valor que deveria ser impresso? Qual o valor que foi impresso? Por que o valor impresso não foi o esperado? Fazer: tirar o comentário da palavra synchronized na classe Variavel e ver o que acontece? O resultado final foi o esperado? Autor: Avelino Zorzo Data: 16.09.2014 */ public class ExemploThread { public static void main(String[] args) { try { // variavel a ser compartilhada Variavel v = new Variavel(); // cria uma thread e inicia sua execução MinhaThread t1 = new MinhaThread("t1",v,1); t1.start(); // cria uma thread e inicia sua execução MinhaThread t2 = new MinhaThread("t2",v,2); t2.start(); // espera as duas threads terminarem suas execuções t1.join(); t2.join(); // variavel deveria ter o valor 3.000.000 System.out.println("Valor em Variavel = "+v.valor()); } catch (InterruptedException e) { } } }
package com.aotuhome.web.controller; import com.aotuhome.dto.RequestBean; import com.aotuhome.dto.RequestParams; import com.aotuhome.dto.ResponseParam; import com.aotuhome.service.RealNameService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @CrossOrigin @Controller public class RealNameController { public static final Logger logger = LoggerFactory.getLogger(RealNameController.class); @Autowired private RealNameService realNameService; @RequestMapping(method= RequestMethod.POST,value = "/returnRealNameData",produces = "application/json;charset=UTF-8") @ResponseBody public ResponseParam returnRealNameData(@RequestBody RequestBean requestBean){ logger.info(requestBean.toString()); ResponseParam responseParam = realNameService.getResponse(requestBean); return responseParam; } @RequestMapping(method= RequestMethod.POST,value = "/returnResponseData",produces = "application/json;charset=UTF-8") @ResponseBody public ResponseParam returnResponseData(@RequestBody RequestParams requestParams){ logger.info(requestParams.toString()); try { ResponseParam responseParam = realNameService.getResponse(requestParams); return responseParam; }catch (Exception e){ e.printStackTrace(); } return null; } }
package br.com.cast.scc.util; public class UtilString { private UtilString() { // Somente metodos estaticos } public static boolean isStringVazia(String valor) { return valor == null || valor.equals(""); } }
package ru.ugame.core; import ru.ugame.objects.Board; import javax.swing.*; public class View extends JFrame { private final static String APP_NAME = "UntitledGame"; private static final int WIN_WIDTH = 250; private static final int WIN_HEIGHT = 350; private static final int GRID_SCALE = 15; Board board; public View (Board board) { this.board = board; } public void init() { add(new GamePanel(board, GRID_SCALE)); setSize((board.getWidth() + 3) * GRID_SCALE, (board.getHeight() + 3) * GRID_SCALE + 22); setTitle(APP_NAME); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); this.addKeyListener(new Input(board)); setLocationRelativeTo(null); } public void display() {} }
package domain; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import org.junit.Test; import exceptions.MiddlewareException; import middleware.MiddlewareFacade; import middleware.MiddlewareFacadeTest; public class DeviceFactoryTests { MiddlewareFacadeTest middlewareFacade = new MiddlewareFacadeTest(); public <T> boolean listEqualsIgnoreOrder(List<T> list1, List<T> list2) { return (new HashSet<>(list1).equals(new HashSet<>(list2))); } public Collection<IDescriptor> getDeviceDescriptor() throws MiddlewareException{ URL url = getClass().getResource("devices.json"); return this.middlewareFacade.getDevicesTest(new File(url.getPath())); } public File fileFunction() throws MiddlewareException{ URL url = getClass().getResource("function_doorLock.txt"); return new File(url.getPath()); } @Test public void testConstructor() throws MiddlewareException { DeviceFactory deviceFactory = new DeviceFactory(); assertTrue(deviceFactory.getInstance().getDescriptor()== null); assertTrue(deviceFactory.getInstance().getFunctions().size()==0); assertTrue(deviceFactory.getInstance().getState().getCurrentState().size()==0); } @Test public void testaddDeviceDescriptor() throws MiddlewareException{ List<IDescriptor> listDesc = (ArrayList<IDescriptor>) this.getDeviceDescriptor(); DeviceFactory deviceFactory = new DeviceFactory(); deviceFactory.addDeviceDescriptor(listDesc.get(0)); // doorLock assertTrue(deviceFactory.getInstance().getDescriptor().equals(listDesc.get(0))); } @Test public void testAddFunctions() throws MiddlewareException { List<IDescriptor> listDesc = (ArrayList<IDescriptor>) this.getDeviceDescriptor(); DeviceFactory deviceFactory = new DeviceFactory(); deviceFactory.addDeviceDescriptor(listDesc.get(0)); // elemento doorLook ArrayList<IFunction> listFunctAdapters = (ArrayList<IFunction>)this.middlewareFacade.getADeviceFunctionsTest(deviceFactory.getInstance().getDescriptor(),this.fileFunction()); deviceFactory.addFunctions(listFunctAdapters); List<IFunction> functions = new ArrayList<>(); for(IFunction f : listFunctAdapters){ Function funct = new Function(f.getId().toString()); funct.setCommands(f.getCommands()); functions.add(funct); } assertTrue(this.listEqualsIgnoreOrder((List)deviceFactory.getInstance().getFunctions(), functions)); } }
package com.zhongyp.spring.demo.factory; public class Dog implements Being { private String msg = null; public void setMsg(String msg){ this.msg = msg; } @Override public void testBeing() { // TODO Auto-generated method stub System.out.println("��" + msg); } }
/* * Copyright (c) 2013-2014, Neuro4j.org * * 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 org.neuro4j.studio.core; import java.util.Set; import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Call Node</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.neuro4j.studio.core.CallNode#getFlowName <em>Flow Name</em>}</li> * <li>{@link org.neuro4j.studio.core.CallNode#getDynamicFlowName <em>Dynamic Flow Name</em>}</li> * <li>{@link org.neuro4j.studio.core.CallNode#getInputParameters <em>Input Parameters</em>}</li> * <li>{@link org.neuro4j.studio.core.CallNode#getOutputParameters <em>Output Parameters</em>}</li> * </ul> * </p> * * @see org.neuro4j.studio.core.Neuro4jPackage#getCallNode() * @model * @generated */ public interface CallNode extends ActionNode { public static final int X_OFFSET = 10; public static final int Y_OFFSET = 17; public static final String NEXT = "NEXT"; /** * Returns the value of the '<em><b>Flow Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Flow Name</em>' attribute isn't clear, there really should be more of a description * here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Flow Name</em>' attribute. * @see #setFlowName(String) * @see org.neuro4j.studio.core.Neuro4jPackage#getCallNode_FlowName() * @model dataType="org.eclipse.emf.ecore.xml.type.String" * @generated */ String getFlowName(); /** * Sets the value of the '{@link org.neuro4j.studio.core.CallNode#getFlowName <em>Flow Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @param value * the new value of the '<em>Flow Name</em>' attribute. * @see #getFlowName() * @generated */ void setFlowName(String value); /** * Returns the value of the '<em><b>Dynamic Flow Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Dynamic Flow Name</em>' attribute isn't clear, there really should be more of a * description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Dynamic Flow Name</em>' attribute. * @see #setDynamicFlowName(String) * @see org.neuro4j.studio.core.Neuro4jPackage#getCallNode_DynamicFlowName() * @model dataType="org.eclipse.emf.ecore.xml.type.String" * @generated */ String getDynamicFlowName(); /** * Sets the value of the '{@link org.neuro4j.studio.core.CallNode#getDynamicFlowName <em>Dynamic Flow Name</em>}' * attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @param value * the new value of the '<em>Dynamic Flow Name</em>' attribute. * @see #getDynamicFlowName() * @generated */ void setDynamicFlowName(String value); /** * Returns the value of the '<em><b>Input Parameters</b></em>' reference list. * The list contents are of type {@link org.neuro4j.studio.core.InOutParameter}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Input Parameters</em>' reference list isn't clear, there really should be more of a * description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Input Parameters</em>' reference list. * @see org.neuro4j.studio.core.Neuro4jPackage#getCallNode_InputParameters() * @model * @generated */ EList<InOutParameter> getInputParameters(); /** * Returns the value of the '<em><b>Output Parameters</b></em>' reference list. * The list contents are of type {@link org.neuro4j.studio.core.InOutParameter}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Output Parameters</em>' reference list isn't clear, there really should be more of a * description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Output Parameters</em>' reference list. * @see org.neuro4j.studio.core.Neuro4jPackage#getCallNode_OutputParameters() * @model * @generated */ EList<InOutParameter> getOutputParameters(); Set<String> getUsedOutputNames(); } // CallNode
// // Decompiled by Procyon v0.5.36 // package com.davivienda.sara.tablas.transacciontemp.servicio; import javax.persistence.Query; import java.util.logging.Level; import com.davivienda.utilidades.conversion.Fecha; import com.davivienda.sara.base.exception.EntityServicioExcepcion; import java.util.Map; import java.util.Collection; import java.util.Date; import javax.persistence.EntityManager; import com.davivienda.sara.base.AdministracionTablasInterface; import com.davivienda.sara.entitys.TransaccionTemp; import com.davivienda.sara.base.BaseEntityServicio; public class TransaccionTempServicio extends BaseEntityServicio<TransaccionTemp> implements AdministracionTablasInterface<TransaccionTemp> { public TransaccionTempServicio(final EntityManager em) { super(em, TransaccionTemp.class); } public Collection<TransaccionTemp> getColeccionTransaccion(final Integer codigoCajero, final Date fechaInicial, final Date fechaFinal) throws EntityServicioExcepcion { return this.getColeccionTransaccion(codigoCajero, fechaInicial, fechaFinal, null, null); } public Collection<TransaccionTemp> getColeccionTransaccion(final Integer codigoCajero, final Date fecha) throws EntityServicioExcepcion { return this.getColeccionTransaccion(codigoCajero, fecha, null, null, null); } public TransaccionTemp getTransaccion(final Integer codigoCajero, final Date fechaProceso, final Integer numeroTransaccion) throws EntityServicioExcepcion { TransaccionTemp reg = null; try { final Date fInicial = (fechaProceso != null) ? fechaProceso : Fecha.getDateHoy(); final Date fFin = Fecha.getFechaFinDia(fInicial); final Integer cCajero = (codigoCajero != null) ? codigoCajero : 9999; final Integer nTran = (numeroTransaccion != null) ? numeroTransaccion : 0; Query query = null; if (!cCajero.equals(9999)) { query = this.em.createNamedQuery("TransaccionTemp.TransaccionBuscarReintegro"); query.setParameter("codigoCajero", (Object)cCajero); query.setParameter("fechaInicial", (Object)fInicial).setParameter("fechaFinal", (Object)fFin); query.setParameter("numeroTransaccion", (Object)nTran); reg = (TransaccionTemp)query.getSingleResult(); } } catch (IllegalStateException ex) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } return reg; } public Collection<TransaccionTemp> getColeccionTransaccion(final Integer codigoCajero, final Date fechaInicial, final Date fechaFinal, final Integer numeroTransaccion, final Map criterios) throws EntityServicioExcepcion { Collection<TransaccionTemp> regs = null; String strQuery = "select object(obj) from TransaccionTemp obj where obj.transaccionTempPK.fechatransaccion between :fechaInicial and :fechaFinal "; final String orderQuery = " order by obj.transaccionTempPK.fechatransaccion"; final String referencia = "%" + criterios.get("referencia"); final String productoOrigen = "%" + criterios.get("productoOrigen"); final String tarjeta = "%" + criterios.get("tarjeta"); try { if (codigoCajero != 0) { strQuery += " and obj.transaccionTempPK.codigocajero =:codigoCajero"; } if (numeroTransaccion != null) { strQuery += " and obj.transaccionTempPK.numerotransaccion = :numeroTransaccion"; } if (!referencia.equals("%")) { strQuery += " and obj.referencia like :referencia"; } if (!productoOrigen.equals("%")) { strQuery += " and obj.cuenta like :productoOrigen"; } if (!tarjeta.equals("%")) { strQuery += " and obj.tarjeta like :tarjeta"; } strQuery += orderQuery; final Date fInicial = (fechaInicial != null) ? fechaInicial : Fecha.getDateHoy(); final Date fFin = (fechaFinal != null) ? Fecha.getFechaFinDia(fechaFinal) : Fecha.getFechaFinDia(fInicial); final Integer cCajero = (codigoCajero != null) ? codigoCajero : 9999; Query query = null; if (!cCajero.equals(9999)) { query = this.em.createQuery(strQuery); query.setParameter("fechaInicial", (Object)fInicial).setParameter("fechaFinal", (Object)fFin); if (codigoCajero != 0) { query.setParameter("codigoCajero", (Object)cCajero); } if (numeroTransaccion != null) { query.setParameter("numeroTransaccion", (Object)numeroTransaccion); } if (!referencia.equals("%")) { query.setParameter("referencia", (Object)referencia); } if (!productoOrigen.equals("%")) { query.setParameter("productoOrigen", (Object)productoOrigen); } if (!tarjeta.equals("%")) { query.setParameter("tarjeta", (Object)tarjeta); } regs = (Collection<TransaccionTemp>)query.getResultList(); } } catch (IllegalStateException ex) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } return regs; } public Date getFechaMinimaTx(final Integer codigoCajero) throws EntityServicioExcepcion, IllegalArgumentException { Date result = null; Query query = null; if (codigoCajero == null || codigoCajero == 0) { throw new IllegalArgumentException("Se debe seleccionar un cajero"); } try { query = this.em.createNamedQuery("TransaccionTemp.minFechaTransaccion"); query.setParameter("codigoCajero", (Object)codigoCajero); result = (Date)query.getSingleResult(); } catch (IllegalStateException ex) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } return result; } public void cargarCicloTempXStoreP() throws EntityServicioExcepcion { try { this.ejecutarSpDesdeJob("ADMINATM.CARGUETRANSACCIONTEMP_INIT;"); } catch (IllegalStateException ex) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "Error al ejecutar el store procedure CARGUETRANSACCIONTEMP No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "Error al ejecutar el store procedure CARGUETRANSACCIONTEMP El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } } public void mantenimientoDiariosStoreP() throws EntityServicioExcepcion { try { final Query query = this.em.createNativeQuery("BEGIN ADMINATM.MANTENIMIENTODIARIOS; END;"); query.executeUpdate(); } catch (IllegalStateException ex) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "Error al ejecutar el store procedure MANTENIMIENTODIARIOS No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "Error al ejecutar el store procedure MANTENIMIENTODIARIOS El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } } public void mantenimientoDiariosBorraStoreP() throws EntityServicioExcepcion { try { this.ejecutarSpDesdeJob("ADMINATM.MANTENIMIENTOTR_TEMP;"); } catch (IllegalStateException ex) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "Error al ejecutar el store procedure MANTENIMIENTOTR_TEMP No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "Error al ejecutar el store procedure MANTENIMIENTOTR_TEMP El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } } public void cargarDiariosElectronicosXStoreP() throws EntityServicioExcepcion { try { final Query query = this.em.createNativeQuery("BEGIN ADMINATM.CARGUEDIARIOSELECTRONICOS_INIT; END;"); query.executeUpdate(); } catch (IllegalStateException ex) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "Error al ejecutar el store procedure CARGUEDIARIOSELECTRONICOS_INIT No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "Error al ejecutar el store procedure CARGUEDIARIOSELECTRONICOS_INIT El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } } public void cargarDiariosElectronicosXStoreP_Automatico() throws EntityServicioExcepcion { try { this.ejecutarSpDesdeJob("ADMINATM.CARGUETRANSACCIONTEMP_AUTO;"); } catch (IllegalStateException ex) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "Error al ejecutar el store procedure CARGUEDIARIOSELECTRONICOS_INIT No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "Error al ejecutar el store procedure CARGUEDIARIOSELECTRONICOS_INIT El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } } public void calcReintegrosDAuto() throws EntityServicioExcepcion { try { this.ejecutarSpDesdeJob("ADMINATM.SP_REINTEGROS_AUTO;"); } catch (IllegalStateException ex) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } } public void descomprimirEDC() throws EntityServicioExcepcion { try { final Query query = this.em.createNativeQuery("BEGIN ADMINATM.SP_CARGA_EDC; END;"); query.executeUpdate(); } catch (IllegalStateException ex) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } } public void descomprimirEDC_Automatico() throws EntityServicioExcepcion { try { final Query query = this.em.createNativeQuery("BEGIN ADMINATM.SP_CARGA_EDC_AUTO; END;"); query.executeUpdate(); } catch (IllegalStateException ex) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { TransaccionTempServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } } }
package ru.client.model.tasks; /** * Created by User on 5/15/2016. */ public class Task8 { private String surname; private String name; private String brigadeName; public Task8(String surname, String name, String brigadeName) { this.surname = surname; this.name = name; this.brigadeName = brigadeName; } public String getSurname() { return surname; } public String getName() { return name; } public String getBrigadeName() { return brigadeName; } public void setSurname(String surname) { this.surname = surname; } public void setName(String name) { this.name = name; } public void setBrigadeName(String brigadeName) { this.brigadeName = brigadeName; } @Override public String toString() { return "Task8{" + "surname='" + surname + '\'' + ", name='" + name + '\'' + ", brigadeName='" + brigadeName + '\'' + '}'; } }
import java.util.Calendar; public class User { public static final String USER_DEFAULT_FIRSTNAME= "NONE"; public static final String USER_DEFAULT_LASTNAME= "NONE"; public static final int USER_DEFAULT_AGE=0; public static final String USER_DEFAULT_EMAIL= "example@domain.com"; public static final int USER_NEW= 0; public static final int USER_ACTIVE= 1; public static final int USER_INACTIVE= 2; public static final int USER_BLOCKED= 3; public static final String[] USER_STATUS= {"NEW", "ACTIVE", "INACTIVE", "BLOCKED"}; private String firstname; private String lastname; private int age; private String email; private int status; private Calendar timestamp; public static void main(String[] args){ } User(){ firstname= USER_DEFAULT_FIRSTNAME; lastname=USER_DEFAULT_LASTNAME; age=USER_DEFAULT_AGE; email=USER_DEFAULT_EMAIL; status=USER_NEW; timestamp= Calendar.getInstance(); } User(String firstname, String lastname, String email, int age, int status, Calendar timestamp){ this.firstname= firstname; this.lastname=lastname; this.age=age; this.email=email; this.status=status; this.timestamp=timestamp; } void setFirstName(String firstname) { this.firstname=firstname; } void setLastName(String lastname) { this.lastname=lastname; } public void setAge(int age) { this.age = age; } void setEmail(String email) { this.email=email; } void setStatus(int status) { this.status=status; } void setTimeStamp(Calendar timestamp) { this.timestamp=timestamp; } public String getFirstname() { return firstname; } public String getLastname() { return lastname; } public int getAge() { return age; } public String getEmail() { return email; } public int getStatus() { return status; } public Calendar getTimestamp() { return timestamp; } public String toString() { return "Firstname: " + firstname + "\nLastname: " + lastname + "\nAge: " + age + "\nEmail: " + email + "\nStatus: " + USER_STATUS[status] + "\ntimestamp: " + timestamp.get(Calendar.DAY_OF_MONTH) + "/" + timestamp.get(Calendar.MONTH) + "/" + timestamp.get(Calendar.YEAR); } }
package br.com.zup.treinocasadocodigo.entities.compra; import br.com.zup.treinocasadocodigo.entities.compra.itemcompra.ItemCompra; import br.com.zup.treinocasadocodigo.entities.cupom.Cupom; import br.com.zup.treinocasadocodigo.entities.estado.Estado; import br.com.zup.treinocasadocodigo.entities.pais.Pais; import br.com.zup.treinocasadocodigo.validators.cpfcnpj.CpfCnpj; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Positive; import java.math.BigDecimal; import java.util.List; /** * Contagem de carga intrínseca da classe: 7 */ @Entity public class Compra { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; //Dados do comprador @NotBlank @Email private String email; @NotBlank private String nome; @NotBlank private String sobrenome; @NotBlank //1 @CpfCnpj private String documento; @NotBlank private String endereco; @NotBlank private String complemento; @NotBlank private String cidade; @NotNull @ManyToOne //1 private Pais pais; @ManyToOne //1 private Estado estado; @NotBlank private String telefone; @NotBlank private String cep; //Dados da compra @NotNull @OneToMany(cascade = CascadeType.PERSIST) @JoinColumn(name = "compra_id") //1 private List<ItemCompra> listaItens; @NotNull @Positive private BigDecimal total; @OneToOne @JoinColumn(name = "cupom_id") //1 private Cupom cupom; protected Compra(){} public Compra(@NotBlank @Email String email, @NotBlank String nome, @NotBlank String sobrenome, @NotBlank String documento, @NotBlank String endereco, @NotBlank String complemento, @NotBlank String cidade, @NotNull Pais pais, Estado estado, @NotBlank String telefone, @NotBlank String cep, @NotNull List<ItemCompra> listaItens, @NotNull @Positive BigDecimal total) { this.email = email; this.nome = nome; this.sobrenome = sobrenome; this.documento = documento; this.endereco = endereco; this.complemento = complemento; this.cidade = cidade; this.pais = pais; this.estado = estado; this.telefone = telefone; this.cep = cep; this.listaItens = listaItens; this.total = total; this.cupom = null; } public Long getId() { return id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getSobrenome() { return sobrenome; } public void setSobrenome(String sobrenome) { this.sobrenome = sobrenome; } public String getDocumento() { return documento; } public void setDocumento(String documento) { this.documento = documento; } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } public String getComplemento() { return complemento; } public void setComplemento(String complemento) { this.complemento = complemento; } public String getCidade() { return cidade; } public void setCidade(String cidade) { this.cidade = cidade; } public Pais getPais() { return pais; } public void setPais(Pais pais) { this.pais = pais; } public Estado getEstado() { return estado; } public void setEstado(Estado estado) { this.estado = estado; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public String getCep() { return cep; } public void setCep(String cep) { this.cep = cep; } public List<ItemCompra> getListaItens() { return listaItens; } public void setListaItens(List<ItemCompra> listaItens) { this.listaItens = listaItens; } public BigDecimal getTotal() { return total; } public void setTotal(BigDecimal total) { this.total = total; } public Cupom getCupom() { return cupom; } public void setCupom(Cupom cupom) { this.cupom = cupom; } @Override public String toString() { return "Compra{" + "id=" + id + ", email='" + email + '\'' + ", nome='" + nome + '\'' + ", sobrenome='" + sobrenome + '\'' + ", documento='" + documento + '\'' + ", endereco='" + endereco + '\'' + ", complemento='" + complemento + '\'' + ", cidade='" + cidade + '\'' + ", pais=" + pais + ", estado=" + estado + ", telefone='" + telefone + '\'' + ", cep='" + cep + '\'' + ", pedido=" + listaItens + ", total=" + total + '}'; } public void setCupom(String codigoCupom, EntityManager manager) { //1 List<Cupom> listaCupom = manager .createQuery("SELECT c FROM Cupom c WHERE c.codigo = :codigo", Cupom.class) .setParameter("codigo", codigoCupom) .setMaxResults(1) .getResultList(); //1 if (!listaCupom.isEmpty()) { this.cupom = listaCupom.get(0); } } }
package org.peterkwan.udacity.mysupermarket.service; import android.app.IntentService; import android.content.Intent; import android.os.Bundle; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.util.Log; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.GeofencingEvent; import java.util.List; import static com.google.android.gms.location.Geofence.GEOFENCE_TRANSITION_ENTER; import static org.peterkwan.udacity.mysupermarket.util.AppConstants.MESSAGE_DATA; import static org.peterkwan.udacity.mysupermarket.util.AppConstants.MESSENGER; /** * An {@link IntentService} subclass for handling asynchronous task requests in * a service on a separate handler thread. * <p> */ public class GeofenceTransitionIntentService extends IntentService { private static final String LOG_TAG = GeofenceTransitionIntentService.class.getSimpleName(); public GeofenceTransitionIntentService() { super("GeofenceTransitionIntentService"); } @Override protected void onHandleIntent(Intent intent) { if (intent != null && intent.getExtras() != null) { GeofencingEvent event = GeofencingEvent.fromIntent(intent); if (event.hasError()) { Log.e(LOG_TAG, "Geofence Error =" + event.getErrorCode()); return; } int transition = event.getGeofenceTransition(); if (transition == GEOFENCE_TRANSITION_ENTER) { List<Geofence> geofenceList = event.getTriggeringGeofences(); String geofenceId = ""; for (Geofence geofence : geofenceList) { geofenceId = geofence.getRequestId(); } Log.d(LOG_TAG, "Geofence ID =" + geofenceId); Messenger messenger = (Messenger) intent.getExtras().get(MESSENGER); Bundle bundle = new Bundle(); bundle.putString(MESSAGE_DATA, geofenceId); Message message = Message.obtain(); message.setData(bundle); try { messenger.send(message); } catch (RemoteException e) { Log.e(LOG_TAG, "Error", e); } } } } }
package labrom.litlbro.widget; import labrom.litlbro.R; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.view.View; import android.widget.TextView; public class TipDialog extends Dialog { /* Static */ public static final int DIALOG_ID = 598324; private static TipMeta[] tips = { new TipMeta(0, "tipFirst"), // fake tip, we won't display any tip at first new TipMeta(R.string.tipSearch, "tipSearch"), new TipMeta(R.string.tipShortcuts, "tipShortcuts"), new TipMeta(R.string.tipSettings, "tipSettings"), }; public static Dialog createNextTip(Context ctx) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext()); for(TipMeta tip : tips) { if(!wasShown(prefs, tip)) { if(tip.isVoid()) { savePref(prefs, tip); return null; } return new TipDialog(ctx, tip); } } return null; } public static void resetAll(Context ctx) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext()); Editor editor = prefs.edit(); for(TipMeta tip : tips) { editor.remove(tip.prefKey); } editor.commit(); } private static boolean wasShown(SharedPreferences prefs, TipMeta tip) { return prefs.getBoolean(tip.prefKey, false); } private static void savePref(SharedPreferences prefs, TipMeta tip) { prefs.edit().putBoolean(tip.prefKey, true).commit(); } private static class TipMeta { final int tipResId; final String prefKey; /** * * @param tipResId use 0 for a void tip (i.e. not displayed but next tip will have to wait for the next time). * @param prefKey */ public TipMeta(int tipResId, String prefKey) { this.tipResId = tipResId; this.prefKey = prefKey; } boolean isVoid() { return tipResId == 0; } } /* Instance */ private final TipMeta tip; private TipDialog(Context context, TipMeta tip) { super(context, R.style.tipDialogFrame); this.tip = tip; setCancelable(false); // View layout = getLayoutInflater().inflate(R.layout.tip_dialog, null); getWindow().setBackgroundDrawable(null); setContentView(R.layout.tip_dialog); TextView text = (TextView)findViewById(R.id.text); text.setText(tip.tipResId); View btn = findViewById(R.id.ok); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext().getApplicationContext()); savePref(prefs, TipDialog.this.tip); dismiss(); } }); } }
public abstract class AClass { int number; public abstract void todoMethod(); @Override public String toString() { this.todoMethod(); return "" + this.number; } }
package de.mineyannik.earthhour; import java.util.Calendar; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.plugin.java.JavaPlugin; /** * * @author mineyannik */ public class EarthHour extends JavaPlugin implements Listener { @Override public void onEnable() { Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { @Override public void run() { if (isEarthHour()) { for (Player p : Bukkit.getOnlinePlayers()) { p.kickPlayer("http://www.earthhour.org"); } } } }, 1200L, 1200L); this.getServer().getPluginManager().registerEvents(this, this); } @EventHandler public void onJoin(PlayerLoginEvent e) { if (isEarthHour()) { e.disallow(PlayerLoginEvent.Result.KICK_OTHER, "http://www.earthhour.org"); } } public boolean isEarthHour() { Calendar d = Calendar.getInstance(); if (d.get(Calendar.DAY_OF_MONTH) == 28 && d.get(Calendar.MONTH) == 2 && d.get(Calendar.YEAR) == 2015) { if (d.get(Calendar.HOUR_OF_DAY) == 20 && d.get(Calendar.MINUTE) >= 30) { return true; } if (d.get(Calendar.HOUR_OF_DAY) == 21 && d.get(Calendar.MINUTE) <= 30) { return true; } } if (d.get(Calendar.DAY_OF_MONTH) == 26 && d.get(Calendar.MONTH) == 2 && d.get(Calendar.YEAR) == 2016) { if (d.get(Calendar.HOUR_OF_DAY) == 20 && d.get(Calendar.MINUTE) >= 30) { return true; } if (d.get(Calendar.HOUR_OF_DAY) == 21 && d.get(Calendar.MINUTE) <= 30) { return true; } } if (d.get(Calendar.DAY_OF_MONTH) == 25 && d.get(Calendar.MONTH) == 2 && d.get(Calendar.YEAR) == 2017) { if (d.get(Calendar.HOUR_OF_DAY) == 20 && d.get(Calendar.MINUTE) >= 30) { return true; } if (d.get(Calendar.HOUR_OF_DAY) == 21 && d.get(Calendar.MINUTE) <= 30) { return true; } } return false; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package byui.cit260.LehisDream.view; import byui.cit260.LehisDream.control.GameControl; import byui.cit260.LehisDream.model.Player; import java.util.Scanner; /** * * @author smith */ public class StartProgramView { private String promptMessage; public StartProgramView() { //promptMessage = "Please enter your name" this.promptMessage = "\nPlease enter your name: "; //display the banner when view is created this.displayBanner(); } public void displayBanner() { System.out.println( "\n**************************************************************" +"\n* *" +"\n* This is the game of Hold to the Rod *" +"\n* In this game you will follow a path to try to make it to *" +"\n* the Tree of Life. The rod represents the word of God. *" +"\n* If you fail to make it to the tree, you *" +"\n* will find yourself at the Great and Spacious Building. *" +"\n* *" +"\n* Along the path, you will encounter challenges and obstacles *" +"\n* where you must decide what to do in situations. You will *" +"\n* need to overcome them in order to advance on the path. If *" +"\n* you run out of energy before you reach the tree, the game *" +"\n* will end and you will end up at the great and spacious *" +"\n* building. *" +"\n* *" +"\n* Good luck in arriving at the Tree of Life. *" +"\n* *" +"\n***************************************************************" ); } public void displayStartProgramView() { boolean done = false;//set flag to not done do{ //prompt for and get players name String playersName = this.getPlayerName(); if (playersName.toUpperCase().equals("Q"))//user wants to quit return;//exit the game //do the requested action and display the next view done = this.doAction(playersName); } while (!done); } private String getPlayerName() { Scanner keyboard = new Scanner(System.in);//get infile for keyboard String value = "";// value to be returned boolean valid = false;// initialize to not valid while (!valid) {// loop while an invalid value is entered System.out.println("\n" + this.promptMessage); value = keyboard.nextLine();// get next line typed on keyboard value = value.trim(); // trim off leading and trailing blanks if (value.length() < 1) {// value is blank System.out.println("\nInvalid value: value can not be blank"); continue; } break; // end the loop } return value; //return the value entered } private boolean doAction(String playersName) { if (playersName.length() < 2){ System.out.println("\nInvalid players name: " + "The name must be greater than one character in length"); return false; } // call createPlayer() control function Player player = GameControl.createPlayer(playersName); if (player == null) {//if unsuccessful System.out.println("\nError creating the player."); return false; } //display next view this.displayNextView(player); return true; //success! } private void displayNextView(Player player) { //display a custom welcome message System.out.println("\n=========================================" + "\n Welcome to the game " + player.getName() + "\n We hope you have a lot of fun!" +"\n=========================================" ); //Create MainMenuView object MainMenuView mainMenuView = new MainMenuView(); //Display the main menu view mainMenuView.displayMainMenuView(); } }
package pt.utl.ist.bw.conditionsinterpreter; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import org.yawlfoundation.yawl.util.PasswordEncryptor; @SuppressWarnings("serial") public class SessionHandler extends ConcurrentHashMap<String, Session>{ private HashMap<String, Client> validUsers = new HashMap<String, Client>(); private static SessionHandler instance; private SessionHandler() { String encriptedPass = PasswordEncryptor.encrypt("datarepositorypass", null); Client dataRep = new Client("datarepository", encriptedPass); this.validUsers.put("datarepository", dataRep); } public static SessionHandler get() { if(instance == null) { instance = new SessionHandler(); } return instance; } public String createNewSession(String username, String pass, long timeout) { Client user= this.validUsers.get(username); if(user == null) { return null; } if(!user.getPassword().equals(pass)) { return null; } Session dataSession = new Session(user, timeout); String handle = dataSession.getHandle(); this.put(handle, dataSession); return handle; } public boolean checkConnection(String handle) { boolean result = false; if(handle != null) { Session dataSession = this.get(handle); if(dataSession != null) { dataSession.resetTimer(); result = true; } } return result; } }
package dev.liambloom.softwareEngineering.chapter14; import java.util.Collections; import java.util.LinkedList; import java.util.Stack; import java.util.Queue; import dev.liambloom.tests.Tester; import dev.liambloom.tests.bjp.*; // Do 7 public class Exercises { @SuppressWarnings("unchecked") public static void main(final String[] args) { final Tester tester = new Tester(Tester.Policy.RunUntilFailure); tester .testAssert(() -> { final Stack<Integer> stack = stackOf(3, -5, 1, 2, -4); splitStack(stack); boolean negative = false; while (!stack.isEmpty()) { if (stack.pop() >= 0) { if (negative) return false; } else negative = true; } return true; }) .testAssert("Test 5", () -> { final Stack<Integer> s1 = stackOf(1, 2, 3); final Stack<Integer> s2 = stackOf(4, 2, 3); return equal(s1, (Stack<Integer>) s1.clone()) && !equal(s1, s2); }) .testAssert("Test 10", () -> { final Stack<Integer> s1 = stackOf(5, 6, 7, 8, 9, 10); final Stack<Integer> s2 = stackOf(7, 8, 9, 10, 12); return isConsecutive(s1) && !isConsecutive(s2) && s1.equals(stackOf(5, 6, 7, 8, 9, 10)) && s2.equals(stackOf(7, 8, 9, 10, 12)); }) .testAssert("Test 15", () -> { final Stack<Integer> s1 = stackOf(20, 20, 17, 11, 8, 8, 3, 2); final Stack<Integer> s2 = stackOf(20, 20, 17, 11, 8, 3, 8, 2); return isSorted(s1) && !isSorted(s2) && s1.equals(stackOf(20, 20, 17, 11, 8, 8, 3, 2)) && s2.equals(stackOf(20, 20, 17, 11, 8, 3, 8, 2)); }) .test("Test 16", () -> { final Stack<Integer> stack = stackOf(10, 53, 19, 24); mirror(stack); return stack; }, stackOf(10, 53, 19, 24, 24, 19, 53, 10)) .test("Test 18", () -> { final Queue<Integer> q = queueOf(10, 50 ,19, 54, 30, 67); mirrorHalves(q); return q; }, queueOf(10, 50, 19, 19, 50, 10, 54, 30, 67, 67, 30, 54)) .test("Test 20", () -> { final var q = queueOf(2, 8, -5, 19, 7, 3, 24, 42); interleave(q); return q; }, queueOf(2, 7, 8, 3, -5, 24, 19, 42)); tester.close(); } @SafeVarargs private static <E> Stack<E> stackOf(final E... elements) { final Stack<E> stack = new Stack<>(); for (final E e : elements) stack.push(e); return stack; } @SafeVarargs private static <E> Queue<E> queueOf(final E... elements) { final Queue<E> queue = new LinkedList<>(); Collections.addAll(queue, elements); return queue; } @Exercise(1) public static void splitStack(final Stack<Integer> stack) { final Queue<Integer> aux = new LinkedList<>(); int lastNegative = 0; for (int i = 0; !stack.isEmpty(); i++) { final Integer e = stack.pop(); if (e < 0) lastNegative = i; aux.add(e); } for (int i = 0; i < lastNegative; i++) { final Integer e = aux.remove(); if (e < 0) stack.push(e); else aux.add(e); } while (!aux.isEmpty()) stack.push(aux.remove()); } @Exercise(5) public static boolean equal(final Stack<Integer> s1, final Stack<Integer> s2) { if (s1.size() != s2.size()) return false; boolean equal = true; final Stack<Integer> aux = new Stack<>(); while (equal && !s1.isEmpty()) { final Integer n1 = s1.pop(); final Integer n2 = s2.pop(); if (!n1.equals(n2)) equal = false; aux.push(n1); aux.push(n2); } while (!aux.isEmpty()) { s2.push(aux.pop()); s1.push(aux.pop()); } return equal; } @Exercise(10) public static boolean isConsecutive(final Stack<Integer> stack) { if (stack.isEmpty()) return true; final Queue<Integer> aux = new LinkedList<>(); while (!stack.isEmpty()) aux.add(stack.pop()); while (!aux.isEmpty()) stack.push(aux.remove()); boolean r = true; Integer prev = stack.pop(); aux.add(prev); while (!stack.isEmpty()) { final Integer next = stack.pop(); aux.add(next); if (prev != next - 1) r = false; prev = next; } while (!aux.isEmpty()) stack.push(aux.remove()); return r; } @Exercise(15) public static boolean isSorted(final Stack<Integer> s) { if (s.isEmpty()) return true; final Stack<Integer> aux = new Stack<>(); Integer prev = s.pop(); aux.push(prev); boolean r = true; while (!s.isEmpty()) { final Integer next = s.pop(); if (prev > next) { r = false; s.push(next); break; } else { aux.push(next); prev = next; } } while (!aux.isEmpty()) s.push(aux.pop()); return r; } @Exercise(16) public static void mirror(final Stack<Integer> s) { final Queue<Integer> aux = new LinkedList<>(); final int size = s.size(); while (!s.isEmpty()) aux.add(s.pop()); for (int i = 0; i < size; i++) { final Integer e = aux.remove(); s.push(e); aux.add(e); } while (!s.isEmpty()) aux.add(s.pop()); for (int i = 0; i < size; i++) aux.add(aux.remove()); while (!aux.isEmpty()) s.push(aux.remove()); } @Exercise(18) public static void mirrorHalves(final Queue<Integer> q) { if (q.size() % 2 != 0) throw new IllegalArgumentException(); final int halfSize = q.size() / 2; mirrorHalf(q, halfSize); mirrorHalf(q, halfSize); } private static void mirrorHalf(final Queue<Integer> q, final int halfSize) { final Stack<Integer> aux = new Stack<>(); for (int i = 0; i < halfSize; i++) { final Integer next = q.remove(); q.add(next); aux.add(next); } while (!aux.isEmpty()) q.add(aux.pop()); } @Exercise(20) public static void interleave(final Queue<Integer> q) { if (q.size() % 2 != 0) throw new IllegalArgumentException(); final Stack<Integer> aux = new Stack<>(); final int size = q.size() / 2; for (int i = 0; i < size; i++) aux.push(q.remove()); while (!aux.isEmpty()) q.add(aux.pop()); for (int i = 0; i < size; i++) q.add(q.remove()); for (int i = 0; i < size; i++) aux.push(q.remove()); for (int i = 0; i < size; i++) { q.add(aux.pop()); q.add(q.remove()); } } }
public class AverageCmd{ public static void main(String [] args){ int bigNum = 0; int smallNum = 2^31; int sum = 0; for(String i : args){ int j = Integer.parseInt(i); if(j > bigNum){ bigNum = j; sum += j; } else if(j < smallNum){ smallNum = j; sum += j; } else{ sum += j; } } System.out.println("Max: " + bigNum); System.out.println("Min " + smallNum); System.out.println("Average: " + sum/args.length); } }
package com.team2915.POWER_UP.TrajectoryGeneration; import com.team2915.POWER_UP.Robot; import jaci.pathfinder.Pathfinder; import jaci.pathfinder.Trajectory; import jaci.pathfinder.Waypoint; public class TrajectoryGenerator { public TrajectoryGenerator(){ } public Trajectory generateTrajectory(){ //I think degrees are in radians Waypoint[] waypoints = new Waypoint[] { new Waypoint(0, 0, 0), new Waypoint(3.048, 0, 0) }; Trajectory.Config config = new Trajectory.Config(Trajectory.FitMethod.HERMITE_CUBIC, Trajectory.Config.SAMPLES_HIGH, 0.05, Robot.smartDashboardManager.velocity_feedforward, Robot.smartDashboardManager.max_acceleration, Robot.smartDashboardManager.max_jerk); Trajectory trajectory = Pathfinder.generate(waypoints, config); return trajectory; } }
class Solution { public int[] countBits(int num) { int[] res = new int[num + 1]; for(int i = 0 ; i <= num; i++){ String number = Integer.toBinaryString(i); int counter = 0; for(int j = 0; j < number.length(); j++){ if(number.charAt(j) == '1') counter++; } res[i] = counter; } return res; } }
/** * @author Johnny Bac * @version 3 * Last updated by: Johnny Bac * Last Date Changed: 4/17/2016 * * Encryption class provides the encrypt and decrypt methods for its subclasses * and allows the user to get and set both the encrypted and unencrypted message. */ public abstract class Encryption { private String message; private String encryptedMessage; /** * Default constructor that sets the data field empty */ public Encryption() { message = ""; encryptedMessage = ""; } /** * Constructor that allows for the message and encryptedMessage to be set * @param aMessage * @param aEncryptedMessage */ public Encryption(String aMessage, String aEncryptedMessage) { message = aMessage; encryptedMessage = aEncryptedMessage; } /** * Gets the unencrypted message. * @return the unencrypted message. */ public String getMessage() { return message; } /** * Sets the message. The message should not be encrypted. * @param aMessage The unencrypted message to be set. */ public void setMessage(String aMessage) { message = aMessage; } /** * Gets the encrypted message * @return the encrypted message */ public String getEncryptedMessage() { return encryptedMessage; } /** * Sets the encrypted message. * @param aEncryptedMessage The encrypted message to be set */ public void setEncryptedMessage(String aEncryptedMessage) { encryptedMessage = aEncryptedMessage; } /** * Abstract method that encrypts the message. Must be implemented * in all subclasses! * * encrypt should call setEncryptedMessage */ public abstract void encrypt() throws CipherException; /** * Abstract method that decrypts the message. Must be implemented * in all subclasses! * * decrypt should call setMessage */ public abstract void decrypt() throws CipherException; } @SuppressWarnings("serial") /** * The CipherException class is a user defined Exception class that is * specifically used for throwing exceptions when invalid input is provided * in the ciphers. * */ class CipherException extends Exception{ public CipherException(String msg) { super(msg); } }
package com.github.fierioziy.particlenativeapi.core; import com.github.fierioziy.particlenativeapi.api.*; import com.github.fierioziy.particlenativeapi.api.utils.ParticleException; import com.github.fierioziy.particlenativeapi.core.asm.ContextASM; import com.github.fierioziy.particlenativeapi.core.asm.mapping.SpigotClassRegistry; import com.github.fierioziy.particlenativeapi.core.asm.mapping.SpigotClassRegistryProvider; import com.github.fierioziy.particlenativeapi.core.asm.mapping.SpigotClassRegistryProviderImpl; import com.github.fierioziy.particlenativeapi.core.asm.particle.ParticleListProvider; import com.github.fierioziy.particlenativeapi.core.asm.utils.InternalResolver; import com.github.fierioziy.particlenativeapi.core.asm.utils.SpigotVersion; import com.github.fierioziy.particlenativeapi.core.utils.ParticleNativeClassLoader; import org.bukkit.plugin.java.JavaPlugin; import java.lang.reflect.Constructor; public class ParticleNativeCore { private final ParticleNativeClassLoader classLoader; private final SpigotClassRegistryProvider spigotClassRegistryProvider; ParticleNativeCore(ParticleNativeClassLoader classLoader, SpigotClassRegistryProvider spigotClassRegistryProvider) { this.classLoader = classLoader; this.spigotClassRegistryProvider = spigotClassRegistryProvider; } /** * <p>Generates particle API based on current server version.</p> * * @param plugin plugin on which class generation should occur. * @return a valid {@link ParticleNativeAPI} instance containing API implementations. * @throws ParticleException if error occurred during classes generation. */ public static ParticleNativeAPI loadAPI(JavaPlugin plugin) throws ParticleException { ClassLoader pluginClassLoader = plugin.getClass().getClassLoader(); ParticleNativeClassLoader classLoader = new ParticleNativeClassLoader(pluginClassLoader); String serverPackageName = plugin.getServer().getClass().getPackage().getName(); String packageVersion = serverPackageName.split("\\.")[3]; SpigotClassRegistryProvider spigotClassRegistryProvider = new SpigotClassRegistryProviderImpl(packageVersion); ParticleNativeCore core = new ParticleNativeCore(classLoader, spigotClassRegistryProvider); return core.setupCore().api; } GenerationResult setupCore() throws ParticleException { try { // obtain necessary info for class generation SpigotClassRegistry classRegistry = spigotClassRegistryProvider.provideRegistry(); InternalResolver resolver = new InternalResolver(classLoader, classRegistry); ContextASM context = new ContextASM(resolver); /* Registers: - ParticlePacket implementation - ParticleType related class implementations - Particles list implementations */ ParticleListProvider particleListProvider = new ParticleListProvider(context); particleListProvider.registerClasses(); Constructor<?> particles_1_8_ctor = particleListProvider .getParticleListASM_1_8() .loadClass() .getConstructor(ParticleNativeAPI.class); Constructor<?> particles_1_13_ctor = particleListProvider .getParticleListASM_1_13() .loadClass() .getConstructor(ParticleNativeAPI.class); Constructor<?> particles_1_19_part_ctor = particleListProvider .getParticleListASM_1_19_part() .loadClass() .getConstructor(ParticleNativeAPI.class); ParticleNativeAPI api = new ParticleNativeAPI_Impl( particles_1_8_ctor, particles_1_13_ctor, particles_1_19_part_ctor); return new GenerationResult(api, context.currentVersion); } catch (Exception e) { throw new ParticleException("Failed to load particle library.", e); } } static class GenerationResult { ParticleNativeAPI api; SpigotVersion spigotVersion; public GenerationResult(ParticleNativeAPI api, SpigotVersion spigotVersion) { this.api = api; this.spigotVersion = spigotVersion; } } }
/* * Copyright 2002-2021 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.messaging.simp.stomp; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.springframework.lang.Nullable; import org.springframework.messaging.Message; import org.springframework.messaging.simp.SimpLogging; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageType; import org.springframework.messaging.support.NativeMessageHeaderAccessor; import org.springframework.util.Assert; /** * An encoder for STOMP frames. * * @author Andy Wilkinson * @author Rossen Stoyanchev * @since 4.0 * @see StompDecoder */ public class StompEncoder { private static final Byte LINE_FEED_BYTE = '\n'; private static final Byte COLON_BYTE = ':'; private static final Log logger = SimpLogging.forLogName(StompEncoder.class); private static final int HEADER_KEY_CACHE_LIMIT = 32; private final Map<String, byte[]> headerKeyAccessCache = new ConcurrentHashMap<>(HEADER_KEY_CACHE_LIMIT); @SuppressWarnings("serial") private final Map<String, byte[]> headerKeyUpdateCache = new LinkedHashMap<>(HEADER_KEY_CACHE_LIMIT, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<String, byte[]> eldest) { if (size() > HEADER_KEY_CACHE_LIMIT) { headerKeyAccessCache.remove(eldest.getKey()); return true; } else { return false; } } }; /** * Encodes the given STOMP {@code message} into a {@code byte[]}. * @param message the message to encode * @return the encoded message */ public byte[] encode(Message<byte[]> message) { return encode(message.getHeaders(), message.getPayload()); } /** * Encodes the given payload and headers into a {@code byte[]}. * @param headers the headers * @param payload the payload * @return the encoded message */ public byte[] encode(Map<String, Object> headers, byte[] payload) { Assert.notNull(headers, "'headers' is required"); Assert.notNull(payload, "'payload' is required"); if (SimpMessageType.HEARTBEAT.equals(SimpMessageHeaderAccessor.getMessageType(headers))) { logger.trace("Encoding heartbeat"); return StompDecoder.HEARTBEAT_PAYLOAD; } StompCommand command = StompHeaderAccessor.getCommand(headers); if (command == null) { throw new IllegalStateException("Missing STOMP command: " + headers); } Result result = new DefaultResult(); result.add(command.toString().getBytes(StandardCharsets.UTF_8)); result.add(LINE_FEED_BYTE); writeHeaders(command, headers, payload, result); result.add(LINE_FEED_BYTE); result.add(payload); result.add((byte) 0); return result.toByteArray(); } private void writeHeaders( StompCommand command, Map<String, Object> headers, byte[] payload, Result result) { @SuppressWarnings("unchecked") Map<String,List<String>> nativeHeaders = (Map<String, List<String>>) headers.get(NativeMessageHeaderAccessor.NATIVE_HEADERS); if (logger.isTraceEnabled()) { logger.trace("Encoding STOMP " + command + ", headers=" + nativeHeaders); } if (nativeHeaders == null) { return; } boolean shouldEscape = (command != StompCommand.CONNECT && command != StompCommand.STOMP && command != StompCommand.CONNECTED); for (Entry<String, List<String>> entry : nativeHeaders.entrySet()) { if (command.requiresContentLength() && "content-length".equals(entry.getKey())) { continue; } List<String> values = entry.getValue(); if ((StompCommand.CONNECT.equals(command) || StompCommand.STOMP.equals(command)) && StompHeaderAccessor.STOMP_PASSCODE_HEADER.equals(entry.getKey())) { values = Collections.singletonList(StompHeaderAccessor.getPasscode(headers)); } byte[] encodedKey = encodeHeaderKey(entry.getKey(), shouldEscape); for (String value : values) { result.add(encodedKey); result.add(COLON_BYTE); result.add(encodeHeaderValue(value, shouldEscape)); result.add(LINE_FEED_BYTE); } } if (command.requiresContentLength()) { int contentLength = payload.length; result.add("content-length:".getBytes(StandardCharsets.UTF_8)); result.add(Integer.toString(contentLength).getBytes(StandardCharsets.UTF_8)); result.add(LINE_FEED_BYTE); } } private byte[] encodeHeaderKey(String input, boolean escape) { String inputToUse = (escape ? escape(input) : input); if (this.headerKeyAccessCache.containsKey(inputToUse)) { return this.headerKeyAccessCache.get(inputToUse); } synchronized (this.headerKeyUpdateCache) { byte[] bytes = this.headerKeyUpdateCache.get(inputToUse); if (bytes == null) { bytes = inputToUse.getBytes(StandardCharsets.UTF_8); this.headerKeyAccessCache.put(inputToUse, bytes); this.headerKeyUpdateCache.put(inputToUse, bytes); } return bytes; } } private byte[] encodeHeaderValue(String input, boolean escape) { String inputToUse = (escape ? escape(input) : input); return inputToUse.getBytes(StandardCharsets.UTF_8); } /** * See STOMP Spec 1.2: * <a href="https://stomp.github.io/stomp-specification-1.2.html#Value_Encoding">"Value Encoding"</a>. */ private String escape(String inString) { StringBuilder sb = null; for (int i = 0; i < inString.length(); i++) { char c = inString.charAt(i); if (c == '\\') { sb = getStringBuilder(sb, inString, i); sb.append("\\\\"); } else if (c == ':') { sb = getStringBuilder(sb, inString, i); sb.append("\\c"); } else if (c == '\n') { sb = getStringBuilder(sb, inString, i); sb.append("\\n"); } else if (c == '\r') { sb = getStringBuilder(sb, inString, i); sb.append("\\r"); } else if (sb != null){ sb.append(c); } } return (sb != null ? sb.toString() : inString); } private StringBuilder getStringBuilder(@Nullable StringBuilder sb, String inString, int i) { if (sb == null) { sb = new StringBuilder(inString.length()); sb.append(inString, 0, i); } return sb; } /** * Accumulates byte content and returns an aggregated byte[] at the end. */ private interface Result { void add(byte[] bytes); void add(byte b); byte[] toByteArray(); } @SuppressWarnings("serial") private static class DefaultResult extends ArrayList<Object> implements Result { private int size; @Override public void add(byte[] bytes) { this.size += bytes.length; super.add(bytes); } @Override public void add(byte b) { this.size++; super.add(b); } @Override public byte[] toByteArray() { byte[] result = new byte[this.size]; int position = 0; for (Object o : this) { if (o instanceof byte[] src) { System.arraycopy(src, 0, result, position, src.length); position += src.length; } else { result[position++] = (Byte) o; } } return result; } } }
/* SelectEvent.java Purpose: Description: History: Thu Jun 16 18:05:51 2005, Created by tomyeh Copyright (C) 2005 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zk.ui.event; import java.util.Set; import java.util.Collections; import java.util.Map; import java.util.List; import org.zkoss.zk.ui.Desktop; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.UiException; import org.zkoss.zk.au.AuRequest; import org.zkoss.zk.au.AuRequests; /** * Represents an event cause by user's the list selection is changed * at the client. * * @author tomyeh */ public class SelectEvent extends Event { private final Set _selectedItems; private final Component _ref; private final int _keys; /** Indicates whether the Alt key is pressed. * It might be returned as part of {@link #getKeys}. */ public static final int ALT_KEY = MouseEvent.ALT_KEY; /** Indicates whether the Ctrl key is pressed. * It might be returned as part of {@link #getKeys}. */ public static final int CTRL_KEY = MouseEvent.CTRL_KEY; /** Indicates whether the Shift key is pressed. * It might be returned as part of {@link #getKeys}. */ public static final int SHIFT_KEY = MouseEvent.SHIFT_KEY; /** Converts an AU request to a select event. * @since 5.0.0 */ public static final SelectEvent getSelectEvent(AuRequest request) { final Map data = request.getData(); final Desktop desktop = request.getDesktop(); return new SelectEvent(request.getCommand(), request.getComponent(), AuRequests.convertToItems(desktop, (List)data.get("items")), desktop.getComponentByUuidIfAny((String)data.get("reference")), AuRequests.parseKeys(data)); } /** Constructs a selection event. * @param selectedItems a set of items that shall be selected. */ public SelectEvent(String name, Component target, Set selectedItems) { this(name, target, selectedItems, null, 0); } /** Constructs a selection event. * @param selectedItems a set of items that shall be selected. */ public SelectEvent(String name, Component target, Set selectedItems, Component ref) { this(name, target, selectedItems, ref, 0); } /** Constructs a selection event. * @param selectedItems a set of items that shall be selected. * @param keys a combination of {@link #CTRL_KEY}, {@link #SHIFT_KEY} * and {@link #ALT_KEY}. * @since 3.6.0 */ public SelectEvent(String name, Component target, Set selectedItems, Component ref, int keys) { super(name, target); _selectedItems = selectedItems != null ? selectedItems: Collections.EMPTY_SET; _ref = ref; _keys = keys; } /** Returns the selected items (never null). */ public final Set getSelectedItems() { return _selectedItems; } /** Returns the reference item that is the component causing the onSelect * event(select or deselect) to be fired. * * <p>It is null, if the onSelect event is not caused by listbox or tree or combobox. * Note: if not multiple, the {@link #getReference} is the same with the first item of {@link #getSelectedItems}. * @since 3.0.2 */ public Component getReference() { return _ref; } /** Returns what keys were pressed when the mouse is clicked, or 0 if * none of them was pressed. * It is a combination of {@link #CTRL_KEY}, {@link #SHIFT_KEY} * and {@link #ALT_KEY}. * @since 3.6.0 */ public final int getKeys() { return _keys; } }
package test; // VO 용도 : 북 클래스에서 다른 클래스들과 메인으로 입력된 값을 출력해주는 용도 public class Book { private String title; private String author; private int page; // 북 클래스에서 사용할 변수를 프라이빗으로 선언 public Book() { super(); } // 북 디폴트 생성자 public Book(String title, String author, int page) { super(); this.title = title; this.author = author; this.page = page; } // 받은 매개변수를 선언한 프라이빗 변수에 담도록 생성자 선언 public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } // 제목 작가 이름을 담을 게터세터 메서드를 만듬 }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package planetsw; import java.util.Scanner; /** * * @author maria */ public class VoucherController { public void AddVoucher(PlanetDB s) { Voucher v=new Voucher(); System.out.println("Enter the name of the voucher: "); Scanner in=new Scanner(System.in); v.setName(in.nextLine()); System.out.println("Enter the ID of the voucher: "); Scanner inn=new Scanner(System.in); v.setID(inn.nextInt()); System.out.println("Enter the value of the voucher: "); Scanner ix=new Scanner(System.in); v.setVal(ix.nextInt()); v.setAvl(true); s.vouchers.add(v); } }
package org.antran.saletax.internal; import org.antran.saletax.api.IAmount; import org.antran.saletax.api.ICart; import org.antran.saletax.api.ICartCalculator; import org.antran.saletax.api.ICartItem; public class MerchandiseTotalCalculator implements ICartCalculator { public IAmount calculate(ICart cart) { IAmount result = Amount.ZERO; for (ICartItem item : cart) { result = result.add(item.product().price()); } return result; } }
/* * Licensed to DuraSpace under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. * * DuraSpace 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.fcrepo.client; import static org.fcrepo.client.MockHttpExpectations.host; import static org.fcrepo.client.MockHttpExpectations.port; import static org.fcrepo.client.TestUtils.TEXT_TURTLE; import static org.fcrepo.client.TestUtils.setField; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Stream; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.NullInputStream; import org.apache.commons.io.output.NullOutputStream; import org.apache.http.HttpClientConnection; import org.apache.http.HttpStatus; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; /** * Integration test used to demonstrate connection management issues with the FcrepoClient. * * @author esm */ @RunWith(MockitoJUnitRunner.class) public class ConnectionManagementTest { /** * Starts a mock HTTP server on a free port */ @Rule public MockServerRule mockServerRule = new MockServerRule(this); // Set by the above @Rule, initialized on @Before via MockHttpExpectations private MockServerClient mockServerClient; /** * URIs that our Mock HTTP server responds to. */ private MockHttpExpectations.SupportedUris uris; /** * Verifies that the expected number of connections have been requested and then closed. * * @param connectionCount the number of connections that have been requested and closed. * @param connectionManager the HttpClientConnectionManager * @return a Consumer that verifies the supplied HttpClientConnectionManager has opened and closed the expected * number of connections. */ private static void verifyConnectionRequestedAndClosed(final int connectionCount, final HttpClientConnectionManager connectionManager) { // A new connection was requested by the Http client ... verify(connectionManager, times(connectionCount)).requestConnection(any(HttpRoute.class), any()); // Verify it was released. verify(connectionManager, times(connectionCount)). releaseConnection(any(HttpClientConnection.class), any(), anyLong(), any(TimeUnit.class)); } /** * Verifies that the expected number of connections have been requested and <em>have not been</em> closed. * * @param connectionCount the number of connections that have been requested. * @param connectionManager the HttpClientConnectionManager */ private static void verifyConnectionRequestedButNotClosed(final int connectionCount, final HttpClientConnectionManager connectionManager) { // A new connection was requested by the Http client ... verify(connectionManager, times(connectionCount)).requestConnection(any(HttpRoute.class), any()); // Verify it was NOT released. verify(connectionManager, times(0)). releaseConnection(any(HttpClientConnection.class), any(), anyLong(), any(TimeUnit.class)); } /** * FcrepoResponse handlers. */ private static class FcrepoResponseHandler { /** * Closes the InputStream that constitutes the response body. */ private static Consumer<FcrepoResponse> closeEntityBody = response -> { try { response.getBody().close(); } catch (final IOException e) { // ignore } }; /** * Reads the InputStream that constitutes the response body. */ private static Consumer<FcrepoResponse> readEntityBody = response -> { assertNotNull("Expected a non-null InputStream.", response.getBody()); try { IOUtils.copy(response.getBody(), NullOutputStream.NULL_OUTPUT_STREAM); } catch (final IOException e) { // ignore } }; } /** * The Fedora Repository client. */ private FcrepoClient client; /** * The Apache HttpClient under test. */ private CloseableHttpClient underTest; /** * The {@link org.apache.http.conn.HttpClientConnectionManager} implementation that the {@link #underTest * HttpClient} is configured to used. */ @Spy private PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); @Before public void setUp() { // Required because we have a test that doesn't close connections, so we have to insure that the // connection manager doesn't block during that test. connectionManager.setDefaultMaxPerRoute(HttpMethods.values().length); // Set up the expectations on the Mock http server new MockHttpExpectations().initializeExpectations(this.mockServerClient, this.mockServerRule.getPort()); // Uris that we connect to, and answered by the Mock http server uris = new MockHttpExpectations.SupportedUris(); // A FcrepoClient configured to throw exceptions when an error is encountered. client = new FcrepoClient(null, null, host + ":" + port, true); // We're testing the behavior of a default HttpClient with a pooling connection manager. underTest = HttpClientBuilder.create().setConnectionManager(connectionManager).build(); // Put our testable HttpClient instance on the FcrepoClient setField(client, "httpclient", underTest); } @After public void tearDown() throws IOException { underTest.close(); } /** * Demonstrates that HTTP connections are released when the FcrepoClient throws an exception. Each method of the * FcrepoClient (get, put, post, etc.) is tested. */ @Test public void connectionReleasedOnException() { // Removing MOVE and COPY operations as the mock server does not handle them final int expectedCount = HttpMethods.values().length - 2; final AtomicInteger actualCount = new AtomicInteger(0); final MockHttpExpectations.Uris uri = uris.uri500; Stream.of(HttpMethods.values()) // MOVE and COPY do not appear to be supported in the mock server .filter(method -> HttpMethods.MOVE != method && HttpMethods.COPY != method) .forEach(method -> { connect(client, uri, method, null); actualCount.getAndIncrement(); }); assertEquals("Expected to make " + expectedCount + " connections; made " + actualCount.get(), expectedCount, actualCount.get()); verifyConnectionRequestedAndClosed(actualCount.get(), connectionManager); } /** * Demonstrates that HTTP connections are released when the user of the FcrepoClient closes the HTTP entity body. * Each method of the FcrepoClient (get, put, post, etc.) is tested. */ @Test public void connectionReleasedOnEntityBodyClose() { final int expectedCount = (int) Stream.of(HttpMethods.values()).filter(m -> m.entity).count(); final AtomicInteger actualCount = new AtomicInteger(0); final MockHttpExpectations.Uris uri = uris.uri200RespBody; Stream.of(HttpMethods.values()) .filter(method -> method.entity) .forEach(method -> { connect(client, uri, method, FcrepoResponseHandler.closeEntityBody); actualCount.getAndIncrement(); }); assertEquals("Expected to make " + expectedCount + " connections; made " + actualCount.get(), expectedCount, actualCount.get()); verifyConnectionRequestedAndClosed(actualCount.get(), connectionManager); } /** * Demonstrates that are connections are released when the user of the FcrepoClient reads the HTTP entity body. */ @Test public void connectionReleasedOnEntityBodyRead() { final int expectedCount = (int) Stream.of(HttpMethods.values()).filter(m -> m.entity).count(); final AtomicInteger actualCount = new AtomicInteger(0); final MockHttpExpectations.Uris uri = uris.uri200RespBody; Stream.of(HttpMethods.values()) .filter(method -> method.entity) .forEach(method -> { connect(client, uri, method, FcrepoResponseHandler.readEntityBody); actualCount.getAndIncrement(); }); assertEquals("Expected to make " + expectedCount + " connections; made " + actualCount.get(), expectedCount, actualCount.get()); verifyConnectionRequestedAndClosed(actualCount.get(), connectionManager); } /** * Demonstrates that are connections are NOT released if the user of the FcrepoClient does not handle the response * body at all. */ @Test public void connectionNotReleasedWhenEntityBodyIgnored() { final int expectedCount = (int) Stream.of(HttpMethods.values()).filter(m -> m.entity).count(); final AtomicInteger actualCount = new AtomicInteger(0); final MockHttpExpectations.Uris uri = uris.uri200RespBody; Stream.of(HttpMethods.values()) .filter(method -> method.entity) .forEach(method -> { connect(client, uri, method, null); actualCount.getAndIncrement(); }); assertEquals("Expected to make " + expectedCount + " connections; made " + actualCount.get(), expectedCount, actualCount.get()); verifyConnectionRequestedButNotClosed(actualCount.get(), connectionManager); } /** * Demonstrates that are connections are released when the FcrepoClient receives an empty response body. */ @Test public void connectionReleasedOnEmptyBody() { final int expectedCount = (int) Stream.of(HttpMethods.values()).filter(m -> m.entity).count(); final AtomicInteger actualCount = new AtomicInteger(0); final MockHttpExpectations.Uris uri = uris.uri200; Stream.of(HttpMethods.values()) .filter(method -> method.entity) .forEach(method -> { connect(client, uri, method, null); actualCount.getAndIncrement(); }); assertEquals("Expected to make " + expectedCount + " connections; made " + actualCount.get(), expectedCount, actualCount.get()); verifyConnectionRequestedAndClosed(actualCount.get(), connectionManager); } /** * Uses the FcrepoClient to connect to supplied {@code uri} using the supplied {@code method}. * This method invokes the supplied {@code responseHandler} on the {@code FcrepoResponse}. * * @param client the FcrepoClient used to invoke the request * @param uri the request URI to connect to * @param method the HTTP method corresponding to the FcrepoClient method invoked * @param responseHandler invoked on the {@code FcrepoResponse}, may be {@code null} */ private void connect(final FcrepoClient client, final MockHttpExpectations.Uris uri, final HttpMethods method, final Consumer<FcrepoResponse> responseHandler) { final NullInputStream nullIn = new NullInputStream(1, true, false); FcrepoResponse response = null; try { switch (method) { case OPTIONS: response = client.options(uri.asUri()).perform(); break; case DELETE: response = client.delete(uri.asUri()).perform(); break; case GET: response = client.get(uri.asUri()).accept(TEXT_TURTLE).perform(); break; case HEAD: response = client.head(uri.asUri()).perform(); break; case PATCH: response = client.patch(uri.asUri()).perform(); break; case POST: response = client.post(uri.asUri()).body(nullIn, TEXT_TURTLE).perform(); break; case PUT: response = client.put(uri.asUri()).body(nullIn, TEXT_TURTLE).perform(); break; case MOVE: response = client.move(uri.asUri(), uri.asUri()).perform(); break; case COPY: response = client.copy(uri.asUri(), uri.asUri()).perform(); break; default: fail("Unknown HTTP method: " + method.name()); } if (uri.statusCode >= HttpStatus.SC_INTERNAL_SERVER_ERROR) { fail("Expected a FcrepoOperationFailedException to be thrown for HTTP method " + method.name()); } } catch (final FcrepoOperationFailedException e) { assertEquals( "Expected request for " + uri.asUri() + " to return a " + uri.statusCode + ". " + "Was: " + e.getStatusCode() + " Method:" + method, uri.statusCode, e.getStatusCode()); } finally { if (responseHandler != null) { responseHandler.accept(response); } } } }
package br.com.rdtecnologia.kafka.producer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringSerializer; import java.time.LocalDateTime; import java.util.Date; import java.util.Properties; public class ProducerTrabalhador { public static void main(String[] args) throws JsonProcessingException, InterruptedException { // create producer properties Properties properties = new Properties(); properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.0.1.119:9092"); properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG , StringSerializer.class.getName()); // create the producer KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties); ObjectMapper mapper = new ObjectMapper(); Trabalhador trabalhador = Trabalhador.builder() .altura(1.85d) .celular("55558855") .circunferencia(10d) .cpf("07750092617") .cracha("x") .dataAlteracao(new Date()) .dataCriacao(new Date()) .email("romero@outlook.com") .genero("M") .id(10l) .nascimento(new Date()) .nome("Romero Gonçalves Dias " + LocalDateTime.now()) .build(); String msg = mapper.writeValueAsString(trabalhador); ProducerRecord<String, String> record = new ProducerRecord<String, String>( "bioimpedancia.trabalhador", msg); // double loop = 200000000000D; //while(loop >= 0) { // send data producer.send(record); // loop--; // System.out.println("sent " + loop); // Thread.sleep(5000); //} //producer.flush(); producer.close(); } }
package de.scads.gradoop_service.server.helper.constructor; import java.util.List; import java.util.Map; import java.util.Objects; import javax.ws.rs.core.Response; import org.gradoop.flink.model.api.epgm.GraphCollection; import org.gradoop.flink.model.api.epgm.LogicalGraph; import org.gradoop.flink.model.impl.functions.epgm.Id; import org.gradoop.flink.model.impl.operators.matching.common.MatchStrategy; import org.gradoop.flink.model.impl.operators.matching.common.statistics.GraphStatistics; import org.gradoop.flink.util.GradoopFlinkConfig; import org.uni_leipzig.biggr.builder.GradoopOperatorConstructor; import org.uni_leipzig.biggr.builder.InvalidSettingsException; public class CypherConstructor implements GradoopOperatorConstructor{ public static final String FORMDATA = "formdata"; /** * {@inheritDoc} */ @Override public Object construct(final GradoopFlinkConfig gfc, final Map<String, Object> arguments, final List<Object> dependencies) throws InvalidSettingsException { LogicalGraph graph = (LogicalGraph)dependencies.get(0); String formdata = (String)arguments.get(FORMDATA); String cypherQuery = ""; String setAttachAttr = ""; String constructionPattern = ""; // formdata has the following structure // option 1: cypher-query=[value1]&cypher-attach-attr=on&cypher-constr-pattern=[value2] // option 2: cypher-query=[value1]&cypher-constr-pattern=[value2] String[] formdataArray = formdata.split("&"); if(formdataArray.length == 2) { String[] cypherQueryArray = formdataArray[0].split("="); // check if argument value is not empty if(cypherQueryArray.length == 2) { cypherQuery = cypherQueryArray[1]; } setAttachAttr = "off"; String[] constructionPatternArray = formdataArray[1].split("="); // check if argument value is not empty if(constructionPatternArray.length == 2) { constructionPattern = constructionPatternArray[1]; } } else { String[] cypherQueryArray = formdataArray[0].split("="); // check if argument value is not empty if(cypherQueryArray.length == 2) { cypherQuery = cypherQueryArray[1]; } setAttachAttr = formdataArray[1].split("=")[1]; String[] constructionPatternArray = formdataArray[2].split("="); // check if argument value is not empty if(constructionPatternArray.length == 2) { constructionPattern = constructionPatternArray[1]; } } // Apparently checkboxes are encoded with "on" and "off" final boolean attachAttr = setAttachAttr.equals("on"); // TODO: Get and store actual GraphStatistics by graphIdentifier GraphStatistics stats = new GraphStatistics(1,1,1,1); if (cypherQuery == null || cypherQuery.isEmpty()) { return Response.status(Response.Status.BAD_REQUEST).build(); } // Making sure to use an empty construction pattern by default. if (Objects.toString(constructionPattern, "").isEmpty()) { constructionPattern = null; } GraphCollection cypher = graph.cypher(cypherQuery, constructionPattern, attachAttr, MatchStrategy.HOMOMORPHISM, MatchStrategy.ISOMORPHISM, stats); LogicalGraph result = graph.getConfig().getLogicalGraphFactory() .fromDataSets(cypher.getVertices().distinct(new Id<>()), cypher.getEdges().distinct(new Id<>())); return result; } }
package lib.hyxen.ui; import android.content.Context; import android.graphics.Bitmap; import android.os.Handler; import android.os.Looper; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.util.ArrayList; /** * Created by redjack on 15/9/16. * * If has 4 items, will create 4 + 2 page: * * Index: 0 1 2 3 4 5 * Item index: 3 0 1 2 3 0 * * first page is to show the last item, last page is to show first item, * so that when user scroll to first page, will has enough time to switch the page last item belong that is page 4. * */ public class LoopingGallery extends PagerAdapter implements ViewPager.OnPageChangeListener { private Context mContext; private ViewPager mViewPager; private Handler mHandler = new Handler(Looper.getMainLooper()); private ArrayList<Bitmap> mImages = new ArrayList<>(0); private int mPosition = 1; private long mLoopingInterval = 7000; public LoopingGallery(Context context, ViewPager viewPager) { this.mContext = context; this.mViewPager = viewPager; viewPager.setAdapter(this); viewPager.addOnPageChangeListener(this); viewPager.setCurrentItem(mPosition); } public LoopingGallery(Context mContext, ViewPager viewPager, ArrayList<Bitmap> images) { this(mContext, viewPager); this.mImages = images; } //region = Control = public void setmImages(ArrayList<Bitmap> mImages) { this.mImages = mImages; mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); mViewPager.setCurrentItem(1); } }); } /** * If has images, then will start lopping, if not won't. * @param second Minimum is 1 second */ public void startLooping(int second) { if (mImages.size() == 0) return; if (second > 1) mLoopingInterval = second * 1000; mHandler.postDelayed(loopingTask, mLoopingInterval); } public void stopLooping() { mHandler.removeCallbacks(loopingTask); } private Runnable loopingTask = new Runnable() { @Override public void run() { if (mHandler != null) { mViewPager.setCurrentItem(mPosition + 1); mHandler.postDelayed(loopingTask, mLoopingInterval); } } }; //endregion //region = On Page Change = @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {} @Override public void onPageSelected(int position) { this.mPosition = position; } @Override public void onPageScrollStateChanged(int state) { if (state != ViewPager.SCROLL_STATE_IDLE) return; int count = mImages.size(); if (mPosition == 0) mViewPager.setCurrentItem(count, false); else if (mPosition == count + 1) mViewPager.setCurrentItem(1, false); } //endregion //region = Adapter = @Override public int getCount() { return mImages.size() > 0 ? mImages.size() + 2 : 0; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { Bitmap img = getImage(position); ImageView imageView = new ImageView(mContext); imageView.setImageBitmap(img); container.addView(imageView); return imageView; } public Bitmap getImage(int position) { int count = mImages.size(); if (position == 0) return mImages.get(count - 1); else if (position == count + 1) return mImages.get(0); else return mImages.get(position - 1); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((ImageView) object); } //endregion }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package recursividad; import java.util.ArrayList; /** * * @author Pablo */ public class Ejemplos { public static void Recursivo(ArrayList ar, int nPos){ if(nPos < ar.size()){ System.out.print(ar.get(nPos)+","); Recursivo(ar, nPos+1); } } public static void Recursivo2(ArrayList ar, int nPos){ if(nPos < ar.size()){ Recursivo2(ar, nPos+1); System.out.print(ar.get(nPos)+","); } } public static void piram(int i, int j){ if(i>0){ System.out.print("*"); piram(--i,j); }else if(j>0){ i=j; System.out.println(""); piram(--i,--j); } } public static void main(String[] args){ ArrayList ar = new ArrayList(); ar.add(1); ar.add(2); ar.add(3); ar.add(4); //Recorrido Iterativo System.out.println("Recorrido Iterativo: "); for(int i = 0; i < ar.size();i++){ System.out.print(""+ar.get(i)+","); } System.out.println(); //Recorrido Recursvo System.out.println("Recorrido Recursivo"); Recursivo(ar, 0); System.out.println(); //Recorrido Recursvo2 System.out.println("Recorrido Recursivo"); Recursivo2(ar, 0); System.out.println(); //Piramide Iterativo System.out.println("Piramide Iterativo\n"); for(int i = 5; i>0;i--){ for(int j = i; j>0;j--){ System.out.print("*"); } System.out.println(); } System.out.println(); //Piramide recursivo System.out.println("Piramide recursivo"); piram(5,5); System.out.println(); } }
package seedu.project.logic.commands; import static seedu.project.logic.commands.CommandTestUtil.VALID_NAME_CP2106; import static seedu.project.logic.commands.CommandTestUtil.VALID_TAG_CP2106; import static seedu.project.logic.commands.CommandTestUtil.VALID_TAG_CS2101; import static seedu.project.logic.commands.CommandTestUtil.assertCommandFailure; import static seedu.project.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.project.testutil.TypicalTasks.getTypicalProjectList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.junit.Test; import seedu.project.logic.CommandHistory; import seedu.project.logic.LogicManager; import seedu.project.model.Model; import seedu.project.model.ModelManager; import seedu.project.model.Name; import seedu.project.model.UserPrefs; import seedu.project.model.project.Project; import seedu.project.model.tag.GroupTag; import seedu.project.model.tag.Tag; public class DefineTagCommandTest { private Model model = new ModelManager(getTypicalProjectList(), new Project(), new UserPrefs()); private Model expectedModel = new ModelManager(getTypicalProjectList(), new Project(), new UserPrefs()); private CommandHistory commandHistory = new CommandHistory(); @Test public void execute_duplicateDefineTag_failure() { model.setProject(model.getFilteredProjectList().get(0)); Set<Tag> sampleTargetSet = new HashSet<Tag>( Arrays.asList(new Tag(VALID_TAG_CS2101), new Tag(VALID_TAG_CP2106))); Name sampleTargetName = new Name(VALID_NAME_CP2106); GroupTag sampleGroupTag = new GroupTag(sampleTargetName, sampleTargetSet); model.addGroupTag(sampleGroupTag); LogicManager.setState(true); DefineTagCommand defineTagCommand = new DefineTagCommand(sampleGroupTag); String expectedMessage = String.format( defineTagCommand.MESSAGE_DUPLICATE_GROUPTAG, sampleGroupTag.getName().toString()); assertCommandFailure(defineTagCommand, model, commandHistory, expectedMessage); } @Test public void execute_validDefineTag_success() { model.setProject(model.getFilteredProjectList().get(0)); expectedModel.setProject(model.getFilteredProjectList().get(0)); Set<Tag> sampleTargetSet = new HashSet<Tag>( Arrays.asList(new Tag(VALID_TAG_CS2101), new Tag(VALID_TAG_CP2106))); Name sampleTargetName = new Name(VALID_NAME_CP2106); GroupTag sampleGroupTag = new GroupTag(sampleTargetName, sampleTargetSet); DefineTagCommand defineTagCommand = new DefineTagCommand(sampleGroupTag); String expectedMessage = String.format(defineTagCommand.SUCCESS_MESSAGE, sampleGroupTag.getName().toString()); expectedModel.addGroupTag(sampleGroupTag); expectedModel.commitProjectList(); assertCommandSuccess(defineTagCommand, model, commandHistory, expectedMessage, expectedModel); } }
package ejercicio07; import java.io.*; /** * * @author Javier */ public class Ejercicio07 { public static void main(String[] args) { File archivo = new File("texto.txt"); String texto = null; FileReader fr = null; try { fr = new FileReader(archivo); BufferedReader br = new BufferedReader(fr); texto = br.readLine(); System.out.println("Texto almacenado en la cadena: " +texto); } catch (Exception e) { System.out.println(e.getMessage()); } finally { if (fr != null) { try { fr.close(); } catch (Exception e) { System.out.println(e); } } } } }
package de.fhdortmund.swt2.pruefungsmeister.Model; import com.google.gson.annotations.Expose; /** * Created by jonas on 22.05.17. */ public class Map { @Expose private MapField[] fields; @Expose private Knot[] knots; @Expose private Edge[] edges; public Map() { fields = new MapField[19]; knots = new Knot[54]; edges = new Edge[72]; for(int i = 0; i < fields.length; i++) { fields[i] = new MapField(); } for(int i = 0; i < knots.length; i++) { knots[i] = new Knot(); } for(int i = 0; i < edges.length; i++) { edges[i] = new Edge(); } knots[0].addMapField(fields[0]); knots[1].addMapField(fields[0]); knots[2].addMapField(fields[0]); knots[8].addMapField(fields[0]); knots[9].addMapField(fields[0]); knots[10].addMapField(fields[0]); knots[2].addMapField(fields[1]); knots[3].addMapField(fields[1]); knots[4].addMapField(fields[1]); knots[10].addMapField(fields[1]); knots[11].addMapField(fields[1]); knots[12].addMapField(fields[1]); knots[4].addMapField(fields[2]); knots[5].addMapField(fields[2]); knots[6].addMapField(fields[2]); knots[12].addMapField(fields[2]); knots[13].addMapField(fields[2]); knots[14].addMapField(fields[2]); knots[7].addMapField(fields[3]); knots[8].addMapField(fields[3]); knots[9].addMapField(fields[3]); knots[17].addMapField(fields[3]); knots[18].addMapField(fields[3]); knots[19].addMapField(fields[3]); knots[9].addMapField(fields[4]); knots[10].addMapField(fields[4]); knots[11].addMapField(fields[4]); knots[19].addMapField(fields[4]); knots[20].addMapField(fields[4]); knots[21].addMapField(fields[4]); knots[11].addMapField(fields[5]); knots[12].addMapField(fields[5]); knots[13].addMapField(fields[5]); knots[21].addMapField(fields[5]); knots[22].addMapField(fields[5]); knots[23].addMapField(fields[5]); knots[13].addMapField(fields[6]); knots[14].addMapField(fields[6]); knots[15].addMapField(fields[6]); knots[23].addMapField(fields[6]); knots[24].addMapField(fields[6]); knots[25].addMapField(fields[6]); knots[16].addMapField(fields[7]); knots[17].addMapField(fields[7]); knots[18].addMapField(fields[7]); knots[27].addMapField(fields[7]); knots[28].addMapField(fields[7]); knots[29].addMapField(fields[7]); knots[18].addMapField(fields[8]); knots[19].addMapField(fields[8]); knots[20].addMapField(fields[8]); knots[29].addMapField(fields[8]); knots[30].addMapField(fields[8]); knots[31].addMapField(fields[8]); knots[20].addMapField(fields[9]); knots[21].addMapField(fields[9]); knots[22].addMapField(fields[9]); knots[31].addMapField(fields[9]); knots[32].addMapField(fields[9]); knots[33].addMapField(fields[9]); knots[22].addMapField(fields[10]); knots[23].addMapField(fields[10]); knots[24].addMapField(fields[10]); knots[33].addMapField(fields[10]); knots[34].addMapField(fields[10]); knots[35].addMapField(fields[10]); knots[24].addMapField(fields[11]); knots[25].addMapField(fields[11]); knots[26].addMapField(fields[11]); knots[35].addMapField(fields[11]); knots[36].addMapField(fields[11]); knots[37].addMapField(fields[11]); knots[28].addMapField(fields[12]); knots[29].addMapField(fields[12]); knots[30].addMapField(fields[12]); knots[38].addMapField(fields[12]); knots[39].addMapField(fields[12]); knots[40].addMapField(fields[12]); knots[30].addMapField(fields[13]); knots[31].addMapField(fields[13]); knots[32].addMapField(fields[13]); knots[40].addMapField(fields[13]); knots[41].addMapField(fields[13]); knots[42].addMapField(fields[13]); knots[32].addMapField(fields[14]); knots[33].addMapField(fields[14]); knots[34].addMapField(fields[14]); knots[42].addMapField(fields[14]); knots[43].addMapField(fields[14]); knots[44].addMapField(fields[14]); knots[34].addMapField(fields[15]); knots[35].addMapField(fields[15]); knots[36].addMapField(fields[15]); knots[44].addMapField(fields[15]); knots[45].addMapField(fields[15]); knots[46].addMapField(fields[15]); knots[39].addMapField(fields[16]); knots[40].addMapField(fields[16]); knots[41].addMapField(fields[16]); knots[47].addMapField(fields[16]); knots[48].addMapField(fields[16]); knots[49].addMapField(fields[16]); knots[41].addMapField(fields[17]); knots[42].addMapField(fields[17]); knots[43].addMapField(fields[17]); knots[49].addMapField(fields[17]); knots[50].addMapField(fields[17]); knots[51].addMapField(fields[17]); knots[43].addMapField(fields[18]); knots[44].addMapField(fields[18]); knots[45].addMapField(fields[18]); knots[51].addMapField(fields[18]); knots[52].addMapField(fields[18]); knots[53].addMapField(fields[18]); knots[0].addEdge(edges[0]); knots[0].addEdge(edges[6]); knots[1].addEdge(edges[0]); knots[1].addEdge(edges[1]); knots[2].addEdge(edges[1]); knots[2].addEdge(edges[2]); knots[2].addEdge(edges[7]); knots[3].addEdge(edges[2]); knots[3].addEdge(edges[3]); knots[4].addEdge(edges[3]); knots[4].addEdge(edges[4]); knots[4].addEdge(edges[8]); knots[5].addEdge(edges[4]); knots[5].addEdge(edges[5]); knots[6].addEdge(edges[5]); knots[6].addEdge(edges[9]); knots[7].addEdge(edges[10]); knots[7].addEdge(edges[18]); knots[8].addEdge(edges[6]); knots[8].addEdge(edges[10]); knots[8].addEdge(edges[11]); knots[9].addEdge(edges[11]); knots[9].addEdge(edges[12]); knots[9].addEdge(edges[19]); knots[10].addEdge(edges[7]); knots[10].addEdge(edges[12]); knots[10].addEdge(edges[13]); knots[11].addEdge(edges[13]); knots[11].addEdge(edges[14]); knots[11].addEdge(edges[20]); knots[12].addEdge(edges[8]); knots[12].addEdge(edges[14]); knots[12].addEdge(edges[15]); knots[13].addEdge(edges[15]); knots[13].addEdge(edges[16]); knots[13].addEdge(edges[21]); knots[14].addEdge(edges[9]); knots[14].addEdge(edges[16]); knots[14].addEdge(edges[17]); knots[15].addEdge(edges[17]); knots[15].addEdge(edges[22]); knots[16].addEdge(edges[23]); knots[16].addEdge(edges[33]); knots[17].addEdge(edges[18]); knots[17].addEdge(edges[23]); knots[17].addEdge(edges[24]); knots[18].addEdge(edges[24]); knots[18].addEdge(edges[25]); knots[18].addEdge(edges[34]); knots[19].addEdge(edges[19]); knots[19].addEdge(edges[25]); knots[19].addEdge(edges[26]); knots[20].addEdge(edges[26]); knots[20].addEdge(edges[27]); knots[20].addEdge(edges[35]); knots[21].addEdge(edges[20]); knots[21].addEdge(edges[27]); knots[21].addEdge(edges[28]); knots[22].addEdge(edges[28]); knots[22].addEdge(edges[29]); knots[22].addEdge(edges[36]); knots[23].addEdge(edges[21]); knots[23].addEdge(edges[29]); knots[23].addEdge(edges[30]); knots[24].addEdge(edges[30]); knots[24].addEdge(edges[31]); knots[24].addEdge(edges[37]); knots[25].addEdge(edges[22]); knots[25].addEdge(edges[31]); knots[25].addEdge(edges[32]); knots[26].addEdge(edges[32]); knots[26].addEdge(edges[38]); knots[27].addEdge(edges[33]); knots[27].addEdge(edges[39]); knots[28].addEdge(edges[39]); knots[28].addEdge(edges[40]); knots[28].addEdge(edges[49]); knots[29].addEdge(edges[34]); knots[29].addEdge(edges[40]); knots[29].addEdge(edges[41]); //------ knots[30].addEdge(edges[41]); knots[30].addEdge(edges[42]); knots[30].addEdge(edges[50]); knots[31].addEdge(edges[35]); knots[31].addEdge(edges[42]); knots[31].addEdge(edges[43]); knots[32].addEdge(edges[43]); knots[32].addEdge(edges[44]); knots[32].addEdge(edges[51]); knots[33].addEdge(edges[36]); knots[33].addEdge(edges[44]); knots[33].addEdge(edges[45]); knots[34].addEdge(edges[45]); knots[34].addEdge(edges[46]); knots[34].addEdge(edges[52]); knots[35].addEdge(edges[37]); knots[35].addEdge(edges[46]); knots[35].addEdge(edges[47]); knots[36].addEdge(edges[47]); knots[36].addEdge(edges[48]); knots[36].addEdge(edges[53]); knots[37].addEdge(edges[38]); knots[37].addEdge(edges[48]); knots[38].addEdge(edges[49]); knots[38].addEdge(edges[54]); knots[39].addEdge(edges[54]); knots[39].addEdge(edges[55]); knots[39].addEdge(edges[62]); knots[40].addEdge(edges[50]); knots[40].addEdge(edges[55]); knots[40].addEdge(edges[56]); knots[41].addEdge(edges[56]); knots[41].addEdge(edges[57]); knots[41].addEdge(edges[63]); knots[42].addEdge(edges[51]); knots[42].addEdge(edges[57]); knots[42].addEdge(edges[58]); knots[43].addEdge(edges[58]); knots[43].addEdge(edges[59]); knots[43].addEdge(edges[64]); knots[44].addEdge(edges[52]); knots[44].addEdge(edges[59]); knots[44].addEdge(edges[60]); knots[45].addEdge(edges[60]); knots[45].addEdge(edges[61]); knots[45].addEdge(edges[65]); knots[46].addEdge(edges[53]); knots[46].addEdge(edges[61]); knots[47].addEdge(edges[62]); knots[47].addEdge(edges[66]); knots[48].addEdge(edges[66]); knots[48].addEdge(edges[67]); knots[49].addEdge(edges[63]); knots[49].addEdge(edges[67]); knots[49].addEdge(edges[68]); knots[50].addEdge(edges[68]); knots[50].addEdge(edges[69]); knots[51].addEdge(edges[64]); knots[51].addEdge(edges[69]); knots[51].addEdge(edges[70]); knots[52].addEdge(edges[70]); knots[52].addEdge(edges[71]); knots[53].addEdge(edges[65]); knots[53].addEdge(edges[71]); //TODO Ressourcen besser verteilen for(int i = 0; i < fields.length; i++) { MapField field = fields[i]; int value = (int) (Math.random() * 5); Resource resource = null; switch (value) { case 0: resource = Resource.ENERGYDRINK; break; case 1: resource = Resource.FASTFOOD; break; case 2: resource = Resource.EXTRA_POINTS; break; case 3: resource = Resource.KNOW_HOW; break; case 4: resource = Resource.TECHNOLOGY; break; default: break; } field.setResource(resource); field.setRandomValue((int)((Math.random() * 11) + 2)); System.out.format("Feld %d hat die Ressource %s und den Zufallswert %d%n", i, resource.toString(), field.getRandomValue()); } } public MapField[] getFields() { return fields; } public Knot[] getKnots() { return knots; } public Edge[] getEdges() { return edges; } }
package com.esum.comp.tcpip.outbound; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.comp.tcpip.TCPIPCode; import com.esum.framework.core.component.listener.channel.ChannelMessageListener; import com.esum.framework.core.event.log.ErrorInfo; import com.esum.framework.core.event.message.MessageEvent; import com.esum.framework.core.exception.SystemException; public class TCPIPInputChannelListener extends ChannelMessageListener<MessageEvent> { private Logger log = LoggerFactory.getLogger(TCPIPInputChannelListener.class); public TCPIPInputChannelListener(String componentId, String channelName) throws SystemException { super(componentId, channelName); } public MessageEvent onEvent(MessageEvent messageEvent) { traceId = "[" + messageEvent.getMessageControlId() + "] "; log.info(traceId + "onMessageEvent Process...."); try { TCPIPOutboundHandler handler = new TCPIPOutboundHandler(getComponentId()); handler.process(messageEvent); return handler.processResponse(messageEvent); } catch (Exception e) { log.error(traceId + "onMessageEvent()", e); ErrorInfo errorInfo = new ErrorInfo(TCPIPCode.ERROR_UNDEFINED, "onMessageEvent()", e.getMessage()); messageEvent.getMessage().getHeader().setErrorInfo(errorInfo); return messageEvent; } } }
package math; public interface Vec<T extends Vec<T>>{ }
package com.example.BankOperation.service; import com.example.BankOperation.model.Card; import com.example.BankOperation.model.Payment; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import javax.validation.ConstraintViolation; import java.util.Set; @Service public class PaymentValidator implements org.springframework.validation.Validator { @Autowired private Validator validator; @Override public boolean supports(Class<?> aClass) { return Card.class.equals(aClass); } @Override public void validate(Object o, Errors errors) { Set<ConstraintViolation<Object>> validates = validator.validate(obj); for (ConstraintViolation<Object> constraintViolation : validates) { String propertyPath = constraintViolation.getPropertyPath().toString(); String message = constraintViolation.getMessage(); errors.rejectValue(propertyPath, "", message); } Card c = (Payment) obj; if (c.getBalance() < 0) { errors.rejectValue("balance - ", "only '+'balance"); } } }
package com.gezhiwei.projectstart.controller; import com.alibaba.fastjson.JSONObject; import com.gezhiwei.projectstart.common.DirConfig; import com.gezhiwei.projectstart.common.TemplateConfig; import com.gezhiwei.projectstart.controller.vo.ProjectInfoVo; import com.gezhiwei.projectstart.service.ICreateProjectService; import org.apache.commons.lang3.StringUtils; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Zip; import org.apache.tools.ant.types.ZipFileSet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.util.FileSystemUtils; import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * @ClassName: MainController * @Author: 葛志伟(赛事) * @Description: * @Date: 2019/1/8 11:17 * @modified By: */ @RestController public class MainController { private transient Map<String, List<File>> temporaryFiles = new LinkedHashMap<>(); @Autowired private ICreateProjectService iCreateProjectService; //创建一个项目直接打到 github上 @RequestMapping("/start/project") public ResponseEntity<byte[]> startNewProject(String params) throws IOException { ProjectInfoVo projectInfoVo = JSONObject.parseObject(params, ProjectInfoVo.class); File dir = iCreateProjectService.initDir(); String packageName = projectInfoVo.getGroupId() + "." + projectInfoVo.getArtifactId().replaceAll("-", ""); String applicationName = StringUtils.capitalize(projectInfoVo.getArtifactId().replaceAll("-", "")); String mysqlUrl = projectInfoVo.getMysqlUrl(); String mysqlUser = projectInfoVo.getMysqlUser(); String mysqlPassword = projectInfoVo.getMysqlPassword(); String groupId = projectInfoVo.getGroupId(); String artifactId = projectInfoVo.getArtifactId(); String projectName = projectInfoVo.getArtifactId(); TemplateConfig templateConfig = new TemplateConfig(packageName, applicationName, mysqlUrl, mysqlUser, mysqlPassword, groupId, artifactId); DirConfig dirConfig = new DirConfig(projectName, packageName); File projectDir = iCreateProjectService.createProjectDir(dir, templateConfig, dirConfig); File download = new File(dir, projectDir.getName() + ".zip"); addTempFile(dir.getName(), download); Zip zip = new Zip(); zip.setProject(new Project()); zip.setDefaultexcludes(false); ZipFileSet set = new ZipFileSet(); set.setDir(projectDir); set.setIncludes("**,"); set.setDefaultexcludes(false); zip.addFileset(set); zip.setDestFile(download.getCanonicalFile()); zip.execute(); return upload(download, dir, generateFileName(artifactId, "zip"), "application/zip"); } private void addTempFile(String group, File file) { this.temporaryFiles.computeIfAbsent(group, (key) -> new ArrayList<>()).add(file); } private static String generateFileName(String artifactId, String extension) { String tmp = artifactId.replaceAll(" ", "-"); try { return URLEncoder.encode(tmp, "UTF-8") + "." + extension; } catch (UnsupportedEncodingException ex) { throw new IllegalStateException("Cannot encode URL", ex); } } private ResponseEntity<byte[]> upload(File download, File dir, String fileName, String contentType) throws IOException { try (FileInputStream fileInputStream = new FileInputStream(download)) { byte[] bytes = StreamUtils.copyToByteArray(fileInputStream); ResponseEntity<byte[]> result = createResponseEntity(bytes, contentType, fileName); cleanTempFiles(dir); // Files.delete(Paths.get(dir.getPath())); return result; } catch (Exception e) { e.printStackTrace(); } return null; } private ResponseEntity<byte[]> createResponseEntity(byte[] content, String contentType, String fileName) { String contentDispositionValue = "attachment; filename=\"" + fileName + "\""; return ResponseEntity .ok() .header("Content-Type", contentType) .header("Content-Disposition", contentDispositionValue) .body(content); } /** * Clean all the temporary files that are related to this root directory. * * @param dir the directory to clean * @see #createDistributionFile */ public void cleanTempFiles(File dir) { List<File> tempFiles = this.temporaryFiles.remove(dir.getName()); if (!tempFiles.isEmpty()) { tempFiles.forEach((File file) -> { if (file.isDirectory()) { FileSystemUtils.deleteRecursively(file); } else if (file.exists()) { file.delete(); } }); } } }
public class BinarySearchTree { public static void main(String[] args){ BinaryTree tree = new BinaryTree(); tree.insert_node(5); tree.insert_node(10); tree.insert_node(2); tree.insert_node(-2); tree.insert_node(3); tree.insert_node(7); tree.insert_node(12); tree.print(); //node to hold the result Tree res; try { res = tree.search(0); System.out.println("\n\n" + res.data); } catch(NullPointerException e){ System.out.println("\n\nElement was not found."); } //tree.remove(2); tree.remove(10); tree.remove(2); tree.remove(5); tree.print(); tree.insert_node(19); tree.insert_node(25); tree.insert_node(-23); tree.insert_node(-45); tree.print(); } }