text
stringlengths
10
2.72M
/* * Copyright 2017 Goldman Sachs. * 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.gs.tablasco.verify; import com.gs.tablasco.verify.indexmap.IndexMapTableVerifier; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SingleTableVerifierMinBestMatchThresholdTest extends AbstractSingleTableVerifierTest { @Override protected IndexMapTableVerifier createSingleTableVerifier(ColumnComparators columnComparators) { return new IndexMapTableVerifier(columnComparators, true, 1, false, false); } @Override protected List<List<ResultCell>> getExpectedVerification(String methodName) { return ROW_KEY_VERIFICATIONS.get(methodName); } static final Map<String, List<List<ResultCell>>> ROW_KEY_VERIFICATIONS; static { ROW_KEY_VERIFICATIONS = new HashMap<>(SingleTableVerifierMaxBestMatchThresholdTest.MAX_BEST_MATCH_THRESHOLD); addVerification("adaptiveMatcherLeavesLeastUnmatchedRows", row(pass("Col 1"), pass("Col 2"), pass("Col 3")), row(pass("A"), pass("A"), fail("0", "1")), row(pass("A"), pass("A"), fail("2", "3")), row(pass("B"), pass("A"), fail("0", "1")), row(pass("C"), pass("B"), fail("0", "1")), row(pass("D"), pass("B"), fail("0", "1")), row(pass("E"), pass("C"), fail("0", "1")), row(surplus("X"), surplus("C"), surplus("0")), row(missing("Y"), missing("C"), missing("1")), row(surplus("X"), surplus("X"), surplus("0")), row(missing("Y"), missing("Y"), missing("1")) ); } private static void addVerification(String testName, List<ResultCell>... rows) { ROW_KEY_VERIFICATIONS.put(testName, Arrays.asList(rows)); } }
package am.bizis.cds.exchange; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import am.bizis.exception.ResponseException; /** * ResponseParser overi vystup podatelny EPO * @author alex */ public class ResponseParser { private final Document RESPONSE; /** * Vytvori response parser s XML docem, ktery jsme ziskali od serveru * @param response odpoved CDS MFCR */ public ResponseParser(Document response){ this.RESPONSE=response; } /** * Zjistime, zda jsou v nasem podani chyby * @return jsou-li v nasem podani chyby (true - podani je s chybou) */ private boolean error(){ if(RESPONSE.getDocumentElement().getNodeName().equals("Chyby")) return true; else return false; } /** * Vrati vyjimku s obsah vsech chyb v podani * @throws ResponseException chyby v podani naparsovane do jednoho stringu */ public void reportErr() throws ResponseException{ if(error()){ NodeList nl=RESPONSE.getElementsByTagName("Chyba"); String report=""; for(int i=0;i<nl.getLength();i++){ Node n=nl.item(i); NamedNodeMap attr=n.getAttributes(); Node polozka=attr.getNamedItem("Polozka"); if(polozka!=null)report+="Polozka: "+polozka.getNodeValue()+", "; Node m=n.getChildNodes().item(0); if(m.getNodeName().equals("Text")) report+="Chyba: "+m.getTextContent()+"\n"; } throw new ResponseException(report); } } }
package com.example.organizations.domain; import org.springframework.data.jpa.domain.Specification; import javax.persistence.criteria.Predicate; /* Класс с реализацией Spring Data JPA Specification для поиска записей по нескольким условиям */ public class OrganizationSpecs { public static Specification<Organization> getOrganizationsByTaxAndRegAndNameAndRegionAndCityAndAddress(String tax, String reg, String name, String region, String city, String address) { return Specification.where(getOrganizationsByTax(tax)).and(getOrganizationsByReg(reg)).and(getOrganizationsByName(name)).and(getOrganizationsByRegion(region)).and(getOrganizationsByCity(city)).and(getOrganizationsByAddress(address)); } public static Specification<Organization> getOrganizationsByTax(String tax) { return (root, query, criteriaBuilder) -> { Predicate likePredicate = criteriaBuilder.like(root.get("tax"), tax.replace("*", "%")); return likePredicate; }; } public static Specification<Organization> getOrganizationsByReg(String reg) { return (root, query, criteriaBuilder) -> { Predicate likePredicate = criteriaBuilder.like(root.get("reg"), reg.replace("*", "%")); return likePredicate; }; } public static Specification<Organization> getOrganizationsByName(String name) { return (root, query, criteriaBuilder) -> { Predicate likePredicate = criteriaBuilder.like(root.get("name"), name.replace("*", "%")); return likePredicate; }; } public static Specification<Organization> getOrganizationsByRegion(String region) { return (root, query, criteriaBuilder) -> { Predicate likePredicate = criteriaBuilder.like(root.get("region"), region.replace("*", "%")); return likePredicate; }; } public static Specification<Organization> getOrganizationsByCity(String city) { return (root, query, criteriaBuilder) -> { Predicate likePredicate = criteriaBuilder.like(root.get("city"), city.replace("*", "%")); return likePredicate; }; } public static Specification<Organization> getOrganizationsByAddress(String address) { return (root, query, criteriaBuilder) -> { Predicate likePredicate = criteriaBuilder.like(root.get("address"), address.replace("*", "%")); return likePredicate; }; } }
package com.sunny.netty.chat.server.handler; /** * <Description> <br> * * @author Sunny<br> * @version 1.0<br> * @taskId: <br> * @createDate 2018/10/27 14:07 <br> * @see com.sunny.netty.chat.server.handler <br> */ import com.sunny.netty.chat.protocol.request.LogoutRequestPacket; import com.sunny.netty.chat.protocol.response.LogoutResponsePacket; import com.sunny.netty.chat.util.SessionUtil; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; /** * 登出请求 */ @ChannelHandler.Sharable public class LogoutRequestHandler extends SimpleChannelInboundHandler<LogoutRequestPacket> { public static final LogoutRequestHandler INSTANCE = new LogoutRequestHandler(); protected LogoutRequestHandler() { } @Override protected void channelRead0(ChannelHandlerContext ctx, LogoutRequestPacket msg) { SessionUtil.unBindSession(ctx.channel()); LogoutResponsePacket logoutResponsePacket = new LogoutResponsePacket(); logoutResponsePacket.setSuccess(true); ctx.channel().writeAndFlush(logoutResponsePacket); } }
package com.tc.nfc.manager; import android.os.AsyncTask; import android.util.Log; import com.tc.nfc.app.utils.StringToOther; import com.tc.nfc.util.Demand; /** * Created by xiansize on 2017/12/19. */ public class UhfManager { private boolean readFlag = true; private AsyncTask<Void,Void,String> asyncTask; private String oldBarcode = ""; private ReadingListner readingListner; private com.handheld.UHF.UhfManager uhfManager; private byte[] password ; public UhfManager() { uhfManager = com.handheld.UHF.UhfManager.getInstance(); uhfManager.setOutputPower(16); password = StringToOther.HexString2Bytes("00000000"); } public void setReadFlag(boolean readFlag) { this.readFlag = readFlag; } public void setOldBarcode(String oldBarcode) { this.oldBarcode = oldBarcode; } public void setReadingListner(ReadingListner readingListner) { this.readingListner = readingListner; } public void readBarcode(){ asyncTask = new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { return readUhfBarcode(); } @Override protected void onPostExecute(String barcode) { if(!"".equals(barcode)){ readingListner.readGetBarcode(barcode); } } }; asyncTask.execute(); } private String readUhfBarcode(){ while (readFlag){ byte[] data = uhfManager.readFrom6C(com.handheld.UHF.UhfManager.EPC,2,6,password); if (data != null && data.length > 1) { String dataStr = StringToOther.Bytes2HexString(data, data.length); Log.d("UHF",dataStr); String barcode = Demand.getTransferBarcode(dataStr); if(!barcode.equals(oldBarcode)){ oldBarcode = barcode; return barcode; }else{ Log.d("test","simple tag"); } } } return ""; } public interface ReadingListner{ void readGetBarcode(String barcode); } }
import java.io.*; public class test { int num = 1; }
package de.domistiller.vp.android; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.ArrayList; public class SectionsPagerAdapter extends FragmentPagerAdapter { private ArrayList<String> dates = null; public SectionsPagerAdapter(FragmentManager fm) { super(fm); try { dates = DataProvider.getInstance().getDates(); } catch (Exception e) { e.printStackTrace(); } } @Override public Fragment getItem(int i) { Fragment fragment = new DateEntryFragment(); Bundle args = new Bundle(); args.putString(DateEntryFragment.ARG_DATE, dates.get(i)); fragment.setArguments(args); return fragment; } @Override public int getCount() { return dates.size(); } public CharSequence getPageTitle(int position) { return dates.get(position); } }
package at.sync.test; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Synchronisation Test * Created by florianmathis on 14/01/16. */ public class SynchronisationTest { @Before public void setUp() throws Exception { } /** * Start a sync task with empty database * - no updates are performed, only inserts */ @Test public void syncRegionEmptyDatabase() { int value = 100; assertEquals(100, value); } }
package com.dalmirdasilva.androidmessagingprotocol.device.message; import android.util.Log; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; /** * Responsible to parse incoming bytes and to buikd a @See{Message} */ public class MessageParser { private static final String TAG = "MessageParser"; public enum State { INITIAL, START_OF_MESSAGE_MARK_PARSED, ID_PARSED, TYPE_PARSED, FLAGS_PARSED, PAYLOAD_LENGTH_PARSED, PAYLOAD_PARSED, END_OF_MESSAGE_MARK_PARSED } private List<Byte> raw; private State state; private int payloadLength; private Queue<Message> messageQueue; public MessageParser() { this.messageQueue = new ArrayDeque<>(); resetState(); } public void resetState() { state = State.INITIAL; } public State getState() { return state; } /** * Parses a array of bytes. * <p> * It return the number of parsed bytes. After a message is decoded, it stores the message * in the message queue and keeps parsing towards the next message. * <p> * If the number of parsed bytes is less than the received array, it means an error occurred * while parsing the array of bytes. * * @param bytes * @return */ public int parse(byte[] bytes) { int i; for (i = 0; i < bytes.length; i++) { if (!parse(bytes[i])) { break; } } return i; } /** * The state machine will stop and @See{resetState} needs to be called to reset the machine. * * @param b * @return */ private boolean parse(byte b) { Log.d(TAG, "Parsing: 0x" + Integer.toHexString(b & 0xff)); boolean ingested = true; switch (state) { case INITIAL: if (b == Message.START_MESSAGE_MARK) { raw = new ArrayList<>(); state = State.START_OF_MESSAGE_MARK_PARSED; } else { Log.d(TAG, "State is INITIAL but START_MESSAGE_MARK mismatches."); ingested = false; } break; case START_OF_MESSAGE_MARK_PARSED: state = State.ID_PARSED; break; case ID_PARSED: state = State.TYPE_PARSED; break; case TYPE_PARSED: state = State.FLAGS_PARSED; break; case FLAGS_PARSED: state = State.PAYLOAD_LENGTH_PARSED; payloadLength = b; // If the message has no payload, jump straight to PAYLOAD_PARSED state. if (payloadLength <= 0) { state = State.PAYLOAD_PARSED; } break; case PAYLOAD_LENGTH_PARSED: if (--payloadLength == 0) { state = State.PAYLOAD_PARSED; } break; case PAYLOAD_PARSED: if (b == Message.END_MESSAGE_MARK) { state = State.END_OF_MESSAGE_MARK_PARSED; enqueueDecodedMessage(); } else { Log.d(TAG, "State is PAYLOAD_PARSED but END_MESSAGE_MARK mismatches."); ingested = false; } break; case END_OF_MESSAGE_MARK_PARSED: Log.d(TAG, "Message was fully parsed and wasn't yet retrieved, but more data is coming."); ingested = false; break; } if (ingested) { raw.add(b); } return ingested; } public boolean wasMessageDecoded() { return this.messageQueue.size() > 0; } public Message collectDecodedMessage() { Message message = null; if (messageQueue.size() > 0) { message = messageQueue.poll(); } return message; } private void enqueueDecodedMessage() { Message message = instantiateDecodedMessage(); messageQueue.offer(message); resetState(); } private Message instantiateDecodedMessage() { Message message = MessageFactory.newMessageFromType(raw.get(Message.TYPE_POS)); message.setId(raw.get(Message.ID_POS)); message.setFlags(raw.get(Message.FLAGS_POS)); List<Byte> payload = raw.subList(Message.PAYLOAD_POS, Message.PAYLOAD_POS + payloadLength); Byte[] bytes = payload.toArray(new Byte[payloadLength]); message.setPayload(bytes); return message; } }
package se.kth.iv1350.amazingpos.controller; import static org.junit.jupiter.api.Assertions.*; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.kth.iv1350.amazingpos.integration.*; import se.kth.iv1350.amazingpos.model.*; class ControllerTest { private ByteArrayOutputStream printoutContent; private PrintStream originalSysOut; private Controller instance; @BeforeEach public void setUp() { originalSysOut = System.out; printoutContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(printoutContent)); instance = new Controller(new SystemCreator(), new RegistryCreator(),new PaymentCreator()); instance.startSale(); } @AfterEach public void tearDown() { printoutContent = null; System.setOut(originalSysOut); instance = null; } @Test public void testStartSale() { instance.startSale(); } @Test public void testTrueScanItem() { String itemId = "apple"; int quantity = 4; String actualResult = instance.scanItem(itemId, quantity); String expResult = ""+itemId+" \tquantity: "+quantity+" \ttaxRate: 4 \tprice: 8 ";; assertTrue(actualResult.contains(expResult),"Wrong printout."); } @Test public void testFalseScanItem() { String itemId = "ap ple"; // Wrong itemID int quantity = 4; String actualResult = instance.scanItem(itemId, quantity); String expResult = ""+itemId+" \tquantity: "+quantity+" \ttaxRate: 4 \tprice: 8 "; assertFalse(actualResult.contains(expResult),"Wrong printout."); } @Test public void testUnavailableItemScanItem() { String itemId = "car"; // unavailable item int quantity = 4; String actualResult = instance.scanItem(itemId, quantity); String expResult = "this item is unavailable or invalid!"; assertEquals(expResult, actualResult," this item is available."); } @Test public void testShowTotalPriceAndVAT() { String itemId = "apple"; int quantity = 4; instance.scanItem(itemId, quantity); int taxRate = 1; int price = 1; String expResult = "total VAT: " + (quantity*taxRate) +"\t total price: "+((quantity*price)+(quantity*taxRate)); String actualResult = instance.showTotalPriceAndVAT(); assertEquals(expResult, actualResult,"Wrong printout of total price and total VAT."); assertTrue(actualResult.contains(expResult),"Wrong printout of total price and total VAT."); } @Test public void testDiscount() { String customerID = "11111"; instance.discount(customerID); double discountRate = instance.getSale().getDiscountRate()*100; String expResult = "discount rate: "+((int)discountRate)+"%\n"; String actualResult = printoutContent.toString(); assertEquals(expResult, actualResult,"Wrong printout of discount rate."); assertTrue(actualResult.contains(expResult),"Wrong printout of discount rate."); } @Test public void testDiscountWithWrongCustomerID() { String customerID = "00000"; // Wrong customerID instance.discount(customerID); String expResult ="this customer's ID does not exist"; String actualResult = printoutContent.toString(); assertTrue(actualResult.contains(expResult),"Wrong printout of discount rate."); } @Test public void testPay() { String itemId = "apple"; int quantity = 4; instance.scanItem(itemId, quantity); int taxRate = 1; int price = 1; instance.showTotalPriceAndVAT(); String customerID = "11111"; instance.discount(customerID); Sale sale = instance.getSale(); double discountRate = instance.getSale().getDiscountRate()*100; instance.pay(new Amount(100)); String expResult = "discount rate: "+((int)discountRate)+"%\n"+ "---------------------RECEIPT---------------------\n"+ sale.setTimeOfSale().toLocalDate().toString() + "\nItems: "+ "\n"+itemId + " \t" +"quantity: " + quantity + " \t"+ "taxRate: " + (price*taxRate*quantity) + " \t"+ "price: " + ((quantity*price)+(price*taxRate*quantity)) +" \t"+ "\ntotal price include discount: "+ sale.getTotalPriceAfterDiscount()+" kr"+ "\ndiscount amount: "+ sale.getDiscountAmount()+" kr"+ "\n----------------------END----------------------\n"; String actualResult = printoutContent.toString(); assertTrue(actualResult.contains(expResult), "Wrong instance of itemId, customerID or paid amount, check if instances are correct."); assertTrue(actualResult.contains(itemId),"Wrong itemId."); assertTrue(actualResult.contains(Integer.toString((int)discountRate)),"Wrong customerID."); assertTrue(actualResult.contains(Double.toString(sale.getDiscountAmount())),"Wrong customerID."); } }
package 飞毛腿外卖团; import java.awt.*; import java.awt.event.*; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.swing.*; import javax.swing.table.JTableHeader; //查询订单界面 public class QueryOrder { long userId; JFrame f; JButton but; JTable jt; JLabel jl; JPanel jp1,jp2,jp3; public QueryOrder(long userId) { this.userId = userId; init(); } public void init() { f = new JFrame("订单查询"); f.setBounds(380, 180, 730, 370); f.setResizable(false); jp1 = new JPanel(); jp2 = new JPanel(); jp3 = new JPanel(); f.setResizable(false); but = new JButton("确定"); jl = new JLabel("<html><font size = '14'> 订 单 明 细<font> <br><br></html>"); Object th[] = new Object[]{ "订单号","菜名","价格","数量","总额","订单人姓名","联系电话","送餐地址","备注" }; GetConnection getcon = new GetConnection(); Statement st = getcon.getStatement(); ResultSet rs = null; ArrayList<Order> al = getList(userId); Object td[][] = new Object[al.size()][9]; for(int i = 0;i < al.size();i++) { Order o = al.get(i); td[i][0] = o.getOrderId(); String menuId = o.getMenuId(); String sql = "select * from 菜单表"; try { rs = st.executeQuery(sql); while(rs.next()) { if(menuId.equals(rs.getString("ID"))) td[i][1] = rs.getString("食物名称"); } } catch (SQLException e) { e.printStackTrace(); } td[i][2] = o.getPrice(); td[i][3] = o.getAmount(); td[i][4] = o.getSum(); td[i][5] = o.getDdName(); td[i][6] = o.getDdTel(); td[i][7] = o.getDdAddress(); td[i][8] = o.getRemark(); } getcon.releaseAll(rs); jt = new JTable(td,th){ public boolean isCellEditable(int row, int column) { return false; } }; jt.getColumnModel().getColumn(2).setPreferredWidth(50); jt.getColumnModel().getColumn(3).setPreferredWidth(50); jt.getColumnModel().getColumn(4).setPreferredWidth(50); jt.getColumnModel().getColumn(7).setPreferredWidth(120); jt.getColumnModel().getColumn(6).setPreferredWidth(120); JTableHeader head = jt.getTableHeader(); jt.setRowHeight(20); jt.setFont(new Font("黑体",Font.BOLD,16)); jp2.add(new JScrollPane(jt)); jp2.add(head,BorderLayout.NORTH); jp2.add(jt,BorderLayout.SOUTH); jp1.add(jl); jp3.add(but); f.add(jp1,BorderLayout.NORTH); f.add(jp2,BorderLayout.CENTER); f.add(jp3,BorderLayout.SOUTH); f.setVisible(true); myEvent(); } public void myEvent() { but.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { f.setVisible(false); } }); } public ArrayList<Order> getList(long userId) { ArrayList<Order> al = new ArrayList<Order>(); GetConnection getcon = new GetConnection(); Statement st = getcon.getStatement(); String sql = "select * from 订单表 where 用户ID =" + userId; ResultSet rs = null; try { rs = st.executeQuery(sql); while(rs.next()) { long userID = rs.getLong("用户ID"); long orderId = rs.getLong("订单号"); int price = rs.getInt("价格"); int count = rs.getInt("数量"); int sum = rs.getInt("总额"); String userName = rs.getString("订单人姓名"); long tel = rs.getLong("送餐电话"); String add = rs.getString("送餐地址"); String time = rs.getString("下单时间"); String remark = rs.getString("备注"); String menuId = rs.getString("菜单ID"); Order o = new Order(userID,orderId,price,count,sum,userName,tel,add,time,remark,menuId); al.add(o); } } catch (SQLException e) { e.printStackTrace(); } getcon.releaseAll(rs); return al; } public JFrame getFrame(){ return f; } public static void main(String args[]) { new QueryOrder(201602); } }
package f.star.iota.milk.ui.search; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import f.star.iota.milk.R; import f.star.iota.milk.base.BaseAdapter; public class SearchAdapter extends BaseAdapter<SearchViewHolder, SearchBean> { @Override public SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new SearchViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_description, parent, false)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ((SearchViewHolder) holder).bindView(mBeans.get(position)); } }
/** */ package iso20022.impl; import java.lang.reflect.InvocationTargetException; import java.util.Map; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.DiagnosticChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import iso20022.DataType; import iso20022.Iso20022Package; import iso20022.LogicalType; import iso20022.MessageAttribute; import iso20022.MessageComponentType; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Message Attribute</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link iso20022.impl.MessageAttributeImpl#getSimpleType <em>Simple Type</em>}</li> * <li>{@link iso20022.impl.MessageAttributeImpl#getComplexType <em>Complex Type</em>}</li> * </ul> * * @generated */ public class MessageAttributeImpl extends MessageElementImpl implements MessageAttribute { /** * The cached value of the '{@link #getSimpleType() <em>Simple Type</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSimpleType() * @generated * @ordered */ protected DataType simpleType; /** * The cached value of the '{@link #getComplexType() <em>Complex Type</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getComplexType() * @generated * @ordered */ protected MessageComponentType complexType; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MessageAttributeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Iso20022Package.eINSTANCE.getMessageAttribute(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DataType getSimpleType() { if (simpleType != null && simpleType.eIsProxy()) { InternalEObject oldSimpleType = (InternalEObject)simpleType; simpleType = (DataType)eResolveProxy(oldSimpleType); if (simpleType != oldSimpleType) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, Iso20022Package.MESSAGE_ATTRIBUTE__SIMPLE_TYPE, oldSimpleType, simpleType)); } } return simpleType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DataType basicGetSimpleType() { return simpleType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSimpleType(DataType newSimpleType) { DataType oldSimpleType = simpleType; simpleType = newSimpleType; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.MESSAGE_ATTRIBUTE__SIMPLE_TYPE, oldSimpleType, simpleType)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MessageComponentType getComplexType() { if (complexType != null && complexType.eIsProxy()) { InternalEObject oldComplexType = (InternalEObject)complexType; complexType = (MessageComponentType)eResolveProxy(oldComplexType); if (complexType != oldComplexType) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, Iso20022Package.MESSAGE_ATTRIBUTE__COMPLEX_TYPE, oldComplexType, complexType)); } } return complexType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MessageComponentType basicGetComplexType() { return complexType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setComplexType(MessageComponentType newComplexType) { MessageComponentType oldComplexType = complexType; complexType = newComplexType; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.MESSAGE_ATTRIBUTE__COMPLEX_TYPE, oldComplexType, complexType)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public boolean MessageAttributeHasExactlyOneType(Map context, DiagnosticChain diagnostics) { // TODO: implement this method >>> DONE // Ensure that you remove @generated or mark it @generated NOT return true; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Iso20022Package.MESSAGE_ATTRIBUTE__SIMPLE_TYPE: if (resolve) return getSimpleType(); return basicGetSimpleType(); case Iso20022Package.MESSAGE_ATTRIBUTE__COMPLEX_TYPE: if (resolve) return getComplexType(); return basicGetComplexType(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Iso20022Package.MESSAGE_ATTRIBUTE__SIMPLE_TYPE: setSimpleType((DataType)newValue); return; case Iso20022Package.MESSAGE_ATTRIBUTE__COMPLEX_TYPE: setComplexType((MessageComponentType)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Iso20022Package.MESSAGE_ATTRIBUTE__SIMPLE_TYPE: setSimpleType((DataType)null); return; case Iso20022Package.MESSAGE_ATTRIBUTE__COMPLEX_TYPE: setComplexType((MessageComponentType)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Iso20022Package.MESSAGE_ATTRIBUTE__SIMPLE_TYPE: return simpleType != null; case Iso20022Package.MESSAGE_ATTRIBUTE__COMPLEX_TYPE: return complexType != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException { switch (operationID) { case Iso20022Package.MESSAGE_ATTRIBUTE___MESSAGE_ATTRIBUTE_HAS_EXACTLY_ONE_TYPE__MAP_DIAGNOSTICCHAIN: return MessageAttributeHasExactlyOneType((Map)arguments.get(0), (DiagnosticChain)arguments.get(1)); } return super.eInvoke(operationID, arguments); } @Override public LogicalType basicGetXmlMemberType() { return getSimpleType() != null ? getSimpleType() : getComplexType(); } @Override public LogicalType basicGetMemberType() { return getSimpleType() != null ? getSimpleType() : getComplexType(); } } //MessageAttributeImpl
package kxg.searchaf.url.gymboree; import java.util.ArrayList; import java.util.List; public class GymboreePage { public String url; public GymboreePage(String url) { this.url = url; } public static List<GymboreePage> getBabyGirlSale() { ArrayList<GymboreePage> urllist = new ArrayList<GymboreePage>(); // String type = "sale"; // String category = ""; // page 1 String url = "http://www.gymboree.com/shop/dept_category.jsp?FOLDER%3C%3Efolder_id=2534374304777285&pageClicked=0"; GymboreePage page = new GymboreePage(url); urllist.add(page); return urllist; } public static List<GymboreePage> getGirlSale() { ArrayList<GymboreePage> urllist = new ArrayList<GymboreePage>(); // String type = "sale"; // String category = ""; // page 1 String url = "http://www.gymboree.com/shop/dept_category.jsp?FOLDER%3C%3Efolder_id=2534374304777283&pageClicked=0"; GymboreePage page = new GymboreePage(url); urllist.add(page); return urllist; } public static List<GymboreePage> getBoySale() { ArrayList<GymboreePage> urllist = new ArrayList<GymboreePage>(); // String type = "sale"; // String category = ""; // page 1 String url = "http://www.gymboree.com/shop/dept_category.jsp?FOLDER%3C%3Efolder_id=2534374306251404&pageClicked=0"; GymboreePage page = new GymboreePage(url); urllist.add(page); return urllist; } public static List<GymboreePage> getBabyBoySale() { ArrayList<GymboreePage> urllist = new ArrayList<GymboreePage>(); // String type = "sale"; // String category = ""; // page 1 String url = "http://www.gymboree.com/shop/dept_category.jsp?FOLDER%3C%3Efolder_id=2534374306251394&pageClicked=0"; GymboreePage page = new GymboreePage(url); urllist.add(page); return urllist; } }
/* * Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.db.generic.reg; import java.util.List; import org.apache.ibatis.session.SqlSession; import pl.edu.icm.unity.db.DBGroups; import pl.edu.icm.unity.db.generic.DependencyChangeListener; import pl.edu.icm.unity.exceptions.EngineException; import pl.edu.icm.unity.exceptions.SchemaConsistencyException; import pl.edu.icm.unity.types.basic.Group; import pl.edu.icm.unity.types.registration.AttributeRegistrationParam; import pl.edu.icm.unity.types.registration.BaseForm; import pl.edu.icm.unity.types.registration.GroupRegistrationParam; public class GroupChangeListener implements DependencyChangeListener<Group> { private FormsSupplier supplier; public GroupChangeListener(FormsSupplier supplier) { this.supplier = supplier; } @Override public String getDependencyObjectType() { return DBGroups.GROUPS_NOTIFICATION_ID; } @Override public void preAdd(Group newObject, SqlSession sql) throws EngineException { } @Override public void preUpdate(Group oldObject, Group updatedObject, SqlSession sql) throws EngineException {} @Override public void preRemove(Group removedObject, SqlSession sql) throws EngineException { List<? extends BaseForm> forms = supplier.getForms(sql); for (BaseForm form: forms) { for (GroupRegistrationParam group: form.getGroupParams()) if (group.getGroupPath().startsWith(removedObject.toString())) throw new SchemaConsistencyException("The group is used by a form " + form.getName()); for (AttributeRegistrationParam attr: form.getAttributeParams()) if (attr.getGroup().startsWith(removedObject.toString())) throw new SchemaConsistencyException("The group is used by an attribute in a form " + form.getName()); if (form.getNotificationsConfiguration() != null && removedObject.toString().equals(form.getNotificationsConfiguration(). getAdminsNotificationGroup())) throw new SchemaConsistencyException("The group is used as administrators notification group in a form " + form.getName()); } } }
package myshop.config; import java.util.Arrays; import org.springframework.security.core.authority.SimpleGrantedAuthority; import myshop.model.User; //点击登陆按钮跳转 public class UserDetailsImpl extends org.springframework.security.core.userdetails.User { private static final long serialVersionUID = 1L; private User user; public UserDetailsImpl(User user) { super(user.getUsername(), user.getPassword(), true, true, true, true, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); this.user = user; } public User getUser() { return user; } }
package br.ufc.crt.bb.model; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import br.ufc.crt.bb.model.enums.ContaTipo; import br.ufc.crt.bb.model.enums.MovimentacoesTipo; public class Banco { private List<Conta> contas = new ArrayList<>(); private Conta conta; Scanner in = new Scanner(System.in); public Conta abrirConta(String nomeTitular, int idConta, double saldo, int limite, ContaTipo tipo){ conta = new Conta(nomeTitular, idConta,saldo,limite,tipo); contas.add(conta); System.out.println("Conta criada com id " + conta.getConta() + ", totalizando " + contas.size()); return conta; } public List<Conta> getContas(){ return this.contas; } public boolean inativarConta(Conta conta){ if(conta != null){ if(!conta.isStatus()){ System.out.println("Você já inativou esta conta"); }else{ conta.setStatus(false); return true; } } return false; } public double saldo(Conta conta){ if(conta != null){ return conta.getSaldo(); } return 0.0; } public void depositar(Conta conta, double dep){ if(conta != null){ if(!conta.isStatus()){ System.out.println("Você não pode efetuar transações com uma conta inativa"); }else{ conta.setSaldo(dep); Movimentacoes mov = new Movimentacoes("depósito", MovimentacoesTipo.CREDITO, dep); conta.movimentacaoAdd(mov); System.out.println("Depósito efetuado!"); } }else{ System.out.println("Transação não efetuada. Conta inexistente"); } } public boolean debitar(Conta conta, double deb){ if(conta != null){ if(!conta.isStatus()){ System.out.println("Você não pode efetuar transações com uma conta inativa"); return false; }else if(conta.getSaldo() > 0) { conta.setSaldo(-deb); Movimentacoes mov = new Movimentacoes("débito",MovimentacoesTipo.DEBITO, deb); conta.movimentacaoAdd(mov); return true; } }else{ System.out.println("Transação não efetuada. Conta inexistente"); } return false; } public void transfConta(Conta contaOrigem, Conta contaDestino, double valor){ if((contaOrigem != null) && (contaDestino != null)){ if(!(saldo(contaOrigem) >= valor)){ System.out.println("Você não tem saldo suficiente para enviar " + valor); }else if(!contaOrigem.isStatus() || !contaDestino.isStatus()){ System.out.println("Você não pode efetuar transações com uma conta inativa"); }else{ System.out.println("Conta à enviar recursos:"); System.out.println(contaOrigem); System.out.println("Conta à receber recursos:"); System.out.println(contaDestino); System.out.println("Você confirma envio de " + valor + "? 1=sim / 2=não"); int confirmacao = in.nextInt(); if(confirmacao == 1){ contaOrigem.setSaldo(-valor); Movimentacoes mov = new Movimentacoes("Envio de recursos", MovimentacoesTipo.TRANSFERENCIA, valor); contaOrigem.movimentacaoAdd(mov); contaDestino.setSaldo(valor); Movimentacoes mov2 = new Movimentacoes("Recebimento de recursos", MovimentacoesTipo.TRANSFERENCIA, valor); contaDestino.movimentacaoAdd(mov2); System.out.println("Transferência concluída."); }else{ System.out.println("Transferência cancelada."); } } }else{ System.out.println("Não é possível efetuar transações com contas inexistentes"); } } public Conta buscarConta(int numConta){ for(Conta co : contas){ if(co.getConta() == numConta){ return co; } } return null; } public void extrato(Conta conta){ int c = 0; List<Movimentacoes> movimentacoes = conta.getMovimentacoes(); if(conta != null){ System.out.println("+++++++++++++++++++++++++++++++++++++++++++++"); System.out.printf("++++++++++ Extrato da conta nº %d +++++++++++++", conta.getConta()); System.out.println(conta); System.out.println("---------------------------------------------"); System.out.println("+++++++++++++ Movimentações +++++++++++++++++\n"); if(movimentacoes.isEmpty()){ System.out.println("\nNenhuma movimentação encontrada para esta conta até aqui..."); }else{ for(Movimentacoes mo : movimentacoes){ System.out.printf("Mov nº #%d ==> %s (%s) de %f \n", ++c, mo.getTipoMovimentacao(), mo.getDescricao(), mo.getValor()); } } } } public void saque(Conta contaTemp, float saque) { if(!contaTemp.isStatus()){ System.out.println("Não é possivel efetuar transações em contas inativas"); }else if((contaTemp.getSaldo() >= saque) & (contaTemp.getSaldo() > 0)){ contaTemp.setSaldo(-saque); Movimentacoes mov = new Movimentacoes("Saque efetuado", MovimentacoesTipo.DEBITO, saque); contaTemp.movimentacaoAdd(mov); System.out.println("Saque efetuado"); }else{ System.out.println("Sem saldo suficiente para efetuar saque!"); } } public String toString(){ System.out.println("##### Bem-vindo ao Sistema Bancário BANCO DO BRASIL #####\n"); System.out.println("-------------------------------------------------------------"); System.out.println("Total de contas => " + contas.size()); return ""; } }
package com.smartsampa.gtfsapi; import java.io.IOException; /** * Created by ruan0408 on 11/03/2016. */ public class GtfsDownloader { private static final String DOWNLOAD_GTFS_SCRIPT_PATH = GtfsDownloader.class.getClassLoader().getResource("downloadGtfs.py").getPath(); private String login; private String password; public GtfsDownloader(String login, String password) { this.login = login; this.password = password; } void downloadToDir(String pathToDir) throws IOException { try { startDownloadProcessOnPath(pathToDir); } catch (Exception e) { e.printStackTrace(); throw new IOException("Failed to download the GTFS files"); } } private void startDownloadProcessOnPath(String path) throws IOException, InterruptedException { ProcessBuilder downloaderProcessBuilder = new ProcessBuilder("python", DOWNLOAD_GTFS_SCRIPT_PATH, login, password, path); Process downloaderProcess = downloaderProcessBuilder.start(); downloaderProcess.waitFor(); } }
package com.pykj.annotation.demo.annotation.configure.lazy; import com.pykj.annotation.project.entity.MyPerson; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; /** * @description: @Lazy * @author: zhangpengxiang * @time: 2020/4/14 17:00 */ @Configuration public class MyConfig { /** * 默认是非延迟加载 * 延迟加载,懒加载只针对单例的Bean起作用 * 默认容器启动时不创建对象,调用对象的功能时才会创建对象,这就是延迟加载 */ @Lazy @Bean(value = "person") public MyPerson person1() { System.out.println("将对象添加到IoC容器中"); return new MyPerson("张鹏祥", 19); } }
package FactorGenerate; import java.util.Collections; import java.util.Comparator; import java.util.List; import DataModel.BlogUnit; import DataModel.FansNode; import DataModel.NodeUnit; public class Generator { static public boolean FactorGenerator(List<NodeUnit> nodes, List<BlogUnit> blogs) { for (NodeUnit nodeUnit : nodes) { double p = 0, d = 0; int cc = 0; for (FansNode fanUnit : nodeUnit.fansNodes) { double count = 0; double delay = 0; for (BlogUnit blogUnit : nodes.get(fanUnit.id).blogUnits) { int index = Collections.binarySearch(nodeUnit.blogUnits, blogUnit, new Comparator<BlogUnit>() { @Override public int compare(BlogUnit o1, BlogUnit o2) { return o1.init_id.compareTo(o2.init_id); } }); if (index >= 0 && nodeUnit.blogUnits.get(index).time < blogUnit.time) { count += 1; delay += (blogUnit.time - nodeUnit.blogUnits.get(index).time); } } if(nodes.get(fanUnit.id).blogUnits.size() == 0) fanUnit.p = 0; else fanUnit.p = count / nodes.get(fanUnit.id).blogUnits.size(); p += fanUnit.p; if(count == 0) fanUnit.delay = 0; else { fanUnit.delay = delay / count; p += fanUnit.p; d += fanUnit.delay; cc++; } } nodeUnit.p1 = p / nodeUnit.fansNodes.size(); nodeUnit.p2 = p / cc; nodeUnit.d1 = d / nodeUnit.fansNodes.size(); nodeUnit.d2 = d / cc; } return true; } }
package com.zeroentropy.game.sprite; import java.util.LinkedList; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.entity.IEntity; import org.andengine.entity.modifier.AlphaModifier; import org.andengine.entity.modifier.FadeOutModifier; import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener; import org.andengine.entity.modifier.ParallelEntityModifier; import org.andengine.entity.modifier.ScaleModifier; import org.andengine.entity.sprite.Sprite; import org.andengine.util.math.MathUtils; import org.andengine.util.modifier.IModifier; import com.zeroentropy.game.ResourcesManager; public class Ink extends Sprite { private static final int mCurrentTileIndex = 0; private static final float BASE_DURATIONS = 16; private static final int TYPE_COUNT = 3; public static LinkedList<Ink> mDisposedInks = new LinkedList<Ink>(); public Ink(final float pX, final float pY) { super(pX, pY, ResourcesManager.getInstance().mInkRegion, ResourcesManager.getInstance().vbom); mTransparentBackground = new Sprite(pX, pY, ResourcesManager.getInstance().mInkRegion, ResourcesManager.getInstance().vbom); // this.stopAnimation(mCurrentTileIndex); } // public static int reduisDisposedInksSize() { // int extraNum = 0; // if (mDisposedInks.size() > MAX_DISPOSEDLIST_SIZE) { // extraNum = mDisposedInks.size() - MAX_DISPOSEDLIST_SIZE; // while (extraNum-- > 0) { // mDisposedInks.poll().detachSelf(); // } // } // return extraNum; // } public void onManagedDestroy() { // this.clearEntityModifiers(); // this.clearUpdateHandlers(); // this.registerEntityModifier(mFadeOutModifier); // final float pScale = this.getScaleX(); // final float pAlpha = this.getAlpha(); if (!mDurationsTimerHandler.isTimerCallbackTriggered()) { mDurationsTimerHandler.setTimerSeconds(1); } // else{ // this.detachSelf(); // } } private ParallelEntityModifier mParallelModifier; private TimerHandler mDurationsTimerHandler; private ScaleModifier mScaleModifier; private FadeOutModifier mFadeOutModifier; private ParallelEntityModifier mBackgroundParallelModifier; // private TimerHandler mDurationsTimerHandler; private ScaleModifier mBackgroundScaleModifier; private AlphaModifier mBackgroundFadeOutModifier; private static final float INIT_BACKGROUND_TRANSPARENCE = 0.1f; public void onManagedCreate() { final int z = 1 << MathUtils.random(TYPE_COUNT);// 1,2,4,8 final float scale = 1.0f / z; final float durations = scale * BASE_DURATIONS; if (mBackgroundParallelModifier == null) { mBackgroundScaleModifier = new ScaleModifier(.5f, scale, scale * 2); mBackgroundFadeOutModifier = new AlphaModifier(.5f, INIT_BACKGROUND_TRANSPARENCE, 0); mBackgroundParallelModifier = new ParallelEntityModifier( mBackgroundScaleModifier, mBackgroundFadeOutModifier); }else{ mBackgroundScaleModifier.reset(.5f, scale, scale*2, scale, scale*2); // mFadeOutModifier.reset(pDuration, pFromValue, pToValue) mBackgroundParallelModifier.reset(); } if (mParallelModifier == null) { mScaleModifier = new ScaleModifier(.5f, scale, scale * 2); mFadeOutModifier = new FadeOutModifier(.5f); mParallelModifier = new ParallelEntityModifier( new IEntityModifierListener() { @Override public void onModifierStarted( IModifier<IEntity> pModifier, IEntity pItem) { // TODO Auto-generated method stub } @Override public void onModifierFinished( IModifier<IEntity> pModifier, IEntity pItem) { // Ink.this.detachSelf(); // if (mDisposedInks.size() < MAX_DISPOSEDLIST_SIZE) // { setIgnoreUpdate(true); mTransparentBackground.setIgnoreUpdate(true); mDisposedInks.addFirst(Ink.this); // mDisposedBackground.addFirst(Ink.this.mTransparentBackground); // } else { // Ink.this.detachSelf(); // } // mInksNum--; } }, mScaleModifier, mFadeOutModifier); }else{ mScaleModifier.reset(.5f, scale, scale*2, scale, scale*2); // mFadeOutModifier.reset(pDuration, pFromValue, pToValue) mParallelModifier.reset(); } if (mDurationsTimerHandler == null) { mDurationsTimerHandler = new TimerHandler(durations, false, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { // Ink.this.unregisterUpdateHandler(pTimerHandler); registerEntityModifier(mParallelModifier); mTransparentBackground.registerEntityModifier(mBackgroundParallelModifier); } }); this.registerUpdateHandler(mDurationsTimerHandler); } else { mDurationsTimerHandler.setTimerSeconds(durations); mDurationsTimerHandler.reset(); } // this.setPosition(pX, pY); setScale(scale); if (getAlpha() != 1.0f) setAlpha(1.0f); // Ink.this.mTransparentBackground mTransparentBackground.setScale(scale); if (mTransparentBackground.getAlpha() != INIT_BACKGROUND_TRANSPARENCE) mTransparentBackground.setAlpha(INIT_BACKGROUND_TRANSPARENCE); setIgnoreUpdate(false); mTransparentBackground.setIgnoreUpdate(false); }// End of onManagedAttached(); // °ë͸Ã÷µ×²¿TransParent private Sprite mTransparentBackground; // public static LinkedList<Ink> mDisposedBackgrounds = new // LinkedList<Ink>(); public Sprite getBackground() { return mTransparentBackground; } }// End of class InkSprite
package Interfce_Grafica; import java.awt.*; import javax.swing.*; import Eventos.*; import Exception.ListaVaziaExeception; import Gerente.Gerente; public class Menu extends JFrame { private Container container, c; private JButton cadastraExercicio, cadastraQuestao, cadastraAluno, alteraPergunta, alteraResposta; private JButton listaExerCasda, sorteaExecicio, sair; private EventoCadastraExercicio eventoCadastraExercicio; private EventoCadastraQuestao eventoCadastraQuestao; private EventoCadastraAluno eventoCadastraAluno; private EventoAlteraPergunta eventoAlteraPergunta; private EventoAlteraResposta eventoAlteraResposta; private EventoListatodosExercicios eventoListaExerCasda; private EventoSorteaExercicio eventoSorteaExecicio; private EventoSair eventoSair; private JFrame telaCadastro; private JFrame telaPesquisa; private JFrame telaAlteraPergunata; private JFrame telaAlteraResposta; private JFrame telaExercicio; private JFrame telaCadastroAluno; private Gerente gerente; public Menu(){ super("MENU"); this.gerente = new Gerente(); this.telaCadastro = new TelaCadastroQuestao(this, this.gerente); this.telaPesquisa = new TelaPesquisa(this.gerente); this.telaAlteraPergunata = new TelaAlteraPergunta(this, this.gerente); this.telaAlteraResposta = new TelaAlteraResposta(this, this.gerente); this.telaExercicio = new TelaExercicio(this.gerente); this.telaCadastroAluno = new TelaCadastroAluno(this, this.gerente); this.inicializandoButao(); this.inicializaEvento(); this.addEventoAoBotao(); this.container = new JPanel(); this.container.setLayout(new GridLayout(17,1,0,4)); this.c = getContentPane(); this.addAoAoContainer(); this.c.add(BorderLayout.WEST, this.container); TelaPesquisa t = (TelaPesquisa) this.telaPesquisa; this.c.add(BorderLayout.EAST, t.getTelaPesquisa()); } public void setMenu(JFrame tela){ this.c.remove(1); this.c.repaint(); if(tela instanceof TelaCadastroQuestao){ TelaCadastroQuestao t = (TelaCadastroQuestao) tela; this.c.add(BorderLayout.EAST, t.getTelaCadastro()); }else if(tela instanceof TelaPesquisa){ TelaPesquisa t = (TelaPesquisa) tela; this.c.add(BorderLayout.EAST, t.getTelaPesquisa()); }else if(tela instanceof TelaAlteraPergunta){ TelaAlteraPergunta t = (TelaAlteraPergunta) tela; this.c.add(BorderLayout.EAST, t.getTelaAlteraPergunta()); }else if(tela instanceof TelaAlteraResposta){ TelaAlteraResposta t = (TelaAlteraResposta) tela; this.c.add(BorderLayout.EAST, t.getTelaAlteraPergunta()); }else if(tela instanceof TelaExercicio){ TelaExercicio t = (TelaExercicio) tela; try { t.motandoExercicio(this.gerente.getSorteaExercicio()); this.c.add(BorderLayout.EAST, t.getTelaExercicio()); } catch (ListaVaziaExeception e) { this.c.add(BorderLayout.EAST, t.getTelaExercicio()); JOptionPane.showMessageDialog(null, e.getMessage()); this.setMenu(this.getTelaPesquisa()); } }else if(tela instanceof TelaCadastroAluno){ TelaCadastroAluno t = (TelaCadastroAluno) tela; this.c.add(BorderLayout.EAST, t.getTelaCadastroAluno()); } setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(735,700); setVisible(true); } private void inicializandoButao(){ this.cadastraExercicio = new JButton("Cadastrar Exercicio"); this.cadastraQuestao = new JButton("Cadastrar Questão"); this.cadastraAluno = new JButton("Cadastrar Aluno"); this.alteraPergunta = new JButton("Alterar Pergunta"); this.alteraResposta = new JButton("Alterar Resposta"); this.listaExerCasda = new JButton("Todos Exercicios"); this.sorteaExecicio = new JButton("Sortear Exercicio"); this.sair = new JButton("Sair"); } private void inicializaEvento(){ this.eventoCadastraExercicio = new EventoCadastraExercicio(this); this.eventoCadastraQuestao = new EventoCadastraQuestao(this); this.eventoCadastraAluno = new EventoCadastraAluno(this); this.eventoAlteraPergunta = new EventoAlteraPergunta(this); this.eventoAlteraResposta = new EventoAlteraResposta(this); this.eventoListaExerCasda = new EventoListatodosExercicios(this, this.gerente); this.eventoSorteaExecicio = new EventoSorteaExercicio(this); this.eventoSair = new EventoSair(); } private void addAoAoContainer(){ this.container.add(this.cadastraExercicio); this.container.add(this.cadastraQuestao); this.container.add(this.cadastraAluno); this.container.add(this.alteraPergunta); this.container.add(this.alteraResposta); this.container.add(this.listaExerCasda); this.container.add(this.sorteaExecicio); this.container.add(this.sair); Font f = new Font("serif", Font.CENTER_BASELINE | Font.ITALIC, 16); JLabel poo = new JLabel(" Projeto de POO"); JLabel versao = new JLabel(" Versão 1.0"); JLabel desen = new JLabel(" Desenvolvedores"); JLabel nome = new JLabel(" Italo"), nome2 = new JLabel(" Raimundo"); poo.setToolTipText("UFPB"); versao.setToolTipText("Beta"); desen.setToolTipText("Java"); nome.setToolTipText("Aluno POO"); nome2.setToolTipText("Aluno POO"); poo.setFont(f); versao.setFont(f); desen.setFont(f); nome.setFont(f); nome2.setFont(f); this.container.add(new JLabel("")); this.container.add(new JLabel("")); this.container.add(poo); this.container.add(versao); this.container.add(desen); this.container.add(nome); this.container.add(nome2); } private void addEventoAoBotao(){ this.cadastraExercicio.addActionListener(this.eventoCadastraExercicio); this.cadastraQuestao.addActionListener(this.eventoCadastraQuestao); this.cadastraAluno.addActionListener(this.eventoCadastraAluno); this.alteraPergunta.addActionListener(this.eventoAlteraPergunta); this.alteraResposta.addActionListener(this.eventoAlteraResposta); this.listaExerCasda.addActionListener(this.eventoListaExerCasda); this.sorteaExecicio.addActionListener(this.eventoSorteaExecicio); this.sair.addActionListener(this.eventoSair); } public JFrame getTelaCadastro() { return this.telaCadastro; } public JFrame getTelaPesquisa() { return this.telaPesquisa; } public JFrame getTelaAlteraPergunta() { return this.telaAlteraPergunata; } public JFrame getTelaAlteraResposta(){ return this.telaAlteraResposta; } public JFrame getTelaExercicio(){ return this.telaExercicio; } public JFrame getTelaCadastroAluno(){ return this.telaCadastroAluno; } public void setTextoPesquisa(String texto){ TelaPesquisa t = (TelaPesquisa) this.telaPesquisa; t.setTexto(texto); } }
// SPDX-License-Identifier: BSD-3-Clause // -*- Java -*- // // Copyright (c) 2005, Matthew J. Rutherford <rutherfo@cs.colorado.edu> // Copyright (c) 2005, University of Colorado at Boulder // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the University of Colorado at Boulder nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // package org.xbill.DNS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.List; import org.junit.jupiter.api.Test; import org.xbill.DNS.utils.base64; class MessageTest { @Test void ctor_0arg() { Message m = new Message(); assertTrue(m.getSection(0).isEmpty()); assertTrue(m.getSection(1).isEmpty()); assertTrue(m.getSection(3).isEmpty()); assertTrue(m.getSection(2).isEmpty()); assertThrows(IndexOutOfBoundsException.class, () -> m.getSection(4)); Header h = m.getHeader(); assertEquals(0, h.getCount(0)); assertEquals(0, h.getCount(1)); assertEquals(0, h.getCount(2)); assertEquals(0, h.getCount(3)); } @Test void ctor_1arg() { Message m = new Message(10); assertEquals(new Header(10).toString(), m.getHeader().toString()); assertTrue(m.getSection(0).isEmpty()); assertTrue(m.getSection(1).isEmpty()); assertTrue(m.getSection(2).isEmpty()); assertTrue(m.getSection(3).isEmpty()); assertThrows(IndexOutOfBoundsException.class, () -> m.getSection(4)); Header h = m.getHeader(); assertEquals(0, h.getCount(0)); assertEquals(0, h.getCount(1)); assertEquals(0, h.getCount(2)); assertEquals(0, h.getCount(3)); } @Test void ctor_byteBuffer() throws IOException { byte[] arr = base64.fromString( "EEuBgAABAAEABAAIA3d3dwZnb29nbGUDY29tAAABAAHADAABAAEAAAAaAASO+rokwBAAAgABAAFHCwAGA25zMcAQwBAAAgABAAFHCwAGA25zNMAQwBAAAgABAAFHCwAGA25zM8AQwBAAAgABAAFHCwAGA25zMsAQwDwAAQABAADObwAE2O8gCsByAAEAAQABrVEABNjvIgrAYAABAAEAAVqZAATY7yQKwE4AAQABAAK9RQAE2O8mCsA8ABwAAQAD4a0AECABSGBIAgAyAAAAAAAAAArAcgAcAAEAAtDgABAgAUhgSAIANAAAAAAAAAAKwGAAHAABAACSagAQIAFIYEgCADYAAAAAAAAACsBOABwAAQAErVoAECABSGBIAgA4AAAAAAAAAAo="); ByteBuffer wrap = ByteBuffer.allocate(arr.length + 2); // prepend length, like when reading a response from a TCP channel wrap.putShort((short) arr.length); wrap.put(arr); wrap.flip(); wrap.getShort(); // read the prepended length Message m = new Message(wrap); assertEquals(Name.fromConstantString("www.google.com."), m.getQuestion().getName()); } @Test void newQuery() throws TextParseException, UnknownHostException { Name n = Name.fromString("The.Name."); ARecord ar = new ARecord(n, DClass.IN, 1, InetAddress.getByName("192.168.101.110")); Message m = Message.newQuery(ar); assertEquals(1, m.getSection(0).size()); assertEquals(ar, m.getSection(0).get(0)); assertTrue(m.getSection(1).isEmpty()); assertTrue(m.getSection(2).isEmpty()); assertTrue(m.getSection(3).isEmpty()); Header h = m.getHeader(); assertEquals(1, h.getCount(0)); assertEquals(0, h.getCount(1)); assertEquals(0, h.getCount(2)); assertEquals(0, h.getCount(3)); assertEquals(Opcode.QUERY, h.getOpcode()); assertTrue(h.getFlag(Flags.RD)); } @Test void sectionToWire() throws IOException { Message m = new Message(4711); Name n2 = Name.fromConstantString("test2.example."); m.addRecord(new TXTRecord(n2, DClass.IN, 86400, "other record"), Section.ADDITIONAL); Name n = Name.fromConstantString("test.example."); m.addRecord(new TXTRecord(n, DClass.IN, 86400, "example text -1-"), Section.ADDITIONAL); m.addRecord(new TXTRecord(n, DClass.IN, 86400, "example text -2-"), Section.ADDITIONAL); m.addRecord(new TXTRecord(n, DClass.IN, 86400, "example text -3-"), Section.ADDITIONAL); m.addRecord(new TXTRecord(n, DClass.IN, 86400, "example text -4-"), Section.ADDITIONAL); m.addRecord(new OPTRecord(512, 0, 0, 0), Section.ADDITIONAL); for (int i = 5; i < 50; i++) { m.addRecord( new TXTRecord(n, DClass.IN, 86400, "example text -" + i + "-"), Section.ADDITIONAL); } byte[] binary = m.toWire(512); Message m2 = new Message(binary); assertEquals(2, m2.getHeader().getCount(Section.ADDITIONAL)); List<Record> records = m2.getSection(Section.ADDITIONAL); assertEquals(2, records.size()); assertEquals(TXTRecord.class, records.get(0).getClass()); assertEquals(OPTRecord.class, records.get(1).getClass()); } @Test void testQuestionClone() { Name qname = Name.fromConstantString("www.example."); Record question = Record.newRecord(qname, Type.A, DClass.IN); Message query = Message.newQuery(question); Message clone = query.clone(); assertEquals(query.getHeader().getID(), clone.getHeader().getID()); assertEquals(query.getQuestion().getName(), clone.getQuestion().getName()); } @Test void testResponseClone() throws UnknownHostException { Name qname = Name.fromConstantString("www.example."); Record question = Record.newRecord(qname, Type.A, DClass.IN); Message response = new Message(); response.getHeader().setFlag(Flags.QR); response.addRecord(question, Section.QUESTION); response.addRecord( new ARecord(qname, DClass.IN, 0, InetAddress.getByName("127.0.0.1")), Section.ANSWER); Message clone = response.clone(); assertEquals(clone.getQuestion(), response.getQuestion()); assertEquals(clone.getSection(Section.ANSWER), response.getSection(Section.ANSWER)); } }
package com.tvm.integrationBasic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.integration.channel.DirectChannel; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.MessageBuilder; import com.tvm.service.PrintService; import com.tvm.service.SMSService; /** * Channel are one of key component in SpringIntegration,Because they decouple * the endpoint which exchange messages.In the last example in package (com.tvm) * we pass the message directly to the service class which is PrintService. * * But with the channel we can decouple the end point to send to which we send * the message.In this example we will create a channel to which we can send the * message. * * ***/ @Configuration @ImportResource("integrationBasic/integration-context-ChannelExample1.xml") public class ChannelExample1 implements ApplicationRunner { // A channel that invokes a single subscriber for each sent Message. // Whoever will be subscribed to this channel will receive the message.In // this case PrintService is subscribed to this channel so it will receive // the message. // The direct channel follow (POP) point-to-point approach for // integration.So it going to connect two end points anf.So they are // directly comment so once // we put a message to this channel it going from one end point to another @Autowired DirectChannel channel; public static void main(String[] args) { SpringApplication.run(ChannelExample1.class, args); } @Override public void run(ApplicationArguments arg0) throws Exception { /* * channel.subscribe(new MessageHandler() { * * @Override public void handleMessage(Message<?> messageToSend) throws * MessagingException { PrintService printService = new PrintService(); * printService.print((Message<String>) messageToSend); } }); * * */ // Alternate way of writing the implementation of Anonymous inner class // through Lambdas.The message handler is a type of functional interface // since it has only one method channel.subscribe((messageToSend) -> { PrintService printService = new PrintService(); printService.print((Message<String>) messageToSend); //Adding one more service i.e. SMSService to get subscribed to this channel SMSService smsService = new SMSService(); smsService.sms((Message<String>) messageToSend); }); Message<String> message = MessageBuilder .withPayload( "Hello World sent through subscribe channel.The PrintService & SMSService class has subscribed to this channel") .setHeader("HeaderKey1", "HeaderValue").build(); channel.send(message); } }
package foo.bar; /** * Created with IntelliJ IDEA. * User: War * Date: 20.04.14 * Time: 21:41 * To change this template use File | Settings | File Templates. */ public class Instrumentalist implements Performer { public Instrumentalist(){} public void perform() { System.out.print("Gram "+song+":"); instrument.play(); } private String song; public void setSong(String song){ this.song = song; } public String getSong(){ return song; } public String screamSong(){ return song; } Instrument instrument; public void setInstrument(Instrument instrument){ this.instrument = instrument; } }
package com.fb.kit; public final class UserBillConstants { private UserBillConstants() { } /** * 造成资金转移的操作类型信息 * @author Administrator * */ public final static class OperatorInfo { /** * 投资成功 */ public final static String INVEST_SUCCESS = "invest_success"; /**管理员干预*/ public final static String ADMIN_OPERATION = "admin_operation"; /**充值成功*/ public final static String RECHARGE_SUCCESS = "recharge_success"; /**申请借款*/ public final static String APPLY_LOAN = "apply_loan"; /**借款申请未通过*/ public final static String REFUSE_APPLY_LOAN = "refuse_apply_loan"; /**申请提现*/ public final static String APPLY_WITHDRAW = "apply_withdraw"; /**提现手续费冻结*/ public final static String APPLY_WITHDRAW_FEE_FROZEN = "apply_withdraw_fee_fee_frozen"; /**提现手续费扣除*/ public final static String APPLY_WITHDRAW_FEE_DEDUCTION = "apply_withdraw_fee_deduction"; /**提现手续费撤回*/ public final static String APPLY_WITHDRAW_FEE_CANCEL = "apply_withdraw_fee_cancel"; /**提现手续费解冻*/ public final static String APPLY_WITHDRAW_FEE_THAW = "apply_withdraw_fee_thaw"; /**提现罚金冻结*/ public final static String APPLY_WITHDRAW_PENALTY_FROZEN = "apply_withdraw_penalty_frozen"; /**提现罚金扣除*/ public final static String APPLY_WITHDRAW_PENALTY_DEDUCTION = "apply_withdraw_penalty_deduction"; /**提现罚金扣除*/ public final static String APPLY_WITHDRAW_PENALTY_CANCEL = "apply_withdraw_penalty_cancel"; /**提现罚金解冻*/ public final static String APPLY_WITHDRAW_PENALTY_THAW = "apply_withdraw_penalty_thaw"; /**使用优惠券抵用提现手续费*/ public final static String APPLY_WITHDRAW_FEE_USECOUPON = "apply_withdraw_fee_usecoupon"; /**体现审核不通过返回优惠券*/ public final static String APPLY_WITHDRAW_FEE_BACKCOUPON = "apply_withdraw_fee_backcoupon"; /**管理员充值*/ public final static String ADMIN_RECHARGE = "admin_recharge"; /**管理员发放红包*/ public final static String RECEIVE_RED = "receive_red"; /**管理员发放红包*/ public final static String RECEIVE_RED_MESSAGE = "红包返现"; /**注册或其他活动送红包*/ public final static String RECEIVE_REG = "receive_reg"; /**注册或其他活动送红包*/ public final static String RECEIVE_REG_MESSAGE = "元红包返现"; /**使用代金券*/ public final static String RECEIVE_VOUCHER = "receive_voucher"; /**提现申请未通过*/ public final static String REFUSE_APPLY_WITHDRAW = "refuse_apply_withdraw"; /**正常还款*/ public final static String NORMAL_REPAY = "normal_repay"; /**提前还款*/ public final static String ADVANCE_REPAY = "advance_repay"; /**逾期还款*/ public final static String OVERDUE_REPAY = "overdue_repay"; /**借款流标*/ public final static String CANCEL_LOAN = "cancel_loan"; /**借款撤标*/ public final static String WITHDRAW_LOAN = "withdraw_loan"; /**借款放款*/ public final static String GIVE_MONEY_TO_BORROWER = "give_money_to_borrower"; /**提现成功*/ public final static String WITHDRAW_SUCCESS = "withdraw_success"; /**提现撤回*/ public final static String WITHDRAW_CANCEL = "withdraw_cancel"; /**投资流标*/ public static final String CANCEL_INVEST = "cancel_invest"; /**caijinmin 增加债权转让成功状态 201501222046 begin*/ /**债权转让成功*/ public static final String TRANSFER = "transfer"; /**债权购买成功*/ public static final String TRANSFER_BUY = "transfer_buy"; /**caijinmin 增加债权转让成功状态 201501222046 end*/ /**众筹投资*/ public static final String RAISE_INVEST = "raise_invest"; /**众筹放款*/ public static final String RAISE_GIVE_MONEY_TO_BORROWER = "raise_give_money_to_borrower"; /**众筹流标*/ public final static String RAISE_CANCEL_LOAN = "raise_cancel_loan"; /**红包使用*/ public final static String USE_COUPON = "use_coupon"; /** 私房钱投资成功**/ public final static String PERSONAL_MONEY_INVEST_SUCCESS = "personal_money_invest_success"; /**私房钱*/ public final static String PERSONAL_MONEY = "personal_money"; /**私房钱*/ public final static String PERSONAL_MONEY_MESSAGE = "收取私房钱"; /**私房钱投资未达到提现门槛扣除私房钱及其收益*/ public final static String PERSONAL_MONEY_DEDUCTION = "personal_money_deduction"; /**私房钱还款*/ public final static String PERSONAL_MONEY_REPAY = "personal_money_repay"; /**提前退出扣款*/ public final static String EXIT_DEBIT = "exit_debit"; /**提前退出加钱*/ public final static String EXIT_ADD_MONEY = "exit_add_money"; /**提前退出手续费*/ public final static String EXIT_FEE = "exit_fee"; /**提前退出冻结资金*/ public final static String EXIT_MONEY_FROZEN = "exit_money_frozen"; /**债权到期还款冻结资金*/ public final static String INVEST_REPAY_FROZEN = "invest_repay_frozen"; /**逾期垫付本金划入/垫付*/ public final static String OVERDUE_PAY_CORPUS = "overdue_pay_corpus"; /**逾期垫付利息划入/垫付*/ public final static String OVERDUE_PAY_INTERSET = "overdue_pay_interset"; /**债转垫付利息划入/垫付*/ public final static String IFTHE_PAY_INTERSET = "ifthe_pay_interset"; /**按月付息利息划入/垫付*/ public final static String MONTH_PAY_INTERSET = "month_pay_interset"; /**债权募集期利息垫付*/ public final static String LOAN_COLLECTION_INTERSET = "loan_collection_interset"; /**提前还款申请拒绝解冻*/ public final static String EARLY_REPAY_REJECT_UNFREEZE = "early_repay_reject_unfreeze"; } public final static class Type{ /** * 冻结 */ public final static String FREEZE = "freeze"; /** * 解冻 */ public final static String UNFREEZE = "unfreeze"; /** * 从余额转出 transfer out from balance */ public final static String TO_BALANCE = "to_balance"; /** * 转入到余额 tansfer into balance */ public final static String TI_BALANCE = "ti_balance"; /** * 从冻结金额中转出 transfer out frome frozen money */ public final static String TO_FROZEN = "to_frozen"; /** * 私房钱投资冻结 */ public final static String PM_FROZEN = "pm_frozen"; /** * 从在投本金转出 transfer out from corpus */ public final static String TO_CORPUS = "to_corpus"; /** * 转入到在投本金 tansfer into corpus */ public final static String TI_CORPUS = "ti_corpus"; } }
package com.citibank.ods.modules.client.bkrportfmgmt.functionality.valueobject; /** * @author Hamilton Matos */ public class BkrPortfMgmtListFncVO extends BaseBkrPortfMgmtListFncVO { }
package com.akulcompany.Groups; import com.akulcompany.auditoriya.Students; import java.util.ArrayList; public class Electronic_group { static final String group_name = "група № 103 кафедри ЕЛЕКТРОНіКИ,"; public Electronic_group () { } public ArrayList<Students> list_group= new ArrayList<Students>();//список групи можна задати статично або Scaner методом ввода, або з файла public void setList_group (ArrayList<Students> list_group) { this.list_group = list_group; } public static String getGroup_name () { return group_name; } public ArrayList<Students> getList_group () { return list_group; } public void addList_group (Students students) { list_group.add(students); } // }
package test; import java.io.File; import java.io.IOException; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class ExcelReader { public static void main(String[] args) { try { //エクセルファイルへアクセスするためのオブジェクト Workbook excel; excel = WorkbookFactory.create(new File("data_file/ReserveData.xlsx")); // シート名がわかっている場合 Sheet sheet = excel.getSheet("Sheet1"); for (int i = 1; i < 50; i++) { //行目から10行目までを繰り返し Row row = sheet.getRow(i); //2~10行目まで行を読み込み Cell cell = row.getCell(2); //Cellを指定 String value = cell.getStringCellValue(); //指定した場所の文字列を取得 System.out.println(i); //件数 System.out.println(value); //取得したデータを出力 } } catch (EncryptedDocumentException | IOException e) { e.printStackTrace(); } } }
package project.handler; public class HelpHandler { public void manual(){ System.out.println(); System.out.println("---------------------------------------------------------------------------------------------------------"); System.out.println("프로그램을 실행시키려면 해당 메뉴의 명령어를 입력하여야 합니다."); System.out.println("메뉴의 명령어와 다른 명령어를 입력시 [실행할 수 없는 명령입니다.] 라는 오류 메세지가 출력됩니다. "); System.out.println("프로그램을 종료 시키고 싶으시다면, [exit] 혹은 [close]를 입력해주세요. "); System.out.println(); System.out.println(); System.out.println("> /help \n" + " >[-] manual - 사용법 \n"); System.out.println("> /user \n" + " >[-] join - 회원가입 \n" + " >[-] modify - 회원정보 수정 \n"); System.out.println(); System.out.println("> /board \n" + " >[-] write - 게시글 작성 \n" + " >[-] list - 게시글 목록 출력 \n" + " >[-] view - 선택 게시글 상세보기 \n" + " >[-] delete - 선택 게시글 삭제 \n"); System.out.println(); System.out.println("> /review \n" + " >[-] write - 리뷰 게시글 작성 \n" + " >[-] list - 리뷰 게시글 목록 출력 \n" + " >[-] view - 선택 리뷰 게시글 상세보기 \n" + " >[-] delete - 선택 리뷰 게시글 삭제 \n"); System.out.println(); System.out.println("> /admin \n" + " >[-] user/list - 회원관리/ 회원목록 출력 \n" + " >[-] user/delete - 회원관리/ 회원정보 삭제 \n" + " >[-] user/detail - 회원관리/ 회원정보 상세보기 \n"); } }
package com.icogroup.baseprojectdatabinding.data.routing; import android.app.Activity; import android.content.Context; import com.icogroup.baseprojectdatabinding.data.model.Movie; /** * Created by Ulises.harris on 4/29/16. */ public interface IRouting { void movieDetail(Activity activity, Context context, Movie movie); }
package com.project.pages; public class LandingPage { //all the webelements declaration and methods }
package data_stuctures; /** */ public class SpecialStructureTest { }
package tech.bts.productcatalog; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.lang.reflect.Type; import java.util.List; import java.util.Scanner; public class ProductCatalog { public static void main(String[] args) throws Exception { Scanner input = new Scanner(System.in); // scanner can read from keyboard List<Product> products; products = readProducts(); while (true) { System.out.print("What do you want to do? "); String line = input.nextLine(); System.out.println("You want to " + line); if (line.equals("exit")) { writeProducts(products); break; } else if (line.equals("add")) { Product product = askProductData(input); products.add(product); System.out.println("Your added product is " + product); } else if (line.equals("list")) { for (Product product : products) { System.out.print("Your added products are " + product); } } else if (line.equals("html")) { PrintWriter write = new PrintWriter("product.html"); write.println("<h1>Products</h1>"); write.println("<h3>Available products</h3>"); write.println("<ul>"); for (Product product : products) { write.println("<li>" + product + "</li>"); } write.println("</ul>"); write.close(); } } } public static List<Product> readProducts() throws Exception { BufferedReader reader = new BufferedReader(new FileReader("product.json")); String json = reader.readLine(); Gson gson = new Gson(); Type type = new TypeToken<List<Product>>() { }.getType(); List<Product> products = gson.fromJson(json, type); return products; } public static void writeProducts(List<Product> products) throws Exception { Gson gson = new Gson(); String json = gson.toJson(products); //serializing: convert object to String System.out.println(json); PrintWriter write = new PrintWriter("product.json"); write.println(json); write.close(); } public static Product askProductData(Scanner input) { System.out.print("Product name? "); String name = input.nextLine(); System.out.print("Price? "); double price = Double.parseDouble(input.nextLine()); System.out.print("Quantity? "); int quantity = Integer.parseInt(input.nextLine()); Product product = new Product(name, price, quantity); return product; } }
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class SortingLinkedLists { public static void main(String[] args) { LinkedList<Integer> numbers = getLinkedListOfNum(); LinkedList<Integer> numbers1 = getLinkedListOfNum(); LinkedList<Integer> numbers2 = getLinkedListOfNum(); // Bubble Sort Time long start = System.nanoTime(); BubbleSort(numbers); long end = System.nanoTime(); System.out.println("Bubble Sort Time: " + (end - start) / 1e6 + "ms"); System.out.println("Array is Sorted: " + isSorted(numbers)); //Quick Sort Time Node<Integer> startNode = numbers1.head; Node<Integer> endNode = numbers1.lastNode(); start = System.nanoTime(); QuickSort(startNode,endNode); end = System.nanoTime(); System.out.println("Quick Sort Time: " + (end - start) / 1e6 + "ms"); System.out.println("Array is Sorted: " + isSorted(numbers1)); //Radix Sort Time start = System.nanoTime(); RadixSort(numbers2); end = System.nanoTime(); System.out.println("Radix Sort Time: " + (end - start) / 1e6 + "ms"); System.out.println("Array is Sorted: " + isSorted(numbers2)); } static LinkedList<Integer> getLinkedListOfNum() { File f = new File("numbers.txt"); LinkedList<Integer> list = new LinkedList<>(); Scanner input; try { input = new Scanner(f); while (input.hasNextInt()) { list.add((Integer) input.nextInt()); } } catch (FileNotFoundException ex) { System.out.println("File Not Found"); System.out.println(ex.getMessage()); } return list; } static void printLinkedList(LinkedList<Integer> list) { Node<Integer> traversal = list.head; while (traversal != null) { System.out.println(traversal.data); traversal = traversal.next; } } static boolean isSorted(LinkedList<Integer> list) { Node<Integer> current = list.head; Node<Integer> previous = list.head; while (current.next != null) { current = current.next; if (current.data < previous.data) { return false; } previous = current; } return true; } // Code adapted from // https://stackoverflow.com/questions/29869094/bubble-sort-manually-a-linked-list-in-java static void BubbleSort(LinkedList<Integer> list) { if (list.length > 1) { boolean wasChanged; do { Node<Integer> current = list.head; Node<Integer> previous = null; Node<Integer> next = list.head.next; wasChanged = false; while (next != null) { if (current.data > next.data) { /* * // This is just a literal translation // of bubble sort in an array Node<Integer> temp * = currentNode; currentNode = next; next = temp; */ wasChanged = true; if (previous != null) { Node<Integer> sig = next.next; previous.next = next; next.next = current; current.next = sig; } else { Node<Integer> sig = next.next; list.head = next; next.next = current; current.next = sig; } previous = next; next = current.next; } else { previous = current; current = next; next = next.next; } } } while (wasChanged); } } //Code adapted from //https://www.geeksforgeeks.org/quicksort-on-singly-linked-list/ static void QuickSort(Node<Integer> start, Node<Integer> end) { if (start == null || start == end || start == end.next) return; // split list and partion recurse Node<Integer> pivot_prev = paritionLast(start, end); QuickSort(start, pivot_prev); // if pivot is picked and moved to the start, // that means start and pivot is same // so pick from next of pivot if (pivot_prev != null && pivot_prev == start){ QuickSort(pivot_prev.next, end); } // if pivot is in between of the list, // start from next of pivot, // since we have pivot_prev, so we move two nodes else if (pivot_prev != null && pivot_prev.next != null) { QuickSort(pivot_prev.next.next, end); } } static Node<Integer> paritionLast(Node<Integer> start, Node<Integer> end) { if (start == end || start == null || end == null) return start; Node<Integer> pivot_prev = start; Node<Integer> curr = start; int pivot = end.data; // iterate till one before the end, // no need to iterate till the end // because end is pivot while (start != end) { if (start.data < pivot) { // keep tracks of last modified item pivot_prev = curr; int temp = curr.data; curr.data = start.data; start.data = temp; curr = curr.next; } start = start.next; } // swap the position of curr i.e. // next suitable index and pivot int temp = curr.data; curr.data = pivot; end.data = temp; // return one previous to current // because current is now pointing to pivot return pivot_prev; } static void RadixSort(LinkedList<Integer> list) { // Find the maximum number to know number of digits int m = getMax(list); // Do counting sort for every digit. Note that // instead of passing digit number, exp is passed. // exp is 10^i where i is current digit number for (int exp = 1; m / exp > 0; exp *= 10) countSort(list, exp); } static int getMax(LinkedList<Integer> list) { Node<Integer> traversal = list.head; int max = traversal.data; while (traversal != null) { if (traversal.data > max) { max = traversal.data; } traversal = traversal.next; } return max; } static void countSort(LinkedList<Integer> list, int exp) { LinkedList<Integer> output = new LinkedList<Integer>(list.length); // output array int i; LinkedList<Integer> count = new LinkedList<>(); int counter = 0; do { count.add(0); counter++; } while (counter < 10); //System.out.println("list length is: " + list.length); // Store count of occurrences in count[] for (i = 0; i < list.length; i++) { int countCurrentIndex = (list.get(i) / exp) % 10; int countCurrentIndexValue = count.get(countCurrentIndex); count.set(countCurrentIndex, ++countCurrentIndexValue); } //printLinkedList(count); // Change count[i] so that count[i] now contains // actual position of this digit in output[] for (i = 1; i < 10; i++) { count.set(i, count.get(i) + count.get(i - 1)); } // Build the output array for (i = list.length - 1; i >= 0; i--) { int countCurrentIndex = (list.get(i) / exp) % 10; int countCurrentIndexValue = count.get(countCurrentIndex); int outputCurrentIndex = countCurrentIndexValue - 1; int listCurrentIndexValue = list.get(i); output.set(outputCurrentIndex,listCurrentIndexValue); count.set(countCurrentIndex, --countCurrentIndexValue); } //printLinkedList(output); // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to current digit for (i = 0; i < list.length; i++) { int temp = output.get(i); list.set(i, temp); } } }
package com.pichincha.prueba.api; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.pichincha.prueba.bo.IPersonaBO; import com.pichincha.prueba.dto.PersonaDTO; import com.pichincha.prueba.dto.ResponseOk; import com.pichincha.prueba.exceptions.BOException; import com.pichincha.prueba.exceptions.CustomExceptionHandler; import com.pichincha.prueba.util.MensajesUtil; @RestController @RequestMapping("/persona") public class PersonaApi { @Autowired private IPersonaBO objIPersonaBO; @SuppressWarnings("unused") private static final Logger logger = LogManager.getLogger(PersonaApi.class.getName()); /** * Crear y actualizar personas * @param strLanguage * @param objPersonaDTO * @return * @throws BOException */ /*PUT http://localhost:8080/persona JSON BODY { "secuenciaPersona":2, --Solo se envia si se va actualizar "primerNombre":"BRYAN", "segundoNombre":"STEVEN",--opcional "primerApellido":"ZAMORA", "segundoApellido":"LITARDO",--opcional "secuenciaTipoIdentificacion":1, "numeroIdentificacion":"0928914464", "secuenciaGenero":1, "esActivo":true --solo se envia si se va actualizar }*/ @RequestMapping(method = RequestMethod.PUT) public ResponseEntity<?> crearOActualizaPersona( @RequestHeader( value = "Accept-Language", required = false) String strLanguage, @RequestBody PersonaDTO objPersonaDTO ) throws BOException { try { return new ResponseEntity<>(new ResponseOk( MensajesUtil.getMensaje("pru.response.ok", MensajesUtil.validateSupportedLocale(strLanguage)), objIPersonaBO.crearOActualizaPersona(objPersonaDTO)), HttpStatus.OK); } catch (BOException be) { logger.error(" ERROR => " + be.getTranslatedMessage(strLanguage)); throw new CustomExceptionHandler(be.getTranslatedMessage(strLanguage), be.getData()); } } @RequestMapping(method = RequestMethod.GET) public ResponseEntity<?> consultarDatosPersonas( @RequestHeader( value = "Accept-Language", required = false) String strLanguage, @RequestParam( value = "numeroIdentificacion", required = false) String strNumeroIdentificacion ) throws BOException { try { return new ResponseEntity<>(new ResponseOk( MensajesUtil.getMensaje("pru.response.ok", MensajesUtil.validateSupportedLocale(strLanguage)), objIPersonaBO.consultarDatosPersonas(strNumeroIdentificacion)) , HttpStatus.OK); } catch (BOException be) { logger.error(" ERROR => " + be.getTranslatedMessage(strLanguage)); throw new CustomExceptionHandler(be.getTranslatedMessage(strLanguage), be.getData()); } } }
package com.lesports.albatross.rss.impl; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import com.lesports.albatross.Constants; import com.lesports.albatross.db.RSSProvider; import com.lesports.albatross.db.RSSTable; import com.lesports.albatross.entity.compertition.RaceDetailEntity; import com.lesports.albatross.json.GsonHelper; import com.lesports.albatross.rss.inter.RSSServiceCallBack; import com.lesports.albatross.rss.utils.RSSNotifyHelper; import com.lesports.albatross.utils.DateUtil; import com.lesports.albatross.utils.LogUtil; import java.util.HashSet; public class RssServiceImpl { private static final String TAG = "RssServiceImpl"; /** * 订阅比赛 * @param context * @param entity * @param callback */ public boolean subscribe(final Context context, final RaceDetailEntity entity, final RSSServiceCallBack callback){ boolean flag = false; Cursor cursor = context.getContentResolver().query(RSSProvider.CONTENT_URI,new String[]{RSSTable.COLUMN_EPISODE_ID},RSSTable.COLUMN_MATCH_STATUS+"<>?",new String[]{"2"},null); if (cursor != null && cursor.getCount() >= Constants.MAX_RSS_COUNT) { if (callback != null) { callback.fail(Constants.ERROR_CODE_OVER_FLOW); } cursor.close(); return flag; } if (cursor != null ) { cursor.close(); } try { //Toast.makeText(context,"rss entity.getEpisodeId()"+entity.getEpisodeId(),2000).show(); ContentValues values = new ContentValues(); values.put(RSSTable.COLUMN_EPISODE_ID,entity.getId()); values.put(RSSTable.COLUMN_MATCH_TIME, DateUtil.str2Date(entity.getStartTime()).getTime()); values.put(RSSTable.COLUMN_MATCH_STATUS, entity.getMatchStatus()); values.put(RSSTable.COLUMN_MATCH_JSON, GsonHelper.toJson(entity)); Uri uri = context.getContentResolver().insert(RSSProvider.CONTENT_URI,values); if ("-1".equals(uri.getLastPathSegment())) { if (callback != null) { callback.fail(Constants.ERROR_CODE_EXCEPTION); } return flag; } if (callback != null ) { flag = true; RSSNotifyHelper.setSubscribed(true, context, entity); callback.success(); } } catch (Exception e) { LogUtil.e(TAG, "subscribe error id::" + entity.getId() + " " + e.toString()); if (callback != null) { callback.fail(Constants.ERROR_CODE_EXCEPTION); } } return flag; } /** * 取消订阅 * @param context * @param entity * @param callback */ public boolean unSubscribe(final Context context, final RaceDetailEntity entity, final RSSServiceCallBack callback){ boolean flag = false; try { int count = context.getContentResolver().delete(RSSProvider.CONTENT_URI, RSSTable.COLUMN_EPISODE_ID + "=?",new String[]{String.valueOf(entity.getId())}); if (count == 1) { if (callback != null) { flag = true; RSSNotifyHelper.setSubscribed(false, context, entity); callback.success(); } } else { if (callback != null) { callback.fail(Constants.ERROR_CODE_NO_DATA); } } } catch (Exception e) { LogUtil.e(TAG,"unSubscribe error id::"+entity.getId()+" "+e.toString()); if (callback != null) { callback.fail(Constants.ERROR_CODE_EXCEPTION); } } return flag; } /** * 获取所有预约的Id * @param context * @return */ public HashSet<String> getSubscribedMatchIds(Context context) { HashSet<String> subscribedMatchIds = new HashSet<String>(); Cursor cursor = null; try { cursor = context.getContentResolver().query(RSSProvider.CONTENT_URI,new String[]{RSSTable.COLUMN_EPISODE_ID}, null,null,null); while (cursor.moveToNext()) { subscribedMatchIds.add(cursor.getString(cursor.getColumnIndex(RSSTable.COLUMN_EPISODE_ID))); } } catch (Exception e) { LogUtil.e(TAG," getSubscribedMatchIds error "+e.toString()); } finally { if (cursor != null) { cursor.close(); } } return subscribedMatchIds; } /** * 清空已结束比赛 * @param context */ public void clearFinishedMatch(Context context,final RSSServiceCallBack callback) { try { context.getContentResolver().delete(RSSProvider.CONTENT_URI, RSSTable.COLUMN_MATCH_STATUS + "=?", new String[]{"2"}); if (callback != null) { callback.success(); } } catch (Exception e) { LogUtil.e(TAG,"clearFinishedMatch error ::"+e.toString()); if (callback != null) { callback.fail(Constants.ERROR_CODE_EXCEPTION); } } } }
package pl.basistam; import java.util.List; public class Book { private List<String> authors; private List<Title> titles; private String isbn; public List<String> getAuthors() { return authors; } public void setAuthors(List<String> authorList) { this.authors = authorList; } public List<Title> getTitles() { return titles; } public void setTitles(List<Title> titleList) { this.titles = titleList; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } @Override public String toString() { StringBuilder builder = new StringBuilder(); if (titles != null) { titles.forEach((t) -> { builder.append(t); builder.append("\n"); }); } if (authors != null) { builder.append("Autorzy: "); authors.forEach((a) -> { builder.append(a); builder.append(","); }); } builder.append("\n"); builder.append("ISBN: ").append(isbn); builder.append("\n"); return builder.toString(); } }
package com.saf.emart.pos.service; public class sn { public String getSerialNumber() { String serialNumber="8138190"; return serialNumber; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.ejbclient; import com.mycompany.Calculator; import com.mycompany.ProjectStarter; import com.mycompany.ProjectStarterImpl; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import weblogic.jndi.WLInitialContextFactory; /** * * @author kerch */ public class Main { public static void main(String[] args) throws NamingException { Hashtable settings = new Hashtable(); settings.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); settings.put(Context.PROVIDER_URL, "t3://127.0.0.1:7001"); InitialContext context = new InitialContext(settings); // context.lookup("projectStarterImpl#com.mycompany.ProjectStarter"); ProjectStarter projectStarter = (ProjectStarter) context.lookup("projectStarterImpl#com.mycompany.ProjectStarter"); int res=projectStarter.process(1, 2); System.out.println("res="+res); projectStarter = (ProjectStarter) context.lookup("b#com.mycompany.ProjectStarter"); res=projectStarter.process(1, 2); System.out.println("res="+res); System.out.println("---------------------------"); // Calculator calculator = (Calculator) context.lookup("calculator#com.mycompany.Calculator"); // calculator.add(1, 4); } }
package edu.mit.cci.simulation.web; import edu.mit.cci.simulation.model.MappedSimulation; import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @RooWebScaffold(path = "mappedsimulations", formBackingObject = MappedSimulation.class) @RequestMapping("/mappedsimulations") @Controller public class MappedSimulationController { @RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "accept=text/xml") @ResponseBody public MappedSimulation showXml(@PathVariable("id") Long id, Model model) { return MappedSimulation.findMappedSimulation(id); } @RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "accept=text/html") public String show(@PathVariable("id") Long id, Model model) { addDateTimeFormatPatterns(model); model.addAttribute("mappedsimulation", MappedSimulation.findMappedSimulation(id)); model.addAttribute("itemId", id); return "mappedsimulations/show"; } }
package in.anandm.oj.controller; import in.anandm.oj.command.RegistrationCommand; import in.anandm.oj.service.UserService; import in.anandm.oj.validator.RegistrationCommandValidator; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; /** * Handles requests for the application home page. */ @Controller public class HomeController extends BaseController { @Autowired private RegistrationCommandValidator registrationCommandValidator; @Autowired private UserService userService; /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { if (isAuthenticated()) { return "redirect:/problem"; } RegistrationCommand registrationCommand = new RegistrationCommand(); model.addAttribute("registrationCommand", registrationCommand); return "home"; } @RequestMapping(value = "/register", method = RequestMethod.POST) public String register(@ModelAttribute(value = "registrationCommand") RegistrationCommand registrationCommand, BindingResult errors, Model model, Locale locale, RedirectAttributes redirectAttributes) { registrationCommandValidator.validate(registrationCommand, errors); if (errors.hasErrors()) { model.addAttribute("registrationCommand", registrationCommand); return "home"; } // register user userService.registerUser(registrationCommand); addAlert(redirectAttributes, Alert.success("Register.User.success")); return "redirect:/"; } @RequestMapping(value = "/forgotPassword", method = RequestMethod.GET) public String forgotPasswordGet(Model model) { return "login/forgotPassword"; } @RequestMapping(value = "/forgotPassword", method = RequestMethod.POST) public String forgotPasswordPost(Model model) { return "redirect:/"; } @RequestMapping(value = "/resetPassword", method = RequestMethod.GET) public String resetPasswordGet(Model model) { return "login/resetPassword"; } @RequestMapping(value = "/resetPassword", method = RequestMethod.POST) public String resetPasswordPost(Model model) { return "redirect:/"; } }
package net.gupt.ebuy.util; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; /** * hibernate工具类 * @author glf * */ public class HibernateUtils { private static Configuration conf; private static ServiceRegistry reg; private static SessionFactory factory; //conf 对象只要加载一次就可以了 static { conf = new Configuration(); conf.configure(); reg = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry(); factory = conf.buildSessionFactory(reg); } /** * 开启会话 * @return */ public static Session openSession() { return factory.openSession(); } /** * 获取总记录数 * @param className 对应实体类名 * @return */ public static Integer getTotalRecord(String className) { Session session = HibernateUtils.openSession(); Query query = session.createQuery("from " + className + " as x"); Integer totalRecord = query.list().size(); session.close(); return totalRecord; } }
package StaticProxy; /** * @Auther: liuyi * @Date: 2019/6/21 15:58 * @Description: */ public class CountProxy { private Count count; public CountProxy(Count count1){ this.count = count1; } public void queryCount(){ System.out.println(count.toString() + " before query"); count.queryCount(); System.out.println(count.toString() + " after query"); } public void updateCount(){ System.out.println(count.toString() + " before update"); count.updateCount(); System.out.println(count.toString() + " after update"); } }
package org.example.codingtest.twoLevel; import java.util.LinkedList; import java.util.List; /** * 초당 최대 처리량 : 임의 시간부터 1초간 처리하는 요청의 최대 개수를 의미한다. - 응답 완료 여부에 관계 없이 * 입력 값으로는 * S : 응답 완료 시간 * T : 처리 시간 **/ public class TrafficKakao { private static final TrafficKakao o = new TrafficKakao(); public static void main(String[] args) { String[] lines = {"2016-09-15 20:59:57.421 0.351s", "2016-09-15 20:59:58.233 1.181s", "2016-09-15 20:59:58.299 0.8s", "2016-09-15 20:59:58.688 1.041s", "2016-09-15 20:59:59.591 1.412s", "2016-09-15 21:00:00.464 1.466s", "2016-09-15 21:00:00.741 1.581s", "2016-09-15 21:00:00.748 2.31s", "2016-09-15 21:00:00.966 0.381s", "2016-09-15 21:00:02.066 2.62s"}; int solution = o.solution(lines); System.out.println(solution); } private class Process { float start; float end; float total; public Process(float start, float end, float total) { this.start = start; this.end = end; this.total = total; } } public int solution(String[] lines) { int answer = 0; List<Process> list = new LinkedList<>(); for (String line : lines) { String s = line.replace("s", ""); String[] date = s.split(" "); String[] time = date[1].split(":"); float totalTime = Float.parseFloat(date[2]); float endTime = (Float.parseFloat(time[0]) * 3600) +(Float.parseFloat(time[1]) * 60) +Float.parseFloat(time[2]); float startTime = endTime - totalTime + 0.001f; list.add(new Process(startTime, endTime, totalTime)); } for(int i=0; i < list.size();i++){ Process cur = list.get(i); float range = cur.end + 0.999f; // 끝 시간을 기준으로 + 1초 int cnt = 0; for (int j = i; j < list.size(); j++) { Process next = list.get(j); if (range >= next.start) cnt++; } answer = Math.max(cnt, answer); } return answer; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.dthebus.gymweb.presentation.rest; import com.dthebus.gymweb.domain.accounts.Fees; import com.dthebus.gymweb.services.TotalFeesService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * * @author darren */ @Controller @RequestMapping(value= "api/fees") public class FeeController { @Autowired TotalFeesService fees; @RequestMapping(value = "all", method= RequestMethod.GET) @ResponseBody public List<Fees> allfees(){ return fees.findAll(); } @RequestMapping(value = "create", method = RequestMethod.POST) @ResponseBody public String create(@RequestBody Fees fee){ fees.persist(fee); return "fee Created"; } @RequestMapping(value ="price/{type}", method =RequestMethod.GET) @ResponseBody public double getPrice(@PathVariable String type){ return fees.getPrice(type); } }
package us.steveboyer.sdremote; import android.util.Log; import com.androidhive.jsonparsing.JSONParser; import org.json.JSONException; import org.json.JSONObject; /** * Created by steve on 4/15/15. */ public class mGPIO { public static class mConnection { public String host; public int port; public String username; public String password; public mConnection(String host) { this.host = host; this.port = 8000; this.username = "webiopi"; this.password = "raspberry"; } public mConnection(String host, int port, String user, String pass) { this.host = host; this.port = port; this.username = user; this.password = pass; } } private mConnection conn; private boolean connected; public mGPIO(mConnection conn){ this.conn = conn; } /** * outputSequence sends a sequence of bits to the specified * GPIO port with the delay specified. The sequence is specified * as a string of 0 and 1 characters. It doesn't validate the * string sent. This method works in an asynchronous way * starting a new Thread to make the request and ends. * <p> * If there is any connection exceptions it generates * a "ConnectionEvent", this is useful to detect if * GPIO is disconnected from the target host. * @param macro Name of macro */ public void sendMacro(final String macro) { final mGPIO self = this; Thread t = new Thread(new Runnable() { @Override public void run() { try { JSONParser parser = new JSONParser(conn.username, conn.password, conn.host); String url = "http://" + conn.host + ":" + conn.port + "/macros/"+macro; Log.d("Sent", url); JSONObject obj = parser.postJSONFromURL(url, conn.port); if (obj != null) { } } catch (JSONException e) { } catch (Exception e) { } } }); t.start(); } }
package com.googlecode.gwtwebgl.utils; import com.google.gwt.core.client.JsArrayBoolean; import com.google.gwt.typedarrays.shared.Float32Array; import com.google.gwt.typedarrays.shared.Int32Array; import com.google.gwt.typedarrays.shared.Uint32Array; import com.googlecode.gwtwebgl.html.WebGLBuffer; import com.googlecode.gwtwebgl.html.WebGLFramebuffer; import com.googlecode.gwtwebgl.html.WebGLProgram; import com.googlecode.gwtwebgl.html.WebGLRenderbuffer; import com.googlecode.gwtwebgl.html.WebGLTexture; public interface Any { public int getInt(); public boolean getBoolean(); public float getFloat(); public double getDouble(); public Uint32Array getUint32Array(); public Float32Array getFloat32Array(); public Object get(); public Int32Array getInt32Array(); public WebGLBuffer getWebGLBuffer(); public WebGLProgram getWebGLProgram(); public WebGLTexture getWebGLTexture(); public WebGLRenderbuffer getWebGLRenderbuffer(); public WebGLFramebuffer getWebGLFramebuffer(); public JsArrayBoolean getJsArrayBoolean(); public String castToString(); boolean isNull(); }
class Student { private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } } public class equal_method_of_object { public static void main(String[] args){ Student obj1 =new Student(1,"ankit"); Student obj2 =new Student(1,"arpit"); Student obj3 =new Student(1,"ankit"); System.out.println(obj1==obj2); System.out.println(obj1==obj3); System.out.println(obj3==obj1); System.out.println(obj1.equals(obj2)); System.out.println(obj1.equals(obj3)); System.out.println(obj2.equals(obj3)); System.out.println(obj2.equals(new Student(1,"arpit"))); } }
package com.ifeng.recom.mixrecall.common.config; import com.ctrip.framework.apollo.Apollo; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.model.ConfigChange; import com.ctrip.framework.apollo.model.ConfigChangeEvent; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.ifeng.recom.mixrecall.common.config.constant.ApolloConstant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.yaml.snakeyaml.Yaml; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by lilg1 on 2018/4/12. */ @Service public class TestUserConfig { private static Map<String, Set<String>> testUserMap; private static Logger logger = LoggerFactory.getLogger(Apollo.class); static { testUserMap = Maps.newHashMap(); } public void init(Config debugConfig) { String yml = debugConfig.getProperty(ApolloConstant.Test_Users, ""); loadTestUserConfig(yml); } public void onChangeJob(ConfigChangeEvent configChangeEvent) { //property未更新,不执行修改 if (!configChangeEvent.changedKeys().contains(ApolloConstant.Test_Users)) { return; } ConfigChange configChange = configChangeEvent.getChange(ApolloConstant.Test_Users); String yml = configChange.getNewValue(); logger.info("update debug user configuration: {}", yml); loadTestUserConfig(yml); } /** * @param updateTestUserMap */ public void updateTestUsers(Map<String, Set<String>> updateTestUserMap) { if (updateTestUserMap != null) { testUserMap.putAll(updateTestUserMap); } } /** * @param key * @param userSet */ public void putUserSet(String key, Set<String> userSet) { if (testUserMap != null) { testUserMap.put(key, userSet); } } /** * @param debugerSetKey * @return */ public static Set<String> getTestUser(String debugerSetKey) { Set<String> debugUsers = testUserMap.get(debugerSetKey); if (debugUsers != null) { return debugUsers; } return Sets.newHashSet(); } /** * 解析yml配置到test用户组 */ public void loadTestUserConfig(String yml) { Yaml yaml = new Yaml(); try { if (StringUtils.isBlank(yml)) { logger.warn("parse debug user configuration empty! "); } Object obj = yaml.load(yml); Map<String, Object> userMap = (Map) obj; for (String key : userMap.keySet()) { List<Object> list = (List<Object>) userMap.get(key); Set<String> userSet = Sets.newHashSet(); list.forEach(x -> userSet.add(String.valueOf(x))); logger.info("init debug:{} , users:{}", key, userSet); putUserSet(key, userSet); } } catch (Exception e) { logger.error("parse debug user configuration error: {}", e); } } }
package drummermc.debug; import java.io.File; import java.io.FileWriter; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import drummermc.debug.network.InfoList; import drummermc.debug.network.PacketCounterTile; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.MinecraftForge; public class CmdCheckVariableTileEntity implements ICommand { private static final String CMD = "tevars"; private ArrayList<TileEntity> tileEntitys; private static List<InfoList> lis; @Override public String getCommandName() { return CMD; } @Override public String getCommandUsage(ICommandSender iCommandSender) { return CMD; } @Override public void processCommand(ICommandSender iCommandSender, String[] args) { if(!(iCommandSender instanceof EntityPlayer)){ return; } EntityPlayer player = (EntityPlayer) iCommandSender; List<InfoList> list = new ArrayList<InfoList>(); for(World world : DimensionManager.getWorlds()){ for(Object obj : world.loadedTileEntityList){ if(obj instanceof TileEntity){ int counter = 0; try{ TileEntity tile = (TileEntity) obj; Class clazz = tile.getClass(); Field[] fields = clazz.getDeclaredFields(); for(Field field : fields){ boolean b1 = field.isAccessible(); field.setAccessible(true); try{ Object o = field.get(tile); if(o != null){ Class clazz2 = o.getClass(); try{ Method f = clazz2.getDeclaredMethod("iterator"); f.setAccessible(true); Iterator itr = (Iterator) f.invoke(o); counter = counter + getAmountOfFields(itr); }catch(Throwable e){ counter = counter + getAmount(o); } } }catch(Throwable e){ } field.setAccessible(b1); } }catch(Throwable e){ } try{ Class clazz = obj.getClass().getSuperclass(); while(clazz != TileEntity.class){ Field[] fields = clazz.getDeclaredFields(); for(Field field : fields){ boolean b1 = field.isAccessible(); field.setAccessible(true); try{ Object o = field.get(obj); if(o != null){ Class clazz2 = o.getClass(); try{ Method f = clazz2.getDeclaredMethod("iterator"); f.setAccessible(true); Iterator itr = (Iterator) f.invoke(o); counter = counter + getAmountOfFields(itr); }catch(Throwable e){ counter = counter + getAmount(o); } } }catch(Throwable e){ } field.setAccessible(b1); } clazz = clazz.getSuperclass(); } }catch(Throwable e){} list.add(new InfoList(obj.getClass().getName(), world.provider.dimensionId, counter)); } } } InfoList[] l = new InfoList[list.size()]; lis = list; Thread t = new Thread(new Runnable(){ List<InfoList> orginal = (List<InfoList>) ((ArrayList)lis).clone(); @Override public void run() { try{ File f = new File("tevars.txt"); if(f.exists()) f.delete(); f.createNewFile(); FileWriter w = new FileWriter(f); ArrayList<InfoList> output = new ArrayList<InfoList>(); for(int i = 0; i < orginal.size(); i++){ InfoList li = orginal.get(i); if(output.size() == 0) output.add(li); else{ for(int i2 = 0; i2 < output.size(); i2++){ if(output.get(i2).count > li.count){ output.add(i2, li); li = null; break; } } if(li != null) output.add(output.size(), li); } } for(int i = 0; i < output.size(); i++){ InfoList li = output.get(i); w.write("Class: " + li.tileEntityName + " Amount: " + li.count + " World id: " + li.worldID + "\n"); } w.close(); }catch(Throwable e){ } } }); t.start(); for(int i = 0; i < list.size(); i++){ l[i] = list.get(i); } new PacketCounterTile(player, l).sendPacketToPlayer(player); } public int getAmountOfFields(Iterator itr){ int i = 0; try{ while(itr.hasNext()) { Object element = itr.next(); i++; } }catch(Throwable e){ } return i; } public int getAmount(Object obj){ int i = 0; try{ for(Object o : (Object[])obj){ i++; } }catch(Throwable e){ } return i == 0 ? 1 : i; } @Override public List getCommandAliases() { return null; } @Override public int compareTo(Object arg0) { return 0; } @Override public boolean canCommandSenderUseCommand(ICommandSender iCommandSender) { return true; } @Override public List addTabCompletionOptions(ICommandSender iCommandSender, String[] args) { return null; } @Override public boolean isUsernameIndex(String[] args, int unknown) { return false; } }
package com.lidaye.shopIndex.domain.entity; import lombok.Data; import java.io.Serializable; @Data public class ShopShopcar implements Serializable { private Integer shopShopcarId; private Integer shopShopcarNumber; private Integer shopId; private Integer userId; private Integer orderId; private Integer shopShopcarStatus; }
package com.koma.component_base.base; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.jude.swipbackhelper.SwipeBackHelper; import io.reactivex.observers.ResourceObserver; /** * @author Koma * @date 18 40 * @des */ public class SwipeActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SwipeBackHelper.onCreate(this); SwipeBackHelper.getCurrentPage(this) .setSwipeBackEnable(true) .setSwipeSensitivity(0.5f) .setSwipeRelateEnable(true) .setSwipeRelateOffset(300); //ViewServer.get(this).addWindow(this); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); SwipeBackHelper.onPostCreate(this); } @Override protected void onDestroy() { super.onDestroy(); SwipeBackHelper.onDestroy(this); //ViewServer.get(this).removeWindow(this); } }
package com.hhdb.csadmin.common.bean; import java.util.HashMap; import java.util.Map; public class ServerBean { private int dbid; private String connKey; private String port; private String dbName; private String host; private String password; private String userName; private String schema; private int schemaId; private String name; public ServerBean() { } public ServerBean(String connKey, String port, String dbName, String host, String password, String userName) { this.connKey = connKey; this.port = port; this.dbName = dbName; this.host = host; this.password = password; this.userName = userName; } public ServerBean(String port, String dbName, String host, String password, String userName) { this.port = port; this.dbName = dbName; this.host = host; this.password = password; this.userName = userName; } public ServerBean(String port, String dbName, String host, String password, String userName, String schema, int schemaId) { this.port = port; this.dbName = dbName; this.host = host; this.password = password; this.userName = userName; this.schema = schema; this.schemaId = schemaId; } public int getDbid() { return dbid; } public void setDbid(int dbid) { this.dbid = dbid; } public String getPort() { return this.port; } public void setPort(String port) { this.port = port; } public String getDBName() { return this.dbName; } public void setDBName(String dbName) { this.dbName = dbName; } public String getHost() { return this.host; } public void setHost(String host) { this.host = host; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public int getSchemaId() { return schemaId; } public void setSchemaId(int schemaId) { this.schemaId = schemaId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getConnKey() { return connKey; } public void setConnKey(String connKey) { this.connKey = connKey; } public Map<String, Object> getConnMap() { Map<String, Object> connMap = new HashMap<String, Object>(); connMap.put("password", password); connMap.put("username", dbName); connMap.put("dbPort", port); connMap.put("dbUrl", host); return connMap; } public Map<String, Object> getConnMapWithDBName() { Map<String, Object> connMap = getConnMap(); connMap.put("dbName", dbName); return connMap; } public Map<String, Object> getConnMapWithSchema() { Map<String, Object> connMap = getConnMapWithDBName(); connMap.put("schema", schema); connMap.put("schemaId", schemaId); return connMap; } public ServerBean clone() { ServerBean sb = new ServerBean(); sb.setHost(host); sb.setPort(port); sb.setUserName(userName); sb.setDBName(dbName); sb.setPassword(password); return sb; } }
package com.shangdao.phoenix.entity.account; import java.util.Date; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import com.shangdao.phoenix.entity.company.Company; import com.shangdao.phoenix.entity.companybill.CompanyBill; import com.shangdao.phoenix.entity.entityManager.EntityManager; import com.shangdao.phoenix.entity.entityManager.EntityManagerRepository; import com.shangdao.phoenix.entity.interfaces.IBaseEntity; import com.shangdao.phoenix.entity.state.State; import com.shangdao.phoenix.entity.user.User; @Entity @Table(name = "account") public class Account implements IBaseEntity{ /** * */ @Transient public static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private long id; @ManyToOne @JoinColumn(name = "entity_manager_id") private EntityManager entityManager; @Column(name = "name") private String name; @Column(name = "deleted_at") @JsonIgnore private Date deletedAt; @ManyToOne @JoinColumn(name = "state_id") private State state; @Column(name = "created_at") @JsonIgnore private Date createdAt; @ManyToOne @JoinColumn(name = "created_by") @JsonIgnore private User createdBy; @Column(name = "remainder") private Double remainder; //当前总余额 @Column(name = "pay_amount") private Double payRemainder; //当前充值剩余 @Column(name = "give_amount") private Double giveRemainder; //当前赠送剩余 @Column(name = "history_pay") private Double historyPay; //历史充值 @Column(name = "history_give") private Double historyGive; //历史赠送 @OneToOne(mappedBy = "account") private Company company; @OneToOne(mappedBy = "account") private User user; @Enumerated(EnumType.STRING) @Transient private CompanyBill.BillTypeEnum payType; @Enumerated(EnumType.STRING) @Transient private CompanyBill.PlatformEnum platType; @Transient private Double payAmount; //当前充值或者扣钱金额 @Transient private Double giveAmount; //当前充值赠送金额 @Transient private String note; @Enumerated(EnumType.STRING) @Column(name = "account_type") private Company.OrganizationEnum accountType; public Account(){ } public Account(EntityManagerRepository repository,String name,Company.OrganizationEnum type){ this.remainder = 0d; this.giveRemainder = 0d; this.payRemainder = 0d; this.historyGive = 0d; this.historyPay = 0d; this.createdAt = new Date(); this.name = name; this.entityManager = repository.findByName("account"); this.accountType = type; } public void deposit(double pay, double give) { double absPay = Math.abs(pay); double absGive = Math.abs(give); remainder += (absPay+absGive); payRemainder += absPay; giveRemainder += absGive; historyPay += absPay; historyGive += absGive; } public void consume (double value, CompanyBill.BillTypeEnum typeEnum) { double absValue = Math.abs(value); remainder -= absValue; if(CompanyBill.BillTypeEnum.CONSUME.equals(typeEnum)){ giveRemainder -= absValue; historyGive -= absValue; }else{ if(payRemainder >= absValue){ payRemainder -= absValue; }else{ payRemainder = 0d; giveRemainder -= (absValue-payRemainder); } } } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public CompanyBill.PlatformEnum getPlatType() { return platType; } public void setPlatType(CompanyBill.PlatformEnum platType) { this.platType = platType; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Company.OrganizationEnum getAccountType() { return accountType; } public void setAccountType(Company.OrganizationEnum accountType) { this.accountType = accountType; } public Double getGiveAmount() { return giveAmount; } public void setGiveAmount(Double giveAmount) { this.giveAmount = giveAmount; } public Double getPayAmount() { return payAmount; } public void setPayAmount(Double payAmount) { this.payAmount = payAmount; } public CompanyBill.BillTypeEnum getPayType() { return payType; } public void setPayType(CompanyBill.BillTypeEnum payType) { this.payType = payType; } @Override public long getId() { return id; } @Override public void setId(long id) { this.id = id; } @Override public EntityManager getEntityManager() { return entityManager; } @Override public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public Date getDeletedAt() { return deletedAt; } @Override public void setDeletedAt(Date deletedAt) { this.deletedAt = deletedAt; } @Override public State getState() { return state; } @Override public void setState(State state) { this.state = state; } @Override public Date getCreatedAt() { return createdAt; } @Override public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } @Override public User getCreatedBy() { return createdBy; } @Override public void setCreatedBy(User createdBy) { this.createdBy = createdBy; } public Double getRemainder() { return remainder; } public void setRemainder(Double remainder) { this.remainder = remainder; } public Double getPayRemainder() { return payRemainder; } public void setPayRemainder(Double payRemainder) { this.payRemainder = payRemainder; } public Double getGiveRemainder() { return giveRemainder; } public void setGiveRemainder(Double giveRemainder) { this.giveRemainder = giveRemainder; } public Double getHistoryPay() { return historyPay; } public void setHistoryPay(Double historyPay) { this.historyPay = historyPay; } public Double getHistoryGive() { return historyGive; } public void setHistoryGive(Double historyGive) { this.historyGive = historyGive; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } }
package com.javasampleapproach.mysql.association.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.javasampleapproach.mysql.association.model.Activities; import com.javasampleapproach.mysql.association.repo.ActivityRepository; import com.javasampleapproach.mysql.model.Api; import com.javasampleapproach.mysql.repo.ApiRepository; @Service public class ActivitiesService { @Autowired private ActivityRepository activityrepo; public void addactivity(Activities activities){ activityrepo.save(activities); } public void deleteactivity(long id) { activityrepo.delete(id); } public void updateactivity(long id, Activities activities) { activityrepo.save(activities); } public Activities getactivity(long id) { return (Activities) activityrepo.findOne(id); } public List<Activities>getallactivity() { List<Activities> activity=new ArrayList<>(); activityrepo.findAll() .forEach(activity::add); return activity; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.inbio.ara.eao.taxonomy.impl; import java.util.List; import org.inbio.ara.eao.taxonomy.*; import javax.ejb.Stateless; import javax.persistence.Query; import org.inbio.ara.eao.BaseEAOImpl; import org.inbio.ara.persistence.taxonomy.ReferenceType; /** * * @author esmata */ @Stateless public class ReferenceTypeEAOImpl extends BaseEAOImpl<ReferenceType, Long> implements ReferenceTypeEAOLocal { public List<ReferenceType> allReferenceTypeOrderByName(){ Query q = em.createQuery("from ReferenceType order by name"); return (List<ReferenceType>)q.getResultList(); } }
/** * This class is generated by jOOQ */ package schema.tables.records; import java.sql.Timestamp; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record9; import org.jooq.Row9; import org.jooq.impl.UpdatableRecordImpl; import org.jooq.types.UInteger; import schema.tables.CredentialsCredentialsapiconfig; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.4" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class CredentialsCredentialsapiconfigRecord extends UpdatableRecordImpl<CredentialsCredentialsapiconfigRecord> implements Record9<Integer, Timestamp, Byte, String, String, Byte, Byte, UInteger, Integer> { private static final long serialVersionUID = -946819266; /** * Setter for <code>bitnami_edx.credentials_credentialsapiconfig.id</code>. */ public void setId(Integer value) { set(0, value); } /** * Getter for <code>bitnami_edx.credentials_credentialsapiconfig.id</code>. */ public Integer getId() { return (Integer) get(0); } /** * Setter for <code>bitnami_edx.credentials_credentialsapiconfig.change_date</code>. */ public void setChangeDate(Timestamp value) { set(1, value); } /** * Getter for <code>bitnami_edx.credentials_credentialsapiconfig.change_date</code>. */ public Timestamp getChangeDate() { return (Timestamp) get(1); } /** * Setter for <code>bitnami_edx.credentials_credentialsapiconfig.enabled</code>. */ public void setEnabled(Byte value) { set(2, value); } /** * Getter for <code>bitnami_edx.credentials_credentialsapiconfig.enabled</code>. */ public Byte getEnabled() { return (Byte) get(2); } /** * Setter for <code>bitnami_edx.credentials_credentialsapiconfig.internal_service_url</code>. */ public void setInternalServiceUrl(String value) { set(3, value); } /** * Getter for <code>bitnami_edx.credentials_credentialsapiconfig.internal_service_url</code>. */ public String getInternalServiceUrl() { return (String) get(3); } /** * Setter for <code>bitnami_edx.credentials_credentialsapiconfig.public_service_url</code>. */ public void setPublicServiceUrl(String value) { set(4, value); } /** * Getter for <code>bitnami_edx.credentials_credentialsapiconfig.public_service_url</code>. */ public String getPublicServiceUrl() { return (String) get(4); } /** * Setter for <code>bitnami_edx.credentials_credentialsapiconfig.enable_learner_issuance</code>. */ public void setEnableLearnerIssuance(Byte value) { set(5, value); } /** * Getter for <code>bitnami_edx.credentials_credentialsapiconfig.enable_learner_issuance</code>. */ public Byte getEnableLearnerIssuance() { return (Byte) get(5); } /** * Setter for <code>bitnami_edx.credentials_credentialsapiconfig.enable_studio_authoring</code>. */ public void setEnableStudioAuthoring(Byte value) { set(6, value); } /** * Getter for <code>bitnami_edx.credentials_credentialsapiconfig.enable_studio_authoring</code>. */ public Byte getEnableStudioAuthoring() { return (Byte) get(6); } /** * Setter for <code>bitnami_edx.credentials_credentialsapiconfig.cache_ttl</code>. */ public void setCacheTtl(UInteger value) { set(7, value); } /** * Getter for <code>bitnami_edx.credentials_credentialsapiconfig.cache_ttl</code>. */ public UInteger getCacheTtl() { return (UInteger) get(7); } /** * Setter for <code>bitnami_edx.credentials_credentialsapiconfig.changed_by_id</code>. */ public void setChangedById(Integer value) { set(8, value); } /** * Getter for <code>bitnami_edx.credentials_credentialsapiconfig.changed_by_id</code>. */ public Integer getChangedById() { return (Integer) get(8); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record9 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row9<Integer, Timestamp, Byte, String, String, Byte, Byte, UInteger, Integer> fieldsRow() { return (Row9) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row9<Integer, Timestamp, Byte, String, String, Byte, Byte, UInteger, Integer> valuesRow() { return (Row9) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Integer> field1() { return CredentialsCredentialsapiconfig.CREDENTIALS_CREDENTIALSAPICONFIG.ID; } /** * {@inheritDoc} */ @Override public Field<Timestamp> field2() { return CredentialsCredentialsapiconfig.CREDENTIALS_CREDENTIALSAPICONFIG.CHANGE_DATE; } /** * {@inheritDoc} */ @Override public Field<Byte> field3() { return CredentialsCredentialsapiconfig.CREDENTIALS_CREDENTIALSAPICONFIG.ENABLED; } /** * {@inheritDoc} */ @Override public Field<String> field4() { return CredentialsCredentialsapiconfig.CREDENTIALS_CREDENTIALSAPICONFIG.INTERNAL_SERVICE_URL; } /** * {@inheritDoc} */ @Override public Field<String> field5() { return CredentialsCredentialsapiconfig.CREDENTIALS_CREDENTIALSAPICONFIG.PUBLIC_SERVICE_URL; } /** * {@inheritDoc} */ @Override public Field<Byte> field6() { return CredentialsCredentialsapiconfig.CREDENTIALS_CREDENTIALSAPICONFIG.ENABLE_LEARNER_ISSUANCE; } /** * {@inheritDoc} */ @Override public Field<Byte> field7() { return CredentialsCredentialsapiconfig.CREDENTIALS_CREDENTIALSAPICONFIG.ENABLE_STUDIO_AUTHORING; } /** * {@inheritDoc} */ @Override public Field<UInteger> field8() { return CredentialsCredentialsapiconfig.CREDENTIALS_CREDENTIALSAPICONFIG.CACHE_TTL; } /** * {@inheritDoc} */ @Override public Field<Integer> field9() { return CredentialsCredentialsapiconfig.CREDENTIALS_CREDENTIALSAPICONFIG.CHANGED_BY_ID; } /** * {@inheritDoc} */ @Override public Integer value1() { return getId(); } /** * {@inheritDoc} */ @Override public Timestamp value2() { return getChangeDate(); } /** * {@inheritDoc} */ @Override public Byte value3() { return getEnabled(); } /** * {@inheritDoc} */ @Override public String value4() { return getInternalServiceUrl(); } /** * {@inheritDoc} */ @Override public String value5() { return getPublicServiceUrl(); } /** * {@inheritDoc} */ @Override public Byte value6() { return getEnableLearnerIssuance(); } /** * {@inheritDoc} */ @Override public Byte value7() { return getEnableStudioAuthoring(); } /** * {@inheritDoc} */ @Override public UInteger value8() { return getCacheTtl(); } /** * {@inheritDoc} */ @Override public Integer value9() { return getChangedById(); } /** * {@inheritDoc} */ @Override public CredentialsCredentialsapiconfigRecord value1(Integer value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public CredentialsCredentialsapiconfigRecord value2(Timestamp value) { setChangeDate(value); return this; } /** * {@inheritDoc} */ @Override public CredentialsCredentialsapiconfigRecord value3(Byte value) { setEnabled(value); return this; } /** * {@inheritDoc} */ @Override public CredentialsCredentialsapiconfigRecord value4(String value) { setInternalServiceUrl(value); return this; } /** * {@inheritDoc} */ @Override public CredentialsCredentialsapiconfigRecord value5(String value) { setPublicServiceUrl(value); return this; } /** * {@inheritDoc} */ @Override public CredentialsCredentialsapiconfigRecord value6(Byte value) { setEnableLearnerIssuance(value); return this; } /** * {@inheritDoc} */ @Override public CredentialsCredentialsapiconfigRecord value7(Byte value) { setEnableStudioAuthoring(value); return this; } /** * {@inheritDoc} */ @Override public CredentialsCredentialsapiconfigRecord value8(UInteger value) { setCacheTtl(value); return this; } /** * {@inheritDoc} */ @Override public CredentialsCredentialsapiconfigRecord value9(Integer value) { setChangedById(value); return this; } /** * {@inheritDoc} */ @Override public CredentialsCredentialsapiconfigRecord values(Integer value1, Timestamp value2, Byte value3, String value4, String value5, Byte value6, Byte value7, UInteger value8, Integer value9) { value1(value1); value2(value2); value3(value3); value4(value4); value5(value5); value6(value6); value7(value7); value8(value8); value9(value9); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached CredentialsCredentialsapiconfigRecord */ public CredentialsCredentialsapiconfigRecord() { super(CredentialsCredentialsapiconfig.CREDENTIALS_CREDENTIALSAPICONFIG); } /** * Create a detached, initialised CredentialsCredentialsapiconfigRecord */ public CredentialsCredentialsapiconfigRecord(Integer id, Timestamp changeDate, Byte enabled, String internalServiceUrl, String publicServiceUrl, Byte enableLearnerIssuance, Byte enableStudioAuthoring, UInteger cacheTtl, Integer changedById) { super(CredentialsCredentialsapiconfig.CREDENTIALS_CREDENTIALSAPICONFIG); set(0, id); set(1, changeDate); set(2, enabled); set(3, internalServiceUrl); set(4, publicServiceUrl); set(5, enableLearnerIssuance); set(6, enableStudioAuthoring); set(7, cacheTtl); set(8, changedById); } }
package com.beike.service.impl.user; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.beike.common.enums.user.ProfileType; import com.beike.dao.GenericDao; import com.beike.dao.user.UserAddressDao; import com.beike.dao.user.UserExpandDao; import com.beike.entity.user.UserAddress; import com.beike.entity.user.UserExpand; import com.beike.form.AccessToken; import com.beike.form.BaiduAccessToken; import com.beike.form.TencentqqAccessToken; import com.beike.form.XiaoNeiAccessToken; import com.beike.service.impl.GenericServiceImpl; import com.beike.service.user.UserExpandService; import com.beike.util.StaticDomain; import com.beike.util.alipay.AlipayModel; import com.beike.util.hao3604j.Tuan360Model; import com.beike.util.sina.RequestToken; import com.beike.util.sina.SinaAccessToken; import com.beike.util.tencent.ResModel; /** * project:beiker * Title:用户扩展信息Service * Description: * Copyright:Copyright (c) 2011 * Company:Sinobo * @author qiaowb * @date Mar 16, 2012 10:50:36 AM * @version 1.0 */ @Service("userExpandService") public class UserExpandServiceImpl extends GenericServiceImpl<UserExpand, Long> implements UserExpandService { @Autowired private UserExpandDao userExpandDao; @Autowired private UserAddressDao userAddressDao; /* (non-Javadoc) * @see com.beike.service.user.UserExpandService#addUserExpand(com.beike.entity.user.UserExpand) */ @Override public Long addUserExpand(UserExpand userExpand) { return userExpandDao.addUserExpand(userExpand); } /* (non-Javadoc) * @see com.beike.service.user.UserExpandService#getUserExpandById(java.lang.Long) */ @Override public UserExpand getUserExpandByUserId(Long userId) { UserExpand userExpand = userExpandDao.getUserExpandByUserId(userId); if(userExpand!=null){ if(StringUtils.isNotEmpty(userExpand.getAvatar())){ if(!userExpand.getAvatar().startsWith("http://")){ userExpand.setAvatar(StaticDomain.getDomain("") + "/" + userExpand.getAvatar()); } }else{ userExpand.setAvatar(""); } } return userExpand; } /* (non-Javadoc) * @see com.beike.service.user.UserExpandService#updateUserAvatar(com.beike.entity.user.UserExpand) */ @Override public int updateUserAvatar(UserExpand userExpand) { int ret = userExpandDao.updateUserExpand(userExpand); if(ret<=0){ userExpandDao.addUserExpand(userExpand); ret = 1; } return ret; } /* (non-Javadoc) * @see com.beike.service.user.UserExpandService#updateUserExpand(com.beike.entity.user.UserExpand) */ @Override public int updateUserExpand(UserExpand userExpand) { userExpand.setAvatar(""); int ret = userExpandDao.updateUserExpand(userExpand); if(ret<=0){ userExpandDao.addUserExpand(userExpand); ret = 1; } return ret; } /* (non-Javadoc) * @see com.beike.service.GenericService#findById(java.io.Serializable) */ @Override public UserExpand findById(Long id) { return null; } @Override public GenericDao<UserExpand, Long> getDao() { return userExpandDao; } @Override public int updateUserExpand(UserExpand userExpand, UserAddress userAddress) { updateUserExpand(userExpand); if(userAddress!=null){ int ret = userAddressDao.updateUserAddress(userAddress); if(ret <= 0){ userAddressDao.addUserAddress(userAddress); } } return 0; } @Override public int addUserExpand(Long userid, AccessToken accessToken, ProfileType profile) { try{ //同步数据 UserExpand userExpand = new UserExpand(); userExpand.setUserId(userid); userExpand.setGender(0); String headIconUrl = null; if(accessToken instanceof BaiduAccessToken){ BaiduAccessToken baiduToken = (BaiduAccessToken)accessToken; userExpand.setNickName(baiduToken.getScreenName()); headIconUrl = baiduToken.getHeadIcon(); }else if(accessToken instanceof RequestToken){ RequestToken sinaToken = (RequestToken)accessToken; userExpand.setNickName(sinaToken.getScreenName()); headIconUrl = sinaToken.getHeadIcon(); }else if(accessToken instanceof XiaoNeiAccessToken){ XiaoNeiAccessToken xiaoneiToken = (XiaoNeiAccessToken)accessToken; userExpand.setNickName(xiaoneiToken.getScreenName()); headIconUrl = xiaoneiToken.getHeadIcon(); }else if(accessToken instanceof TencentqqAccessToken){ TencentqqAccessToken qqToken = (TencentqqAccessToken)accessToken; userExpand.setNickName(qqToken.getScreenName()); headIconUrl = qqToken.getHeadIcon(); }else if(accessToken instanceof ResModel){ ResModel tencentweiboToken = (ResModel)accessToken; userExpand.setNickName(tencentweiboToken.getWeiboname()); headIconUrl = tencentweiboToken.getHeadIcon(); }else if(accessToken instanceof Tuan360Model){ Tuan360Model tuan360Model=(Tuan360Model) accessToken; userExpand.setNickName(tuan360Model.getQname()); headIconUrl = ""; }else if(accessToken instanceof AlipayModel){ AlipayModel alipayModel = (AlipayModel)accessToken; userExpand.setNickName(alipayModel.getReal_name()); headIconUrl = ""; } if(StringUtils.isNotEmpty(headIconUrl)){ if(profile.equals(ProfileType.BAIDUCONFIG)){ headIconUrl = "http://himg.bdimg.com/sys/portrait/item/" + headIconUrl; }else if(profile.equals(ProfileType.TENCENTCONFIG)){ headIconUrl = headIconUrl + "/100"; } } userExpand.setAvatar(headIconUrl); if(StringUtils.isNotEmpty(userExpand.getNickName()) || StringUtils.isNotEmpty(userExpand.getAvatar())){ //插入用户扩展信息 if(userExpandDao.getUserExpandByUserId(userid) == null){ //插入数据 userExpandDao.addUserExpand(userExpand); } } }catch(Exception ex){ ex.printStackTrace(); } return 0; } }
package test; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import pojo.Book; import utils.DbUtils; public class Program { public static void main(String[] args) { try( Connection connection = DbUtils.getConnection(); Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);) { String sql = "select * from BookTable"; try( ResultSet rs = statement.executeQuery(sql); ) { if( rs.first()) { Book book = new Book(rs.getInt("book_id"),rs.getString("subject_name"),rs.getString("book_name"),rs.getString("author_name"),rs.getFloat("price"),rs.getDate("publish_date")); System.out.println(book.toString()); } if( rs.last()) { Book book = new Book(rs.getInt("book_id"),rs.getString("subject_name"),rs.getString("book_name"),rs.getString("author_name"),rs.getFloat("price"),rs.getDate("publish_date")); System.out.println(book.toString()); } } } catch (SQLException e) { e.printStackTrace(); } } }
/* * Copyright (c) 2004 Steve Northover and Mike Wilson * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ package part1.ch15; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; import org.eclipse.swt.layout.*; public class FormLayout7 { public static void main(String[] args) { Display display = new Display(); final Shell shell = new Shell(display); int style = SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL; List list = new List(shell, style); list.setItems(new String[] { "One", "Two", "Three" }); Sash sash = new Sash(shell, SWT.VERTICAL); Text text = new Text(shell, style); /* Create a FormLayout to configure the Sash */ FormLayout layout = new FormLayout(); shell.setLayout(layout); FormData listData = new FormData(); listData.left = new FormAttachment(0); listData.right = new FormAttachment(sash); listData.top = new FormAttachment(0); listData.bottom = new FormAttachment(100); list.setLayoutData(listData); final FormData sashData = new FormData(); sashData.left = new FormAttachment(30); sashData.top = new FormAttachment(0); sashData.bottom = new FormAttachment(100); sash.setLayoutData(sashData); sash.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (event.detail != SWT.DRAG) { sashData.left = new FormAttachment(0, event.x); shell.layout(); } } }); FormData data2 = new FormData(); data2.left = new FormAttachment(sash); data2.right = new FormAttachment(100); data2.top = new FormAttachment(0); data2.bottom = new FormAttachment(100); text.setLayoutData(data2); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
package com.pisen.ott.launcher.widget; import java.io.File; import android.content.Context; import android.content.res.Resources; import android.izy.util.LogCat; import android.izy.util.StringUtils; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import com.pisen.ott.launcher.R; import com.pisen.ott.launcher.service.UiVersionInfo.UiContent; import com.pisen.ott.launcher.utils.AppUtils; import com.pisen.ott.launcher.utils.FileDownLoader; import com.pisen.ott.launcher.utils.FileDownLoader.AsyncLoaderListener; import com.pisen.ott.launcher.utils.FileUtils; import com.pisen.ott.launcher.utils.HttpUtils; /** * 支持下载安装的控件 * * @author yangyp * @version 1.0, 2015年2月12日 下午3:31:16 */ public class SearchDownloadItemView extends FrameLayout implements OnClickListener, IDownloadItem { private static final int DWON_FAILED = 0x01; private static final int DWON_START = 0x02; private static final int DWON_LODING = 0x03; private static final int DWON_FINISH = 0x04; private TextView txtName; private LinearLayout controlLayout; private ImageView imgIcon; private Button btnInstall; private UiContent uiContent; private Context context; private GridScaleView gridView; public SearchDownloadItemView(Context context) { this(context, null); } public SearchDownloadItemView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; View.inflate(context, R.layout.icon_reflect_download_search, this); txtName = (TextView) findViewById(R.id.txtName); imgIcon = (ImageView) findViewById(R.id.imgIcon); controlLayout = (LinearLayout) findViewById(R.id.controlLayout); btnInstall = (Button) findViewById(R.id.btnInstall); btnInstall.setOnClickListener(this); } @Override public void setUiContent(UiContent content) { this.uiContent = content; } public void setName(String name) { txtName.setText(name); if (StringUtils.isEmpty(name)) { txtName.setVisibility(View.GONE); }else{ txtName.setVisibility(View.VISIBLE); } } public void setAppIcon(Bitmap bm){ imgIcon.setImageBitmap(bm); } public void setAppIcon(Drawable drawable){ imgIcon.setImageDrawable(drawable); } public boolean checkInstalled() { if (AppUtils.checkInstalled(context, uiContent)) { if (gridView != null) { gridView.unlockItem(); } hideControlLayout(); // showControlLayout(); // btnInstall.setText("已安装"); // setDrawbleLeft(btnInstall, R.drawable.app_statu_exist); return true; } return false; } @Override public void nextClick(UiContent uiContent, GridScaleView grdContent) { Log.e("hegang", "nextClick = "); this.gridView = grdContent; if (!HttpUtils.isNetworkAvailable(context)) { Toast.makeText(context, getResources().getString(R.string.error_net), 1).show(); return; } this.uiContent = uiContent; // 判断是否安装,如果安装了直接启动 if (!AppUtils.isInstalledApk(context, uiContent)) { if (!isShowControl()) { showControlLayout(); if (FileUtils.isExists(FileUtils.getUpdateFile(context), FileUtils.getFileName(uiContent.ApkFile))) { btnInstall.setText(getResources().getString(R.string.install_now)); } } else { // Install Click dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)); } }else{ if (gridView != null) { gridView.unlockItem(); } } } public boolean isShowControl() { return controlLayout.getVisibility() == View.VISIBLE; } @Override public void showControlLayout() { if (!isShowControl()) { int id = getId(); setNextFocusUpId(id); setNextFocusDownId(id); setNextFocusLeftId(id); setNextFocusRightId(id); controlLayout.setVisibility(View.VISIBLE); btnInstall.setVisibility(View.VISIBLE); btnInstall.setText(getResources().getString(R.string.install_down)); setDrawbleLeft(btnInstall, R.drawable.app_statu_down); } } @Override public void hideControlLayout() { if (isShowControl()) { setNextFocusUpId(View.NO_ID); setNextFocusDownId(View.NO_ID); setNextFocusLeftId(View.NO_ID); setNextFocusRightId(View.NO_ID); controlLayout.setVisibility(View.GONE); btnInstall.setText(getResources().getString(R.string.install_down)); setDrawbleLeft(btnInstall, R.drawable.app_statu_down); } } @Override public boolean dispatchKeyEvent(KeyEvent event) { Log.e("hegang", "dispatchKeyEvent = "); if (isShowControl()) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_HOME) { hideControlLayout(); cancelDownload(); return true; } if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_DOWN: return true; case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_DPAD_CENTER: if (btnInstall.getVisibility() == View.VISIBLE) { btnInstall.performClick(); } return true; } } } return super.dispatchKeyEvent(event); } @Override public void onClick(View v) { Log.e("hegang", "onClick = "); if (!HttpUtils.isNetworkAvailable(context)) { Toast.makeText(context, getResources().getString(R.string.error_net), 1).show(); return; } if (!AppUtils.isInstalledApk(context, uiContent)) { String btnVaule = btnInstall.getText().toString(); if (btnVaule.equals(getResources().getString(R.string.install_now))) { File file = new File(FileUtils.getUpdateFile(context), FileUtils.getFileName(uiContent.ApkFile)); if (file.exists()) { if (gridView != null) { gridView.unlockItem(); } AppUtils.installApk(context, file); } else { downLoadApk(uiContent.ApkFile); LogCat.e(getResources().getString(R.string.error_down_package_lose)); } } // else if(btnVaule.equals("已安装")){ // AppUtils.isInstalledApk(context, uiContent); // } else { downLoadApk(uiContent.ApkFile); } } } private void downLoadApk(String url) { Log.e("hegang", "downLoadApk = "); if (!HttpUtils.isNetworkAvailable(context)) { Toast.makeText(context, getResources().getString(R.string.error_net), 1).show(); return; } if (StringUtils.isEmpty(url)) { return; } FileDownLoader.getDownLoader(context).download(url, new AsyncLoaderListener() { @Override public void onStart() { updateHanlder.sendEmptyMessage(DWON_START); } @Override public void onSuccess(File file) { LogCat.i("FileDownLoader:onSuccess"); Message msg = new Message(); msg.what = DWON_FINISH; msg.arg1 = 0; updateHanlder.sendMessage(msg); // 启动安装 AppUtils.installApk(context, file); } @Override public void onFailed(String erroInfo) { LogCat.e("下载失败--FileDownLoader:" + erroInfo); // 下载出错,恢复到下载安装界面 Message msg = new Message(); msg.what = DWON_FAILED; msg.arg1 = 0; msg.obj = erroInfo; updateHanlder.sendMessage(msg); } @Override public void onDownLoading(int progress, String temSize, String totalSize) { sendUpdateProgress(progress); } }); } /** * 取消下载任务 */ public void cancelDownload() { FileDownLoader.getDownLoader(context).cancelTasks(); } /** * 根据progress进度移动imageview */ private final Handler updateHanlder = new Handler() { @Override public void handleMessage(Message msg) { RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) controlLayout.getLayoutParams(); if (msg.what == DWON_FAILED) { lp.bottomMargin = 0; hideControlLayout(); String info = (String) msg.obj; Toast.makeText(getContext(), info, 1).show(); } else if (msg.what == DWON_LODING) { int margin = ((controlLayout.getHeight()+lp.bottomMargin) * msg.arg1) / 100; if (margin > lp.bottomMargin) { lp.bottomMargin = margin; } if (msg.arg1 == 100) { controlLayout.setVisibility(View.GONE); } } else if (msg.what == DWON_FINISH) { lp.bottomMargin = 0; showControlLayout(); btnInstall.setText(getResources().getString(R.string.install_now)); }else if (msg.what == DWON_START) { btnInstall.setVisibility(View.GONE); controlLayout.setVisibility(View.VISIBLE); } controlLayout.setLayoutParams(lp); } }; /** * animView所在的整体布局必须限制大小,否则会出现整个布局往下拉伸的效果,而不是当前view向上移动 * * @param progress * @param animView */ public void sendUpdateProgress(int progress) { Message msg = new Message(); msg.what = DWON_LODING; msg.arg1 = progress; updateHanlder.sendMessage(msg); } private void setDrawbleLeft(Button v,int imgId){ Resources res = getResources(); Drawable d = res.getDrawable(imgId); d.setBounds(0, 0, d.getMinimumWidth(), d.getMinimumHeight()); v.setCompoundDrawables(d, null, null, null); //设置左图标 } }
package com.marijannovak.littletanks; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import java.util.ArrayList; import java.util.Random; /** * Created by marij on 27.3.2017.. */ class GameScreen implements Screen { private final LittleTanks game; private final static String TAG = "LOGIRANJE"; private OrthographicCamera camera; private Player tank; private Controls controller; private ArrayList<Bullet> bulletList; private ArrayList<Bullet> enemyBulletList; private ArrayList<Enemy> enemyList; private ArrayList<Sprite> lifeSprites; private ShapeRenderer shapeRenderer; private Texture gamebg; private Texture playerTexture; private BitmapFont font; private Sound fireSound; private Sound enemyFireSound; private Sound shotSound; private Sound tankDead; private float gameTime = 0; private float lastFireTime = 0; private float enemyLastFireTime = 0; private float lastSpeedUp = 0; private float blockTankTime = 0; private Random rand; private boolean tankCanMove = true; private boolean [ ] spotTaken; private Vector2 [] enemySpots; private int numberOfEnemies = 4; private int score = 0; private int enemiesKilled = 0; private int enemySpeed = 5; private double enemyShootSpeed = 0.4; public GameScreen(final LittleTanks game) { this.game = game; init(); } @Override public void render(float delta) { Gdx.gl.glClearColor(1, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); //Gdx.app.log(TAG, "Lives: " + tank.getLives()); //Gdx.app.log(TAG, "Score : " + this.score); //Gdx.app.log(TAG, "Kut tenka je " + tank.getRotation()); //Gdx.app.log(TAG, "Broj metaka: " + bulletList.size()); //Gdx.app.log(TAG, "Accelerometer X: " + Gdx.input.getAccelerometerX()); //Gdx.app.log(TAG, "Accelerometer Y: " + Gdx.input.getAccelerometerY()); //Gdx.app.log(TAG, "Accelerometer Z: " + Gdx.input.getAccelerometerZ()); if(tank.getLives() == 0) game.gameOverCallback.gameOver(game.playerName, score, (int) gameTime, enemiesKilled); gameTime += delta; updateScore(1); spawnEnemies(); handlePlayerCollision(); if(!tankCanMove && (gameTime - blockTankTime) > 0.5) tankCanMove = true; handleEnemyCollision(); speedUpEnemies(); moveEnemies(); for(int i = 0; i < numberOfEnemies; i++) if(enemyList.size() == numberOfEnemies) spotTaken[i] = false; moveBullets(); if(tankCanMove) handleInput(); enemyShoot(); drawGame(); } private void init() { enemySpeed += 2 * game.difficulty; enemyShootSpeed += game.difficulty/5; camera = new OrthographicCamera(); camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); shapeRenderer = new ShapeRenderer(); playerTexture = new Texture("player.png"); gamebg = new Texture("gamebg.jpg"); tank = new Player(playerTexture); tank.setScale(camera.viewportHeight/500); tank.setPosition(camera.viewportWidth/2, camera.viewportHeight/2); lifeSprites = new ArrayList<Sprite>(); for(int i = 0; i < tank.getLives(); i++) { lifeSprites.add(new Sprite(playerTexture)); lifeSprites.get(i).setSize(camera.viewportWidth/40, camera.viewportHeight/20); if(i == 0) { lifeSprites.get(i).setPosition(lifeSprites.get(i).getWidth()*0.2f, camera.viewportHeight - lifeSprites.get(i).getHeight()*2); } else { lifeSprites.get(i).setPosition(lifeSprites.get(i-1).getX() + lifeSprites.get(i).getWidth()*1.2f, camera.viewportHeight - lifeSprites.get(i).getHeight()*2); } } font = new BitmapFont(); font.getData().setScale(camera.viewportHeight/300); controller = new Controls(new Texture("joystick.png"), new Texture ("fire.png"), (int) camera.viewportWidth); controller.setJoystickSize(camera.viewportHeight/3, camera.viewportHeight/3); controller.setFireSize(camera.viewportHeight/3, camera.viewportHeight/3); controller.setJoystickCenter(new Vector2(controller.getJoystickSprite().getWidth()/2, controller.getJoystickSprite().getHeight()/2)); controller.setJoystickPos(0,0); controller.setFirePos(camera.viewportWidth - controller.getFireSprite().getWidth(), 0); bulletList = new ArrayList<Bullet>(); enemyBulletList = new ArrayList<Bullet>(); enemyList = new ArrayList<Enemy>(); fireSound = Gdx.audio.newSound(Gdx.files.internal("firesound.wav")); shotSound = Gdx.audio.newSound(Gdx.files.internal("shot.wav")); tankDead = Gdx.audio.newSound(Gdx.files.internal("tank_dead.wav")); enemyFireSound = Gdx.audio.newSound(Gdx.files.internal("enemy_firesound.wav")); rand = new Random(); spotTaken = new boolean[4]; enemySpots = new Vector2[4]; enemySpots[0] = new Vector2(camera.viewportWidth/4, camera.viewportHeight/3); enemySpots[1] = new Vector2(camera.viewportWidth/4, camera.viewportHeight*2/3); enemySpots[2] = new Vector2(camera.viewportWidth*3/4, camera.viewportHeight*2/3); enemySpots[3] = new Vector2(camera.viewportWidth*3/4, camera.viewportHeight*3); } private void enemyShoot() { if((gameTime - enemyLastFireTime) > 1/enemyShootSpeed && enemyBulletList.size() < 5 && enemyList.size() == 4) { enemyList.get(rand.nextInt(4)).fire(enemyBulletList, new Bullet(new Texture("bullet_enemy.png")), camera.viewportHeight / 500); if(game.sound) enemyFireSound.play(0.5f); enemyLastFireTime = gameTime; } } private void updateScore(float addedScore) { this.score += addedScore; } private void handlePlayerCollision() { if(tank.collidedEnemy(enemyList) || tank.collidedEnemyBullet(enemyBulletList)) { tank.loseLife(); enemyList.clear(); enemySpeed = 5 + 2*game.difficulty; enemyShootSpeed = 0.4 + game.difficulty/5; spawnEnemies(); if(lifeSprites.size() >= 1) lifeSprites.remove(lifeSprites.size() - 1); if(game.sound) tankDead.play(); Gdx.input.vibrate(200); tankCanMove = false; blockTankTime = gameTime; } } private void handleEnemyCollision() { for (int i = 0; i < enemyList.size(); i++) { if(enemyList.get(i).isShot(bulletList) >= 0) { //Gdx.app.log(TAG, "shot"); int whichShot = enemyList.get(i).isShot(bulletList); enemyList.get(i).getSprite().getTexture().dispose(); enemyList.remove(i); bulletList.get(whichShot).getSprite().getTexture().dispose(); bulletList.remove(whichShot); if(game.sound) shotSound.play(); enemiesKilled++; updateScore(200); } } } private void speedUpEnemies() { if(gameTime - lastSpeedUp > 30) { for(Enemy enemy : enemyList) { enemy.speedUp(1); enemySpeed++; enemyShootSpeed += 0.1; } lastSpeedUp = gameTime; } } private void moveEnemies() { for(Enemy enemy : enemyList) //kreci neprijatelje { enemy.move(enemy.getRotation()); if(enemy.getPosition().x > camera.viewportWidth) enemy.getSprite().setPosition(0, enemy.getPosition().y); if(enemy.getPosition().x < -enemy.getSprite().getWidth()) enemy.getSprite().setPosition(camera.viewportWidth, enemy.getPosition().y); if(enemy.getPosition().y > camera.viewportHeight) enemy.getSprite().setPosition(enemy.getPosition().x, 0); if(enemy.getPosition().y < -enemy.getSprite().getHeight()) enemy.getSprite().setPosition(enemy.getPosition().x, camera.viewportHeight); } } private void spawnEnemies() { if(enemyList.size() < numberOfEnemies && enemyList.size() >= 0) //stvori neprijatelje { enemyList.add(new Enemy(new Texture("enemy.png"))); int i; for(i = 0; i < numberOfEnemies; i++) { if (!spotTaken[i]) { spotTaken[i] = true; break; } } enemyList.get(enemyList.size()-1).setPosition(enemySpots[i].x, enemySpots[i].y); enemyList.get(enemyList.size()-1).setScale(camera.viewportHeight/600); enemyList.get(enemyList.size()-1).rotateTo(rand.nextInt(360)); enemyList.get(enemyList.size()-1).setSpeed(enemySpeed); } } private void handleInput() { screenWrapTank(); if (game.sensor) sensorMove(); for (int i = 0; i < 2; i++) { if (Gdx.input.isTouched(i)) { Vector3 touch = new Vector3(Gdx.input.getX(i), Gdx.input.getY(i), 0); camera.unproject(touch); if (controller.getJoystickSprite().getBoundingRectangle().contains(touch.x, touch.y)) { tank.move(controller.getJoystickAngle(touch)); } if (controller.getFireSprite().getBoundingRectangle().contains(touch.x, touch.y)) { if (gameTime - lastFireTime > 0.5 && bulletList.size() < 5) { tank.fire(bulletList, new Bullet(new Texture("bullet.png")), camera.viewportHeight / 500); if (game.sound) fireSound.play(0.5f); lastFireTime = gameTime; } } } } } private void sensorMove() { if(Gdx.input.isTouched()) { Vector3 touch = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0); camera.unproject(touch); if(!controller.getJoystickSprite().getBoundingRectangle().contains(touch.x, touch.y)) { if(Gdx.input.getAccelerometerX() > 0) tank.moveSensor(Gdx.input.getAccelerometerY() , -Gdx.input.getAccelerometerX() + 5); else if(Gdx.input.getAccelerometerX() < 0) tank.moveSensor(Gdx.input.getAccelerometerY(), -Gdx.input.getAccelerometerX()); } } else { if(Gdx.input.getAccelerometerX() > 0) tank.moveSensor(Gdx.input.getAccelerometerY() , -Gdx.input.getAccelerometerX() + 5); else if(Gdx.input.getAccelerometerX() < 0) tank.moveSensor(Gdx.input.getAccelerometerY(), -Gdx.input.getAccelerometerX() + 8); } } private void moveBullets() { for(int i = 0; i < bulletList.size(); i++) { bulletList.get(i).move(bulletList.get(i).getRotation()); if(bulletList.get(i).isOutOfScreen(camera)) { bulletList.get(i).getSprite().getTexture().dispose(); bulletList.remove(i); } } for(int i = 0; i < enemyBulletList.size(); i++) { enemyBulletList.get(i).move(enemyBulletList.get(i).getRotation()); if(enemyBulletList.get(i).isOutOfScreen(camera)) { enemyBulletList.get(i).getSprite().getTexture().dispose(); enemyBulletList.remove(i); } } } private void drawGame() { game.batch.begin(); game.batch.draw(gamebg, 0, 0, camera.viewportWidth, camera.viewportHeight); for(Bullet bullet : bulletList) {bullet.draw(game.batch);} for(Bullet enemyBullet : enemyBulletList) {enemyBullet.draw(game.batch);} tank.draw(game.batch); for(Enemy enemy : enemyList){enemy.draw(game.batch);} for (Sprite lifeSprite : lifeSprites) lifeSprite.draw(game.batch); font.draw(game.batch, "Score: " + String.valueOf(this.score), 0, camera.viewportHeight); controller.drawControls(game.batch); game.batch.end(); //drawCollisionRects(); } private void drawCollisionRects() { shapeRenderer.begin(ShapeRenderer.ShapeType.Line); shapeRenderer.setColor(Color.BLUE); shapeRenderer.polygon(tank.getCollisionBox().getTransformedVertices()); for (Enemy enemy : enemyList) shapeRenderer.polygon(enemy.getCollisionBox().getTransformedVertices()); shapeRenderer.end(); } private void screenWrapTank() { if(tank.getPosition().x > camera.viewportWidth) tank.getSprite().setPosition(0, tank.getPosition().y); if(tank.getPosition().x < -tank.getSprite().getWidth()) tank.getSprite().setPosition(camera.viewportWidth, tank.getPosition().y); if(tank.getPosition().y > camera.viewportHeight) tank.getSprite().setPosition(tank.getPosition().x, 0); if(tank.getPosition().y < -tank.getSprite().getHeight()) tank.getSprite().setPosition(tank.getPosition().x, camera.viewportHeight); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { playerTexture.dispose(); } @Override public void show() { } }
package de.mvbonline.tools.restapidoc.model; import java.util.LinkedList; import java.util.List; public class ApiObjectDoc implements Comparable<ApiObjectDoc> { private String modelClass; private String name; private String description; private List<ApiObjectFieldDoc> fields; private boolean primitiv; public ApiObjectDoc(String name, String description, String modelClass, boolean primitiv) { super(); this.name = name; this.description = description; this.modelClass = modelClass; this.primitiv = primitiv; } public void addField(ApiObjectFieldDoc field) { if(fields == null) { fields = new LinkedList<ApiObjectFieldDoc>(); } fields.add(field); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ApiObjectDoc other = (ApiObjectDoc) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public String getDescription() { return description; } public List<ApiObjectFieldDoc> getFields() { return fields; } public String getModelClass() { return modelClass; } public String getName() { return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public int compareTo(ApiObjectDoc o) { if (this.equals(o)) return 0; if (o == null) return 1; if (o.getName() == null) { if (this.getName() == null) return 0; return 1; } if (this.getName() == null) return -1; return this.getName().compareTo(o.getName()); } public boolean isPrimitiv() { return primitiv; } }
package com.goldenasia.lottery.data; import com.goldenasia.lottery.base.net.RequestConfig; /** * 开奖信息获取 * Created by ACE-PC on 2016/1/22. */ @RequestConfig(api = "?c=game&a=getIssueInfo") public class IssueLastCommand { private String op; private int lotteryId; private String issue; public String getOp() { return op; } public void setOp(String op) { this.op = op; } public int getLotteryId() { return lotteryId; } public void setLotteryId(int lotteryId) { this.lotteryId = lotteryId; } public String getIssue() { return issue; } public void setIssue(String issue) { this.issue = issue; } }
package pruebasUnitarias; import java.util.List; import com.upc.dsd.api.TrabajadorApiResource; import com.upc.dsd.structures.Perfil; import com.upc.dsd.structures.Trabajador; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class ColaTest extends TestCase{ public void testConcat() { TrabajadorApiResource trabajador = new TrabajadorApiResource(); Trabajador tra = new Trabajador(); tra.setCodTrabajador(9); tra.setApeMat("sss"); tra.setApePat("sss"); tra.setEdad(20); tra.setEstado(1); tra.setNombre(""); tra.setNombre(""); Trabajador obj = trabajador.crearTrabajador(tra); Integer existeData = 0; if(obj != null ){ existeData = 1; } assertTrue( existeData.equals(1) ); } public static Test suite() { return new TestSuite(ColaTest.class); } // suite public static void main (String[] args) { junit.textui.TestRunner.run(suite()); } }
package me.sh4rewith.config.jmx; import java.util.Date; import java.util.concurrent.atomic.AtomicReference; import me.sh4rewith.persistence.Repositories; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jmx.export.annotation.ManagedAttribute; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.stereotype.Component; @Component @ManagedResource(objectName = "sh4rewith.me:name=ApplicationMetrics", description = "Sh4reWith.me Application Metrics", log = true, logFile = "jmx.log", currencyTimeLimit = 15, persistPolicy = "OnUpdate", persistPeriod = 200, persistLocation = "sh4reWith.me", persistName = "metrics") public class ApplicationMetrics { @Autowired private Repositories repositories; private AtomicReference<Stat> numberOfRegisteredUsers = new AtomicReference<Stat>(); private AtomicReference<Stat> numberOfSharedFiles = new AtomicReference<Stat>(); private AtomicReference<Long> updateRateTimeMillis = new AtomicReference<Long>(); private AtomicReference<Date> lastUpdate = new AtomicReference<Date>(); @ManagedAttribute(description = "Update Rate in Milliseconds") public Long getUpdateRateTimeMillis() { return updateRateTimeMillis.get(); } @ManagedAttribute(description = "Update Rate in Milliseconds") public void setUpdateRateTimeMillis(Long updateRateTimeMillis) { this.updateRateTimeMillis.lazySet(updateRateTimeMillis); } @ManagedAttribute(description = "Last Update time") public Date getLastUpdate() { return lastUpdate.get(); } @ManagedAttribute(description = "Last Update time") public void setLastUpdate(Date lastUpdate) { this.lastUpdate.lazySet(lastUpdate); } @ManagedAttribute(description = "Number of Registered Users") public Long getNumberOfRegisteredUsers() { getStats(); return numberOfRegisteredUsers.get().getValue(); } @ManagedAttribute(description = "Number of Shared Files") public Long getNumberOfSharedFiles() { getStats(); return numberOfSharedFiles.get().getValue(); } private synchronized void getStats() { Date date = getCurrentDateOffsetByUpdateRate(); // if lastUpdate time is inferior to current time - updateRate // Then update the stat from source if (lastUpdate.get().compareTo(date) < 0) { numberOfRegisteredUsers.set(new Stat("NbRegisteredUsers", repositories.usersRepository().countAll())); numberOfSharedFiles.set(new Stat("NbSharedFiles", repositories.sharedFilesRepository().countAll())); lastUpdate.set(new Date()); } } private Date getCurrentDateOffsetByUpdateRate() { Date date = new Date(new Date().getTime() - updateRateTimeMillis.get()); return date; } public ApplicationMetrics() { } }
package com.example.sample.usertribe.Activities; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.ResultReceiver; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.sample.usertribe.Fragments.BookServiceFragment; import com.example.sample.usertribe.Fragments.JobFragment; import com.example.sample.usertribe.Fragments.SettinFragment; import com.example.sample.usertribe.Helper.CustomDialog; import com.example.sample.usertribe.Helper.PermissionUtils; import com.example.sample.usertribe.Helper.SharedHelper; import com.example.sample.usertribe.Model.UserAccount; import com.example.sample.usertribe.R; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStates; import com.google.android.gms.location.LocationSettingsStatusCodes; import com.google.android.gms.maps.model.Dash; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class DashBoardActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{ private FusedLocationProviderClient fusedLocationClient; private static final int LOCATION_PERMISSION_REQUEST_CODE = 2; private LocationAddressResultReceiver addressResultReceiver; private Location currentLocation; private LocationCallback locationCallback; private ImageView appbar_image; private LocationManager locationmanager; public Context context=DashBoardActivity.this; private String provider; UserAccount userAccount; TextView username; ImageView profile; private Location mLastLocation; private GoogleApiClient mGoogleApiClient; double latitude; double longitude; ArrayList<String> permissions=new ArrayList<>(); PermissionUtils permissionUtils; boolean isPermissionGranted; CustomDialog customDialog; TextView enter_location_0; private FirebaseAuth mFirebaseAuth; private FirebaseAuth.AuthStateListener mAuthStateListener; public int navItemIndex = 0; public String CURRENT_TAG = TAG_BOOK; private static final String TAG_BOOK = "book service"; private static final String TAG_SETTING = "setting"; private static final String TAG_JOB = "job"; boolean push = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dash_board); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); // appbar_image = (ImageView) findViewById(R.id.appbar_image); // appbar_image.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // startActivity(new Intent(DashBoardActivity.this, AutoCompleteSearch.class)); // finish(); // } // }); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); View header=navigationView.getHeaderView(0); username=(TextView)header.findViewById(R.id.usernameTxt); profile=(ImageView)header.findViewById(R.id.img_profile); username.setText(SharedHelper.getKey(this,"fname")+" "+SharedHelper.getKey(this,"lname")); if (!SharedHelper.getKey(this, "photo").equalsIgnoreCase("") && !SharedHelper.getKey(this, "photo").equalsIgnoreCase(null) && SharedHelper.getKey(this, "photo") != null) { Picasso.get() .load(SharedHelper.getKey(this, "photo")) .placeholder(R.drawable.ic_dummy_user) .error(R.drawable.ic_dummy_user) .into(profile); } else { Picasso.get() .load(R.drawable.ic_dummy_user) .placeholder(R.drawable.ic_dummy_user) .error(R.drawable.ic_dummy_user) .into(profile); } // header.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // loadMethod(); // } // }); navigationView.setNavigationItemSelectedListener(this); displaySelectedScreen(R.id.book_service); setUpFirebaseAuthListening(); // enter_location_0 = (TextView) findViewById(R.id.enter_location_0); addressResultReceiver = new LocationAddressResultReceiver(new Handler()); fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); locationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { currentLocation = locationResult.getLocations().get(0); getAddress(); }; }; startLocationUpdates(); } private void setUpFirebaseAuthListening() { mFirebaseAuth = FirebaseAuth.getInstance(); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { Log.d("Auth Listener", "DASHBOARD- onAuthStateChanged"); FirebaseUser user = firebaseAuth.getCurrentUser(); if(user == null){ //Cleanup other resources as well Log.d("DASHBOARD- Signed", "Out"); user = null; Intent loginActivityIntent = new Intent(DashBoardActivity.this, FlatActivity.class); startActivity(loginActivityIntent); finish(); } } }; } private void getAddress() { if (!Geocoder.isPresent()) { Toast.makeText(DashBoardActivity.this, "Can't find current address, ", Toast.LENGTH_SHORT).show(); return; } // Intent intent = new Intent(this, GetAddressIntentService.class); // intent.putExtra("add_receiver", addressResultReceiver); // intent.putExtra("add_location", currentLocation); // startService(intent); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case LOCATION_PERMISSION_REQUEST_CODE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startLocationUpdates(); } else { Toast.makeText(this, "Location permission not granted, " + "restart the app if you want the feature", Toast.LENGTH_SHORT).show(); } return; } } } private class LocationAddressResultReceiver extends ResultReceiver { LocationAddressResultReceiver(Handler handler) { super(handler); } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (resultCode == 0) { //Last Location can be null for various reasons //for example the api is called first time //so retry till location is set //since intent service runs on background thread, it doesn't block main thread Log.d("Address", "Location null retrying"); getAddress(); } if (resultCode == 1) { Toast.makeText(DashBoardActivity.this, "Address not found, " , Toast.LENGTH_SHORT).show(); } String currentAdd = resultData.getString("address_result"); showResults(currentAdd); } } private void showResults(String currentAdd){ enter_location_0.setText(currentAdd); } @Override protected void onResume() { super.onResume(); startLocationUpdates(); } @Override protected void onPause() { super.onPause(); fusedLocationClient.removeLocationUpdates(locationCallback); } private void startLocationUpdates() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE); } else { @SuppressLint("RestrictedApi") LocationRequest locationRequest = new LocationRequest(); locationRequest.setInterval(2000); locationRequest.setFastestInterval(1000); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null); } } public class GetAddressIntentService extends IntentService { private static final String IDENTIFIER = "GetAddressIntentService"; private ResultReceiver addressResultReceiver; public GetAddressIntentService() { super(IDENTIFIER); } //handle the address request @Override protected void onHandleIntent(@Nullable Intent intent) { String msg = ""; //get result receiver from intent addressResultReceiver = intent.getParcelableExtra("add_receiver"); if (addressResultReceiver == null) { Log.e("GetAddressIntentService", "No receiver, not processing the request further"); return; } Location location = intent.getParcelableExtra("add_location"); //send no location error to results receiver if (location == null) { msg = "No location, can't go further without location"; sendResultsToReceiver(0, msg); return; } //call GeoCoder getFromLocation to get address //returns list of addresses, take first one and send info to result receiver Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> addresses = null; try { addresses = geocoder.getFromLocation( location.getLatitude(), location.getLongitude(), 1); } catch (Exception ioException) { Log.e("", "Error in getting address for the location"); } if (addresses == null || addresses.size() == 0) { msg = "No address found for the location"; sendResultsToReceiver(1, msg); } else { Address address = addresses.get(0); StringBuffer addressDetails = new StringBuffer(); addressDetails.append(address.getFeatureName()); addressDetails.append("\n"); addressDetails.append(address.getThoroughfare()); addressDetails.append("\n"); addressDetails.append("Locality: "); addressDetails.append(address.getLocality()); addressDetails.append("\n"); addressDetails.append("County: "); addressDetails.append(address.getSubAdminArea()); addressDetails.append("\n"); } } //to send results to receiver in the source activity private void sendResultsToReceiver(int resultCode, String message) { Bundle bundle = new Bundle(); bundle.putString("address_result", message); addressResultReceiver.send(resultCode, bundle); } } private void loadMethod() { startActivity(new Intent(this,EditProfileActivity.class)); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } Intent a = new Intent(Intent.ACTION_MAIN); a.addCategory(Intent.CATEGORY_HOME); a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(a); } /* Remove the location listener updates when Activity is paused */ @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { setTitle(item.getTitle()); displaySelectedScreen(item.getItemId()); return true; } private void displaySelectedScreen(int itemId) { Fragment fragment=null; switch (itemId) { case R.id.book_service: navItemIndex = 0; CURRENT_TAG = TAG_BOOK; fragment = new BookServiceFragment(); Bundle bundle = new Bundle(); bundle.putBoolean("push", push); fragment.setArguments(bundle); break; case R.id.jobe: navItemIndex = 1; CURRENT_TAG = TAG_JOB; fragment=new JobFragment(); break; case R.id.pro: startActivity(new Intent(DashBoardActivity.this,ProfileVisitActivity.class)); break; case R.id.nav_share: navItemIndex = 4; CURRENT_TAG = TAG_SETTING; fragment=new SettinFragment(); } if (fragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, fragment); ft.commit(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); } @Override protected void onDestroy() { super.onDestroy(); } }
package com.defrag.code.product; import java.sql.Date; /** * ���̺�� : TPRODUCTM * ���� ���̺� : TPRODUCTDT, TPRODUCT_GRADE, TPRODUCT_REVIEW, TPRODUCT_PRICE * @author joon7 */ public class ProductVO { private String productCode; /* */ private String productTitle; /* */ private String categoryCode; /* */ // private String productContents; /* */ // private int productPrice; /* */ // private String productGradeSeq; /* */ // private String productReviewSeq; /* */ private int hit; /* */ private int like; /* */ private String useYn; /* */ private String delYn; /* */ private String insertId; /* */ private Date insertDate; /* */ private String modifyId; /* */ private Date modifyDate; /* */ public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public String getProductTitle() { return productTitle; } public void setProductTitle(String productTitle) { this.productTitle = productTitle; } public String getCategoryCode() { return categoryCode; } public void setCategoryCode(String categoryCode) { this.categoryCode = categoryCode; } public int getHit() { return hit; } public void setHit(int hit) { this.hit = hit; } public int getLike() { return like; } public void setLike(int like) { this.like = like; } public String getUseYn() { return useYn; } public void setUseYn(String useYn) { this.useYn = useYn; } public String getDelYn() { return delYn; } public void setDelYn(String delYn) { this.delYn = delYn; } public String getInsertId() { return insertId; } public void setInsertId(String insertId) { this.insertId = insertId; } public Date getInsertDate() { return insertDate; } public void setInsertDate(Date insertDate) { this.insertDate = insertDate; } public String getModifyId() { return modifyId; } public void setModifyId(String modifyId) { this.modifyId = modifyId; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } }
package com.gaoshin.onsalelocal.osl.entity; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class UserDetails extends User { private int followers; private int followings; private int offers; public int getFollowers() { return followers; } public void setFollowers(int followers) { this.followers = followers; } public int getFollowings() { return followings; } public void setFollowings(int followings) { this.followings = followings; } public int getOffers() { return offers; } public void setOffers(int offers) { this.offers = offers; } }
package com.distributie.model; import java.io.IOException; import java.net.ConnectException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import org.ksoap2.HeaderProperty; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.distributie.beans.EvenimentNou; import com.distributie.connectors.ConnectionStrings; import com.distributie.enums.EnumNetworkStatus; import com.distributie.listeners.AsyncTaskListener; public class AsyncTaskWSCall { private String methodName; private HashMap<String, String> params; private Context context; private AsyncTaskListener contextListener; private AsyncTaskListener myListener; private ProgressDialog dialog; private EvenimentNou eveniment; public AsyncTaskWSCall(String methodName, HashMap<String, String> params, AsyncTaskListener myListener, Context context) { this.myListener = myListener; this.methodName = methodName; this.params = params; this.context = context; } public AsyncTaskWSCall() { } public AsyncTaskWSCall(Context context) { this.context = context; } public AsyncTaskWSCall(Context context, String methodName, HashMap<String, String> params) { this.context = context; this.methodName = methodName; this.params = params; } public void setEveniment(EvenimentNou eveniment) { this.eveniment = eveniment; } public AsyncTaskWSCall(Context context, AsyncTaskListener contextListener, String methodName, HashMap<String, String> params) { this.context = context; this.methodName = methodName; this.params = params; this.contextListener = contextListener; } public void getCallResults() { new WebServiceCall(this.myListener).execute(); } private class WebServiceCall extends AsyncTask<Void, Void, String> { String errMessage = ""; Exception exception = null; private AsyncTaskListener myListener; private WebServiceCall(AsyncTaskListener myListener) { super(); this.myListener = myListener; } protected void onPreExecute() { dialog = new ProgressDialog(context); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setMessage("Asteptati..."); dialog.setCancelable(false); dialog.show(); } @Override protected String doInBackground(Void... url) { String response = ""; try { SoapObject request = new SoapObject(ConnectionStrings.getInstance().getNamespace(), methodName); for (Entry<String, String> entry : params.entrySet()) { request.addProperty(entry.getKey(), entry.getValue()); } SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(ConnectionStrings.getInstance().getUrl(), 60000); List<HeaderProperty> headerList = new ArrayList<HeaderProperty>(); headerList.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode("bflorin:bflorin".getBytes()))); androidHttpTransport.call(ConnectionStrings.getInstance().getNamespace() + methodName, envelope, headerList); Object result = envelope.getResponse(); if (result != null) response = result.toString(); } catch (ConnectException con) { errMessage = con.toString(); exception = con; } catch (Exception e) { exception = e; errMessage = e.toString(); } return response; } @Override protected void onPostExecute(String result) { try { if (dialog != null) { dialog.dismiss(); dialog = null; } EnumNetworkStatus netStat = EnumNetworkStatus.ON; if (exception instanceof ConnectException) { handleTimeoutConnection(); netStat = EnumNetworkStatus.OFF; } if (!errMessage.equals("") && !(exception instanceof ConnectException)) { Toast toast = Toast.makeText(context, errMessage, Toast.LENGTH_SHORT); toast.show(); } else { if (exception == null) clearStoredObjects(); myListener.onTaskComplete(methodName, result, netStat); } } catch (Exception e) { Log.e("Error", e.toString()); } } } private void handleTimeoutConnection() { LocalStorage storage = new LocalStorage(context); try { storage.serObject(eveniment); myListener.onTaskComplete(methodName, "", EnumNetworkStatus.OFF); } catch (IOException e) { e.printStackTrace(); } } private void clearStoredObjects() { LocalStorage storage = new LocalStorage(context); storage.deleteAllObjects(); } public void getCallResults2() { new WebServiceCall2(context, contextListener).execute(); } public class WebServiceCall2 extends AsyncTask<Void, Void, String> { String errMessage = ""; Context mContext; private AsyncTaskListener listener; private WebServiceCall2(Context context, AsyncTaskListener contextListener) { super(); this.mContext = context; this.listener = contextListener; } @Override protected String doInBackground(Void... url) { String response = ""; try { SoapObject request = new SoapObject(ConnectionStrings.getInstance().getNamespace(), methodName); for (Entry<String, String> entry : params.entrySet()) { request.addProperty(entry.getKey(), entry.getValue()); } SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(ConnectionStrings.getInstance().getUrl(), 60000); List<HeaderProperty> headerList = new ArrayList<HeaderProperty>(); headerList.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode("bflorin:bflorin".getBytes()))); androidHttpTransport.call(ConnectionStrings.getInstance().getNamespace() + methodName, envelope, headerList); Object result = envelope.getResponse(); response = result.toString(); } catch (Exception e) { errMessage = e.getMessage(); } return response; } @Override protected void onPostExecute(String result) { try { if (!errMessage.equals("")) { Toast toast = Toast.makeText(context, errMessage, Toast.LENGTH_SHORT); toast.show(); } else { listener.onTaskComplete(methodName, result, EnumNetworkStatus.ON); } } catch (Exception e) { Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show(); } } } }
package indi.jcl.magicblog.filter; import org.springframework.util.StringUtils; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by Magic Long on 2016/9/22. */ public class PermissionFilter implements Filter { private List<String> excludeList;// 不做过滤的地址 @Override public void init(FilterConfig filterConfig) throws ServletException { excludeList = new ArrayList<String>(); String excludeStr = filterConfig.getInitParameter("exclude"); String[] arr = excludeStr.split(","); for (String str : arr) { excludeList.add(str.trim()); } } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(true); String loginPath = request.getContextPath() + "/login.html"; String path = request.getServletPath(); path = path.substring(1, path.length()); if (excludeList.contains(path)) { chain.doFilter(req, res); return; } if (session.getAttribute("session") == null) { // 此处考虑ajax操作session过期的操作,如果ajax请求过程中session过期,则指定过期状态码为:911. String requestType = request.getHeader("X-Requested-With"); if (!StringUtils.isEmpty(requestType) && requestType.equalsIgnoreCase("XMLHttpRequest")) { response.setStatus(911); response.setHeader("sessionstatus", "timeout"); response.addHeader("loginPath", loginPath); return; } else { response.sendRedirect(loginPath); return; } } else { chain.doFilter(req, res); } } @Override public void destroy() { } }
package com.sum.flowable.task; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import org.flowable.cmmn.api.CmmnRuntimeService; import org.flowable.cmmn.api.delegate.DelegatePlanItemInstance; import org.flowable.cmmn.api.delegate.PlanItemJavaDelegate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.google.cloud.firestore.DocumentReference; import com.google.cloud.firestore.SetOptions; import com.sum.flowable.service.FirebaseService; import com.sum.flowable.service.FirebaseServiceException; @Component("cmmnUpdateMembers") public class CMMNUpdateMembers implements PlanItemJavaDelegate { private static final Logger log = LoggerFactory.getLogger(CMMNUpdateMembers.class); /* import org.flowable.engine.impl.util.json.JSONObject; JSONObject response = new JSONObject(“String version of your processVariable”); import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; JsonNode json = new ObjectMapper().readTree('{"array":[1,2,3],"boolean":true,"string":"stringvalue","number":1}'); execution.setVariable("test", json); ${execution.setVariable("resultString", test.string)} ${execution.setVariable("resultBoolean", test.boolean)} ${execution.setVariable("resultNumber", test.number)} ${cmmnUpdateMembers} private Expression respCode; */ @Autowired private FirebaseService firebaseService; @Autowired private CmmnRuntimeService runtimeService; @Override public void execute(DelegatePlanItemInstance planItemInstance) { try { String accountId = planItemInstance.getTenantId(); String collaborationId = (String) planItemInstance.getVariable("collaborationId"); String statusVariable = (String) planItemInstance.getVariable("statusVariableName"); updateStatus(accountId, collaborationId, statusVariable); } catch (Exception e) { log.error(e.getMessage()); } } private void updateStatus(String accountId, String collaborationId, String statusVariable) throws FirebaseServiceException, InterruptedException, ExecutionException { String path = String.format("accounts/%s/collaborations/%s", accountId, collaborationId); DocumentReference doc = firebaseService.getFirestore().document(path); Map<String, Object> statusObj = (Map<String, Object>) doc.get().get().get("status"); if (statusObj == null) statusObj = new HashMap<>(); statusObj.put(statusVariable, "new status"); Map<String, Object> fields = new HashMap<>(); fields.put("status", statusObj); doc.set(fields, SetOptions.merge()); } }
package CFG.Helper; import CFG.CFGSystem; import CFG.ChatBot; import java.io.File; import java.util.*; public class TestingTesting { public static void main(String[] args) { CFGSystem.load(new File("src/skillParserFiles/CFGSkill.txt")); System.out.println(CFGSystem.run("which lectures are there at 9?")); System.out.println(CFGSystem.run("wHat is <day>?")); System.out.println(CFGSystem.run("y")); System.out.println(CFGSystem.run("tuesday")); } }
public interface ITime { void SendCallBack(); void Start(); void Stop(); }
package com.example.shreyesh.sarinstituteofmedicalscience; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; public class AdminDoctorListAdapter extends RecyclerView.Adapter<AdminDoctorListAdapter.ViewHolder> { @NonNull private Context context; private List<Doctor> doctorList; public AdminDoctorListAdapter(List<Doctor> doctorList) { this.doctorList = doctorList; } @Override public AdminDoctorListAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.doctor_single_layout, parent, false); context = parent.getContext(); return new AdminDoctorListAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull AdminDoctorListAdapter.ViewHolder holder, int position) { String name = doctorList.get(position).getName(); String department = doctorList.get(position).getDepartment(); String monday = doctorList.get(position).getMonday(); String tuesday = doctorList.get(position).getTuesday(); String wednesday = doctorList.get(position).getWednesday(); String thursday = doctorList.get(position).getThursday(); String friday = doctorList.get(position).getFriday(); String saturday = doctorList.get(position).getSaturday(); String sunday = doctorList.get(position).getSunday(); String image = doctorList.get(position).getImage(); holder.setname(name); holder.setDepartment(department); holder.setSunday(sunday); holder.setMonday(monday); holder.setThursday(thursday); holder.setTuesday(tuesday); holder.setWednesday(wednesday); holder.setFriday(friday); holder.setSaturday(saturday); holder.setBookingButton(); holder.setImage(image); } @Override public int getItemCount() { return doctorList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { View view; public ViewHolder(View itemView) { super(itemView); view = itemView; } public void setname(String n) { TextView dname = (TextView) view.findViewById(R.id.doctorNameSingle); dname.setText(n); } public void setDepartment(String dept) { TextView department = (TextView) view.findViewById(R.id.doctorDepartmentSingle); department.setText(dept); } public void setSunday(String time) { TextView sunday = (TextView) view.findViewById(R.id.sundayTimings); sunday.setText(time); } public void setMonday(String time) { TextView monday = (TextView) view.findViewById(R.id.mondayTimings); monday.setText(time); } public void setTuesday(String time) { TextView tuesday = (TextView) view.findViewById(R.id.tuesdayTimings); tuesday.setText(time); } public void setWednesday(String time) { TextView wed = (TextView) view.findViewById(R.id.wednesdayTimings); wed.setText(time); } public void setThursday(String time) { TextView th = (TextView) view.findViewById(R.id.thursdayTimings); th.setText(time); } public void setFriday(String time) { TextView friday = (TextView) view.findViewById(R.id.fridayTimings); friday.setText(time); } public void setSaturday(String time) { TextView sat = (TextView) view.findViewById(R.id.saturdayTimings); sat.setText(time); } public void setBookingButton() { Button button = (Button) view.findViewById(R.id.bookAppointmentSingle); button.setVisibility(View.GONE); } public void setImage(String img) { CircleImageView imageView = (CircleImageView) view.findViewById(R.id.doctorImageSingle); Picasso.get().load(img).placeholder(R.drawable.avatarplaceholder).into(imageView); } } }
package com.code515.report.report_demo.Service.Impl; import com.code515.report.report_demo.Repository.ReportViewRepository; import com.code515.report.report_demo.Service.ReportService; import com.code515.report.report_demo.entity.view.ReportView; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @Service public class ReportServiceImpl implements ReportService { @Autowired private ReportViewRepository repository; @Override public Page<ReportView> getAll(Integer pageNum, Integer pageSize) { Pageable pageable = PageRequest.of(pageNum, pageSize); Page<ReportView> page = repository.findAll(pageable); return page; } }
package com.iks.education.calculator.auxiliary; public enum Operator { ADD("+"), SUBTRACT("-"), MULTIPLY("*"), DIVIDE("/"), INVERSE("1/x", "1/", true), SQUARE_ROOT("sqrt", "sqrt", true), SQUARE("sqr", "sqr", true), PERCENT("%"); public final String symbol; public final String representation; public final boolean isUnary; Operator(String symbol) { this.symbol = symbol; this.representation = symbol; this.isUnary = false; } Operator(String symbol, String representation) { this.symbol = symbol; this.representation = representation; this.isUnary = false; } Operator(String symbol, String representation, boolean unary) { this.symbol = symbol; this.representation = representation; this.isUnary = unary; } @Override public String toString() { return representation; } public String toString(String operand) { if (isUnary) { return representation + "(" + operand + ")"; } return toString(); } }
package com.ut.commoncomponent; import android.content.Context; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; /** * author : zhouyubin * time : 2018/12/13 * desc : * version: 1.0 */ public class Flowlayout extends ViewGroup { public Flowlayout(Context context) { super(context); } public Flowlayout(Context context, AttributeSet attrs) { super(context, attrs); } public Flowlayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public Flowlayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width = 0; int height = 0; int lineWidth = 0; int lineHeight = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); measureChild(child, widthMeasureSpec, heightMeasureSpec); MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin; int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin; if (lineWidth + childWidth <= widthSize) { lineWidth += childWidth; lineHeight = Math.max(lineHeight, childHeight); } else {//下一行 width = Math.max(lineWidth, childWidth); height += lineHeight;//加上上一行行高 lineHeight = childHeight;//下一行初始行高 lineWidth = childWidth; } if (i == childCount - 1) { width = Math.max(width, lineWidth); height += lineHeight; } } int finalWidth = (widthMode == MeasureSpec.EXACTLY) ? widthSize : width; int finalHeight = (heightMode == MeasureSpec.EXACTLY) ? heightSize : height; setMeasuredDimension(finalWidth, finalHeight); } List<Integer> lineHeights = new ArrayList<>(); List<List<View>> listLineViews = new ArrayList<>(); @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { lineHeights.clear(); listLineViews.clear(); initLineHeightsAndListLineViews(lineHeights, listLineViews); int lineNums = listLineViews.size(); int top = 0; for (int i = 0; i < lineNums; i++) { List<View> lineViews = listLineViews.get(i); int lineHeight = lineHeights.get(i); int lineChildCounts = lineViews.size(); int left = 0; for (int j = 0; j < lineChildCounts; j++) { View child = lineViews.get(j); if (child.getVisibility() == View.GONE) { continue; } MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); int cl = left + lp.leftMargin; int cr = cl + child.getMeasuredWidth(); int ct = top + lp.topMargin; int cb = ct + child.getMeasuredHeight(); child.layout(cl, ct, cr, cb); left = cr + lp.rightMargin; } top += lineHeight; } } private void initLineHeightsAndListLineViews(List<Integer> lineHeights, List<List<View>> listLineViews) { int childCount = getChildCount(); int lineWidth = 0; int lineHeight = 0; int parentWidth = getWidth(); List<View> lineViews = new ArrayList<>(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); int childAllWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin; int childAllHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin; if (lineWidth + childAllWidth <= parentWidth) { lineWidth += childAllWidth; lineHeight = Math.max(lineHeight, childAllHeight); } else { lineHeights.add(lineHeight); listLineViews.add(lineViews); lineViews = new ArrayList<>(); lineWidth = childAllWidth; lineHeight = childAllHeight; } lineViews.add(child); if (i == childCount - 1) { lineHeights.add(lineHeight); listLineViews.add(lineViews); } } } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } }
package com.example.administrator.panda_channel_app.Fragment; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.example.administrator.panda_channel_app.Activity.ReportActivity; import com.example.administrator.panda_channel_app.Adapter.HigHlightListviewAdapter; import com.example.administrator.panda_channel_app.MVP_Framework.base.BaseFragment; import com.example.administrator.panda_channel_app.R; import com.example.administrator.panda_channel_app.histroy.DaoMaster; import com.example.administrator.panda_channel_app.histroy.DaoSession; import com.example.administrator.panda_channel_app.histroy.Histroy; import com.example.administrator.panda_channel_app.histroy.HistroyDao; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import de.greenrobot.dao.query.QueryBuilder; /** * Created by 闫雨婷 on 2017/7/13. */ public class Highlights_Tab_Fragment extends BaseFragment { @BindView(R.id.highlight_listview) ListView highlightListview; public static TextView textView; @BindView(R.id.quanxuan) TextView quanxuan; @BindView(R.id.shanchu) TextView shanchu; @BindView(R.id.dilog) LinearLayout dilog; private int number = 0; public Highlights_Tab_Fragment(TextView textView) { this.textView = textView; } private ArrayList<Histroy> arr1; public static HigHlightListviewAdapter adapter; @Override protected void onShow() { } @Override protected void onHidden() { } // @Override protected void loadData() { arr1 = new ArrayList<>(); adapter = new HigHlightListviewAdapter(arr1, getContext()); highlightListview.setAdapter(adapter); quer(); highlightListview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (Highlights_Tab_Fragment.textView.getText().equals("完成")) { if (arr1.get(i).isFlag() == false) { arr1.get(i).setFlag(true); number++; shanchu.setText("删除" + number); } else { number--; shanchu.setText("删除" + number); arr1.get(i).setFlag(false); } if (number == 0) { shanchu.setText("删除"); } adapter.notifyDataSetChanged(); }else{ adapter.notifyDataSetChanged(); Intent intent = new Intent(getContext(), ReportActivity.class); intent.putExtra("url", arr1.get(i).getUrl()); intent.putExtra("img", arr1.get(i).getImg()); startActivity(intent); } } }); textView.setVisibility(View.VISIBLE); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (textView.getText().equals("编辑")) { for (int i = 0; i < arr1.size(); i++) { arr1.get(i).setBb(true); } dilog.setVisibility(View.VISIBLE); textView.setText("完成"); adapter.notifyDataSetChanged(); } else { for (int i = 0; i < arr1.size(); i++) { arr1.get(i).setBb(false); } for (int i = 0; i < arr1.size(); i++) { arr1.get(i).setFlag(false); } dilog.setVisibility(View.GONE); textView.setText("编辑"); adapter.notifyDataSetChanged(); } } }); quanxuan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (quanxuan.getText().equals("全选")) { quanxuan.setText("取消全选"); if (textView.getText().equals("完成")) { for (int i = 0; i < arr1.size(); i++) { arr1.get(i).setFlag(true); } number = arr1.size(); shanchu.setText("删除" + number); adapter.notifyDataSetChanged(); } } else { for (int i = 0; i < arr1.size(); i++) { arr1.get(i).setFlag(false); } number = 0; shanchu.setText("删除"); quanxuan.setText("全选"); adapter.notifyDataSetChanged(); } } }); shanchu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (textView.getText().equals("完成")) { Log.e("tag===list.size", arr1.size() + ""); for (int i = arr1.size() - 1; i >= 0; i--) { if (arr1.get(i).isFlag()) { delect(arr1.get(i)); arr1.remove(arr1.get(i)); } } number = 0; adapter.notifyDataSetChanged(); shanchu.setText("删除"); if (arr1.size() == 0) { textView.setVisibility(View.GONE); //historyRelative.setVisibility(View.GONE); //historyBackgroud.setVisibility(View.VISIBLE); dilog.setVisibility(View.GONE); } } } }); } @Override protected void initView(View view) { } @Override protected int getLayoutId() { return R.layout.shoucang_highlights_tab_fragment; } public void quer() { DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getContext(), "tryrt.db", null); SQLiteDatabase database = helper.getWritableDatabase(); DaoMaster daoMaster = new DaoMaster(database); DaoSession daoSession = daoMaster.newSession(); HistroyDao histroyDao = daoSession.getHistroyDao(); QueryBuilder<Histroy> histroyQueryBuilder = histroyDao.queryBuilder(); List<Histroy> list = histroyQueryBuilder.list(); arr1.clear(); for (int x = 0; x < list.size(); x++) { Histroy histroy = list.get(x); arr1.add(histroy); } adapter.notifyDataSetChanged(); helper.close(); } public void delect(Histroy histroy) { DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getContext(), "tryrt.db", null); SQLiteDatabase database = helper.getWritableDatabase(); DaoMaster daoMaster = new DaoMaster(database); DaoSession daoSession = daoMaster.newSession(); HistroyDao histroyDao = daoSession.getHistroyDao(); histroyDao.delete(histroy); helper.close(); } }
package com.gogo.base.constant; public class NumberNoType { public static final String ORDER = "order"; public static final String ORDER_ITEM = "orderItem"; public static final String ORDER_ADDRESS = "orderAddress"; public static final String PRODUCT = "product"; public static final String PRODUCT_STYLE = "productStyle"; }
package com.haku.light.graphics.g2d; import com.haku.light.Light; import com.haku.light.assets.impl.Mesh; import com.haku.light.assets.impl.font.BitmapFont; import com.haku.light.graphics.gl.GLVertexAttribute; public class TextMesh extends Mesh { public final BitmapFont font; private float maxWidth = 0; private String text = ""; private float height = 0; private float width = 0; public TextMesh(String text) { this(text, BitmapFont.DEFAULT_FONT); } public TextMesh(String text, String fontName) { this(text, Light.assets.<BitmapFont>get(fontName)); } public TextMesh(String text, BitmapFont font) { super(4 * text.length(), 6 * text.length(), GLVertexAttribute.POSITION_2D, GLVertexAttribute.TEXTURE_0); this.font = font; this.text = text; this.update(); } public void update() { this.vertices.set(this.getVBOData()); this.indices.set(this.getIBOData()); } private float[] getVBOData() { char[] chars = this.text.toCharArray(); float[] out = new float[chars.length * 16]; float lineHeight = this.font.metrics.getLineHeight(); float advance = 0; float tCellSize = (1f / 16f); this.height = lineHeight; this.width = 0; for (int i = 0; i < out.length; i += 16) { char c = chars[i / 16]; float width = this.font.metrics.getWidth(c); float cTexWidth = width / this.font.texture.getWidth(); float cTexHeight = lineHeight / this.font.texture.getHeight(); if (this.maxWidth > 0 && (advance + width) > this.maxWidth) { this.height += lineHeight; for (int j = 0; j < i; j += 16) { out[j + 1] += lineHeight; out[j + 5] += lineHeight; out[j + 9] += lineHeight; out[j + 13] += lineHeight; } if (advance > this.width) this.width = advance; advance = 0; } int y = 15 - (c / 16); int x = c % 16; out[i] = advance; out[i + 1] = 0; out[i + 2] = x * tCellSize; out[i + 3] = y * tCellSize; out[i + 4] = advance + width; out[i + 5] = 0; out[i + 6] = x * tCellSize + cTexWidth; out[i + 7] = y * tCellSize; out[i + 8] = advance + width; out[i + 9] = lineHeight; out[i + 10] = x * tCellSize + cTexWidth; out[i + 11] = y * tCellSize + cTexHeight; out[i + 12] = advance; out[i + 13] = lineHeight; out[i + 14] = x * tCellSize; out[i + 15] = y * tCellSize + cTexHeight; advance += width; } if (advance > this.width) this.width = advance; return out; } private int[] getIBOData() { int[] out = new int[this.text.length() * 6]; for (int i = 0; i < out.length; i += 6) { int begin = (i / 6) * 4; out[i] = begin; out[i + 1] = begin + 1; out[i + 2] = begin + 2; out[i + 3] = begin; out[i + 4] = begin + 2; out[i + 5] = begin + 3; } return out; } public void setMaxWidth(float maxWidth) { if (this.maxWidth != maxWidth) { this.maxWidth = maxWidth; this.update(); } } public TextMesh setText(String text) { if (!this.text.equals(text)) { this.text = text; this.update(); } return this; } public String getText() { return this.text; } public float getHeight() { return this.height; } public float getWidth() { return this.width; } }
// ********************************************************** // 1. 제 목: 모듈 관리 // 2. 프로그램명 : MenuSubAdminBean.java // 3. 개 요: 메뉴 관리 // 4. 환 경: JDK 1.3 // 5. 버 젼: 1.0 // 6. 작 성: 강성욱 2004. 12. 16 // 7. 수 정: // ********************************************************** package com.ziaan.system; import java.sql.PreparedStatement; import java.util.ArrayList; import java.util.Vector; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.ErrorManager; import com.ziaan.library.ListSet; import com.ziaan.library.RequestBox; import com.ziaan.library.StringManager; /** * 메뉴 관리(ADMIN) * * @date : 2003. 7 * @author : s.j Jung */ public class MenuSubAdminBean { private static final String CONFIG_NAME = "cur_nrm_grcode"; public MenuSubAdminBean() { } /** 메뉴화면 리스트 @param box receive from the form object and session @return ArrayList 메뉴 리스트 */ public ArrayList selectListMenu(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null, ls1 = null; ArrayList list = null; String sql = "", sql1 = ""; MenuData data = null; String v_grcode = CodeConfigBean.getConfigValue(CONFIG_NAME); String v_searchtext = box.getString("p_searchtext"); int v_cnt = 0; try { connMgr = new DBConnectionManager(); list = new ArrayList(); sql = "SELECT MENU \n"; sql += " , MENUNM \n"; sql += " , UPPER \n"; sql += " , PARENT \n"; sql += " , PGM \n"; sql += " , ISDISPLAY \n"; sql += " , PARA1 \n"; sql += " , PARA2 \n"; sql += " , PARA3 \n"; sql += " , PARA4 \n"; sql += " , PARA5 \n"; sql += " , PARA6 \n"; sql += " , PARA7 \n"; sql += " , PARA8 \n"; sql += " , PARA9 \n"; sql += " , PARA10 \n"; sql += " , PARA11 \n"; sql += " , PARA12 \n"; sql += " , CREATED \n"; sql += " , LUSERID \n"; sql += " , LDATE \n"; sql += " , LEVELS \n"; sql += " , ORDERS \n"; sql += " , SYSTEMGUBUN \n"; sql += " ,(SELECT COUNT(*) FROM TZ_MENUSUB WHERE MENU = A.MENU) AS CNT \n"; sql += "FROM TZ_MENU A \n"; sql += "WHERE GRCODE = " + StringManager.makeSQL(v_grcode) + " \n"; if(!v_searchtext.equals("")) { // 검색어가 있으면 sql += "AND MENUNM LIKE " + StringManager.makeSQL("%" + v_searchtext + "%"); } sql += "ORDER BY \n"; sql += " (SELECT ORDERS \n"; sql += " FROM TZ_MENU \n"; sql += " WHERE MENU = A.PARENT) ASC \n"; sql += " , PARENT ASC \n"; sql += " , LEVELS ASC \n"; sql += " , ORDERS ASC \n"; /*sql = " select menu, menunm, upper, parent, pgm, isdisplay, para1, para2, para3, para4, "; sql += " para5, para6, para7, para8, para9, para10, para11, para12, "; sql += " created, luserid, ldate, levels, orders, systemgubun "; sql += " from TZ_MENU "; sql += " where grcode = " + StringManager.makeSQL(v_grcode); if ( !v_searchtext.equals("") ) { // 검색어가 있으면 sql += " and menunm like " + StringManager.makeSQL("%" + v_searchtext + "%"); } sql += " order by menu asc, levels asc";*/ ls = connMgr.executeQuery(sql); while ( ls.next() ) { data = new MenuData(); data.setMenu( ls.getString("menu") ); data.setMenunm( ls.getString("menunm") ); data.setUpper( ls.getString("upper") ); data.setParent( ls.getString("parent") ); data.setPgm( ls.getString("pgm") ); data.setIsdisplay( ls.getString("isdisplay") ); data.setPara1( ls.getString("para1") ); data.setPara2( ls.getString("para2") ); data.setPara3( ls.getString("para3") ); data.setPara4( ls.getString("para4") ); data.setPara5( ls.getString("para5") ); data.setPara6( ls.getString("para6") ); data.setPara7( ls.getString("para7") ); data.setPara8( ls.getString("para8") ); data.setPara9( ls.getString("para9") ); data.setPara10( ls.getString("para10") ); data.setPara11( ls.getString("para11") ); data.setPara12( ls.getString("para12") ); data.setCreated( ls.getString("created") ); data.setLuserid( ls.getString("luserid") ); data.setLdate( ls.getString("ldate") ); data.setLevels( ls.getInt("levels") ); data.setOrders( ls.getInt("orders") ); data.setSystemgubun( ls.getString("systemgubun") ); /* sql1 = "select count(*) from tz_menusub where menu='" +ls.getString("menu") + "'"; ls1 = connMgr.executeQuery(sql1); if ( ls1.next() ) { v_cnt = ls1.getInt(1); } ls1.close(); data.setCnt(v_cnt); */ data.setCnt(ls.getInt("cnt")); list.add(data); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** 모듈화면 리스트 @param box receive from the form object and session @return ArrayList 모듈 리스트 */ public ArrayList selectListMenuSub(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; String sql = ""; MenuSubData data = null; String v_grcode = CodeConfigBean.getConfigValue(CONFIG_NAME); String v_menu = box.getString("p_menu"); try { connMgr = new DBConnectionManager(); list = new ArrayList(); sql = " select menu, seq, servlet, modulenm, luserid, ldate "; sql += " from TZ_MENUSUB "; sql += " where grcode = " + StringManager.makeSQL(v_grcode); sql += " and menu = " + StringManager.makeSQL(v_menu); sql += " order by menu asc"; ls = connMgr.executeQuery(sql); while ( ls.next() ) { data = new MenuSubData(); data.setMenu( ls.getString("menu") ); data.setSeq( ls.getInt("seq") ); data.setServlet( ls.getString("servlet") ); data.setModulenm( ls.getString("modulenm") ); data.setLuserid( ls.getString("luserid") ); data.setLdate( ls.getString("ldate") ); list.add(data); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** 모듈화면 상세보기 @param box receive from the form object and session @return MenuData 조회한 상세정보 */ public MenuSubData selectViewMenuSub(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; MenuSubData data = null; String v_grcode = CodeConfigBean.getConfigValue(CONFIG_NAME); String v_menu = box.getString("p_menu"); int v_seq = box.getInt("p_seq"); try { connMgr = new DBConnectionManager(); sql = " select menu, seq, servlet, modulenm, luserid, ldate "; sql += " from TZ_MENUSUB "; sql += " where grcode = " + StringManager.makeSQL(v_grcode); sql += " and menu = " + StringManager.makeSQL(v_menu); sql += " and seq = " + v_seq; ls = connMgr.executeQuery(sql); if ( ls.next() ) { data = new MenuSubData(); data.setMenu( ls.getString("menu") ); data.setSeq( ls.getInt("seq") ); data.setServlet( ls.getString("servlet") ); data.setModulenm( ls.getString("modulenm") ); data.setLuserid( ls.getString("luserid") ); data.setLdate( ls.getString("ldate") ); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return data; } /** 모듈 등록할때 @param box receive from the form object and session @return isOk 1:insert success,0:insert fail */ public int insertMenuSub(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; PreparedStatement pstmt = null; String sql = ""; String sql1 = ""; int isOk = 0; String v_grcode = CodeConfigBean.getConfigValue(CONFIG_NAME); String v_menu = box.getString("p_menu"); int v_seq = 0; String v_servlet = box.getString("p_servlet"); String v_modulenm = box.getString("p_modulenm"); String v_systemgubun= box.getString("p_systemgubun"); String s_userid = box.getSession("userid"); try { connMgr = new DBConnectionManager(); sql = "select nvl(max(seq),-1) seq from TZ_MENUSUB "; sql += " where grcode = " + StringManager.makeSQL(v_grcode); sql += " and menu = " + StringManager.makeSQL(v_menu); ls = connMgr.executeQuery(sql); if ( ls.next() ) { v_seq = ls.getInt(1) + 1; } else { v_seq = 0; } sql1 = "insert into TZ_MENUSUB(grcode, menu, seq, servlet, modulenm, systemgubun, luserid, ldate ) "; sql1 += " values (?, ?, ?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS')) "; pstmt = connMgr.prepareStatement(sql1); pstmt.setString(1, v_grcode); pstmt.setString(2, v_menu); pstmt.setInt(3, v_seq); pstmt.setString(4, v_servlet); pstmt.setString(5, v_modulenm); pstmt.setString(6, v_systemgubun); pstmt.setString(7, s_userid); isOk = pstmt.executeUpdate(); box.put("p_seq",String.valueOf(v_seq)); } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** 모듈 수정하여 저장할때 @param box receive from the form object and session @return isOk 1:update success,0:update fail */ public int updateMenuSub(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; String sql = ""; int isOk = 0; String v_grcode = CodeConfigBean.getConfigValue(CONFIG_NAME); String v_menu = box.getString("p_menu"); int v_seq = box.getInt("p_seq"); String v_servlet = box.getString("p_servlet"); String v_modulenm = box.getString("p_modulenm"); String v_systemgubun = box.getString("p_systemgubun"); String s_userid = box.getSession("userid"); try { connMgr = new DBConnectionManager(); sql = " update TZ_MENUSUB set servlet = ? , modulenm = ?, luserid= ? , ldate = to_char(sysdate, 'YYYYMMDDHH24MISS') , systemgubun= ? "; sql += " where grcode = ? and menu = ? and seq = ? "; pstmt = connMgr.prepareStatement(sql); pstmt.setString(1, v_servlet); pstmt.setString(2, v_modulenm); pstmt.setString(3, s_userid); pstmt.setString(4, v_systemgubun); pstmt.setString(5, v_grcode); pstmt.setString(6, v_menu); pstmt.setInt(7, v_seq); isOk = pstmt.executeUpdate(); } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk; } /** 모듈 삭제할때 - 하위 프로세서 삭제 @param box receive from the form object and session @return isOk 1:delete success,0:delete fail */ public int deleteMenuSub(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt1 = null; PreparedStatement pstmt2 = null; String sql1 = ""; String sql2 = ""; int isOk1 = 0; int isOk2 = 0; String v_grcode = CodeConfigBean.getConfigValue(CONFIG_NAME); String v_menu = box.getString("p_menu"); int v_seq = box.getInt("p_seq"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); sql1 = " delete from TZ_MENUSUB "; sql1 += " where grcode = ? and menu = ? and seq = ? "; sql2 = " delete from TZ_MENUSUBPROCESS "; sql2 += " where grcode = ? and menu = ? and seq = ? "; pstmt1 = connMgr.prepareStatement(sql1); pstmt1.setString(1, v_grcode); pstmt1.setString(2, v_menu); pstmt1.setInt(3, v_seq); isOk1 = pstmt1.executeUpdate(); pstmt2 = connMgr.prepareStatement(sql2); pstmt2.setString(1, v_grcode); pstmt2.setString(2, v_menu); pstmt2.setInt(3, v_seq); isOk2 = pstmt2.executeUpdate(); // if ( isOk1 > 0 && isOk2 > 0) connMgr.commit(); // 2가지 sql 이 꼭 같이 delete 되어야 하는 경우이므로 // else connMgr.rollback(); if ( isOk1 > 0 ) connMgr.commit(); // 하위 분류의 로우가 없을경우 isOk2 가 0 이므로 isOk2 > 0 조건 제외 else connMgr.rollback(); } catch ( Exception ex ) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql1 + "\r\n" +sql2); throw new Exception("sql = " + sql1 + "\r\n" + sql2 + "\r\n" + ex.getMessage() ); } finally { if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e ) { } } if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e ) { } } if ( connMgr != null ) try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } // return isOk1*isOk2; return isOk1; } /** 권한 리스트 @param box receive from the form object and session @return ArrayList 권한 리스트 */ public ArrayList selectListMenuAuth(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; String sql = ""; MenuAuthData data = null; String v_grcode = CodeConfigBean.getConfigValue(CONFIG_NAME); String v_menu = box.getString("p_menu"); String v_seq = box.getString("p_seq"); try { connMgr = new DBConnectionManager(); list = new ArrayList(); sql = " select a.gadmin,a.control,a.systemgubun, b.gadminnm "; sql += " from TZ_MENUAUTH a, TZ_GADMIN b "; sql += " where a.gadmin = b.gadmin "; sql += " and a.grcode = " + StringManager.makeSQL(v_grcode); sql += " and a.menu = " + StringManager.makeSQL(v_menu); sql += " and a.menusubseq = " + v_seq; sql += " order by a.gadmin asc"; System.out.println(sql); ls = connMgr.executeQuery(sql); while ( ls.next() ) { data = new MenuAuthData(); data.setGadmin( ls.getString("gadmin") ); data.setGadminnm( ls.getString("gadminnm") ); data.setControl( ls.getString("control") ); data.setSystemgubun( ls.getString("systemgubun") ); list.add(data); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** 권한 리스트 @param box receive from the form object and session @return ArrayList 리스트 */ public ArrayList selectListGadmin(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; String sql = ""; GadminData data = null; try { connMgr = new DBConnectionManager(); list = new ArrayList(); sql = " select gadmin, gadminnm from TZ_GADMIN "; sql += " order by gadmin asc "; ls = connMgr.executeQuery(sql); while ( ls.next() ) { data = new GadminData(); data.setGadmin( ls.getString("gadmin") ); data.setGadminnm( ls.getString("gadminnm") ); list.add(data); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** 권한 등록 @param box receive from the form object and session @return isOk 1:insert success,0:insert fail */ public int insertMenuAuth(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt1 = null; PreparedStatement pstmt2 = null; String sql1 = ""; String sql2 = ""; int isOk1 = 0; int isOk2 = 0; int isOk2_check = 0; ArrayList list1 = (ArrayList)selectListGadmin(box); // 권한종류리스트 int v_gadmincnt = list1.size(); String v_grcode = CodeConfigBean.getConfigValue(CONFIG_NAME); String v_systemgubun = box.getString("p_systemgubun"); String v_menu = box.getString("p_menu"); int v_seq = box.getInt("p_seq"); // Vector v_vgadmin = box.getVector("p_gadmin"); // Vector v_vcontrolr = box.getVector("p_controlR"); // Vector v_vcontrolw = box.getVector("p_controlW"); Vector v_vgadmin[] = new Vector[v_gadmincnt]; Vector v_vcontrolr[] = new Vector[v_gadmincnt]; Vector v_vcontrolw[] = new Vector[v_gadmincnt]; String v_gadmin = ""; String v_controlr = ""; String v_controlw = ""; String v_control = ""; String s_userid = box.getSession("userid"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // 기존 데이타 삭제 sql1 = " delete from TZ_MENUAUTH "; sql1 += " where grcode = ? and menu = ? and menusubseq = ? "; pstmt1 = connMgr.prepareStatement(sql1); pstmt1.setString(1, v_grcode); pstmt1.setString(2, v_menu); pstmt1.setInt(3, v_seq); isOk1 = pstmt1.executeUpdate(); // 변경된 자료 등록 sql2 = " insert into TZ_MENUAUTH (grcode, gadmin, menusubseq, menu, control, systemgubun, luserid, ldate) "; sql2 += " values (?, ?, ?, ?, ?, ?, ?, to_char(sysdate, 'YYYYMMDDHH24MISS')) "; pstmt2 = connMgr.prepareStatement(sql2); isOk2 = 1; for ( int i = 0; i < v_gadmincnt; i++ ) { v_vgadmin[i] = box.getVector("p_gadmin" + i); v_vcontrolr[i] = box.getVector("p_controlR" + i); v_vcontrolw[i] = box.getVector("p_controlW" + i); // 권한 갯수만큼 루프 v_gadmin = (String)v_vgadmin[i].elementAt(0); if ( v_vcontrolr[i].size() > 0) v_controlr = (String)v_vcontrolr[i].elementAt(0); else v_controlr = ""; if ( v_vcontrolw[i].size() > 0) v_controlw = (String)v_vcontrolw[i].elementAt(0); else v_controlw = ""; v_control = StringManager.chkNull(v_controlr) + StringManager.chkNull(v_controlw); // DB INSERT pstmt2.setString(1, v_grcode); pstmt2.setString(2, v_gadmin); pstmt2.setInt(3, v_seq); pstmt2.setString(4, v_menu); pstmt2.setString(5, v_control); pstmt2.setString(6, v_systemgubun); pstmt2.setString(7, s_userid); isOk2_check = pstmt2.executeUpdate(); System.out.println("isOk2_check=" +isOk2_check); if ( isOk2_check == 0) isOk2 = 0; } // 기존 등록된 자료가 없을 수 있으므로 isOk1 체크 제외 if ( isOk2 > 0) connMgr.commit(); else connMgr.rollback(); } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e ) { } } if ( pstmt2 != null ) { try { pstmt2.close(); } catch ( Exception e ) { } } if ( connMgr != null ) try { connMgr.setAutoCommit(true); } catch ( Exception e ) { } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk2; } }
import java.util.ArrayList; import java.util.List; /* * 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. */ /** * * @author listya */ public class Herd implements Movable { private List<Organism> entries; public Herd() { this.entries = new ArrayList<>(); } public String toString() { StringBuilder sb = new StringBuilder(); for (Organism mov : entries) { sb.append(mov.toString() + "\n"); } return sb.toString(); } public void addToHerd(Movable movable) { Organism move = (Organism) movable; this.entries.add(move); } @Override public void move(int dx, int dy) { for (Organism mov: entries) { mov.move(dx,dy); } } }
package com.proky.booking.service; import com.proky.booking.dto.PageDto; import com.proky.booking.dto.StationDto; import com.proky.booking.dto.TrainDto; import com.proky.booking.exception.ServiceException; import com.proky.booking.persistence.dao.ITrainDao; import com.proky.booking.persistence.entities.Station; import com.proky.booking.persistence.entities.Train; import com.proky.booking.util.MessageSourceWrapper; import com.proky.booking.util.SqlDateTimeConverter; import lombok.AllArgsConstructor; import lombok.extern.log4j.Log4j2; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Lookup; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.sql.Date; import java.sql.Time; import java.util.List; import java.util.stream.Collectors; @Log4j2 @Service @AllArgsConstructor public class TrainService { private ITrainDao trainDao; private SqlDateTimeConverter sqlDateTimeConverter; private StationService stationService; private ModelMapper modelMapper; private MessageSourceWrapper messageSourceWrapper; @Transactional public PageDto findTrains(final PageDto pageDto, String requestDate, String requestTime, String stationId) { final Date date = sqlDateTimeConverter.convertToSqlDate(requestDate); final Time time = sqlDateTimeConverter.convertToSqlTime(requestTime); final Station station = stationService.findById(Long.parseLong(stationId)); final PaginationService paginationService = getProxyPaginationService(); paginationService.setPageDto(pageDto); paginationService.calculatePageIndex(); Pageable pageable = PageRequest.of(paginationService.getCurrentPageIndex(), paginationService.getPageSize()); final Page<Train> foundTrains = trainDao.findAllByDepartureDateAndDepartureTimeAndStation(date, time, station, pageable); final List<TrainDto> trainDtoList = foundTrains.get().map(this::mapTrainToDto).collect(Collectors.toList()); paginationService.setAllPagesAmount(foundTrains.getTotalPages()); paginationService.changeIndexBoundariesAndButtonsState(); pageDto.setPageList(trainDtoList); paginationService.updatePageDto(); return paginationService.getpageDto(); } public TrainDto getTrainDtoById(Long id) { final Train train = findTrainById(id); return modelMapper.map(train, TrainDto.class); } public Train findTrainById(Long id) { return trainDao.findById(id).orElseThrow(() -> new ServiceException(messageSourceWrapper.getMessage("error.notfound"))); } @Lookup public PaginationService getProxyPaginationService() { return null; } private TrainDto mapTrainToDto(final Train train) { final TrainDto trainDto = modelMapper.map(train, TrainDto.class); final List<Station> stations = train.getRoute().getStations(); final List<StationDto> stationsDto = stations .stream() .map(routeStation -> modelMapper.map(routeStation, StationDto.class)) .collect(Collectors.toList()); trainDto.setStations(stationsDto); return trainDto; } }
/** * Created by mohammad on 5/17/17. */ public abstract class BarnamehPolicyChecker { public abstract boolean satisfy(Barnameh barnameh); }
package f.star.iota.milk.ui.zu80.www; import android.os.Bundle; import f.star.iota.milk.base.ScrollImageFragment; public class ZUFragment extends ScrollImageFragment<ZUPresenter, ZUAdapter> { public static ZUFragment newInstance(String url) { ZUFragment fragment = new ZUFragment(); Bundle bundle = new Bundle(); bundle.putString("base_url", url+"/"); fragment.setArguments(bundle); return fragment; } @Override protected ZUPresenter getPresenter() { return new ZUPresenter(this); } @Override protected ZUAdapter getAdapter() { return new ZUAdapter(); } @Override protected boolean isHideFab() { return false; } }
package main; import java.util.ArrayList; public class ConstraintDif extends ConstraintAbstract { public ConstraintDif(ArrayList<String> var) { super(var); } public ConstraintDif(ArrayList<String> var, String name) { super(var, name); } @Override public boolean constraintIsRespectee(ArrayList<Object> tuples) { if (tuples.isEmpty()) { return true; } for (Object o : tuples) { if (o != null) for (Object other : tuples) { if (other != o && o.equals(other)) { return false; } } } return true; } @Override public String toString() { return super.toString()+" : DIF"; } }
package net.leloubil.mcpwn.mcapi; import android.annotation.SuppressLint; import android.content.Context; import android.os.AsyncTask; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.load.model.LazyHeaders; import com.bumptech.glide.request.RequestOptions; import com.bumptech.glide.signature.ObjectKey; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import lombok.experimental.FieldDefaults; import net.leloubil.mcpwn.DataManagement; import net.leloubil.mcpwn.async.CallBackPair; import net.leloubil.mcpwn.carvinglabs.CLMemberShip; import net.mcdonalds.OrderGet; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; @Data @AllArgsConstructor @FieldDefaults(level = AccessLevel.PRIVATE) public class UserData implements Serializable { private static final String barcode_url = "/api/customer/%s/barcode"; private UserInfo info; UserToken userToken; @Getter private CLMemberShip memberShip; private List<Consumer<UserInfo>> onInfoUpdate = new ArrayList<>(); private UserData() { } private UserData(UserToken userToken, Consumer<UserData> dataConsumer) { this.userToken = userToken; this.getInfo((i) -> { this.info = i; refreshMembership(m -> { this.memberShip = m; dataConsumer.accept(this); }); }); } public static void fromRefresh(String token, CallBackPair<UserData, Class> cons) { UserToken.refresh(token, in -> { UserData d = new UserData(); d.userToken = in; if (DataManagement.hasInfo(token, cons.getContext())) { d.info = DataManagement.cachedInfo(token, cons.getContext()); d.updateLater(); d.refreshMembership(m -> { d.memberShip = m; cons.success(d); }); } else { d.getInfo(i -> { d.info = i; d.refreshMembership(m -> { d.memberShip = m; cons.success(d); }); }); } }); } public static void createUser(UserToken s, Context c) { UserData d = new UserData(s, (da) -> DataManagement.addUser(da, c)); } public static void onLoginLocation(Context c, String code, Consumer<UserToken> oncode) { McAPI.getIoAuth().logUser(McAPI.client_id, McAPI.client_secret, "authorization_code", code, "mcdo:login").enqueue(new Callback<UserToken>() { @Override public void onResponse(Call<UserToken> call, Response<UserToken> response) { oncode.accept(response.body()); } @Override public void onFailure(Call<UserToken> call, Throwable t) { } }); } private void updateLater() { @SuppressLint("StaticFieldLeak") AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { UserData.this.getInfo(UserData.this::updateInfo); return null; } }; task.execute(); } private void updateInfo(UserInfo i) { this.info = i; onInfoUpdate.forEach(c -> c.accept(i)); onInfoUpdate.clear(); } public void syncInfo(Consumer<UserInfo> i) { if (info != null) { i.accept(info); } else onInfoUpdate.add(i); } private void getInfo(Consumer<UserInfo> infoMcPwnCallback) { McAPI.getUserAuth().retrieveUserInformations("Bearer " + userToken.getToken(), null).enqueue(new Callback<UserInfo>() { @Override public void onResponse(Call<UserInfo> call, Response<UserInfo> response) { infoMcPwnCallback.accept(response.body()); } @Override public void onFailure(Call<UserInfo> call, Throwable t) { } }); } private void refreshMembership(Consumer<CLMemberShip> consumer) { getUserToken().getToken(t -> McAPI.getCarvinglabs().getListSubscribesActiveByUser("Bearer " + t, getInfo().getRef()).enqueue(new Callback<List<CLMemberShip>>() { @Override public void onResponse(Call<List<CLMemberShip>> call, Response<List<CLMemberShip>> response) { if (response.body() == null || response.body().size() == 0) consumer.accept(null); else consumer.accept(response.body().get(0)); } @Override public void onFailure(Call<List<CLMemberShip>> call, Throwable t) { } })); } public void loadBarCode(ImageView viewById) { Glide.with(viewById) .load(new GlideUrl(McAPI.baseUrl + barcode_url.replace("%s", getInfo().getRef()), new LazyHeaders.Builder().setHeader("Authorization", "Bearer " + getUserToken().getToken()).build())) .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).signature(new ObjectKey(getInfo().getRef()))) .into(viewById); } public void getOrders(Consumer<List<OrderGet>> consumer) { getUserToken().getToken(t -> McAPI.getUserAuth().retrieveOrders("Bearer " + t, getInfo().getRef(), "RG.ORDER.ITEMS").enqueue(new Callback<List<OrderGet>>() { @Override public void onResponse(Call<List<OrderGet>> call, Response<List<OrderGet>> response) { if (response.body() == null || response.body().size() == 0) consumer.accept(null); else consumer.accept(response.body()); } @Override public void onFailure(Call<List<OrderGet>> call, Throwable t) { } })); } }
package com.eappcat.base.repository; import com.querydsl.jpa.impl.JPAQueryFactory; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.repository.NoRepositoryBean; @NoRepositoryBean public interface BaseRepository<T> extends JpaRepository<T,String>, QuerydslPredicateExecutor<T>, JpaSpecificationExecutor<T> { default JPAQueryFactory jpaQueryFactory(){ return JPAQueryFactoryHolder.get(); } class JPAQueryFactoryHolder{ public JPAQueryFactoryHolder(JPAQueryFactory jpaQueryFactory){ this.jpaQueryFactory=jpaQueryFactory; } private static JPAQueryFactory jpaQueryFactory; public static JPAQueryFactory get(){ return jpaQueryFactory; } } }
package com.biz.servlet; import com.biz.service.StudentService; import com.biz.vo.Student; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.ParseException; /** * Created by Administrator on 2017/4/18. */ @WebServlet("/update") public class UpdateServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); StudentService studentService = new StudentService(); try { Student student = studentService.getById(request.getParameter("id")); request.setAttribute("student", student); request.getRequestDispatcher("updatestudent.jsp").forward(request, response); } catch (ParseException e) { e.printStackTrace(); } } }
import java.lang.*; import java.util.*; // #!/usr/bin/python -O // #include <stdio.h> // #include <stdlib.h> // #include <string.h> // #include<stdbool.h> // #include<limits.h> // #include<iostream> // #include<algorithm> // #include<string> // #include<vector> // using namespace std; /* # Author : @RAJ009F # Topic or Type : GFG/BT # Problem Statement : find the height of the tree given their indexs # Description : # Complexity : ======================= #steps: =---------------- #sample output ---------------------- ======================= */ class Node { Node l; Node r; int data; Node(int data) { this.data = data; this.l = this.r = null; } } class QNode { Node node; int hd; QNode(Node node, int hd) { this.node = node; this.hd = hd; } } class TreeTopView { Node root; public void printTopView(Node node) { if(node == null) return; HashSet<Integer> hs = new HashSet<Integer>(); Queue<QNode> q = new LinkedList<QNode>(); q.add(new QNode(node, 0)); while(!q.isEmpty()) { QNode qnode = q.peek(); q.poll(); if(!hs.contains(qnode.hd)) { hs.add(qnode.hd); System.out.print(qnode.node.data+" " ); } if(qnode.node.l !=null) q.add(new QNode(qnode.node.l, qnode.hd-1)); if(qnode.node.r !=null) q.add(new QNode(qnode.node.r , qnode.hd+1)); } } public static void main(String args[]) { TreeTopView bt = new TreeTopView(); bt.root = new Node(1); bt.root.l = new Node(2); bt.root.r = new Node(3); bt.root.l.l = new Node(4); bt.root.l.r = new Node(5); bt.root.r.r = new Node(7); bt.root.r.l = new Node(6); bt.root.l.r = new Node(9); bt.root.l.r.r = new Node(10); bt.root.l.r.r.r = new Node(11); bt.root.l.r.r.r.r = new Node(12); bt.root.l.r.r.r.r.r = new Node(13); bt.root.l.r.r.r.r.r.r = new Node(14); bt.printTopView(bt.root); } }
package com.epam.university.spring.httpconverters; import com.epam.university.spring.domain.Ticket; import com.epam.university.spring.rest.domain.BookedTicketsResponse; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.PageSize; import com.lowagie.text.Table; import com.lowagie.text.pdf.PdfWriter; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.Collections; import java.util.List; import java.util.Map; public class PdfHttpMessageConverter implements HttpMessageConverter<Object> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private static final MediaType MEDIA_TYPE_PDF = new MediaType("application", "pdf"); @Override public boolean canRead(Class<?> aClass, MediaType mediaType) { return false; } @Override public boolean canWrite(Class<?> aClass, MediaType mediaType) { return aClass.equals(BookedTicketsResponse.class); } @Override public List<MediaType> getSupportedMediaTypes() { return Collections.singletonList(MEDIA_TYPE_PDF); } @Override public Object read(Class<?> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException { return null; } @Override public void write(Object o, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException { BookedTicketsResponse tickets = (BookedTicketsResponse) o; // IE workaround: write into byte array first. ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); // Apply preferences and build metadata. Document document = new Document(PageSize.A4); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, baos); writer.setViewerPreferences(PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage); document.open(); buildPdfDocument(tickets, document); document.close(); } catch (Exception e) { e.printStackTrace(); } httpOutputMessage.getBody().write(baos.toByteArray()); } protected void buildPdfDocument(BookedTicketsResponse tickets, Document document) throws Exception { Table table = new Table(2); table.addCell("Show"); table.addCell(tickets.getShow()); table.addCell("Price"); table.addCell(tickets.getPrice().toString()); table.addCell("Seats"); table.addCell(tickets.getSeats().toString()); document.add(table); } }
package first.improve.递增的三元子序列; public class Solution { public boolean increasingTriplet(int[] nums) { // 时间复杂度O(n^2), 空间复杂度O(1) // 从头扫描, 设定指针second // 再设双指针, first, third // 然后从该位置向两端扫描 // 先向前扫, 如果出现nums[firstIndex] < nums[secondIndex], 则再向后, 中间可能需要一个标记 // nums[secondIndex] < nums[thirdIndex] 则返回true for (int secondIndex = 0;secondIndex < nums.length;secondIndex++) { boolean hasFirst = false; for (int firstIndexx = secondIndex;firstIndexx >= 0;firstIndexx--) { if (nums[firstIndexx] < nums[secondIndex]) { hasFirst = true; break; } } if (hasFirst) { for (int thirdIndex = secondIndex;thirdIndex < nums.length;thirdIndex++) { if (nums[secondIndex] < nums[thirdIndex]) return true; } } } return false; } public static void main(String[] args) { Solution solution = new Solution(); // int[] nums = {1, 2, 3, 4, 5}; int[] nums = {5, 4, 3, 2, 1}; boolean isIncrease = solution.increasingTriplet(nums); System.out.println(isIncrease); } }
/* * Copyright 2017 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License"). See License in the project root for license information. */ package com.linkedin.kafka.cruisecontrol.servlet; import com.codahale.metrics.MetricRegistry; import com.linkedin.kafka.cruisecontrol.KafkaClusterState; import com.linkedin.kafka.cruisecontrol.common.Resource; import com.linkedin.kafka.cruisecontrol.KafkaCruiseControlState; import com.linkedin.kafka.cruisecontrol.analyzer.goals.Goal; import com.linkedin.kafka.cruisecontrol.analyzer.GoalOptimizer; import com.linkedin.kafka.cruisecontrol.executor.ExecutionProposal; import com.linkedin.kafka.cruisecontrol.executor.ExecutionTask; import com.linkedin.kafka.cruisecontrol.executor.ExecutorState; import com.linkedin.kafka.cruisecontrol.async.OperationFuture; import com.linkedin.kafka.cruisecontrol.model.ClusterModel; import com.linkedin.kafka.cruisecontrol.model.ClusterModelStats; import com.linkedin.kafka.cruisecontrol.model.Partition; import com.linkedin.kafka.cruisecontrol.monitor.ModelCompletenessRequirements; import com.linkedin.kafka.cruisecontrol.monitor.sampling.aggregator.SampleExtrapolation; import com.linkedin.kafka.cruisecontrol.async.AsyncKafkaCruiseControl; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.StringJoiner; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.kafka.common.Cluster; import org.apache.kafka.common.Node; import org.apache.kafka.common.PartitionInfo; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.utils.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import static com.linkedin.kafka.cruisecontrol.servlet.KafkaCruiseControlServlet.DataFrom.VALID_WINDOWS; import static com.linkedin.kafka.cruisecontrol.servlet.EndPoint.*; import static javax.servlet.http.HttpServletResponse.SC_OK; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; /** * The servlet for Kafka Cruise Control. */ public class KafkaCruiseControlServlet extends HttpServlet { private static final Logger LOG = LoggerFactory.getLogger(KafkaCruiseControlServlet.class); private static final Logger ACCESS_LOG = LoggerFactory.getLogger("CruiseControlPublicAccessLogger"); private static final int JSON_VERSION = 1; private static final String PARTITION_MOVEMENTS = "partition movements"; private static final String LEADERSHIP_MOVEMENTS = "leadership movements"; private final AsyncKafkaCruiseControl _asyncKafkaCruiseControl; private final SessionManager _sessionManager; private final long _maxBlockMs; private final ThreadLocal<Integer> _asyncOperationStep; public KafkaCruiseControlServlet(AsyncKafkaCruiseControl asynckafkaCruiseControl, long maxBlockMs, long sessionExpiryMs, MetricRegistry dropwizardMetricRegistry) { _asyncKafkaCruiseControl = asynckafkaCruiseControl; _sessionManager = new SessionManager(5, sessionExpiryMs, Time.SYSTEM, dropwizardMetricRegistry); _maxBlockMs = maxBlockMs; _asyncOperationStep = new ThreadLocal<>(); _asyncOperationStep.set(0); } @Override public void destroy() { super.destroy(); _sessionManager.close(); } /** * OPTIONS request takes care of CORS applications * * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Examples_of_access_control_scenarios */ protected void doOptions(HttpServletRequest request, HttpServletResponse response) { response.setStatus(SC_OK); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Request-Method", "OPTIONS, GET, POST"); } /** * The GET requests can do the following: * * NOTE: ADD json=true to the query parameters to get 200/OK response in JSON format. * * <pre> * 1. Bootstrap the load monitor * RANGE MODE: * GET /kafkacruisecontrol/bootstrap?start=[START_TIMESTAMP]&amp;end=[END_TIMESTAMP] * SINCE MODE: * GET /kafkacruisecontrol/bootstrap?start=[START_TIMESTAMP] * RECENT MODE: * GET /kafkacruisecontrol/bootstrap * * 2. Train the Kafka Cruise Control linear regression model. The trained model will only be used if * use.linear.regression.model is set to true. * GET /kafkacruisecontrol/train?start=[START_TIMESTAMP]&amp;end=[END_TIMESTAMP] * * 3. Get the cluster load * GET /kafkacruisecontrol/load?time=[TIMESTAMP] * * 4. Get the partition load sorted by the utilization of a given resource and filtered by given topic regular expression * and partition number/range * GET /kafkacruisecontrol/partition_load?resource=[RESOURCE]&amp;start=[START_TIMESTAMP]&amp;end=[END_TIMESTAMP] * &amp;topic=[topic]&amp;partition=[partition/start_partition-end_partition] * * 5. Get an optimization proposal * GET /kafkacruisecontrol/proposals?verbose=[ENABLE_VERBOSE]&amp;ignore_proposal_cache=[true/false] * &amp;goals=[goal1,goal2...]&amp;data_from=[valid_windows/valid_partitions] * * 6. query the state of Kafka Cruise Control * GET /kafkacruisecontrol/state * * 7. query the Kafka cluster state * GET /kafkacruisecontrol/kafka_cluster_state * * <b>NOTE: All the timestamps are epoch time in second granularity.</b> * </pre> */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { ACCESS_LOG.info("Received {}, {} from {}", KafkaCruiseControlServletUtils.urlEncode(request.toString()), KafkaCruiseControlServletUtils.urlEncode(request.getRequestURL().toString()), KafkaCruiseControlServletUtils.getClientIpAddress(request)); try { _asyncOperationStep.set(0); EndPoint endPoint = KafkaCruiseControlServletUtils.endPoint(request); if (endPoint != null) { Set<String> validParamNames = KafkaCruiseControlServletUtils.VALID_ENDPOINT_PARAM_NAMES.get(endPoint); Set<String> userParams = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); if (validParamNames != null) { userParams.addAll(request.getParameterMap().keySet()); userParams.removeAll(validParamNames); } if (!userParams.isEmpty()) { // User request specifies parameters that are not a subset of the valid parameters. String errorResp = String.format("Unrecognized endpoint parameters in %s get request: %s.", endPoint, userParams.toString()); setErrorResponse(response, "", errorResp, SC_BAD_REQUEST, KafkaCruiseControlServletUtils.wantJSON(request)); } else { switch (endPoint) { case BOOTSTRAP: bootstrap(request, response); break; case TRAIN: train(request, response); break; case LOAD: if (getClusterLoad(request, response)) { _sessionManager.closeSession(request); } break; case PARTITION_LOAD: if (getPartitionLoad(request, response)) { _sessionManager.closeSession(request); } break; case PROPOSALS: if (getProposals(request, response)) { _sessionManager.closeSession(request); } break; case STATE: if (getState(request, response)) { _sessionManager.closeSession(request); } break; case KAFKA_CLUSTER_STATE: getKafkaClusterState(request, response); break; default: throw new UserRequestException("Invalid URL for GET"); } } } else { String errorMessage = String.format("Unrecognized endpoint in GET request '%s'%nSupported GET endpoints: %s", request.getPathInfo(), EndPoint.getEndpoint()); setErrorResponse(response, "", errorMessage, SC_NOT_FOUND, KafkaCruiseControlServletUtils.wantJSON(request)); } } catch (UserRequestException ure) { LOG.error("Why are you failing?", ure); String errorMessage = String.format("Bad GET request '%s'", request.getPathInfo()); StringWriter sw = new StringWriter(); ure.printStackTrace(new PrintWriter(sw)); setErrorResponse(response, sw.toString(), errorMessage, SC_BAD_REQUEST, KafkaCruiseControlServletUtils.wantJSON(request)); _sessionManager.closeSession(request); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String errorMessage = String.format("Error processing GET request '%s' due to '%s'.", request.getPathInfo(), e.getMessage()); LOG.error(errorMessage, e); setErrorResponse(response, sw.toString(), errorMessage, SC_INTERNAL_SERVER_ERROR, KafkaCruiseControlServletUtils.wantJSON(request)); _sessionManager.closeSession(request); } finally { try { response.getOutputStream().close(); } catch (IOException e) { LOG.warn("Error closing output stream: ", e); } } } /** * The POST method allows user to perform the following actions: * * <pre> * 1. Decommission a broker. * POST /kafkacruisecontrol/remove_broker?brokerid=[id1,id2...]&amp;dryrun=[true/false]&amp;throttle_removed_broker=[true/false]&amp;goals=[goal1,goal2...] * &amp;allow_capacity_estimation=[true/false]&amp;concurrent_partition_movements_per_broker=[true/false]&amp;concurrent_leader_movements=[true/false] * &amp;json=[true/false] * * 2. Add a broker * POST /kafkacruisecontrol/add_broker?brokerid=[id1,id2...]&amp;dryrun=[true/false]&amp;throttle_added_broker=[true/false]&amp;goals=[goal1,goal2...] * &amp;allow_capacity_estimation=[true/false]&amp;concurrent_partition_movements_per_broker=[true/false]&amp;concurrent_leader_movements=[true/false] * &amp;json=[true/false] * * 3. Trigger a workload balance. * POST /kafkacruisecontrol/rebalance?dryrun=[true/false]&amp;force=[true/false]&amp;goals=[goal1,goal2...]&amp;allow_capacity_estimation=[true/false] * &amp;concurrent_partition_movements_per_broker=[true/false]&amp;concurrent_leader_movements=[true/false]&amp;json=[true/false] * * 4. Stop the proposal execution. * POST /kafkacruisecontrol/stop_proposal_execution?json=[true/false] * * 5. Pause metrics sampling. (RUNNING -&gt; PAUSED). * POST /kafkacruisecontrol/pause_sampling?json=[true/false] * * 6. Resume metrics sampling. (PAUSED -&gt; RUNNING). * POST /kafkacruisecontrol/resume_sampling?json=[true/false] * * 7. Demote a broker * POST /kafkacruisecontrol/demote_broker?brokerid=[id1,id2...]&amp;dryrun=[true/false]&amp;concurrent_leader_movements=[true/false] * &amp;allow_capacity_estimation=[true/false]&amp;json=[true/false] * * <b>NOTE: All the timestamps are epoch time in second granularity.</b> * </pre> */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { ACCESS_LOG.info("Received {}, {} from {}", KafkaCruiseControlServletUtils.urlEncode(request.toString()), KafkaCruiseControlServletUtils.urlEncode(request.getRequestURL().toString()), KafkaCruiseControlServletUtils.getClientIpAddress(request)); try { _asyncOperationStep.set(0); EndPoint endPoint = KafkaCruiseControlServletUtils.endPoint(request); if (endPoint != null) { Set<String> validParamNames = KafkaCruiseControlServletUtils.VALID_ENDPOINT_PARAM_NAMES.get(endPoint); Set<String> userParams = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); if (validParamNames != null) { userParams.addAll(request.getParameterMap().keySet()); userParams.removeAll(validParamNames); } if (!userParams.isEmpty()) { // User request specifies parameters that are not a subset of the valid parameters. String errorResp = String.format("Unrecognized endpoint parameters in %s post request: %s.", endPoint, userParams.toString()); setErrorResponse(response, "", errorResp, SC_BAD_REQUEST, KafkaCruiseControlServletUtils.wantJSON(request)); } else { switch (endPoint) { case ADD_BROKER: case REMOVE_BROKER: if (addOrRemoveBroker(request, response, endPoint)) { _sessionManager.closeSession(request); } break; case REBALANCE: if (rebalance(request, response, endPoint)) { _sessionManager.closeSession(request); } break; case STOP_PROPOSAL_EXECUTION: stopProposalExecution(); setSuccessResponse(response, "Proposal execution stopped.", KafkaCruiseControlServletUtils.wantJSON(request)); break; case PAUSE_SAMPLING: pauseSampling(); setSuccessResponse(response, "Metric sampling paused.", KafkaCruiseControlServletUtils.wantJSON(request)); break; case RESUME_SAMPLING: resumeSampling(); setSuccessResponse(response, "Metric sampling resumed.", KafkaCruiseControlServletUtils.wantJSON(request)); break; case DEMOTE_BROKER: if (demoteBroker(request, response, endPoint)) { _sessionManager.closeSession(request); } break; default: throw new UserRequestException("Invalid URL for POST"); } } } else { String errorMessage = String.format("Unrecognized endpoint in POST request '%s'%nSupported POST endpoints: %s", request.getPathInfo(), EndPoint.postEndpoint()); setErrorResponse(response, "", errorMessage, SC_NOT_FOUND, KafkaCruiseControlServletUtils.wantJSON(request)); } } catch (UserRequestException ure) { LOG.error("Why are you failing?", ure); String errorMessage = String.format("Bad POST request '%s'", request.getPathInfo()); StringWriter sw = new StringWriter(); ure.printStackTrace(new PrintWriter(sw)); setErrorResponse(response, sw.toString(), errorMessage, SC_BAD_REQUEST, KafkaCruiseControlServletUtils.wantJSON(request)); _sessionManager.closeSession(request); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String errorMessage = String.format("Error processing POST request '%s' due to: '%s'.", request.getPathInfo(), e.getMessage()); LOG.error(errorMessage, e); setErrorResponse(response, sw.toString(), errorMessage, SC_INTERNAL_SERVER_ERROR, KafkaCruiseControlServletUtils.wantJSON(request)); _sessionManager.closeSession(request); } finally { try { response.getOutputStream().close(); } catch (IOException e) { LOG.warn("Error closing output stream: ", e); } } } private void bootstrap(HttpServletRequest request, HttpServletResponse response) throws Exception { Long startMs; Long endMs; boolean clearMetrics; boolean json = KafkaCruiseControlServletUtils.wantJSON(request); try { startMs = KafkaCruiseControlServletUtils.startMs(request); endMs = KafkaCruiseControlServletUtils.endMs(request); clearMetrics = KafkaCruiseControlServletUtils.clearMetrics(request); if (startMs == null && endMs != null) { String errorMsg = "The start time cannot be empty when end time is specified."; setErrorResponse(response, "", errorMsg, SC_BAD_REQUEST, json); return; } } catch (Exception e) { handleParameterParseException(e, response, e.getMessage(), json); return; } if (startMs != null && endMs != null) { _asyncKafkaCruiseControl.bootstrapLoadMonitor(startMs, endMs, clearMetrics); } else if (startMs != null) { _asyncKafkaCruiseControl.bootstrapLoadMonitor(startMs, clearMetrics); } else { _asyncKafkaCruiseControl.bootstrapLoadMonitor(clearMetrics); } String msg = String.format("Bootstrap started. Check status through %s", getStateCheckUrl(request)); setSuccessResponse(response, msg, json); } private void setErrorResponse(HttpServletResponse response, String stackTrace, String errorMessage, int responseCode, boolean json) throws IOException { String resp; if (json) { Map<String, Object> exceptionMap = new HashMap<>(); exceptionMap.put("version", JSON_VERSION); exceptionMap.put("stackTrace", stackTrace); exceptionMap.put("errorMessage", errorMessage); Gson gson = new Gson(); resp = gson.toJson(exceptionMap); } else { resp = errorMessage == null ? "" : errorMessage; } setResponseCode(response, responseCode, json); response.setContentLength(resp.length()); response.getOutputStream().write(resp.getBytes(StandardCharsets.UTF_8)); response.getOutputStream().flush(); } private void setSuccessResponse(HttpServletResponse response, String message, boolean json) throws IOException { String resp; if (json) { Map<String, Object> respMap = new HashMap<>(); respMap.put("version", JSON_VERSION); respMap.put("Message", message); Gson gson = new Gson(); resp = gson.toJson(respMap); } else { resp = message == null ? "" : message; } setResponseCode(response, SC_OK, json); response.setContentLength(resp.length()); response.getOutputStream().write(resp.getBytes(StandardCharsets.UTF_8)); response.getOutputStream().flush(); } private void train(HttpServletRequest request, HttpServletResponse response) throws Exception { Long startMs; Long endMs; boolean json = KafkaCruiseControlServletUtils.wantJSON(request); try { startMs = KafkaCruiseControlServletUtils.startMs(request); endMs = KafkaCruiseControlServletUtils.endMs(request); if (startMs == null || endMs == null) { throw new UserRequestException("Missing start or end parameter."); } } catch (Exception e) { handleParameterParseException(e, response, e.getMessage(), json); return; } _asyncKafkaCruiseControl.trainLoadModel(startMs, endMs); String message = String.format("Load model training started. Check status through %s", getStateCheckUrl(request)); setSuccessResponse(response, message, json); } private boolean getClusterLoad(HttpServletRequest request, HttpServletResponse response) throws Exception { long time; boolean json = KafkaCruiseControlServletUtils.wantJSON(request); try { time = KafkaCruiseControlServletUtils.time(request); } catch (Exception e) { handleParameterParseException(e, response, e.getMessage(), json); // Close session return true; } ModelCompletenessRequirements requirements = new ModelCompletenessRequirements(1, 0.0, true); boolean allowCapacityEstimation = KafkaCruiseControlServletUtils.allowCapacityEstimation(request); ClusterModel.BrokerStats brokerStats = _asyncKafkaCruiseControl.cachedBrokerLoadStats(allowCapacityEstimation); if (brokerStats == null) { // Get the broker stats asynchronously. brokerStats = getAndMaybeReturnProgress( request, response, () -> _asyncKafkaCruiseControl.getBrokerStats(time, requirements, allowCapacityEstimation)); if (brokerStats == null) { return false; } } String brokerLoad = json ? brokerStats.getJSONString(JSON_VERSION) : brokerStats.toString(); setResponseCode(response, SC_OK, json); response.setContentLength(brokerLoad.length()); response.getOutputStream().write(brokerLoad.getBytes(StandardCharsets.UTF_8)); response.getOutputStream().flush(); return true; } private boolean getPartitionLoad(HttpServletRequest request, HttpServletResponse response) throws Exception { Resource resource; long startMs; long endMs; int entries; Pattern topic = KafkaCruiseControlServletUtils.topic(request); int partitionUpperBoundary; int partitionLowerBoundary; boolean json = KafkaCruiseControlServletUtils.wantJSON(request); String resourceString = KafkaCruiseControlServletUtils.resourceString(request); try { resource = Resource.valueOf(resourceString.toUpperCase()); } catch (IllegalArgumentException iae) { String errorMsg = String.format("Invalid resource type %s. The resource type must be one of the following: " + "CPU, DISK, NW_IN, NW_OUT", resourceString); handleParameterParseException(iae, response, errorMsg, json); // Close session return true; } try { Long startMsValue = KafkaCruiseControlServletUtils.startMs(request); startMs = startMsValue == null ? -1L : startMsValue; Long endMsValue = KafkaCruiseControlServletUtils.endMs(request); endMs = endMsValue == null ? System.currentTimeMillis() : endMsValue; partitionLowerBoundary = KafkaCruiseControlServletUtils.partitionBoundary(request, false); partitionUpperBoundary = KafkaCruiseControlServletUtils.partitionBoundary(request, true); entries = KafkaCruiseControlServletUtils.entries(request); } catch (Exception e) { handleParameterParseException(e, response, e.getMessage(), json); // Close session return true; } boolean allowCapacityEstimation = KafkaCruiseControlServletUtils.allowCapacityEstimation(request); ModelCompletenessRequirements requirements = new ModelCompletenessRequirements(1, 0.98, false); // Get cluster model asynchronously. ClusterModel clusterModel = getAndMaybeReturnProgress( request, response, () -> _asyncKafkaCruiseControl.clusterModel(startMs, endMs, requirements, allowCapacityEstimation)); if (clusterModel == null) { return false; } List<Partition> sortedPartitions = clusterModel.replicasSortedByUtilization(resource); OutputStream out = response.getOutputStream(); int numEntries = 0; setResponseCode(response, SC_OK, json); boolean wantMaxLoad = KafkaCruiseControlServletUtils.wantMaxLoad(request); if (!json) { int topicNameLength = clusterModel.topics().stream().mapToInt(String::length).max().orElse(20) + 5; out.write(String.format("%" + topicNameLength + "s%10s%30s%20s%20s%20s%20s%n", "PARTITION", "LEADER", "FOLLOWERS", "CPU (%)", "DISK (MB)", "NW_IN (KB/s)", "NW_OUT (KB/s)") .getBytes(StandardCharsets.UTF_8)); for (Partition p : sortedPartitions) { if ((topic != null && !topic.matcher(p.topicPartition().topic()).matches()) || p.topicPartition().partition() < partitionLowerBoundary || p.topicPartition().partition() > partitionUpperBoundary) { continue; } if (++numEntries > entries) { break; } List<Integer> followers = p.followers().stream().map((replica) -> replica.broker().id()).collect(Collectors.toList()); out.write(String.format("%" + topicNameLength + "s%10s%30s%19.6f%19.3f%19.3f%19.3f%n", p.leader().topicPartition(), p.leader().broker().id(), followers, p.leader().load().expectedUtilizationFor(Resource.CPU, wantMaxLoad), p.leader().load().expectedUtilizationFor(Resource.DISK, wantMaxLoad), p.leader().load().expectedUtilizationFor(Resource.NW_IN, wantMaxLoad), p.leader().load().expectedUtilizationFor(Resource.NW_OUT, wantMaxLoad)) .getBytes(StandardCharsets.UTF_8)); } } else { Map<String, Object> partitionMap = new HashMap<>(); List<Object> partitionList = new ArrayList<>(); partitionMap.put("version", JSON_VERSION); for (Partition p : sortedPartitions) { if ((topic != null && !topic.matcher(p.topicPartition().topic()).matches()) || p.topicPartition().partition() < partitionLowerBoundary || p.topicPartition().partition() > partitionUpperBoundary) { continue; } if (++numEntries > entries) { break; } List<Integer> followers = p.followers().stream().map((replica) -> replica.broker().id()).collect(Collectors.toList()); Map<String, Object> record = new HashMap<>(); record.put("topic", p.leader().topicPartition().topic()); record.put("partition", p.leader().topicPartition().partition()); record.put("leader", p.leader().broker().id()); record.put("followers", followers); record.put("CPU", p.leader().load().expectedUtilizationFor(Resource.CPU, wantMaxLoad)); record.put("DISK", p.leader().load().expectedUtilizationFor(Resource.DISK, wantMaxLoad)); record.put("NW_IN", p.leader().load().expectedUtilizationFor(Resource.NW_IN, wantMaxLoad)); record.put("NW_OUT", p.leader().load().expectedUtilizationFor(Resource.NW_OUT, wantMaxLoad)); partitionList.add(record); } partitionMap.put("records", partitionList); Gson gson = new Gson(); String g = gson.toJson(partitionMap); response.setContentLength(g.length()); out.write(g.getBytes(StandardCharsets.UTF_8)); } out.flush(); return true; } private boolean getProposals(HttpServletRequest request, HttpServletResponse response) throws Exception { boolean verbose = KafkaCruiseControlServletUtils.isVerbose(request); boolean ignoreProposalCache; DataFrom dataFrom; List<String> goals; boolean json = KafkaCruiseControlServletUtils.wantJSON(request); try { goals = KafkaCruiseControlServletUtils.getGoals(request); dataFrom = KafkaCruiseControlServletUtils.getDataFrom(request); ignoreProposalCache = KafkaCruiseControlServletUtils.ignoreProposalCache(request) || !goals.isEmpty(); } catch (Exception e) { handleParameterParseException(e, response, e.getMessage(), json); // Close session return true; } GoalsAndRequirements goalsAndRequirements = getGoalsAndRequirements(request, response, goals, dataFrom, ignoreProposalCache); if (goalsAndRequirements == null) { return false; } boolean allowCapacityEstimation = KafkaCruiseControlServletUtils.allowCapacityEstimation(request); // Get the optimization result asynchronously. GoalOptimizer.OptimizerResult optimizerResult = getAndMaybeReturnProgress( request, response, () -> _asyncKafkaCruiseControl.getOptimizationProposals(goalsAndRequirements.goals(), goalsAndRequirements.requirements(), allowCapacityEstimation)); if (optimizerResult == null) { return false; } setResponseCode(response, SC_OK, json); OutputStream out = response.getOutputStream(); if (!json) { String loadBeforeOptimization = optimizerResult.brokerStatsBeforeOptimization().toString(); String loadAfterOptimization = optimizerResult.brokerStatsAfterOptimization().toString(); if (!verbose) { out.write( optimizerResult.getProposalSummary().getBytes(StandardCharsets.UTF_8)); } else { out.write(optimizerResult.goalProposals().toString().getBytes(StandardCharsets.UTF_8)); } for (Map.Entry<Goal, ClusterModelStats> entry : optimizerResult.statsByGoalPriority().entrySet()) { Goal goal = entry.getKey(); out.write(String.format("%n%nStats for goal %s%s:%n", goal.name(), goalResultDescription(goal, optimizerResult)) .getBytes(StandardCharsets.UTF_8)); out.write(entry.getValue().toString().getBytes(StandardCharsets.UTF_8)); } // Print summary before & after optimization out.write(String.format("%n%nCurrent load:").getBytes(StandardCharsets.UTF_8)); out.write(loadBeforeOptimization.getBytes(StandardCharsets.UTF_8)); out.write(String.format("%n%nOptimized load:").getBytes(StandardCharsets.UTF_8)); out.write(loadAfterOptimization.getBytes(StandardCharsets.UTF_8)); } else { Map<String, Object> proposalMap = new HashMap<>(); if (!verbose) { proposalMap.put("summary", optimizerResult.getProposalSummaryForJson()); } else { proposalMap.put("proposals", optimizerResult.goalProposals().stream().map(ExecutionProposal::getJsonStructure).collect(Collectors.toList())); } // Build all the goal summary List<Map<String, Object>> allGoals = new ArrayList<>(); for (Map.Entry<Goal, ClusterModelStats> entry : optimizerResult.statsByGoalPriority().entrySet()) { Goal goal = entry.getKey(); String goalViolation = goalResultDescription(goal, optimizerResult); Map<String, Object> goalMap = new HashMap<>(); goalMap.put("goal", goal.name()); goalMap.put("goalViolated", goalViolation); goalMap.put("clusterModelStats", entry.getValue().getJsonStructure()); allGoals.add(goalMap); } proposalMap.put("version", JSON_VERSION); proposalMap.put("goals", allGoals); proposalMap.put("loadBeforeOptimization", optimizerResult.brokerStatsBeforeOptimization().getJsonStructure()); proposalMap.put("loadAfterOptimization", optimizerResult.brokerStatsAfterOptimization().getJsonStructure()); Gson gson = new GsonBuilder() .serializeNulls() .serializeSpecialFloatingPointValues() .create(); String proposalsString = gson.toJson(proposalMap); out.write(proposalsString.getBytes(StandardCharsets.UTF_8)); } out.flush(); return true; } private String goalResultDescription(Goal goal, GoalOptimizer.OptimizerResult optimizerResult) { return optimizerResult.violatedGoalsBeforeOptimization().contains(goal) ? optimizerResult.violatedGoalsAfterOptimization().contains(goal) ? "(VIOLATED)" : "(FIXED)" : "(NO-ACTION)"; } private ModelCompletenessRequirements getRequirements(DataFrom dataFrom) { if (dataFrom == DataFrom.VALID_PARTITIONS) { return new ModelCompletenessRequirements(Integer.MAX_VALUE, 0.0, true); } else { return new ModelCompletenessRequirements(1, 1.0, true); } } private void writeKafkaClusterState(OutputStream out, SortedSet<PartitionInfo> partitions, int topicNameLength) throws IOException { for (PartitionInfo partitionInfo : partitions) { Set<String> replicas = Arrays.stream(partitionInfo.replicas()).map(Node::idString).collect(Collectors.toSet()); Set<String> inSyncReplicas = Arrays.stream(partitionInfo.inSyncReplicas()).map(Node::idString).collect(Collectors.toSet()); Set<String> outOfSyncReplicas = new HashSet<>(replicas); outOfSyncReplicas.removeAll(inSyncReplicas); out.write(String.format("%" + topicNameLength + "s%10s%10s%40s%40s%30s%n", partitionInfo.topic(), partitionInfo.partition(), partitionInfo.leader() == null ? -1 : partitionInfo.leader().id(), replicas, inSyncReplicas, outOfSyncReplicas) .getBytes(StandardCharsets.UTF_8)); } } private void getKafkaClusterState(HttpServletRequest request, HttpServletResponse response) throws Exception { boolean verbose = KafkaCruiseControlServletUtils.isVerbose(request); boolean json = KafkaCruiseControlServletUtils.wantJSON(request); KafkaClusterState state = _asyncKafkaCruiseControl.kafkaClusterState(); OutputStream out = response.getOutputStream(); setResponseCode(response, SC_OK, json); if (json) { String stateString = state.getJSONString(JSON_VERSION, verbose); response.setContentLength(stateString.length()); out.write(stateString.getBytes(StandardCharsets.UTF_8)); } else { Cluster clusterState = state.kafkaCluster(); // Brokers summary. SortedMap<Integer, Integer> leaderCountByBrokerId = new TreeMap<>(); SortedMap<Integer, Integer> outOfSyncCountByBrokerId = new TreeMap<>(); SortedMap<Integer, Integer> replicaCountByBrokerId = new TreeMap<>(); state.populateKafkaBrokerState(leaderCountByBrokerId, outOfSyncCountByBrokerId, replicaCountByBrokerId); String initMessage = "Brokers with replicas:"; out.write(String.format("%s%n%20s%20s%20s%20s%n", initMessage, "BROKER", "LEADER(S)", "REPLICAS", "OUT-OF-SYNC") .getBytes(StandardCharsets.UTF_8)); for (Integer brokerId : replicaCountByBrokerId.keySet()) { out.write(String.format("%20d%20d%20d%20d%n", brokerId, leaderCountByBrokerId.getOrDefault(brokerId, 0), replicaCountByBrokerId.getOrDefault(brokerId, 0), outOfSyncCountByBrokerId.getOrDefault(brokerId, 0)) .getBytes(StandardCharsets.UTF_8)); } // Partitions summary. int topicNameLength = clusterState.topics().stream().mapToInt(String::length).max().orElse(20) + 5; initMessage = verbose ? "All Partitions in the Cluster (verbose):" : "Under Replicated and Offline Partitions in the Cluster:"; out.write(String.format("%n%s%n%" + topicNameLength + "s%10s%10s%40s%40s%30s%n", initMessage, "TOPIC", "PARTITION", "LEADER", "REPLICAS", "IN-SYNC", "OUT-OF-SYNC") .getBytes(StandardCharsets.UTF_8)); // Gather the cluster state. Comparator<PartitionInfo> comparator = Comparator.comparing(PartitionInfo::topic).thenComparingInt(PartitionInfo::partition); SortedSet<PartitionInfo> underReplicatedPartitions = new TreeSet<>(comparator); SortedSet<PartitionInfo> offlinePartitions = new TreeSet<>(comparator); SortedSet<PartitionInfo> otherPartitions = new TreeSet<>(comparator); state.populateKafkaPartitionState(underReplicatedPartitions, offlinePartitions, otherPartitions, verbose); // Write the cluster state. out.write(String.format("Offline Partitions:%n").getBytes(StandardCharsets.UTF_8)); writeKafkaClusterState(out, offlinePartitions, topicNameLength); out.write(String.format("Under Replicated Partitions:%n").getBytes(StandardCharsets.UTF_8)); writeKafkaClusterState(out, underReplicatedPartitions, topicNameLength); if (verbose) { out.write(String.format("Other Partitions:%n").getBytes(StandardCharsets.UTF_8)); writeKafkaClusterState(out, otherPartitions, topicNameLength); } } response.getOutputStream().flush(); } private boolean getState(HttpServletRequest request, HttpServletResponse response) throws Exception { boolean verbose = KafkaCruiseControlServletUtils.isVerbose(request); boolean superVerbose = KafkaCruiseControlServletUtils.isSuperVerbose(request); boolean json = KafkaCruiseControlServletUtils.wantJSON(request); KafkaCruiseControlState state = getAndMaybeReturnProgress(request, response, _asyncKafkaCruiseControl::state); if (state == null) { return false; } OutputStream out = response.getOutputStream(); setResponseCode(response, SC_OK, json); if (json) { String stateString = state.getJSONString(JSON_VERSION, verbose); response.setContentLength(stateString.length()); out.write(stateString.getBytes(StandardCharsets.UTF_8)); } else { String stateString = state.toString(); out.write(stateString.getBytes(StandardCharsets.UTF_8)); if (verbose || superVerbose) { out.write(String.format("%n%nMonitored Windows [Window End_Time=Data_Completeness]:%n").getBytes(StandardCharsets.UTF_8)); StringJoiner joiner = new StringJoiner(", ", "{", "}"); for (Map.Entry<Long, Float> entry : state.monitorState().monitoredWindows().entrySet()) { joiner.add(String.format("%d=%.3f%%", entry.getKey(), entry.getValue() * 100)); } out.write(joiner.toString().getBytes(StandardCharsets.UTF_8)); out.write(String.format("%n%nGoal Readiness:%n").getBytes(StandardCharsets.UTF_8)); for (Map.Entry<Goal, Boolean> entry : state.analyzerState().readyGoals().entrySet()) { Goal goal = entry.getKey(); out.write(String.format("%50s, %s, %s%n", goal.getClass().getSimpleName(), goal.clusterModelCompletenessRequirements(), entry.getValue() ? "Ready" : "NotReady").getBytes(StandardCharsets.UTF_8)); } ExecutorState executorState = state.executorState(); if (executorState.state() == ExecutorState.State.REPLICA_MOVEMENT_TASK_IN_PROGRESS || executorState.state() == ExecutorState.State.STOPPING_EXECUTION) { out.write(String.format("%n%nIn progress %s:%n", PARTITION_MOVEMENTS).getBytes(StandardCharsets.UTF_8)); for (ExecutionTask task : executorState.inProgressPartitionMovements()) { out.write(String.format("%s%n", task).getBytes(StandardCharsets.UTF_8)); } out.write(String.format("%n%nAborting %s:%n", PARTITION_MOVEMENTS).getBytes(StandardCharsets.UTF_8)); for (ExecutionTask task : executorState.abortingPartitionMovements()) { out.write(String.format("%s%n", task).getBytes(StandardCharsets.UTF_8)); } out.write(String.format("%n%nAborted %s:%n", PARTITION_MOVEMENTS).getBytes(StandardCharsets.UTF_8)); for (ExecutionTask task : executorState.abortedPartitionMovements()) { out.write(String.format("%s%n", task).getBytes(StandardCharsets.UTF_8)); } out.write(String.format("%n%nDead %s:%n", PARTITION_MOVEMENTS).getBytes(StandardCharsets.UTF_8)); for (ExecutionTask task : executorState.deadPartitionMovements()) { out.write(String.format("%s%n", task).getBytes(StandardCharsets.UTF_8)); } out.write(String.format("%n%n%s %s:%n", executorState.state() == ExecutorState.State.STOPPING_EXECUTION ? "Cancelled" : "Pending", PARTITION_MOVEMENTS).getBytes(StandardCharsets.UTF_8)); for (ExecutionTask task : executorState.pendingPartitionMovements()) { out.write(String.format("%s%n", task).getBytes(StandardCharsets.UTF_8)); } } else if (executorState.state() == ExecutorState.State.LEADER_MOVEMENT_TASK_IN_PROGRESS) { out.write(String.format("%n%nPending %s:%n", LEADERSHIP_MOVEMENTS).getBytes(StandardCharsets.UTF_8)); for (ExecutionTask task : executorState.pendingLeadershipMovements()) { out.write(String.format("%s%n", task).getBytes(StandardCharsets.UTF_8)); } } if (superVerbose) { out.write(String.format("%n%nExtrapolated metric samples:%n").getBytes(StandardCharsets.UTF_8)); Map<TopicPartition, List<SampleExtrapolation>> sampleFlaws = state.monitorState().sampleExtrapolations(); if (sampleFlaws != null && !sampleFlaws.isEmpty()) { for (Map.Entry<TopicPartition, List<SampleExtrapolation>> entry : sampleFlaws.entrySet()) { out.write(String.format("%n%s: %s", entry.getKey(), entry.getValue()).getBytes(StandardCharsets.UTF_8)); } } else { out.write("None".getBytes(StandardCharsets.UTF_8)); } if (state.monitorState().detailTrainingProgress() != null) { out.write( String.format("%n%nLinear Regression Model State:%n%s", state.monitorState().detailTrainingProgress()).getBytes(StandardCharsets.UTF_8)); } } } } response.getOutputStream().flush(); return true; } private String generateGoalAndClusterStatusAfterExecution(boolean json, GoalOptimizer.OptimizerResult optimizerResult, EndPoint endPoint, List<Integer> brokerIds) { StringBuilder sb = new StringBuilder(); if (!json) { sb.append(optimizerResult.getProposalSummary()); for (Map.Entry<Goal, ClusterModelStats> entry : optimizerResult.statsByGoalPriority().entrySet()) { Goal goal = entry.getKey(); sb.append(String.format("%n%nStats for goal %s%s:%n", goal.name(), goalResultDescription(goal, optimizerResult))); sb.append(entry.getValue().toString()); } switch (endPoint) { case REBALANCE: sb.append("%n%nCluster load after rebalance:%n"); break; case ADD_BROKER: sb.append(String.format("%n%nCluster load after adding broker %s:%n", brokerIds)); break; case REMOVE_BROKER: sb.append(String.format("%n%nCluster load after removing broker %s:%n", brokerIds)); break; case DEMOTE_BROKER: sb.append(String.format("%n%nCluster load after demoting broker %s:%n", brokerIds)); break; default: break; } sb.append(optimizerResult.brokerStatsAfterOptimization().toString()); } else { Map<String, Object> retMap = new HashMap<>(); retMap.put("proposalSummary", optimizerResult.getProposalSummaryForJson()); List<Object> goalStatusList = new ArrayList<>(); for (Map.Entry<Goal, ClusterModelStats> entry : optimizerResult.statsByGoalPriority().entrySet()) { Goal goal = entry.getKey(); Map<String, Object> goalRecord = new HashMap<>(); goalRecord.put("goalName", goal.name()); goalRecord.put("status", goalResultDescription(goal, optimizerResult)); goalRecord.put("clusterModelStats", entry.getValue().getJsonStructure()); goalStatusList.add(goalRecord); } retMap.put("goalSummary", goalStatusList); retMap.put("resultingClusterLoad", optimizerResult.brokerStatsAfterOptimization().getJsonStructure()); retMap.put("version", JSON_VERSION); Gson gson = new GsonBuilder() .serializeNulls() .serializeSpecialFloatingPointValues() .create(); sb.append(gson.toJson(retMap)); } return sb.toString(); } private boolean addOrRemoveBroker(HttpServletRequest request, HttpServletResponse response, EndPoint endPoint) throws Exception { List<Integer> brokerIds; Integer concurrentPartitionMovements; Integer concurrentLeaderMovements; boolean dryrun; DataFrom dataFrom; boolean throttleAddedOrRemovedBrokers; List<String> goals; boolean json = KafkaCruiseControlServletUtils.wantJSON(request); try { brokerIds = KafkaCruiseControlServletUtils.brokerIds(request); dryrun = KafkaCruiseControlServletUtils.getDryRun(request); goals = KafkaCruiseControlServletUtils.getGoals(request); dataFrom = KafkaCruiseControlServletUtils.getDataFrom(request); throttleAddedOrRemovedBrokers = KafkaCruiseControlServletUtils.throttleAddedOrRemovedBrokers(request, endPoint); concurrentPartitionMovements = KafkaCruiseControlServletUtils.concurrentMovementsPerBroker(request, true); concurrentLeaderMovements = KafkaCruiseControlServletUtils.concurrentMovementsPerBroker(request, false); } catch (Exception e) { handleParameterParseException(e, response, e.getMessage(), json); // Close session return true; } GoalsAndRequirements goalsAndRequirements = getGoalsAndRequirements(request, response, goals, dataFrom, false); if (goalsAndRequirements == null) { return false; } // Get proposals asynchronously. GoalOptimizer.OptimizerResult optimizerResult; boolean allowCapacityEstimation = KafkaCruiseControlServletUtils.allowCapacityEstimation(request); if (endPoint == ADD_BROKER) { optimizerResult = getAndMaybeReturnProgress(request, response, () -> _asyncKafkaCruiseControl.addBrokers(brokerIds, dryrun, throttleAddedOrRemovedBrokers, goalsAndRequirements.goals(), goalsAndRequirements.requirements(), allowCapacityEstimation, concurrentPartitionMovements, concurrentLeaderMovements)); } else { optimizerResult = getAndMaybeReturnProgress(request, response, () -> _asyncKafkaCruiseControl.decommissionBrokers(brokerIds, dryrun, throttleAddedOrRemovedBrokers, goalsAndRequirements.goals(), goalsAndRequirements.requirements(), allowCapacityEstimation, concurrentPartitionMovements, concurrentLeaderMovements)); } if (optimizerResult == null) { return false; } setResponseCode(response, SC_OK, json); OutputStream out = response.getOutputStream(); out.write(generateGoalAndClusterStatusAfterExecution(json, optimizerResult, endPoint, brokerIds).getBytes(StandardCharsets.UTF_8)); out.flush(); return true; } private boolean rebalance(HttpServletRequest request, HttpServletResponse response, EndPoint endPoint) throws Exception { boolean dryrun; DataFrom dataFrom; List<String> goals; Integer concurrentPartitionMovements; Integer concurrentLeaderMovements; boolean json = KafkaCruiseControlServletUtils.wantJSON(request); try { dryrun = KafkaCruiseControlServletUtils.getDryRun(request); goals = KafkaCruiseControlServletUtils.getGoals(request); dataFrom = KafkaCruiseControlServletUtils.getDataFrom(request); concurrentPartitionMovements = KafkaCruiseControlServletUtils.concurrentMovementsPerBroker(request, true); concurrentLeaderMovements = KafkaCruiseControlServletUtils.concurrentMovementsPerBroker(request, false); } catch (Exception e) { handleParameterParseException(e, response, e.getMessage(), json); // Close session return true; } GoalsAndRequirements goalsAndRequirements = getGoalsAndRequirements(request, response, goals, dataFrom, false); if (goalsAndRequirements == null) { return false; } boolean allowCapacityEstimation = KafkaCruiseControlServletUtils.allowCapacityEstimation(request); GoalOptimizer.OptimizerResult optimizerResult = getAndMaybeReturnProgress(request, response, () -> _asyncKafkaCruiseControl.rebalance(goalsAndRequirements.goals(), dryrun, goalsAndRequirements.requirements(), allowCapacityEstimation, concurrentPartitionMovements, concurrentLeaderMovements)); if (optimizerResult == null) { return false; } setResponseCode(response, SC_OK, false); OutputStream out = response.getOutputStream(); out.write(generateGoalAndClusterStatusAfterExecution(json, optimizerResult, endPoint, null).getBytes(StandardCharsets.UTF_8)); out.flush(); return true; } private void handleParameterParseException(Exception e, HttpServletResponse response, String errorMsg, boolean json) throws IOException { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); setErrorResponse(response, sw.toString(), errorMsg, SC_BAD_REQUEST, json); } private boolean demoteBroker(HttpServletRequest request, HttpServletResponse response, EndPoint endPoint) throws Exception { List<Integer> brokerIds; boolean dryrun; Integer concurrentLeaderMovements; boolean json = KafkaCruiseControlServletUtils.wantJSON(request); try { brokerIds = KafkaCruiseControlServletUtils.brokerIds(request); dryrun = KafkaCruiseControlServletUtils.getDryRun(request); concurrentLeaderMovements = KafkaCruiseControlServletUtils.concurrentMovementsPerBroker(request, false); } catch (Exception e) { handleParameterParseException(e, response, e.getMessage(), json); // Close session return true; } // Get proposals asynchronously. boolean allowCapacityEstimation = KafkaCruiseControlServletUtils.allowCapacityEstimation(request); GoalOptimizer.OptimizerResult optimizerResult = getAndMaybeReturnProgress(request, response, () -> _asyncKafkaCruiseControl.demoteBrokers(brokerIds, dryrun, allowCapacityEstimation, concurrentLeaderMovements)); if (optimizerResult == null) { return false; } setResponseCode(response, SC_OK, false); OutputStream out = response.getOutputStream(); out.write(generateGoalAndClusterStatusAfterExecution(json, optimizerResult, endPoint, brokerIds).getBytes(StandardCharsets.UTF_8)); out.flush(); return true; } private void stopProposalExecution() { _asyncKafkaCruiseControl.stopProposalExecution(); } private void pauseSampling() { _asyncKafkaCruiseControl.pauseLoadMonitorActivity(); } private void resumeSampling() { _asyncKafkaCruiseControl.resumeLoadMonitorActivity(); } private <T> T getAndMaybeReturnProgress(HttpServletRequest request, HttpServletResponse response, Supplier<OperationFuture<T>> supplier) throws ExecutionException, InterruptedException, IOException { int step = _asyncOperationStep.get(); OperationFuture<T> future = _sessionManager.getAndCreateSessionIfNotExist(request, supplier, step); _asyncOperationStep.set(step + 1); try { return future.get(_maxBlockMs, TimeUnit.MILLISECONDS); } catch (TimeoutException te) { returnProgress(response, future, KafkaCruiseControlServletUtils.wantJSON(request)); return null; } } private void setResponseCode(HttpServletResponse response, int code, boolean json) { response.setStatus(code); if (json) { response.setContentType("application/json"); } else { response.setContentType("text/plain"); } response.setCharacterEncoding("utf-8"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Request-Method", "OPTIONS, GET, POST"); } private void returnProgress(HttpServletResponse response, OperationFuture future, boolean json) throws IOException { setResponseCode(response, SC_OK, json); String resp; if (!json) { resp = future.progressString(); } else { Gson gson = new GsonBuilder().serializeNulls().serializeSpecialFloatingPointValues().create(); Map<String, Object> respMap = new HashMap<>(); respMap.put("version", JSON_VERSION); respMap.put("progress", future.getJsonArray()); resp = gson.toJson(respMap); } response.setContentLength(resp.length()); response.getOutputStream().write(resp.getBytes(StandardCharsets.UTF_8)); response.getOutputStream().flush(); } private String getStateCheckUrl(HttpServletRequest request) { String url = request.getRequestURL().toString(); int pos = url.indexOf("/kafkacruisecontrol/"); return url.substring(0, pos + "/kafkacruisecontrol/".length()) + "state"; } // package private for testing. GoalsAndRequirements getGoalsAndRequirements(HttpServletRequest request, HttpServletResponse response, List<String> userProvidedGoals, DataFrom dataFrom, boolean ignoreCache) throws Exception { if (!userProvidedGoals.isEmpty() || dataFrom == DataFrom.VALID_PARTITIONS) { return new GoalsAndRequirements(userProvidedGoals, getRequirements(dataFrom)); } KafkaCruiseControlState state = getAndMaybeReturnProgress(request, response, _asyncKafkaCruiseControl::state); if (state == null) { return null; } int availableWindows = state.monitorState().numValidWindows(); List<String> allGoals = new ArrayList<>(); List<String> readyGoals = new ArrayList<>(); state.analyzerState().readyGoals().forEach((goal, ready) -> { allGoals.add(goal.name()); if (ready) { readyGoals.add(goal.name()); } }); if (allGoals.size() == readyGoals.size()) { // If all the goals work, use it. return new GoalsAndRequirements(ignoreCache ? allGoals : Collections.emptyList(), null); } else if (availableWindows > 0) { // If some valid windows are available, use it. return new GoalsAndRequirements(ignoreCache ? allGoals : Collections.emptyList(), getRequirements(VALID_WINDOWS)); } else if (readyGoals.size() > 0) { // If no window is valid but some goals are ready, use them. return new GoalsAndRequirements(readyGoals, null); } else { // Ok, use default setting and let it throw exception. return new GoalsAndRequirements(Collections.emptyList(), null); } } static class GoalsAndRequirements { private final List<String> _goals; private final ModelCompletenessRequirements _requirements; private GoalsAndRequirements(List<String> goals, ModelCompletenessRequirements requirements) { _goals = goals; _requirements = requirements; } List<String> goals() { return _goals; } ModelCompletenessRequirements requirements() { return _requirements; } } enum DataFrom { VALID_WINDOWS, VALID_PARTITIONS } }
package org.blockwiseph.codingsessionslogdataanalysis.data.impl; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import org.blockwiseph.codingsessionslogdataanalysis.data.ReportOutputWriter; import org.json.JSONObject; import com.google.inject.Inject; import com.google.inject.name.Named; public class ReportOutputWriterImpl implements ReportOutputWriter { private final String filename; @Inject public ReportOutputWriterImpl(@Named("outputFile") String filename) { this.filename = filename; } @Override public void writeToFile(JSONObject jsonObject) { try { OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8); writer.write(jsonObject.toString()); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
package org.giddap.dreamfactory.leetcode.onlinejudge; import org.giddap.dreamfactory.leetcode.commons.TreeNode; /** * <a href="http://oj.leetcode.com/problems/recover-binary-search-tree/">Recover Binary Search Tree</a> * <p/> * Two elements of a binary search tree (BST) are swapped by mistake. * <p/> * Recover the tree without changing its structure. * <p/> * Note: * A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? * confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. * <p/> * * @see <a href="http://discuss.leetcode.com/questions/272/recover-binary-search-tree">Leetcode discussion</a> * @see <a href="http://n00tc0d3r.blogspot.com/2013/05/recover-binary-search-tree.html"> * N00tC0d3r</a> */ public interface RecoverBinarySearchTree { void recoverTree(TreeNode root); }
/** * Copyright 2015 EIS Co., Ltd. All rights reserved. */ package Java002; /** * @author 笹田 裕介 <br /> * 別クラスメソッドの呼出(ループ文による加算(引数間)) <br /> * 2つの実行時引数の間の整数の総和を求めるメソッドを呼び出して表示する <br /> * 更新履歴 2015/12/13(更新者):笹田 裕介:新規作成 <br /> */ public class Test10 { /** * メインメソッド <br /> * 引数間の値の総和を求めるメソッドを呼び出す <br /> * * @param args 実行時引数 */ public static void main( String[] args ) { // a:実行時引数を整数型として格納する int a = Integer.parseInt( args[0] ); // b:実行時引数を整数型として格納する int b = Integer.parseInt( args[1] ); // addメソッドで計算した実行時引数間の整数の総和を表示する System.out.print( args[0] + " と " + args[1] + " の間の整数の総和は " + Test07.getSum( a, b ) + " です" ); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pmm.sdgc.ws.model; import com.pmm.sdgc.model.EscalaTipo; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; /** * * @author setinf */ public class ModelRegimeWs { private String nome; private String idRegime; private Boolean ativo; public ModelRegimeWs(String nome, String id, Boolean ativo) { this.nome = nome; this.idRegime = id; this.ativo = ativo; } public ModelRegimeWs(String nome, String id) { this.nome = nome; this.idRegime = id; } public ModelRegimeWs() { } public static List<ModelRegimeWs> toModelRegimeWs(List<EscalaTipo> regimes) { List<ModelRegimeWs> mrw = new ArrayList(); for (EscalaTipo r : regimes) { ModelRegimeWs rw = new ModelRegimeWs( r.getNomeEscalaTipo(), r.getId(), false ); mrw.add(rw); } return mrw; } public static List<ModelRegimeWs> toModelRegimeInfoWs(List<EscalaTipo> regimes) { List<ModelRegimeWs> mrw = new ArrayList(); for (EscalaTipo r : regimes) { ModelRegimeWs rw = new ModelRegimeWs( r.getNomeEscalaTipo(), r.getId() ); mrw.add(rw); } return mrw; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Boolean getAtivo() { return ativo; } public void setAtivo(Boolean ativo) { this.ativo = ativo; } public String getIdRegime() { return idRegime; } public void setIdRegime(String idRegime) { this.idRegime = idRegime; } @Override public String toString() { return "ModelRegimeWs{" + "nome=" + nome + ", idRegime=" + idRegime + ", ativo=" + ativo + '}'; } }
package io.electrum.sdk.masking2; /** * Interface that will be used by various maskers (such as {@link MaskPan}) that define rules for how to mask the given * string. */ public abstract class Masker { // globally disable masking if this is set. Typically toggled via configuration in apps making use of this library private static boolean disabled = false; public abstract String mask(String value); public static final boolean isDisabled() { return disabled; } public static final void setDisabled(boolean disabled) { Masker.disabled = disabled; } }