text
stringlengths
10
2.72M
package com.tencent.mm.plugin.card.d; import android.graphics.Bitmap; import android.graphics.PorterDuff.Mode; import com.tencent.mm.plugin.card.d.m.1; class m$1$1 implements Runnable { final /* synthetic */ Bitmap hIM; final /* synthetic */ 1 hIN; m$1$1(1 1, Bitmap bitmap) { this.hIN = 1; this.hIM = bitmap; } public final void run() { this.hIN.hIK.setImageBitmap(this.hIM); this.hIN.hIK.setColorFilter(this.hIN.fdh, Mode.SRC_IN); } }
/*Copy List with Random Pointer question: http://www.lintcode.com/en/problem/copy-list-with-random-pointer/ A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. */ package FastSlowPointers; import java.util.HashMap; //version2: hash map: 1 traverse //้šๆœบๆŒ‡้’ˆๆŒ‡ๅ‘่Š‚็‚นไธๅฎš๏ผŒๆ•…ๅŠ ๅ…ฅๅ“ˆๅธŒ่กจไน‹ๅ‰ๅˆคๆ–ญไธ€ไธ‹ key ๆ˜ฏๅฆๅญ˜ๅœจๅณๅฏ /*ๅคๆ‚ๅบฆๅˆ†ๆž ้ๅކไธ€ๆฌกๅŽŸ้“พ่กจ๏ผŒๅˆคๆ–ญๅ“ˆๅธŒ่กจไธญ key ๆ˜ฏๅฆๅญ˜ๅœจ๏ผŒๆ•…ๆ—ถ้—ดๅคๆ‚ๅบฆไธบ $$O(n)$$, ็ฉบ้—ดๅคๆ‚ๅบฆไธบ $$O(n)$$. */ public class CopyListswithRandomPointers2 { public RandomListNode copylists(RandomListNode head){ if (head == null){ return null; } //create a dummy node RandomListNode dummy = new RandomListNode(0); RandomListNode current = dummy; //create a hashmap HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>(); while (head != null){ RandomListNode newnode = null; //1. link new node to new list if (map.containsKey(head)){ newnode = map.get(head); }else{ newnode = new RandomListNode(head.label); map.put(head, newnode); } current.next = newnode; //2. re-mapping old random node to new node if (head.random != null){ if (map.containsKey(head.random)){ newnode.random = map.get(head.random); }else{ newnode.random = new RandomListNode(head.random.label); map.put(head.random, newnode.random); } } head = head.next; current = current.next; } return dummy.next; } public static void main(String[] args) { // TODO Auto-generated method stub CopyListswithRandomPointers object = new CopyListswithRandomPointers(); RandomListNode n1 = new RandomListNode(1); RandomListNode n2 = new RandomListNode(2); RandomListNode n3 = new RandomListNode(3); n1.random = n3; System.out.println(object.copylists(n1)); } }
package collection.visualizer.examples.linear; import java.util.Collection; import collection.visualizer.layout.nodes.LinearElement; import collection.visualizer.trappers.*; import util.models.VectorMethodsListener; import bus.uigen.shapes.LabelShape; import bus.uigen.shapes.Shape; import bus.uigen.shapes.SimpleShape; import bus.uigen.shapes.TextShape; import collection.visualizer.common.*; public class ALinearEventTrapper<ElementType> extends AnAbstractLinearEventTrapper<ElementType> implements EventTrapper<VectorMethodsListener<ElementType>, ListenableVector<ElementType>> { private static final long serialVersionUID = 8683688773211768379L; protected LinearElement root; protected int boxWidth; protected int boxHeight; protected boolean dynamicWidth; protected boolean dynamicHeight; protected collection.visualizer.examples.linear.LinearVisualizer<ElementType> visualizer; protected ListenableVector<Shape> shapes; public ALinearEventTrapper( collection.visualizer.examples.linear.LinearVisualizer<ElementType> visualizer) { this.visualizer = visualizer; root = visualizer.getRoot(); boxWidth = ((ALinearLayoutManager<ElementType>) visualizer .getLayoutManager()).getBoxWidth(); boxHeight = ((ALinearLayoutManager<ElementType>) visualizer .getLayoutManager()).getBoxHeight(); dynamicWidth = ((ALinearLayoutManager<ElementType>) visualizer .getLayoutManager()).getDynamicWidth(); dynamicHeight = ((ALinearLayoutManager<ElementType>) visualizer .getLayoutManager()).getDynamicHeight(); shapes = visualizer.shapes(); } public synchronized void elementAdded(Object source, ElementType element, int newSize) { elementInserted(source, element, newSize - 1, newSize); } public synchronized void elementChanged(Object source, ElementType element, int pos) { LinearElement node = root.getVector().get(pos); AnimationUtil.move(node, node.getX() + boxWidth / 3, node.getY(), true, ((ALinearLayoutManager<ElementType>) visualizer .getLayoutManager()).getHighlighting(), ((Shape) visualizer.getLayoutManager()).getColor()); node.setObject(element); SimpleShape shape = node.getShape(); try { double shapeStretchFactor = Double.parseDouble(element.toString()); shape.setWidth((int) (boxWidth * (dynamicWidth ? shapeStretchFactor : 1))); shape.setHeight((int) (boxHeight * (dynamicHeight ? shapeStretchFactor : 1))); } catch (Exception e) { shape.setWidth((int) (boxWidth)); shape.setHeight((int) (boxHeight)); } if (shape instanceof TextShape) ((TextShape) shape).setText(element.toString()); if (shape instanceof LabelShape) ((LabelShape) shape).setText(element.toString()); AnimationUtil.move(node, node.getX() - boxWidth / 3, node.getY(), true, ((ALinearLayoutManager<ElementType>) visualizer .getLayoutManager()).getHighlighting(), ((Shape) visualizer.getLayoutManager()).getColor()); } public synchronized void elementCopied(Object source, int fromIndex, int toIndex, int newSize) { // TODO Auto-generated method stub } public synchronized void elementCopied(Object source, int fromIndex, int fromNewSize, Object to, int toIndex) { // TODO Auto-generated method stub } public synchronized void elementInserted(Object source, ElementType element, int pos, int newSize) { LinearElement parent = root; LinearElement previousChild = pos - 1 >= 0 ? root.getVector().get( pos - 1) : null; LinearElement newElement = visualizer.initElement(element, parent, previousChild); if (pos + 1 < newSize) // if there is a child after us // use pos not pos + 1 because the element has not been // added to the vector yet, so pos + 1 in the user's // vector is pos in the roots vector. root.getVector().get(pos).setPreviousChild(newElement); parent.getVector().insertElementAt(newElement, pos); root.focusPosition(); } public synchronized void elementMoved(Object source, int fromIndex, int toIndex) { // TODO Auto-generated method stub } public synchronized void elementMoved(Object source, int fromIndex, int fromNewSize, Object to, int toIndex) { // TODO Auto-generated method stub } public synchronized void elementRemoved(Object source, int pos, int newSize) { LinearElement toBeRemoved = root.getVector().get(pos); shapes.remove(toBeRemoved.getShape()); visualizer.removeLine(toBeRemoved.getVerticalLine()); visualizer.removeLine(toBeRemoved.getHorizontalLine()); LinearElement parent = root; LinearElement previousChild = toBeRemoved.getPreviousChild(); if (pos + 1 <= newSize)// If it is not the last element root.getVector().get(pos + 1).setPreviousChild(previousChild); parent.getVector().remove(toBeRemoved); root.focusPosition(); } public synchronized void elementRemoved(Object source, ElementType element, int newSize) { // TODO Auto-generated method stub } public synchronized void elementReplaced(Object source, int fromIndex, int toIndex, int newSize) { // TODO Auto-generated method stub } public synchronized void elementReplaced(Object source, int fromIndex, int newFromSize, Object to, int toIndex) { // TODO Auto-generated method stub } public synchronized void elementsCleared(Object source) { // TODO Auto-generated method stub } public synchronized void collectionRemoved(int collectionNum) { // TODO Auto-generated method stub } public synchronized void elementSwapped(Object source, int index1, Object other, int index2) { // TODO Auto-generated method stub } /* * This method takes two elements and exchanges their parents and previous * elements. It then makes sure spacing is correct by calling * focusPositionAndLines */ public synchronized void elementSwapped(Object newParam, int index1, int index2) { if (index1 < index2) { swapElements(newParam, index1, index2); } else { swapElements(newParam, index2, index1); } } /* * This method takes two elements and exchanges their parents and previous * elements. It then makes sure spacing is correct by calling * focusPositionAndLines * * This method assumes index1 < index2 */ private synchronized void swapElements(Object newParam, int index1, int index2) { // the two elements to be swapped LinearElement firstElement = root.getVector().get(index1); LinearElement secondElement = root.getVector().get(index2); // the two elements after each of the elements to be swapped LinearElement secondElementNext; LinearElement firstElementNext; /* * There is a corner case where secondElement.previousChild is * firstElement */ // the first element's previous child before it is reassigned LinearElement tempPrevChild = firstElement.getPreviousChild(); if (index2 != index1 + 1) {// the elements are not adjacent // set previous elements for the two nodes firstElement.setPreviousChild(secondElement.getPreviousChild()); secondElement.setPreviousChild(tempPrevChild); // set previous elements for the nodes referencing the swapped nodes if (index1 + 1 < root.getVector().size()) { firstElementNext = root.getVector().get(index1 + 1); firstElementNext.setPreviousChild(secondElement); } if (index2 + 1 < root.getVector().size()) { secondElementNext = root.getVector().get(index2 + 1); secondElementNext.setPreviousChild(firstElement); } } else { // the elements are adjacent firstElement.setPreviousChild(secondElement); secondElement.setPreviousChild(tempPrevChild); // set previous elements for the nodes referencing the second node if (index2 + 1 < root.getVector().size()) { secondElementNext = root.getVector().get(index2 + 1); secondElementNext.setPreviousChild(firstElement); } } // swap the elements in root root.getVector().swap(index1, index2); root.focusPosition(); } public synchronized void elementsAdded(Object source, Collection<? extends ElementType> element, int newSize) { // TODO Auto-generated method stub } }
package com.bright.springcloud.service.impl; import com.bright.springcloud.service.IMessageProvider; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.messaging.Source; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.MessageBuilder; import javax.annotation.Resource; import java.util.UUID; /** * @author bright * @version 1.0 * @description * @date 2021-01-25 16:00 */ @EnableBinding(Source.class) //ๅฎšไน‰ๆถˆๆฏ็š„ๆŽจ้€channel public class MessageProviderImpl implements IMessageProvider { @Resource private MessageChannel output; @Override public String send() { String serial = UUID.randomUUID().toString(); output.send(MessageBuilder.withPayload(serial).build()); System.out.println("*****serial: " + serial); return serial; } }
package jaja; import com.fasterxml.jackson.annotation.JsonProperty; public class Valor { @JsonProperty("id") private int id; @JsonProperty("quote") private String cita; public Valor() { } public Valor(int id, String cita) { this.id = id; this.cita = cita; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the cita */ public String getCita() { return cita; } /** * @param cita the cita to set */ public void setCita(String cita) { this.cita = cita; } }
package com.timmy.highUI.path; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import com.timmy.R; import com.timmy.base.BaseActivity; /** * Path็š„ไฝฟ็”จ */ public class PathUseActicity extends BaseActivity { private PathLoadingView loadingView; private Button mBtnSuccess; private Button mBtnFail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_path_use); initToolBar(); initView(); // WaveView waveView = (WaveView) findViewById(R.id.wave_view); // waveView.startWaveAnimate(); // final PathMeasureUseView view = new PathMeasureUseView(this); // setContentView(view); // view.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // view.startMove(); // } // }); } private void initView() { loadingView = (PathLoadingView) findViewById(R.id.loading_view); mBtnSuccess = (Button) findViewById(R.id.btn_success); mBtnFail = (Button) findViewById(R.id.btn_fail); mBtnSuccess.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadingView.paySuccess(); } }); mBtnFail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadingView.payFail(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_path_measure,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_path_measure){ return true; }else if (itemId == R.id.menu_path){ return true; } return super.onOptionsItemSelected(item); } }
package com.deltastuido.store; import java.math.BigDecimal; import java.sql.Timestamp; import java.time.Instant; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import com.deltastuido.project.Project; import com.deltastuido.shared.IEntity; import com.deltastuido.user.User; @Entity @Table(name = "orders") @NamedQueries({ @NamedQuery(name = "countUserOrders", query = "SELECT COUNT(o.id) FROM Order o WHERE o.buyer.id = ?1 AND o.project.stage in ?2"), @NamedQuery(name = "getUserOrders", query = "SELECT o FROM Order o WHERE o.buyer.id = ?1 AND o.project.stage in ?2"), }) public class Order implements IEntity { @Id private String id; private BigDecimal amount; @ManyToOne @JoinColumn(name = "user_id") private User buyer; @ManyToOne private Project project; @ManyToOne private Product product; @OneToOne(cascade = CascadeType.ALL, mappedBy="order") private OrderAddress address; @Convert(converter = OrderStageConverter.class) private OrderStage stage = OrderStage.INIT; @Column(name = "time_expired") private Timestamp timeExpired = Timestamp.from(Instant.now()); private String customization; @OneToMany(cascade = CascadeType.ALL) @JoinColumn(name = "order_id") private List<OrderItem> orderItems = new ArrayList<>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public User getBuyer() { return buyer; } public void setBuyer(User buyer) { this.buyer = buyer; } public OrderAddress getAddress() { return address; } public void setAddress(OrderAddress address) { this.address = address; } public void setOrderItems(List<OrderItem> orderItems) { this.orderItems = orderItems; } public List<OrderItem> getOrderItems() { return orderItems; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public OrderStage getStage() { return stage; } public void setStage(OrderStage stage) { this.stage = stage; } public void paid() { if (!this.stage.equals(OrderStage.INIT)) { throw new IllegalStateException("่ฎขๅ•็Šถๆ€้”™่ฏฏ"); } this.stage = OrderStage.PAID; } public String getCustomization() { return customization; } public void setCustomization(String customization) { this.customization = customization; } public Timestamp getTimeExpired() { return timeExpired; } public void setTimeExpired(Timestamp timeExpired) { this.timeExpired = timeExpired; } }
package hirondelle.web4j.model; /** Thrown when a Model Object (MO) cannot be constructed because of invalid constructor arguments. <P>Arguments to a MO constructor have two sources: the end user and the the database. In both cases, errors in the values of these arguments are outside the immediate control of the application. Hence, MO constructors should throw a checked exception - (<tt>ModelCtorException</tt>). <P>Using a checked exception has the advantage that it cannot be ignored by the caller. Example use case:<br> <PRE> //a Model Object constructor Blah(String aText, int aID) throws ModelCtorException { //check validity of all params. //if one or more params is invalid, throw a ModelCtorException. //for each invalid param, add a corresponding error message to //ModelCtorException. } //call the Model Object constructor try { Blah blah = new Blah(text, id); } catch(ModelCtorException ex){ //place the exception in scope, for subsequent //display to the user in a JSP } </PRE> <P>In the case of an error, the problem arises of how to redisplay the original, erroneous user input. The {@link hirondelle.web4j.ui.tag.Populate} tag accomplishes this in an elegant manner, simply by recycling the original request parameters. */ public final class ModelCtorException extends AppException { //empty }
import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Node { private String name; private Set<Node> connected = new HashSet<Node>(); public Node(String name) { this.name = name; } public void connect(Node node) { this.connected.add(node); } public boolean isConnected(Node node) { return connected.contains(node); } public Iterator<Node> getConnected() { return this.connected.iterator(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return this.getName(); } public int getI(String s[][]){// int n = 0; for (int i = 0; i < s.length; i++) for (int j = 0; j < s[i].length; j++) { if (s[i][j] == name) { n = i;break; } } return n; } }
package com.tencent.mm.plugin.appbrand.app; import com.tencent.mm.bt.h.d; import com.tencent.mm.plugin.appbrand.widget.h; class e$34 implements d { final /* synthetic */ e ffn; e$34(e eVar) { this.ffn = eVar; } public final String[] xb() { return h.dzV; } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.solrfacetsearch.integration; import static org.junit.Assert.assertEquals; import de.hybris.platform.catalog.CatalogVersionService; import de.hybris.platform.catalog.model.CatalogVersionModel; import de.hybris.platform.solrfacetsearch.search.Document; import de.hybris.platform.solrfacetsearch.search.OrderField.SortOrder; import de.hybris.platform.solrfacetsearch.search.SearchResult; import java.util.Arrays; import java.util.Collections; import javax.annotation.Resource; import org.junit.Test; public class SearchQueryCatalogVersionsTest extends AbstractSearchQueryTest { @Resource private CatalogVersionService catalogVersionService; @Override protected void loadData() throws Exception { importConfig("/test/integration/SearchQueryCatalogVersionsTest.csv"); } @Test public void searchOnCatalogVersion() throws Exception { // given final CatalogVersionModel onlineCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), ONLINE_CATALOG_VERSION + getTestId()); // when final SearchResult searchResult = executeSearchQuery(searchQuery -> { searchQuery.setCatalogVersions(Arrays.asList(onlineCatalogVersion)); }); // then assertEquals(1, searchResult.getNumberOfResults()); final Document document = searchResult.getDocuments().get(0); assertDocumentField(PRODUCT1_CODE, document, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT1_NAME, document, PRODUCT_NAME_FIELD); } @Test public void searchOnMultipleCatalogVersions() throws Exception { // given final CatalogVersionModel onlineCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), ONLINE_CATALOG_VERSION + getTestId()); final CatalogVersionModel stagedCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), STAGED_CATALOG_VERSION + getTestId()); // when final SearchResult searchResult = executeSearchQuery(searchQuery -> { searchQuery.addSort(PRODUCT_CODE_FIELD, SortOrder.ASCENDING); searchQuery.setCatalogVersions(Arrays.asList(onlineCatalogVersion, stagedCatalogVersion)); }); // then assertEquals(2, searchResult.getNumberOfResults()); final Document document1 = searchResult.getDocuments().get(0); assertDocumentField(PRODUCT1_CODE, document1, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT1_NAME, document1, PRODUCT_NAME_FIELD); final Document document2 = searchResult.getDocuments().get(1); assertDocumentField(PRODUCT2_CODE, document2, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT2_NAME, document2, PRODUCT_NAME_FIELD); } @Test public void searchOnCatalogVersionFromSession() throws Exception { // given final CatalogVersionModel onlineCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), ONLINE_CATALOG_VERSION + getTestId()); // when catalogVersionService.setSessionCatalogVersions(Arrays.asList(onlineCatalogVersion)); final SearchResult searchResult = executeSearchQuery(); // then assertEquals(1, searchResult.getNumberOfResults()); final Document document = searchResult.getDocuments().get(0); assertDocumentField(PRODUCT1_CODE, document, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT1_NAME, document, PRODUCT_NAME_FIELD); } @Test public void searchOnMultipleCatalogVersionsFromSession() throws Exception { // given final CatalogVersionModel onlineCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), ONLINE_CATALOG_VERSION + getTestId()); final CatalogVersionModel stagedCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), STAGED_CATALOG_VERSION + getTestId()); // when catalogVersionService.setSessionCatalogVersions(Arrays.asList(onlineCatalogVersion, stagedCatalogVersion)); final SearchResult searchResult = executeSearchQuery(searchQuery -> { searchQuery.addSort(PRODUCT_CODE_FIELD, SortOrder.ASCENDING); }); // then assertEquals(2, searchResult.getNumberOfResults()); final Document document1 = searchResult.getDocuments().get(0); assertDocumentField(PRODUCT1_CODE, document1, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT1_NAME, document1, PRODUCT_NAME_FIELD); final Document document2 = searchResult.getDocuments().get(1); assertDocumentField(PRODUCT2_CODE, document2, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT2_NAME, document2, PRODUCT_NAME_FIELD); } @Test public void searchOnNotIndexedCatalogVersion() throws Exception { // given final CatalogVersionModel catalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), "Test" + getTestId()); // when final SearchResult searchResult = executeSearchQuery(searchQuery -> { searchQuery.setCatalogVersions(Collections.singletonList(catalogVersion)); }); // then assertEquals(0, searchResult.getNumberOfResults()); } @Test public void searchOnCatalogVersionWithEscaping() throws Exception { // given final CatalogVersionModel catalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId() + ", 2", STAGED_CATALOG_VERSION + getTestId() + ", 2"); // when final SearchResult searchResult = executeSearchQuery(searchQuery -> { searchQuery.setCatalogVersions(Collections.singletonList(catalogVersion)); }); // then assertEquals(1, searchResult.getNumberOfResults()); final Document document = searchResult.getDocuments().get(0); assertDocumentField(PRODUCT2_CODE, document, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT2_NAME + ", 2", document, PRODUCT_NAME_FIELD); } @Test public void searchOnCatalogVersionForLegacyMode() throws Exception { // given enabledSearchLegacyMode(); final CatalogVersionModel onlineCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), ONLINE_CATALOG_VERSION + getTestId()); // when final SearchResult searchResult = executeSearchQuery(searchQuery -> { searchQuery.setCatalogVersions(Arrays.asList(onlineCatalogVersion)); }); // then assertEquals(1, searchResult.getNumberOfResults()); final Document document = searchResult.getDocuments().get(0); assertDocumentField(PRODUCT1_CODE, document, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT1_NAME, document, PRODUCT_NAME_FIELD); } @Test public void searchOnMultipleCatalogVersionsForLegacyMode() throws Exception { // given enabledSearchLegacyMode(); final CatalogVersionModel onlineCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), ONLINE_CATALOG_VERSION + getTestId()); final CatalogVersionModel stagedCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), STAGED_CATALOG_VERSION + getTestId()); // when final SearchResult searchResult = executeSearchQuery(searchQuery -> { searchQuery.addSort(PRODUCT_CODE_FIELD, SortOrder.ASCENDING); searchQuery.setCatalogVersions(Arrays.asList(onlineCatalogVersion, stagedCatalogVersion)); }); // then assertEquals(2, searchResult.getNumberOfResults()); final Document document1 = searchResult.getDocuments().get(0); assertDocumentField(PRODUCT1_CODE, document1, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT1_NAME, document1, PRODUCT_NAME_FIELD); final Document document2 = searchResult.getDocuments().get(1); assertDocumentField(PRODUCT2_CODE, document2, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT2_NAME, document2, PRODUCT_NAME_FIELD); } @Test public void searchOnCatalogVersionFromSessionForLegacyMode() throws Exception { // given enabledSearchLegacyMode(); final CatalogVersionModel onlineCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), ONLINE_CATALOG_VERSION + getTestId()); // when catalogVersionService.setSessionCatalogVersions(Arrays.asList(onlineCatalogVersion)); final SearchResult searchResult = executeSearchQuery(); // then assertEquals(1, searchResult.getNumberOfResults()); final Document document = searchResult.getDocuments().get(0); assertDocumentField(PRODUCT1_CODE, document, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT1_NAME, document, PRODUCT_NAME_FIELD); } @Test public void searchOnMultipleCatalogVersionsFromSessionForLegacyMode() throws Exception { // given enabledSearchLegacyMode(); final CatalogVersionModel onlineCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), ONLINE_CATALOG_VERSION + getTestId()); final CatalogVersionModel stagedCatalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), STAGED_CATALOG_VERSION + getTestId()); // when catalogVersionService.setSessionCatalogVersions(Arrays.asList(onlineCatalogVersion, stagedCatalogVersion)); final SearchResult searchResult = executeSearchQuery(searchQuery -> { searchQuery.addSort(PRODUCT_CODE_FIELD, SortOrder.ASCENDING); }); // then assertEquals(2, searchResult.getNumberOfResults()); final Document document1 = searchResult.getDocuments().get(0); assertDocumentField(PRODUCT1_CODE, document1, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT1_NAME, document1, PRODUCT_NAME_FIELD); final Document document2 = searchResult.getDocuments().get(1); assertDocumentField(PRODUCT2_CODE, document2, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT2_NAME, document2, PRODUCT_NAME_FIELD); } @Test public void searchOnNotIndexedCatalogVersionForLegacyMode() throws Exception { // given enabledSearchLegacyMode(); final CatalogVersionModel catalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId(), "Test" + getTestId()); // when final SearchResult searchResult = executeSearchQuery(searchQuery -> { searchQuery.setCatalogVersions(Collections.singletonList(catalogVersion)); }); // then assertEquals(0, searchResult.getNumberOfResults()); } @Test public void searchOnCatalogVersionWithEscapingForLegacyMode() throws Exception { // given enabledSearchLegacyMode(); final CatalogVersionModel catalogVersion = catalogVersionService.getCatalogVersion(HW_CATALOG + getTestId() + ", 2", STAGED_CATALOG_VERSION + getTestId() + ", 2"); // when final SearchResult searchResult = executeSearchQuery(searchQuery -> { searchQuery.setCatalogVersions(Collections.singletonList(catalogVersion)); }); // then assertEquals(1, searchResult.getNumberOfResults()); final Document document = searchResult.getDocuments().get(0); assertDocumentField(PRODUCT2_CODE, document, PRODUCT_CODE_FIELD); assertDocumentField(PRODUCT2_NAME + ", 2", document, PRODUCT_NAME_FIELD); } }
package bean.item.name; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.session.SqlSession; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import bean.manager.ManagerDTO; import bean.manager.ManagerServiceImpl; @Controller @RequestMapping("/master") public class ItemType { @Autowired private SqlSessionTemplate dao = null; @RequestMapping("item.do") public String item(HttpServletRequest request, HttpServletResponse response) { ManagerServiceImpl ma = new ManagerServiceImpl(); ma.sessionChk(request, response); return"/master/Item"; } /* '๋ฐ์ดํ„ฐ ํ™œ์šฉ ์„œ๋น„์Šค' ์‚ฌ์ดํŠธ์˜ '๊ฑด๊ฐ•๊ธฐ๋Šฅ์‹ํ’ˆ ํ’ˆ๋ชฉ์ œ์กฐ์‹ ๊ณ (์›์žฌ๋ฃŒ) OpenAPI' ๋ฅผ ์ด์šฉํ•˜์—ฌ DB์— ์ €์žฅํ•˜๋Š” ํด๋ž˜์Šค. * www.foodsafetykorea.go.kr * OpenAPI์—์„œ ํ—ˆ๊ฐ€๋ฐ›์€ key๋ฅผ URL ํŽ˜์ด์ง€์— ์—ฐ๊ฒฐํ•˜์—ฌ ๊ด€๋ จ๋œ ๋‚ด์šฉ์„ JSON ํ˜•ํƒœ๋กœ ๊ฐ€์ ธ์˜จ๋‹ค. * * URL ๊ตฌ์„ฑ ๋ฐฉ์‹ * 'https://openapi.foodsafetykorea.go.kr/api/'์ธ์ฆํ‚ค/์„œ๋น„์Šค๋ช…/์š”์ฒญํŒŒ์ผํƒ€์ž…/์š”์ฒญ์‹œ์ž‘์œ„์น˜/์š”์ฒญ์ข…๋ฃŒ์œ„์น˜ * ์ธ์ฆ ํ‚ค = 287bd69b5be34b4ead96 * API์˜ ์„œ๋น„์Šค ๋ช… = C003 * ์š”์ฒญ ๊ฐ€๋Šฅ ํŒŒ์ผ ํƒ€์ž… = xml / JSON * * ์š”์ฒญ์™„๋ฃŒ์‹œ์˜ ์ถœ๋ ฅ๊ฐ’์˜ ์ •๋ณด * - ItemTypeDTO.java ์ฃผ์„ ์ฐธ์กฐ */ @RequestMapping("/iteminsert.do") public String ItemTypeInsert() { String key = "287bd69b5be34b4ead96"; String result = ""; ItemTypeDTO dto = null; try { // dao.delete("item_type.deleteItemType"); for(int j = 350; j <= 500; j++) { int StartNum = (j * 10) + 1; int EndNum = (j * 10) + 10; URL url = new URL("https://openapi.foodsafetykorea.go.kr/api/"+key+"/C003/json/"+StartNum+"/"+EndNum); BufferedReader bf; bf = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); result = bf.readLine(); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject)jsonParser.parse(result); JSONObject itemTypeResult = (JSONObject)jsonObject.get("C003"); JSONArray itemArray = (JSONArray)itemTypeResult.get("row"); String [] count; List arr; int searchCount; for(int i =0; i < itemArray.size(); i++) { JSONObject itemInfo = (JSONObject)itemArray.get(i); arr = new ArrayList(); dto = new ItemTypeDTO(); dto.setLCNS_NO(itemInfo.get("LCNS_NO").toString()); dto.setPRMS_DT(itemInfo.get("PRMS_DT").toString()); dto.setPRDLST_REPORT_NO(itemInfo.get("PRDLST_REPORT_NO").toString()); dto.setCRET_DTM(itemInfo.get("CRET_DTM").toString()); dto.setLAST_UPDT_DTM(itemInfo.get("LAST_UPDT_DTM").toString()); dto.setBSSH_NM(itemInfo.get("BSSH_NM").toString()); dto.setPRDLST_NM(itemInfo.get("PRDLST_NM").toString()); dto.setNTK_MTHD(itemInfo.get("NTK_MTHD").toString()); dto.setRAWMTRL_NM(itemInfo.get("RAWMTRL_NM").toString()); dto.setPOG_DAYCNT(itemInfo.get("POG_DAYCNT").toString()); dto.setPRIMARY_FNCLTY(itemInfo.get("PRIMARY_FNCLTY").toString()); dto.setCSTDY_MTHD(itemInfo.get("CSTDY_MTHD").toString()); dto.setIFTKN_ATNT_MATR_CN(itemInfo.get("IFTKN_ATNT_MATR_CN").toString()); dto.setSTDR_STND(itemInfo.get("STDR_STND").toString()); dto.setDISPOS(itemInfo.get("DISPOS").toString()); dto.setSHAP(itemInfo.get("SHAP").toString()); count = dto.getRAWMTRL_NM().split(","); for(String v : count) { arr.add(v); } dto.setELE_COUNT(arr.size()); searchCount = dao.selectOne("item_type.SearchTypeCount",dto.getPRDLST_REPORT_NO()); if(searchCount == 0) { dao.insert("item_type.insert",dto); } } } }catch(Exception e) { e.printStackTrace(); } return "/master/itemPro"; } /* * ์ œํ’ˆ์ •๋ณด์˜ ์„ฑ๋ถ„์ด ๊ฒน์น˜์ง€ ์•Š๋Š” ํ•ญ๋ชฉ์ด ๋ช‡์ข…๋ฅ˜์ธ์ง€๋ฅผ ํŒŒ์•…ํ•˜๊ธฐ ์œ„ํ•ด ๋งŒ๋“  * ITEM_TYPE ํ…Œ์ด๋ธ”์˜ RAWMTRL_NA์˜ ์ •๋ณด๋ฅผ CSVํŒŒ์ผ๋กœ ๋ณ€ํ™˜ํ•ด์ฃผ๋Š” ๋ฉ”์„œ๋“œ * System.lineSeparator(); > ์ค„๋ฐ”๊ฟˆ(\n) */ @RequestMapping("/itemTypeCSVWrite.do") public String ItemTypeCSVWrite() { String filePath = "C:/Users/Yoo/Desktop/BIG_DATA/10. ๋ฌธ์„œ/Table/csv_demo.csv"; File file = null; BufferedWriter bw = null; List list = null; String NEWLINE = System.lineSeparator(); try { file = new File(filePath); bw = new BufferedWriter(new FileWriter(file)); ItemTypeDTO dto = new ItemTypeDTO(); String [] splitText; ArrayList<String> arr = new ArrayList<String>(); List<String> result = new ArrayList<String>(); // DB์—์„œ ์ œํ’ˆ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์™€์„œ ํ…์ŠคํŠธ๋ฅผ splitํ•˜์—ฌ arr์— ํ•˜๋‚˜์”ฉ List๋กœ ๋‹ด์Œ list = dao.selectList("item_type.selectType"); for(int i =0; i < list.size(); i++) { dto = (ItemTypeDTO)list.get(i); splitText = dto.getRAWMTRL_NM().split(","); for(String v : splitText) { arr.add(v); } } // arr์— ์žˆ๋Š” ํ•˜๋‚˜์”ฉ๋‹ด๊ธด ๋‚ด์šฉ์„ ์ค‘๋ณต๊ฒ€์‚ฌํ•˜์—ฌ ํ•˜๋‚˜์”ฉ ๋‹ค์‹œ ๋‹ด์Œ for(String v : arr) { if(!result.contains(v)) { result.add(v); } } // ํ•˜๋‚˜์”ฉ ๋‹ด์€ ๋‚ด์šฉ์„ csvํŒŒ์ผ์— ํ•˜๋‚˜์”ฉ ์ž…๋ ฅํ•จ for(int i=0; i < result.size(); i++) { String v = result.get(i); bw.write(v); bw.write(NEWLINE); } bw.flush(); bw.close(); }catch(Exception e) { e.printStackTrace(); } return "/master/itemPro"; } /* ์ œํ’ˆ์ •๋ณด์˜ ์„ฑ๋ถ„์ด ๊ฒน์น˜์ง€ ์•Š๋Š” ํ•ญ๋ชฉ์„ 'ITEM_TYPE_KEY' ํ…Œ์ด๋ธ”์— ์ถ”๊ฐ€ํ•˜๋Š” ๋ฉ”์„œ๋“œ * DB์—์„œ ์ œํ’ˆ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์™€์„œ ํ…์ŠคํŠธ๋ฅผ splitํ•˜์—ฌ arr์— ํ•˜๋‚˜์”ฉ List๋กœ ๋‹ด์Œ * arr์— ์žˆ๋Š” ํ•˜๋‚˜์”ฉ๋‹ด๊ธด ๋‚ด์šฉ์„ ์ค‘๋ณต๊ฒ€์‚ฌํ•˜์—ฌ ํ•˜๋‚˜์”ฉ ๋‹ค์‹œ ๋‹ด์Œ * ํ•˜๋‚˜์”ฉ ๋‹ด์€ ๋‚ด์šฉ์„ 'ITEM_TYPE_KEY' ํ…Œ์ด๋ธ”์— ํ•˜๋‚˜์”ฉ ์ž…๋ ฅํ•จ */ @RequestMapping("/ItemTypeKeyInsert.do") public String ItemTypeKeyInsert() { List list = null; ArrayList<String> arr = new ArrayList<String>(); List<String> result = new ArrayList<String>(); HashMap hash = new HashMap(); String [] splitText; try { ItemTypeDTO dto = new ItemTypeDTO(); dao.delete("item_type.deleteItemTypeKey"); list = dao.selectList("item_type.selectType"); for(int i =0; i < list.size(); i++) { dto = (ItemTypeDTO)list.get(i); splitText = dto.getRAWMTRL_NM().split(","); for(String v : splitText) { arr.add(v); } } for(String v : arr) { if(!result.contains(v)) { result.add(v); } } for(int i=0; i < result.size(); i++) { String v = result.get(i); hash.put("num", i+1); hash.put("element", v); dao.insert("item_type.type_insert", hash); } }catch(Exception e) { e.printStackTrace(); } return "/master/itemPro"; } /* * ITEM_TYPE ํ…Œ์ด๋ธ”์˜ ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์™€, ์›์žฌ๋ฃŒ ์„ฑ๋ถ„์˜ ๊ฐฏ์ˆ˜๋ฅผ ํ™•์ธํ•˜๊ณ , ๊ฐฏ์ˆ˜์— ๋”ฐ๋ฅธ ๊ฐ€์ค‘์น˜๋ฅผ ITEM_TYPE_VALUECHECK ๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ * ITEM_TYPE_VALUE ํ…Œ์ด๋ธ”์— ๊ฐ€์ค‘์น˜ ๋ณ„ ํ…Œ์ด๋ธ” ์ •๋ณด๋ฅผ ๊ธฐ์žฌํ•œ๋‹ค. * ITEM_TYPE ํ…Œ์ด๋ธ”์˜ ์œ ๋‹ˆํฌ ๊ฐ’์˜ ์ปฌ๋Ÿผ๋ช…์€ 'PRDLST_REPORT_NO' ์ด๋‹ค. * * ์ž‘์—…์ˆœ์„œ... * 1. 'ITEM_TYPE' ํ…Œ์ด๋ธ”์˜ ๋‚ด์šฉ์„ DTO์— ๋‹ด์€ LIST๋ฅผ ๋ฐ›๋Š”๋‹ค. * 2. LIST์—์„œ ํ•˜๋‚˜์”ฉ ๋นผ์„œ dto๋ฅผ ๊ฐ€์ง€๊ณ  ์›์žฌ๋ฃŒ ๊ฐฏ์ˆ˜๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค. * 3. dto์—์„œ ์›์žฌ๋ฃŒ๋ฅผ splitํ•ด์„œ ๋ฐฐ์—ด๋กœ ๋‹ด๋Š”๋‹ค. * 4. ์›์žฌ๋ฃŒ ๊ฐฏ์ˆ˜๊ฐ€ 10๊ฐœ์ดˆ๊ณผ์ผ ๊ฒฝ์šฐ ๊ฐ’์„ 10์œผ๋กœ ๋Œ€์ž… * 5. ์›์žฌ๋ฃŒ ๊ฐฏ์ˆ˜๋กœ 'ITEM_TYPE_VALUECHECK' ํ…Œ์ด๋ธ”์—์„œ select ํ•œ๋‹ค. * 6. split ํ•œ ๋ฐฐ์—ด์„ ๋ฐ˜๋ณตํ•˜๋˜ * 6-1. 'ITEM_TYPE_KEY' ํ…Œ์ด๋ธ”์—์„œ key ๊ฐ’์„ ์ฐพ๊ณ , * 6-2. 'ITEM_TYPE_VALUECHECK' ํ…Œ์ด๋ธ”์—์„œ ๋ฐฐ์—ด ์œ„์น˜์— ๋”ฐ๋ผ val๊ฐ’์„ ์ฐพ๋Š”๋‹ค. * 6-3. ์ฐพ์€ key, value๊ฐ’์„ ํ…Œ์ด๋ธ”์— insertํ•ด์ค€๋‹ค. * 6-4. ๋ฐ˜๋ณต... */ @RequestMapping("/ItemTypeValueInsert.do") public String ItemTypeValueInsert() { List list = new ArrayList(); ItemTypeDTO dto; ItemTypeValueCheckDTO vcdto; ItemTypeValueDTO vdto; String [] ele; String element; Integer itemNum; list = dao.selectList("item_type.selectType"); dao.delete("item_type.deleteItemTypeValue"); for(int i = 0; i < list.size(); i++) { vcdto = new ItemTypeValueCheckDTO(); dto = (ItemTypeDTO)list.get(i); ele = dto.getRAWMTRL_NM().split(","); if(dto.getELE_COUNT() > 10) { dto.setELE_COUNT(10); } vcdto = dao.selectOne("item_type.selectVC",dto.getELE_COUNT()); vdto = new ItemTypeValueDTO(); vdto.setPRDLST_REPORT_NO(dto.getPRDLST_REPORT_NO()); for(int v = 0; v < dto.getELE_COUNT(); v++) { element = ele[v]; itemNum = dao.selectOne("item_type.SelectKey", element); if(itemNum == null) { v = 100; } switch(v) { case 0: vdto.setKey_1(itemNum);vdto.setValue_1(vcdto.getVal1());break; case 1: vdto.setKey_2(itemNum);vdto.setValue_2(vcdto.getVal2());break; case 2: vdto.setKey_3(itemNum);vdto.setValue_3(vcdto.getVal3());break; case 3: vdto.setKey_4(itemNum);vdto.setValue_4(vcdto.getVal4());break; case 4: vdto.setKey_5(itemNum);vdto.setValue_5(vcdto.getVal5());break; case 5: vdto.setKey_6(itemNum);vdto.setValue_6(vcdto.getVal6());break; case 6: vdto.setKey_7(itemNum);vdto.setValue_7(vcdto.getVal7());break; case 7: vdto.setKey_8(itemNum);vdto.setValue_8(vcdto.getVal8());break; case 8: vdto.setKey_9(itemNum);vdto.setValue_9(vcdto.getVal9());break; case 9: vdto.setKey_10(itemNum);vdto.setValue_10(vcdto.getVal10());break; case 100: break; } } dao.insert("item_type.insertValue",vdto); } return "/master/itemPro"; } /* * 1. 'ITEM_TYPE_VALUE' ํ…Œ์ด๋ธ”์„ ์ฐธ์กฐํ•˜๋˜, * 2. ํ˜ธ์žฌ๋‹˜์—๊ฒŒ ๋ฐ›์€ nutrist.csv ํŒŒ์ผ์˜ ์˜์–‘์„ฑ๋ถ„ ์ปฌ๋Ÿผ๋ช…์„ 'ITEM_TYPE_KEY'์—์„œ ๊ณ ์œ ๋ช…์‚ฌ์˜ ๋ฌธ๊ตฌ๋ฅผ ์ฐพ๋Š”๋‹ค... * 3. ๋ฉ”์„œ๋“œ๋ฅผ ์ž‘์„ฑํ•˜์—ฌ ๊ณ ์œ ๋ช…์‚ฌ๋ฅผ ์ด์šฉํ•ด์„œ key๋ฅผ ์ฐพ๋„๋ก ํ•˜๊ณ , ๊ทธ์— ๋งž๋Š” 'ITEM_TYPE_VALUE' ํ…Œ์ด๋ธ”์˜ ๊ฐ’์„ ๊ฐ€์ ธ์™€, ํ‘œ ํ˜•์‹์˜ LIST๋ฅผ ๋งŒ๋“ ๋‹ค. * 4. ์ด ๋•Œ ํ‘œ์—๋Š” ์œ ๋‹ˆํฌ ์ œ์กฐ๋ฒˆํ˜ธ ๊ฐ’, ์˜์–‘์„ฑ๋ถ„ 24๊ฐœ์˜ ์ปฌ๋Ÿผ์ด ์žˆ์–ด์•ผํ•œ๋‹ค. * * 1. 'ITEM_TYPE_VALUE' ํ…Œ์ด๋ธ” ๊ฐ’์„ LIST๋กœ ๊ฐ€์ ธ์˜จ๋‹ค. * 2. */ @RequestMapping("/RetrunValueLists.do") public String RetrunValueLists(Model model) { List result = ReturnValueListat(dao); ItemKeyValueDTO ikvDto; for(int i = 0; i < result.size(); i++) { ikvDto = (ItemKeyValueDTO)result.get(i); dao.insert("item_type.InsertItemTypeKeyValue",ikvDto); } model.addAttribute("result",result); return "/master/itemPro"; } /* ์„ค๋ฌธ์—์„œ ์ œํ’ˆ์˜ ํ‘œ์ค€ํŽธ์ฐจ๋ฅผ List๋กœ ๋ฐ›์•„๊ฐ€๊ธฐ ์œ„ํ•ด ๋งŒ๋“  ๋ฉ”์„œ๋“œ * ์„ค๋ฌธ์—์„œ ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด return ๊ฐ’์œผ๋กœ List๋ฅผ ๋ฐ˜ํ™˜ํ•˜์—ฌ * ์ „๋‹ฌํ•˜์—ฌ ์ค€๋‹ค. List ์ธ๋ฑ์Šค์—” 'ItemKeyValueDTO' ํ˜•์‹์˜ dto๊ฐ€ * ์ž…๋ ฅ๋˜์–ด ์ „๋‹ฌ๋œ๋‹ค. */ public List ReturnValueListat(SqlSessionTemplate dao) { ItemTypeValueDTO itvdto; ItemKeyValueDTO ikvdto; KeyNumberCheck(dao); List list = dao.selectList("item_type.selectTypeValue"); List result = new ArrayList(); for(int i = 0; i < list.size(); i++) { itvdto = (ItemTypeValueDTO)list.get(i); ikvdto = new ItemKeyValueDTO(); ikvdto = dtoFactoring(itvdto, dao); ikvdto.setPRDLST_REPORT_NO(itvdto.getPRDLST_REPORT_NO()); result.add(ikvdto); } return result; } public List ReturnValueList(SqlSessionTemplate dao) { List list = null; list = dao.selectList("item_type.SelectItemKeyValue"); return list; } // ์ „๋‹ฌ๋ฐ›์€ DTO์ •๋ณด๋ฅผ ์ด์šฉํ•˜์—ฌ case์— ๋งž์ถฐ 'ItemKeyValueDTO'์— ์ •๋ณด๋ฅผ ๋‹ด์Œ. public ItemKeyValueDTO dtoFactoring(ItemTypeValueDTO itvdto, SqlSessionTemplate dao) { ItemKeyValueDTO ikvdto = new ItemKeyValueDTO(); Integer count; Integer index; List arr; for(int i = 1; i <= 10; i ++) { switch(i) { case 1 : if(itvdto.getKey_1() != 0) {int key = itvdto.getKey_1(); count = dao.selectOne("item_type.SearchKeysFindCount", key); if(count > 1) { arr = dao.selectList("item_type.SearchKeysFindIndex", key); for(int j = 0; j < arr.size(); j++) { index = (Integer)arr.get(j); switchIndex(itvdto.getValue_1(), ikvdto, index);} }else { index = dao.selectOne("item_type.SearchKeysFindIndex", key); switchIndex(itvdto.getValue_1(), ikvdto, index);}}break; case 2 : if(itvdto.getKey_2() != 0) {int key = itvdto.getKey_2(); count = dao.selectOne("item_type.SearchKeysFindCount", key); if(count > 1) { arr = dao.selectList("item_type.SearchKeysFindIndex", key); for(int j = 0; j < arr.size(); j++) { index = (Integer)arr.get(j); switchIndex(itvdto.getValue_2(), ikvdto, index);} }else { index = dao.selectOne("item_type.SearchKeysFindIndex", key); switchIndex(itvdto.getValue_2(), ikvdto, index);}}break; case 3 : if(itvdto.getKey_3() != 0) {int key = itvdto.getKey_3(); count = dao.selectOne("item_type.SearchKeysFindCount", key); if(count > 1) { arr = dao.selectList("item_type.SearchKeysFindIndex", key); for(int j = 0; j < arr.size(); j++) { index = (Integer)arr.get(j); switchIndex(itvdto.getValue_3(), ikvdto, index);} }else { index = dao.selectOne("item_type.SearchKeysFindIndex", key); switchIndex(itvdto.getValue_3(), ikvdto, index);}}break; case 4 : if(itvdto.getKey_4() != 0) {int key = itvdto.getKey_4(); count = dao.selectOne("item_type.SearchKeysFindCount", key); if(count > 1) { arr = dao.selectList("item_type.SearchKeysFindIndex", key); for(int j = 0; j < arr.size(); j++) { index = (Integer)arr.get(j); switchIndex(itvdto.getValue_4(), ikvdto, index);} }else { index = dao.selectOne("item_type.SearchKeysFindIndex", key); switchIndex(itvdto.getValue_4(), ikvdto, index);}}break; case 5 : if(itvdto.getKey_5() != 0) {int key = itvdto.getKey_5(); count = dao.selectOne("item_type.SearchKeysFindCount", key); if(count > 1) { arr = dao.selectList("item_type.SearchKeysFindIndex", key); for(int j = 0; j < arr.size(); j++) { index = (Integer)arr.get(j); switchIndex(itvdto.getValue_5(), ikvdto, index);} }else { index = dao.selectOne("item_type.SearchKeysFindIndex", key); switchIndex(itvdto.getValue_5(), ikvdto, index);}}break; case 6 : if(itvdto.getKey_6() != 0) {int key = itvdto.getKey_6(); count = dao.selectOne("item_type.SearchKeysFindCount", key); if(count > 1) { arr = dao.selectList("item_type.SearchKeysFindIndex", key); for(int j = 0; j < arr.size(); j++) { index = (Integer)arr.get(j); switchIndex(itvdto.getValue_6(), ikvdto, index);} }else { index = dao.selectOne("item_type.SearchKeysFindIndex", key); switchIndex(itvdto.getValue_6(), ikvdto, index);}}break; case 7 : if(itvdto.getKey_7() != 0) {int key = itvdto.getKey_7(); count = dao.selectOne("item_type.SearchKeysFindCount", key); if(count > 1) { arr = dao.selectList("item_type.SearchKeysFindIndex", key); for(int j = 0; j < arr.size(); j++) { index = (Integer)arr.get(j); switchIndex(itvdto.getValue_7(), ikvdto, index);} }else { index = dao.selectOne("item_type.SearchKeysFindIndex", key); switchIndex(itvdto.getValue_7(), ikvdto, index);}}break; case 8 : if(itvdto.getKey_8() != 0) {int key = itvdto.getKey_8(); count = dao.selectOne("item_type.SearchKeysFindCount", key); if(count > 1) { arr = dao.selectList("item_type.SearchKeysFindIndex", key); for(int j = 0; j < arr.size(); j++) { index = (Integer)arr.get(j); switchIndex(itvdto.getValue_8(), ikvdto, index);} }else { index = dao.selectOne("item_type.SearchKeysFindIndex", key); switchIndex(itvdto.getValue_8(), ikvdto, index);}}break; case 9 : if(itvdto.getKey_9() != 0) {int key = itvdto.getKey_9(); count = dao.selectOne("item_type.SearchKeysFindCount", key); if(count > 1) { arr = dao.selectList("item_type.SearchKeysFindIndex", key); for(int j = 0; j < arr.size(); j++) { index = (Integer)arr.get(j); switchIndex(itvdto.getValue_9(), ikvdto, index);} }else { index = dao.selectOne("item_type.SearchKeysFindIndex", key); switchIndex(itvdto.getValue_9(), ikvdto, index);}}break; case 10 : if(itvdto.getKey_10() != 0) {int key = itvdto.getKey_10(); count = dao.selectOne("item_type.SearchKeysFindCount", key); if(count > 1) { arr = dao.selectList("item_type.SearchKeysFindIndex", key); for(int j = 0; j < arr.size(); j++) { index = (Integer)arr.get(j); switchIndex(itvdto.getValue_10(), ikvdto, index);} }else { index = dao.selectOne("item_type.SearchKeysFindIndex", key); switchIndex(itvdto.getValue_10(), ikvdto, index);}}break; default : break; } } return ikvdto; } /* ์ธ๋ฑ์Šค ์ •๋ณด๋ฅผ ์ง€์—ญ๋ณ€์ˆ˜๋กœ ๋ฐ›์•„, * ์ธ๋ฑ์Šค์— ๋งž๋Š” 'ItemKeyValueDTO' ํด๋ž˜์Šค์— ํ•ด๋‹นํ•˜๋Š” ๋ฒจ๋ฅ˜๊ฐ’์„ ๋”ํ•ด์ค€๋‹ค. */ public void switchIndex(double values, ItemKeyValueDTO ikvdto, Integer index) { if(index != null) { switch(index) { case 1 : ikvdto.addVitaA(values);break; case 2 : ikvdto.addVitaB(values);break; case 3 : ikvdto.addVitaC(values);break; case 4 : ikvdto.addVitaD(values);break; case 5 : ikvdto.addVitaE(values);break; case 6 : ikvdto.addVitaK(values);break; case 7 : ikvdto.addOmega3(values);break; case 8 : ikvdto.addLutein(values);break; case 9 : ikvdto.addProbiotics(values);break; case 10 : ikvdto.addCalcium(values);break; case 11 : ikvdto.addCollagen(values);break; case 12 : ikvdto.addRedGinseng(values);break; case 13 : ikvdto.addMagnesium(values);break; case 14 : ikvdto.addMineral(values);break; case 15 : ikvdto.addZinc(values);break; case 16 : ikvdto.addBiotin(values);break; case 17 : ikvdto.addMilkthistle(values);break; case 18 : ikvdto.addIron(values);break; case 19 : ikvdto.addPropolis(values);break; case 20 : ikvdto.addAmino(values);break; case 21 : ikvdto.addDietryfiber(values);break; case 22 : ikvdto.addGammalinolenic(values);break; default : System.out.println("ํ•ด๋‹น์—†์Œ");break; } } } // dto ๋ฐ›์•„์™€์„œ key๊ฒ€์‚ฌํ•ด์„œ ์ฐธ์กฐํ…Œ์ด๋ธ”๋กœ ํ™•์ธํ•ด์•ผํ•จ.. // ์ •์ œ์ž‘์—…์„ ๋งˆ์น˜๊ณ  return๊ฐ’์„ ItemKeyValueDTO ๋กœ ์ „๋‹ฌํ•ด์ค€๋‹ค.. // key๊ฐ’์ด 0์ด ์•„๋‹ˆ๋ฉด, public ItemKeyValueDTO KeyCheck(ItemTypeValueDTO dto) { ItemKeyValueDTO ikvDto = null; if(dto.getKey_1() != 0) { dto.getKey_1(); } return ikvDto; } // item_search_key ํ…Œ์ด๋ธ”์˜ key๊ฐ’์„ ๋„ฃ์–ด์ฃผ๋Š” ์ž‘์—…... public void KeyNumberCheck(SqlSessionTemplate dao) { HashMap searchDto; Integer count; List list; List eleList; String indexed; dao.delete("item_type.deleteSearchKeys"); list = dao.selectList("item_type.SearchKeyFind"); for(int i =0; i < list.size(); i++) { searchDto = (HashMap)list.get(i); count = dao.selectOne("item_type.SearchKeyCount",searchDto.get("SEARCHSTRING")); indexed = searchDto.get("INDEXED").toString(); if(count > 1) { eleList = dao.selectList("item_type.SearchKeyLike",searchDto.get("SEARCHSTRING")); for(int l = 0; l < eleList.size(); l++) { searchDto = (HashMap)eleList.get(l); searchDto.put("INDEXED", indexed); dao.insert("item_type.InsertItem_Search_Keys",searchDto); } }else if(count == 1){ searchDto = dao.selectOne("item_type.SearchKeyLike",searchDto.get("SEARCHSTRING")); searchDto.put("INDEXED", indexed); dao.insert("item_type.InsertItem_Search_Keys",searchDto); }else { System.out.println("-------null-------"); System.out.println(searchDto); System.out.println("-------null๋-------"); } } } }
package recursionAndBacktracking; import java.util.*; public class PrintPatternRec { public static void main(String[] args) { // printPatternMy(16, 5); printPattern(16, 16, true, 5); } // this is my solution static ArrayList<Integer> arr = new ArrayList<>(); static void printPatternMy(int n, int k) { printTIllZero(n, k); printAfterZero(arr.get(arr.size() - 1) + k, n, k); System.out.println(arr); } static void printTIllZero(int n, int k) { arr.add(n); if (n > 0) { printTIllZero(n - k, k); } if (n < 0) { return; } } static void printAfterZero(int current, int n, int k) { arr.add(current); if (current < n) { printAfterZero(current + k, n, k); } if (current > n) { return; } // my solution ends here } static void printPattern(int limit, int current, boolean flag, int k) { // Here flag false means we are adding k // if flag is true means we are subtracting k // Print the current element System.out.print(current + " "); // If we are addint k and we get to the end of the series which is n if (flag == false && limit == current) { return; } if (flag) { // if the current element is greater than zero if (current - k > 0) { printPattern(limit, current - 5, true, k); } else { printPattern(limit, current - 5, false, k); } } else { printPattern(limit, current + 5, false, k); } } }
package com.am.pertaminapps.Model; /** * Created by Laurensius D.S on 3/25/2018. */ public class DealerProduct { public int icon; public String id; public String nama_product; public String harga; public DealerProduct(int icon, String id, String nama_product, String harga){ this.icon = icon; this.id = id; this.nama_product = nama_product; this.harga = harga; } }
package com.jt.common.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisSentinelPool; @Service public class RedisService { //ๆณจๅ…ฅๅˆ†็‰‡็š„ๆฑ ๅฏน่ฑก //required=falseไฝฟ็”จๆ—ถๆ‰ๆณจๅ…ฅๅฏน่ฑก //(ๅ› ไธบๅฎƒ้œ€่ฆๅ…ถไป–ๅŠ ่ฝฝไน‹ๅŽๆ‰่ƒฝๆณจๅ…ฅ๏ผŒๅฆ‚ๆžœๆ˜ฏtrue๏ผŒๆฒกๆœ‰ๅŠ ่ฝฝๅ…ถไป–ๅฐฑๅŠ ่ฝฝ่ฟ™ไธชไผšๆŠฅ้”™) //ๅบ”็”จๅœบๆ™ฏ๏ผšๆœ‰ไธ€ไธชๅ…ฌ็”จๆ–นๆณ•๏ผŒ้œ€่ฆๆณจๅ…ฅๆŸไธชๅ…ƒ็ด ๏ผŒๅนถไธ”่ฟ™ไธชๆ–นๆณ•ๅœจๅ…ฌ็”จๆจกๅ—้‡Œ //public ShardedJedisPool shardedJedisPool; @Autowired(required=false) public JedisSentinelPool jedisSentinelPool; public void set(String key,String value){ Jedis shardedJedis = jedisSentinelPool.getResource(); shardedJedis.set(key, value); shardedJedis.close(); } public String get(String key){ Jedis shardedJedis = jedisSentinelPool.getResource(); String result = shardedJedis.get(key); shardedJedis.close(); return result; } /**่ฎพๅฎš่ถ…ๆ—ถๆ—ถ้—ด*/ public void set(String key,String value,int seconds){ Jedis shardedJedis = jedisSentinelPool.getResource(); shardedJedis.setex(key,seconds,value); shardedJedis.close(); } }
/** * @copyright * ==================================================================== * Copyright (c) 2007 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== * @endcopyright */ package org.tigris.subversion.javahl; import java.util.Date; /** * This interface is used to receive every single line for a file on a * the SVNClientInterface.blame call. * * @since 1.5 */ public interface BlameCallback2 { /** * the method will be called for every line in a file. * @param date the date of the last change. * @param revision the revision of the last change. * @param author the author of the last change. * @param merged_date the date of the last merged change. * @param merged_revision the revision of the last merged change. * @param merged_author the author of the last merged change. * @param merged_path the path of the last merged change. * @param line the line in the file */ public void singleLine(Date date, long revision, String author, Date merged_date, long merged_revision, String merged_author, String merged_path, String line); }
package com.ias.webide.jetty; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Enumeration; import java.util.Properties; import java.util.Stack; /** * Used to read properties files and to reuse properties * * @author jchardis * */ public class ConfigPropertiesUtil { public ConfigPropertiesUtil() { } /** * Returns the properties read from a file. * * @param file * @return * @throws IOException */ public Properties readProperties(File file) throws IOException { FileInputStream propFile = new FileInputStream(file); Properties properties = new Properties(); return properties; } /** * Resolves properties from a file and adds them to system properties * * @param file * @return * @throws IOException */ public Properties resolveProperties(File file) throws IOException { FileInputStream propFile = new FileInputStream(file); Properties properties = new Properties(); Properties newProperties = new Properties(); Enumeration<?> keys = properties.propertyNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String oldProperty = properties.getProperty(key); String newProperty = resolve(oldProperty); System.setProperty(key, newProperty); newProperties.setProperty(key, newProperty); } return newProperties; } /** * Resolves string by replacing referenced keys with their property value * * @param string * @return * @throws IllegalArgumentException */ public String resolve(String string) throws IllegalArgumentException { StringBuffer sb = new StringBuffer(); Stack<StringBuffer> stack = new Stack<StringBuffer>(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); switch (c) { case '$': if (i + 1 < string.length() && string.charAt(i + 1) == '{') { stack.push(sb); sb = new StringBuffer(); i++; } break; case '}': if (stack.isEmpty()) throw new IllegalArgumentException("unexpected '}'"); String name = sb.toString(); sb = stack.pop(); sb.append(System.getProperty(name, null)); break; default: sb.append(c); break; } } if (!stack.isEmpty()) throw new IllegalArgumentException("expected '}'"); return sb.toString(); } }
package leetcode; /** * @Author: Mr.M * @Date: 2019-03-02 13:37 * @Description: https://leetcode-cn.com/problems/number-of-islands/ **/ public class T200ๅฒ›ๅฑฟ็š„ไธชๆ•ฐ { public int numIslands(char[][] grid) { int num = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == '1') { num++; findnext(grid, i, j, num); } } } return num; } int x[] = {-1, +1, 0, 0}; int y[] = {0, 0, -1, +1}; // i+d[k] , j+d[k+1] d={0,1,-1,0} private void findnext(char[][] grid, int i, int j, int num) { grid[i][j] = 0; for (int k = 0; k < x.length; k++) { if (i + x[k] >= 0 && i + x[k] < grid.length && j + y[k] >= 0 && j + y[k] < grid[0].length && grid[i + x[k]][j + y[k]] == 1) { findnext(grid, i + x[k], j + y[k], num); } } } }
package UsingObjectsParameters; //Returning an object. class ReturnObject { int a; ReturnObject(int i) { a = i; } ReturnObject incrByTen() { ReturnObject temp = new ReturnObject(a+10); return temp; } }
import java.text.DecimalFormat; public class Dog implements Comparable { //Initializing Variables private String name; private int age; private String breed; private double weight; private static int count; //Constructors public Dog(String name, int age, String breed, double weight) { this.name = name; this.age = age; this.breed = breed; this.weight = weight; count++; } public Dog() { this.name = "Unnamed"; this.age = 0; this.breed = "Unknown"; this.weight = 0; count++; } //Getters public String getName() { return name; } public int getAge() { return age; } public String getBreed() { return breed; } public double getWeight() { return weight; } public static int getCount() { return count; } //Setters public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setBreed(String breed) { this.breed = breed; } public void setWeight(double weight) { this.weight = weight; } //Brain Methods public String weightToKilo() { DecimalFormat fmt = new DecimalFormat("0.##"); final double KILO_TO_POUND = 2.205; return fmt.format(weight / KILO_TO_POUND); } @Override public int compareTo(Object obj) { int value = 0; if (this.getAge() > ((Dog)obj).getAge()) { value = 1; } else if (this.getAge() < ((Dog)obj).getAge()) { value = -1; } return value; } //toString method public String toString() { return "Name: " + name + "\nAge: " + age + "\nBreed: " + breed + "\nWeight: " + weight; } }
package cz.root.rohlik.entity; import javax.persistence.*; import java.time.ZonedDateTime; @Entity(name="ORDER_ITEM_TABLE") public class OrderItem { @Id @GeneratedValue(strategy= GenerationType.AUTO) private Long id; @ManyToOne @JoinColumn(name = "orderId") private Order orderId; private String productName; private int productQuantity; public void setOrderId(Order order) { this.orderId = order; } public Order getOrderId() { return orderId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public int getProductQuantity() { return productQuantity; } public void setProductQuantity(int productQuantity) { this.productQuantity = productQuantity; } }
import java.util.Arrays; /** * 268. Missing Number * Easy */ public class Solution { public int missingNumber(int[] nums) { int n = nums.length + 1; int sum = Arrays.stream(nums).sum(); int nsum = n * (n - 1) / 2; return nsum - sum; } }
package offer; /** * @author kangkang lou */ /** * ่ฏทๅฎž็Žฐไธ€ไธชๅ‡ฝๆ•ฐ็”จๆฅๅˆคๆ–ญๅญ—็ฌฆไธฒๆ˜ฏๅฆ่กจ็คบๆ•ฐๅ€ผ๏ผˆๅŒ…ๆ‹ฌๆ•ดๆ•ฐๅ’Œๅฐๆ•ฐ๏ผ‰ใ€‚ไพ‹ๅฆ‚๏ผŒๅญ—็ฌฆไธฒ"+100","5e2","-123","3.1416"ๅ’Œ"-1E-16"้ƒฝ่กจ็คบๆ•ฐๅ€ผใ€‚ ไฝ†ๆ˜ฏ"12e","1a3.14","1.2.3","+-5"ๅ’Œ"12e+4.3"้ƒฝไธๆ˜ฏใ€‚ */ public class IsNumber { public static boolean isNumeric(char[] str) { String s = new String(str); boolean result = true; if (str[0] == '+' || str[0] == '-') { s = s.substring(1); } if (s.startsWith("+") || s.startsWith("-")) { return false; } if (s.contains("e") || s.contains("E")) { int pos = -1; if (s.contains("e")) { pos = s.indexOf("e"); } if (s.contains("E")) { pos = s.indexOf("E"); } String a_str = s.substring(pos + 1); String b_str = s.substring(0, pos); try { Float.parseFloat(b_str); Integer.parseInt(a_str); } catch (Exception e) { result = false; } } else { try { Float.parseFloat(s); } catch (Exception e) { result = false; } } return result; } public static void main(String[] args) { System.out.println(isNumeric("5e2".toCharArray())); } }
package com.tencent.mm.pluginsdk.ui.d; import android.content.Context; import android.content.Intent; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.pluginsdk.ui.d.l.7; import com.tencent.mm.ui.base.h.c; class l$7$1 implements c { final /* synthetic */ String hGV; final /* synthetic */ 7 qQi; l$7$1(7 7, String str) { this.qQi = 7; this.hGV = str; } public final void ju(int i) { if (this.qQi.qQd != null) { this.qQi.qQd.onDismiss(null); } switch (i) { case 0: if (l.cfi()) { Context context = this.qQi.val$context; String str = this.hGV; Intent intent = new Intent("android.intent.action.INSERT"); intent.setType("vnd.android.cursor.dir/contact"); intent.putExtra("phone", str); context.startActivity(intent); h.mEJ.k(10113, "1"); return; } l.bo(this.qQi.val$context, this.hGV); h.mEJ.k(10114, "1"); return; case 1: l.bo(this.qQi.val$context, this.hGV); h.mEJ.k(10114, "1"); return; default: return; } } }
package com.home.closematch.controller; import com.home.closematch.entity.Account; import com.home.closematch.entity.Humanresoucres; import com.home.closematch.entity.Position; import com.home.closematch.entity.SeekerDeliver; import com.home.closematch.entity.vo.CheckDeliverVo; import com.home.closematch.pojo.Msg; import com.home.closematch.service.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; /** * hr controller */ @Api(tags = "Hr็›ธๅ…ณๆ“ไฝœ") @RestController public class HrController { @Autowired private HumanresoucresService humanresoucresService; @Autowired private JobSeekerService jobSeekerService; @Autowired private PositionService positionService; @Autowired private SeekerDeliverService seekerDeliverService; @ApiOperation(value="่Žทๅ–ๅฝ“ๅ‰id็š„hrๆ‰€ๅ‘ๅธƒ็š„ๆ‰€ๆœ‰่Œไฝ", notes = "็ฎก็†ๅ‘˜่กŒไธบ") @GetMapping("/hr/{hrId}/publishPosition") public Msg getHrPublishPositions(@PathVariable("hrId")Long hrId){ return Msg.success("success").add("items", positionService.getPublishPosition(hrId)); } @ApiOperation(value="่Žทๅ–ๅฝ“ๅ‰hr็š„ไฟกๆฏ") @GetMapping("/hr") public Msg getHrInfoWithCompany(){ Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return Msg.success().add("detailInfo", humanresoucresService.getHrInfoWithCompany(account)); } @ApiOperation(value="ๆ›ดๆ–ฐ/ไฟๅญ˜ๅฝ“ๅ‰hr็š„ไฟกๆฏ") @PostMapping("/hr") public Msg saveOrUpdateHrInfo(@RequestBody @Validated Humanresoucres humanresoucres){ Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); humanresoucres.setId(account.getUserId()); humanresoucresService.saveOrUpdate(humanresoucres); return Msg.success(); } @ApiOperation(value="่Žทๅ–ๅฝ“ๅ‰hr่‡ชๅทฑๅ‘ๅธƒ็š„ๆ‰€ๆœ‰่Œไฝ", notes = "ๅ’ŒไธŠ้ข็š„ๆ–นๆณ•ๅŠŸ่ƒฝไธ€ๆ ท, ๅชไธ่ฟ‡่ฟ™้‡Œๆ˜ฏhr่‡ชๅทฑ่Žทๅ–, ไผ˜ๅŒ–Url") @GetMapping("/hr/positions") public Msg getHrPublishPosition(){ Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return Msg.success().add("items", positionService.getPublishPosition(account.getUserId())); } @ApiOperation(value="hrๅŽปๆ”นๅ˜่ฏฅ่Œไฝ็š„ๅฏ็”จ็Šถๆ€", notes = "hr่กŒไธบ") @PutMapping("/hr/position/{positionId}") public Msg updatePositionUseStatus(@PathVariable("positionId")Long positionId){ Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); positionService.changePositionUseStatus(account.getUserId(), positionId); return Msg.success("ไฟฎๆ”นๆˆๅŠŸ"); } @ApiOperation(value="ๆทปๅŠ /ไฟฎๆ”นhrๅ‘ๅธƒ็š„่Œไฝไฟกๆฏ", notes = "hr่กŒไธบ") @PostMapping("/hr/position") public Msg saveOrUpdatePosition(@RequestBody @Validated Position position) { Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // ่ฟ™ๆกๅบ”่ฏฅๅฏๆ˜ฏๆณจ้‡Šๆމ humanresoucresService.checkHrInfoEnrolCondition(account.getUserId()); positionService.saveOrUpdatePosition(account.getUserId(), position); return Msg.success(); } /** * ่Žทๅ–ๆ‰€ๅ‘ๅธƒ็š„ๆ‰€ๆœ‰็š„่Œไฝ็š„ๅบ”่˜่€… * @return Msg ไธญๅŒ…ๅซ็š„ๆ˜ฏไธ€ไธชDTO * ไป…ไป…ๅŒ…ๅซ็›ธๅบ”็š„ๆ•™่‚ฒไฟกๆฏ, ๅฝ“ๅ‰็Šถๆ€: ๅบ”ๅฑŠ / ๆฑ‚่Œ * ๅบ”่˜็š„่Œไฝ * ้œ€่ฆๆŸฅ่ฏฆ็ป†seeker็š„่ฏฆ็ป†ไฟกๆฏๅ†pull */ @ApiOperation(value="hr่Žทๅ–ๆ‰€ๅ‘ๅธƒ็š„ๆ‰€ๆœ‰็š„่Œไฝ็š„ๅบ”่˜่€…", notes = "hr่กŒไธบ") @GetMapping("/hr/positions/applicants") public Msg getApplicantsWithPosition() { // ่Žทๅ–accountId ๅนถ้ชŒ่ฏAccount Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return Msg.success().add("items", positionService.getApplicantsWithPosition(account.getUserId())); } @ApiOperation(value="ๅฎกๆ‰นๆฑ‚่Œ็”ณ่ฏท", notes = "hr่กŒไธบ") @PutMapping("/hr/position/checkDeliver") public Msg checkDeliver(@RequestBody @Validated CheckDeliverVo checkDeliverVo){ Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); seekerDeliverService.checkDeliver(account.getUserId(), checkDeliverVo); return Msg.success(); } @ApiOperation(value = "่Žทๅ–ๆŠ•้€’่€…ๅŸบๆœฌไฟกๆฏ", notes = "hr่กŒไธบ, ่Žทๅ–ๅฝ“ๅ‰ๆŠ•้€’่€…็š„่ฏฆ็ป†ไฟกๆฏ") @GetMapping("/hr/position/deliver/{deliverId}") public Msg getSeekerDetailInfo(@PathVariable("deliverId") Long deliverId){ Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return Msg.success().add("detailData", jobSeekerService.hrGetSeekerDetailInfo(account.getUserId(), deliverId)); } @ApiOperation(value = "่Žทๅ–ๆฑ‚่Œ่€…็š„ๅทฅไฝœ็ปๅކ", notes = "ๆ นๆฎ็›ธๅบ”็š„deliverId ๆŸฅ่ฏข็›ธๅบ”็š„deliver่ฎฐๅฝ•, " + "ๆ นๆฎdeliver็š„seekerId ๆŸฅ่ฏขๅฐฑ่Œ็ปๅކ" + "ไธบไบ†ไธŽไธŠ้ข็š„ๆ–นๆณ•่งฃ่€ฆ") @GetMapping("/hr/position/deliver/{deliverId}/workExperience") public Msg hrGetSeekerWorkExperience(@PathVariable("deliverId") Long deliverId){ Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return Msg.success().add("items", jobSeekerService.hrGetSeekerWorkExperience(account.getUserId(), deliverId)); } @ApiOperation(value = "่Žทๅ–ๆฑ‚่Œ่€…็š„ๅทฅไฝœ็ปๅކ็š„ๅކๅฒ่ฏ„ไปท", notes = "ๆ นๆฎdeliverId ่Žทๅ– positionIdๅ’ŒseekerId, ๅ†ๅˆฐ็›ธๅบ”่กจไธญๆŸฅๆ‰พ่ฏ„ไปท") @GetMapping("/hr/position/deliver/{deliverId}/workExperience/comment") public Msg hrGetWorkExperienceComment(@PathVariable("deliverId") Long deliverId) { Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // ่Žทๅ–ๆฑ‚่Œ่€…็š„ไฟกๆฏไน‹ๅ‰, ๅ…ˆ็œ‹็œ‹ๆ˜ฏๅฆๆœ‰ๆƒๅˆฉ่ฟ›่กŒไฟกๆฏ่Žทๅ– SeekerDeliver seekerDeliver = jobSeekerService.checkSeekerRelationOfHr(account.getUserId(), deliverId); return Msg.success().add("items", positionService.getPositionComments(seekerDeliver.getSeekId(), seekerDeliver.getPositionId())); } }
package com.smartcity.commonbase.widget.pagestatus; import android.content.Context; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.util.Log; import android.view.View; import android.view.ViewParent; /** * Author: YuJunKui * Time:2017/12/9 9:41 * Tips: */ public class ViewUtils { private static final String TAG = "ViewUtils"; /** * ๆต‹้‡viewๆ–นๆณ• * * @param view * @return int[0] width int[1] height */ public static int[] getViewMetrics(View view) { int[] ints = new int[2]; ints[0] = view.getWidth(); ints[1] = view.getHeight(); if (ints[0] == 0 || ints[1] == 0) { try { view.measure(0, 0); } catch (Exception e) { } ints[0] = view.getMeasuredWidth(); ints[1] = view.getMeasuredHeight(); } return ints; } /** * ็ฎ€ๅ•ๅค„็†ไธ‹ๆœ‰ไบ›ๆƒ…ๅ†ตไธ‹ๅผ‚ๅธธ็š„้—ฎ้ข˜ * * @param view * @return int[0] width int[1] height */ public static int[] getNormalBindViewMetric(View view) { int[] ints = getViewMetrics(view); //็›ฎๅ‰่ฟ™็งๆต‹้‡ๆ–นๆณ•ไธๅฅฝ ๅ…ผๅฎนไธ‹่Žทๅ–็ˆถ็ฑป็š„ if (ints[0] == 0 && ints[1] == 0) { View parent = (View) view.getParent(); if (parent != null) { return getViewMetrics(parent); } } return ints; } /** * ่ฟ™้‡Œไผšๅค„็†ๅฆ‚ๆžœbindView็š„ๆŸไธช็ˆถ็ฑปๆ˜ฏCoordinatorLayout็š„่ฏ * ๅฐ†ๆญฃ็กฎ้ซ˜ๅบฆ CoordinatorLayout-AppBarLayout ่ฟ”ๅ›ž * @param bindView * @return */ public static int[] getBindViewMetrics(View bindView) { CoordinatorLayout parent = findCoordinatorLayoutParent(bindView); if (parent != null) { int[] ints; //ๅฏปๆ‰พAppBarLayout AppBarLayout appBarLayout = null; for (int i = 0; i < parent.getChildCount(); i++) { View childAt = parent.getChildAt(i); if (childAt instanceof AppBarLayout) { appBarLayout = (AppBarLayout) childAt; break; } } if (appBarLayout == null) { return getNormalBindViewMetric(bindView); } ints=new int[]{parent.getWidth(),parent.getHeight()-appBarLayout.getHeight()}; return ints; } else { return getNormalBindViewMetric(bindView); } } /** * ๆ นๆฎๆ‰‹ๆœบ็š„ๅˆ†่พจ็އไปŽ dp ็š„ๅ•ไฝ ่ฝฌๆˆไธบ px(ๅƒ็ด ) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * @param v * @return */ public static CoordinatorLayout findCoordinatorLayoutParent(View v) { View parent; if (v == null || v.getParent()==null|| ! (v.getParent() instanceof View)) { return null; } parent= (View) v.getParent(); if (parent instanceof CoordinatorLayout) { return (CoordinatorLayout) parent; } else { return findCoordinatorLayoutParent(parent); } } /** * ็ˆถviewๆ˜ฏๅฆๆ˜ฏCoordinatorLayout(ไผš้€’ๅฝ’่‡ณnull) * * @param v * @return */ public static boolean parentCoordinatorLayout(View v) { return findCoordinatorLayoutParent(v) != null; } }
package com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.dbconnection.ConnectToOracle; import com.model.Employee; public class EmployeeDAO { private Connection connection; private PreparedStatement ps; private ResultSet rs; private String sql; public EmployeeDAO() { this.connection = new ConnectToOracle().connect(); } public void employeeRegister(Employee employee) { sql = "INSERT INTO employeeform VALUES (employee_id.nextval,?,?,?,?,?,?)"; try { ps = connection.prepareStatement(sql); ps.setString(1,employee.getFirstname()); ps.setString(2, employee.getLastname()); ps.setString(3, employee.getEmail()); ps.setDate(4, employee.getDate()); ps.setString(5, employee.getPhone()); ps.setString(6, employee.getPassword()); ps.execute(); }catch(SQLException e) { System.out.println("Error during insert Employee on Oracle\n" + e); } } public ResultSet employeeLogin(String email, String password) { sql = "SELECT email, accesspassword FROM employeeform WHERE email = ? AND accesspassword = ?"; try { ps = connection.prepareStatement(sql); ps.setString(1, email); ps.setString(2, password); rs = ps.executeQuery(); }catch(SQLException e) { System.out.println("Error during retrievement Employee on Oracle\n" + e); } return rs; } public boolean adminAuthentication(String adm_email,String adm_password) { boolean access_authorized = false; sql = "SELECT email, accesspassword FROM employeeform WHERE email = ? AND accesspassword = ?"; try { ps = connection.prepareStatement(sql); ps.setString(1, adm_email); ps.setString(2, adm_password); rs = ps.executeQuery(); if(rs.next()) access_authorized = true; }catch(SQLException e) { System.out.println("Error during ADM password authentication on Oracle\n" + e); } return access_authorized; } public String retrieveName(String employee_email) { String aux = null; sql = "SELECT employeeform.firstname FROM employeeform WHERE employeeform.email = ?"; try { ps = connection.prepareStatement(sql); ps.setString(1, employee_email); rs = ps.executeQuery(); if(rs.next()) { aux = rs.getString("firstname"); } else { System.out.println("Code not associate with any register."); } }catch(SQLException e) { System.out.println("Error during retrievement name User on Oracle\n" + e); } return aux; } }
package com.bluesky.admin.common.consts; /** * @author Lijinchun * @Package com.wywk.member.expiredclean.common.consts.RedisConstant * @date 2019/7/22 16:40 */ public final class RedisConstant { private RedisConstant(){} /** * ๅฎšๆ—ถไปปๅŠก็›ธๅ…ณ */ public static final class Task extends Base{ /** * ไปปๅŠก้” */ public static final String TASK_LOCK_KEY="TASK:LOCK_KEY:"; /** * ไปปๅŠก้”่ถ…ๆ—ถ้—ด๏ผˆ็ง’๏ผ‰ */ public static final long LOCK_TIMEOUT = 600; } /** * ไธšๅŠกๅค„็†้˜ฒ้‡ๅค„็† */ public static final class Business extends Base{ /** *ไธšๅŠก้” */ public static final String LOCK_KEY_PREFIX ="BUSINESS:LOCK_KEY:"; /** * ไปปๅŠก้”่ถ…ๆ—ถ้—ด๏ผˆ็ง’๏ผ‰ */ public static final long LOCK_TIMEOUT = 600; } /** * ็ฝ‘้ฑผAPPๆœๅŠก็ณป็ปŸๆŽฅๅฃ้…็ฝฎ */ public static final class AppSys extends Base{ /** * ๆŽฅๅฃAIP */ public static final String CFG_BASE_API_URL_KEY ="EXPIRED_CLEAN:APP_SYS:CFG:BASE_API_URL"; public static final String CFG_BASE_API_MD5_SALT_KEY ="EXPIRED_CLEAN:APP_SYS:CFG:MD5_SALT"; public static final String CFG_BASE_API_TEMPLATE_ID_KEY ="EXPIRED_CLEAN:APP_SYS:CFG:TEMPLATE_ID"; /** * ไปปๅŠก้”่ถ…ๆ—ถ้—ด๏ผˆ็ง’๏ผ‰ */ public static final long LOCK_TIMEOUT = 600; } private static class Base{ private Base(){} } }
package com.thoughtworks.domain.cart.usecases; import com.thoughtworks.domain.UseCaseDataReceiver; import com.thoughtworks.domain.UseCaseError; import com.thoughtworks.domain.cart.CartRepository; /** * Created on 15-06-2018. */ public class AddToCartUseCase implements AddToCart { private final CartRepository mCartRepo; private AddToCartUseCase(final CartRepository cartRepository) { mCartRepo = cartRepository; } public static AddToCartUseCase newInstance(CartRepository cartRepository) { return new AddToCartUseCase(cartRepository); } @Override public void execute(final Integer prodId, final UseCaseDataReceiver<Boolean> useCaseDataReceiver) { final Boolean repositoryOutput = mCartRepo.addToCart(prodId); if (!repositoryOutput) { useCaseDataReceiver.onUseCaseDataReceivedFailed(new UseCaseError()); } else { useCaseDataReceiver.onUseCaseDataReceived(repositoryOutput); } } }
package com.beiyelin.projectportal.entity; import com.beiyelin.commonsql.jpa.BaseItemEntity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import static com.beiyelin.commonsql.constant.Repository.*; /** * @Description: * @Author: newmann * @Date: Created in 20:55 2018-02-22 */ @Data @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper=true) @Entity @Table(name = SettleDetailBorrowMoneyTicket.TABLE_NAME) public class SettleDetailBorrowMoneyTicket extends BaseItemEntity { public static final String TABLE_NAME="s_settle_detail_borrow_money_ticket"; private static final long serialVersionUID = 1L; private EmbeddableProject project; @Column(length = PRIMARY_ID_LENGTH) private String borrowMoneyTicketId; @Column(length = BILL_NO_LENGTH) private String borrowMoneyTicketNo; }
/* * 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 Rules; import Properties.data.rules.ConfigProperties; import WriteToFiles.OutputToFile; import WrongDataRegister.WrongData; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; //import org.apache.poi.openxml4j.exceptions.InvalidFormatException; /** * * @author Elshan.Abdullayev */ public class RecordWrongDataGate { private WrongData WDataObj; private OutputToFile Otf; public void RecordingGate(String Counter, String VlrKod, String VlrDescription, String WrongData,String AccountNo) throws FileNotFoundException, IOException, InvalidFormatException { //System.out.println(); // System.out.println("Counter:"+Counter); // System.out.println("VlrKod:"+VlrKod); // System.out.println("VlrDesc:"+VlrDescription); // System.out.println("WrongData:"+WrongData); // System.out.println("Account_no:"+AccountNo); WDataObj= new WrongData(); Otf = new OutputToFile(); WDataObj.setSaygac(Counter); WDataObj.setVLRkod(VlrKod); WDataObj.setVLRkod_description(VlrDescription); WDataObj.setWrong_data(WrongData); WDataObj.setAccount_no(AccountNo); //Otf.FillFile(WDataObj); Otf.MakeExcel(WDataObj); } }
package com.tencent.mm.plugin.mmsight; import com.tencent.mm.g.a.qa; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; class e$1 extends c<qa> { final /* synthetic */ e lez; e$1(e eVar) { this.lez = eVar; this.sFo = qa.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { qa qaVar = (qa) bVar; qaVar.caH.result = d.mZ(qaVar.caG.caI); return true; } }
package b.c.b; import b.e.a; import b.e.d; public abstract class g extends a implements d { public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof g)) { return obj instanceof d ? obj.equals(cJI()) : false; } else { g gVar = (g) obj; if (cJJ().equals(gVar.cJJ()) && getName().equals(gVar.getName()) && cmO().equals(gVar.cmO()) && e.i(cJH(), gVar.cJH())) { return true; } return false; } } public int hashCode() { return (((cJJ().hashCode() * 31) + getName().hashCode()) * 31) + cmO().hashCode(); } public String toString() { a cJI = cJI(); if (cJI != this) { return cJI.toString(); } return "property " + getName() + " (Kotlin reflection is not available)"; } }
package com.Flonx6; /** * @Auther:Flonx * @Date:2021/1/9 - 01 - 09 - 21:11 * @Description: com.Flonx6 * @Version: 1.0 */ public class Girl { private int age = 0; private int sno; private String name; private double height; // public int getAge() { return age; } public int getSno() { return sno; } public void setSno(int sno) { this.sno = sno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } // ๅฐ่ฃ…:ๅฐ†ๆŸไบ›ไธœ่ฅฟ้š่—,็„ถๅŽๆไพ›็›ธๅบ”็š„ๆ–นๅผ่ฟ›่กŒ่Žทๅ– // ๆ‰€ไปฅprivateๅ…ถๅฎžไธ็ฎ—ๅฐ่ฃ…,ๆฒกๆœ‰ๆไพ›็›ธๅบ”็š„ๆ–นๅผ่ฟ›่กŒ่Žทๅ– // ไธ€่ˆฌๆ˜ฏๅŠ ไบ†้™ๅˆถ่ฎฟ้—ฎไฟฎ้ฅฐ็ฌฆ็š„ๅŸบ็ก€ไธŠ,้€š่ฟ‡ๅ†™ๆ–นๆณ• // // ่ฏปๅ–ๅนด้พ„ public int readAge(){ return age; } // ่ฎพ็ฝฎๅนด้พ„ public void setAge(int age){ if (age>=30){ this.age = 18; } else this.age = age; } }
/* * SUNSHINE TEAHOUSE PRIVATE LIMITED CONFIDENTIAL * __________________ * * [2015] - [2017] Sunshine Teahouse Private Limited * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Sunshine Teahouse Private Limited and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Sunshine Teahouse Private Limited * and its suppliers, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Sunshine Teahouse Private Limited. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.12.19 at 12:10:26 PM IST // package www.chaayos.com.chaimonkbluetoothapp.domain.model.new_model; public enum OrderStatus { INITIATED, PROCESSING, WAITING, SETTLED, CLOSED, CANCELLED; public String value() { return name(); } public static OrderStatus fromValue(String v) { return valueOf(v); } }
/* Directions: * Hereโ€™s an interesting way to remove duplicates from an array. The insertion * sort uses a loop-within-a-loop algorithm that compares every item in the * array with every other item. If you want to remove duplicates, this is one * way to start. (See also Exercise 2.6 in Chapter 2.) Modify the * insertionSort() method in the insertSort.java program so that it removes * duplicates as it sorts. Hereโ€™s one approach: When a duplicate is found, * write over one of the duplicated items with a key value less than any * normally used (such as โ€“1, if all the normal keys are positive). Then the * normal insertion sort algorithm, treating this new key like any other item, * will put it at index 0. From now on the algorithm can ignore this item. The * next duplicate will go at index 1, and so on. When the sort is finished, all * the removed dups (now represented by โ€“1 values) will be found at the * beginning of the array. The array can then be resized and shifted down so it * starts at 0. */ package chapter3; import java.util.Random; public class Project3_6 { public static void main(String[] args) { final int SIZE = 8; ArrayInsertionSortNoDups arr = new ArrayInsertionSortNoDups(SIZE); Random rand = new Random(); // fill w/ values from 0-7 for (int i = 0; i < SIZE; i++) { arr.insert(rand.nextInt(8)); } arr.display(); arr.insertionSortNoDupes(); arr.display(); } } class ArrayInsertionSortNoDups { private int[] arr; private int numberOfElements; public ArrayInsertionSortNoDups(int max) { arr = new int[max]; numberOfElements = 0; } public void insert(int value) { arr[numberOfElements++] = value; } // Removes duplicate keys while performing an insertion sort public void insertionSortNoDupes() { markDupes(); for (int i = 1; i < numberOfElements; i++) { int temp = arr[i]; int j = i; while (j > 0 && arr[j - 1] >= temp) { arr[j] = arr[j - 1]; j--; } arr[j] = temp; } removeDupes(); } // sets duplicate keys to -1 private void markDupes() { for (int i = 0; i < numberOfElements; i++) { for (int j = i + 1; j < numberOfElements; j++) { if (arr[j] == -1) { continue; } if (arr[j] == arr[i]) { arr[i] = -1; } } } } // removes all duplicates (marked as -1) from array private void removeDupes() { int x = 0; while (arr[x] == -1) { x++; } for (int i = 0; i < numberOfElements - x; i++) { arr[i] = arr[i + x]; } numberOfElements -= x; } public void display() { if (numberOfElements == 0) { System.out.println("--"); } else { for(int i = 0; i < numberOfElements; i++) { System.out.print(arr[i] + " "); } System.out.println(); } } }
package keyword.ex1; import java.io.IOException; import java.util.List; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import util.Commons; public class TestLogin { KeyWordUtil keywordUtil; KeyDrivenExcelUtils utils ; private String excelFilePath = "C:\\test\\keywords.xlsx"; @BeforeTest public void setup() { keywordUtil = new KeyWordUtil(Commons.getChromeDriver()); utils = new KeyDrivenExcelUtils(excelFilePath); } @AfterTest public void close() { keywordUtil.close(); } @Test public void performLogin() throws IOException, InterruptedException { List<Action> actions = utils.getActions(); for(Action action : actions) { if(!action.getKeyword().contains("TEST_CASE#")) { System.out.println(action.getDescription()); keywordUtil.perform(action); }else { System.out.println(action.getKeyword() +" started"); } } } }
package jie.android.ip.setup; import java.io.File; import java.sql.Connection; import jie.android.ip.CommonConsts.SystemConfig; import jie.android.ip.database.ConnectionAdapter; import jie.android.ip.database.DesktopConnectionAdapter; public class DesktopSetup extends Setup { // private final ConnectionAdapter connectionAdapter; public DesktopSetup() { super(); // connectionAdapter = new DesktopConnectionAdapter(getStorageDirectory() + SystemConfig.DATABASE_FILE); } @Override public void create() { // TODO Auto-generated method stub } @Override public final String getStorageDirectory() { return "./doc/"; } @Override public final String getAppDirectory() { return "./doc/"; } @Override public final String getCacheDirectory() { return "./doc/cache/"; } @Override public final Connection getDatabaseConnection() { final ConnectionAdapter connectionAdapter = new DesktopConnectionAdapter(getStorageDirectory() + SystemConfig.DATABASE_FILE); return connectionAdapter.getConnection(); } @Override public Connection getPatchConnection() { final ConnectionAdapter connectionAdapter = new DesktopConnectionAdapter(getCacheDirectory() + SystemConfig.PATCH_FILE); return connectionAdapter.getConnection(); } @Override public boolean shareScreen() { return false; } }
import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class MostFrequentWord { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] textArray = scanner.nextLine().split("\\W+"); Map<String, Integer> wordCount = new TreeMap<>(); int maxWordCount = 0; for (String word : textArray) { word = word.toLowerCase(); Integer count = wordCount.get(word); if (count == null) { count = 0; } if (count + 1 > maxWordCount) { maxWordCount = count + 1; } wordCount.put(word, count + 1); } for (Map.Entry<String, Integer> entry : wordCount.entrySet()) { if (entry.getValue() == maxWordCount) { System.out.printf("%s -> %d times", entry.getKey(), maxWordCount); System.out.println(); } } } }
package org.gokareless.examples.aspects.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.gokareless.examples.aspects.ApplicationConfiguration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Import(ApplicationConfiguration.class) @Aspect @Configuration public class RequestCountAspect { @Autowired Counter counter; @After("execution(* org.gokareless.examples.aspects.rest.*.*(..))") public void after(JoinPoint joinPoint){ System.out.println("!!!YEAH!!! I'm in RequestCountAspect"); counter.increment(); } }
package io; import org.junit.Assert; import org.junit.Test; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * @author zhoubo * @create 2018-07-23 11:41 */ public class SerializableTestTest { @Test public void deserialize() throws Exception { SerializableTest serializableTest = new SerializableTest(new TestObject()); final Object o = serializableTest.deserialize(); Assert.assertTrue(o instanceof TestObject); TestObject testObject = (TestObject) o; final Method[] declaredMethods = testObject.getClass().getDeclaredMethods(); for (Method method : declaredMethods) { method.setAccessible(true); // System.out.println(""); } final Field[] fields = testObject.getClass().getDeclaredFields(); for (Field field : fields) { System.out.println("field: " + field.getName()); } System.out.println("class name = " + testObject.getClass().getName()); } @Test public void serialize() throws Exception { SerializableTest serializableTest = new SerializableTest(new TestObject()); serializableTest.serialize(); } }
package tech.adrianohrl.stile.control.bean.personnel; import tech.adrianohrl.stile.control.bean.DataSource; import tech.adrianohrl.stile.control.bean.personnel.services.ManagerService; import tech.adrianohrl.stile.control.bean.personnel.services.SubordinateService; import tech.adrianohrl.stile.control.bean.personnel.services.SupervisorService; import tech.adrianohrl.stile.control.dao.personnel.io.PersonnelReaderDAO; import tech.adrianohrl.stile.model.personnel.Employee; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.persistence.EntityManager; import org.primefaces.event.FileUploadEvent; import org.primefaces.model.UploadedFile; /** * * @author Adriano Henrique Rossette Leite (contact@adrianohrl.tech) */ @ManagedBean @ViewScoped public class EmployeeImportBean implements Serializable { @ManagedProperty(value = "#{subordinateService}") private SubordinateService subordinateService; @ManagedProperty(value = "#{supervisorService}") private SupervisorService supervisorService; @ManagedProperty(value = "#{managerService}") private ManagerService managerService; private final List<Employee> employees = new ArrayList<>(); public void upload(FileUploadEvent event) { FacesContext context = FacesContext.getCurrentInstance(); FacesMessage message; UploadedFile file = event.getFile(); EntityManager em = DataSource.createEntityManager(); try { PersonnelReaderDAO readerDAO = new PersonnelReaderDAO(em); readerDAO.readFile(file.getInputstream()); employees.addAll(readerDAO.getRegisteredEmployees()); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso no upload", "O arquivo " + event.getFile().getFileName() + " foi importado para a aplicaรงรฃo!!!"); update(); } catch (java.io.IOException | tech.adrianohrl.stile.exceptions.IOException e) { message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro no upload", "Nรฃo foi possรญvel fazer o upload do arquivo " + event.getFile().getFileName() + ": " + e.getMessage()); System.out.println("IOException catched during importation: " + e.getMessage()); } em.close(); context.addMessage(null, message); } public void update() { subordinateService.update(); supervisorService.update(); managerService.update(); } public List<Employee> getEmployees() { return employees; } public String toString(String employeeType) { String str = ""; switch (employeeType) { case "Subordinate": str = "Subordinado"; break; case "Supervisor": str = "Supervisor"; break; case "Manager": str = "Gerente"; break; } return str; } public void setSubordinateService(SubordinateService subordinateService) { this.subordinateService = subordinateService; } public void setSupervisorService(SupervisorService supervisorService) { this.supervisorService = supervisorService; } public void setManagerService(ManagerService managerService) { this.managerService = managerService; } }
package UI.Chart; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class DataTable extends JTable{ public DataTable(String[] columnNames) { super(new DefaultTableModel(null, columnNames)); } }
package com.tuanhk.home.contacts; import com.tuanhk.data.cache.UserConfig; import com.tuanhk.ui.presenter.AbstractPresenter; import javax.inject.Inject; public class ContactsPresenter extends AbstractPresenter<IContactsView> { private UserConfig mUserConfig; @Inject ContactsPresenter(UserConfig userConfig) { mUserConfig = userConfig; } }
package com.example.myoga; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.myoga.models.Utils; import com.example.myoga.models.VideosDataSource; import java.util.ArrayList; public class VideoRecyclerViewAdapter extends RecyclerView.Adapter<VideoRecyclerViewAdapter.ViewHolder> { private final Context context; private final RV_TYPE RvType; private ArrayList<VideosDataSource.Video> watchVideos; private ArrayList<VideosDataSource.Video> breathVideos; public enum RV_TYPE { BREATH("BREATH"), WATCH("WATCH"); private final String stringVal; RV_TYPE(String stringVal) { this.stringVal = stringVal; } public String getStringVal() { return stringVal; } } public VideoRecyclerViewAdapter(Context context, RV_TYPE type, ArrayList<VideosDataSource.Video> videos) { this.context = context; this.RvType = type; switch (type) { case WATCH: watchVideos = videos; break; case BREATH: breathVideos = videos; break; } } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // We need: View v = How to inflate XMl file. // Create new ViewHolder. LayoutInflater inflater = LayoutInflater.from(context); View v = inflater.inflate(R.layout.video_item, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { String videoName = ""; String videoURL = ""; switch (RvType) { case BREATH: videoName = breathVideos.get(position).getVideoName(); videoURL = breathVideos.get(position).getUrl(); break; case WATCH: videoName = watchVideos.get(position).getVideoName(); videoURL = watchVideos.get(position).getUrl(); break; } holder.webView_text.setText(videoName); Utils.loadEmbedVideo(videoURL, holder.webView, context, 300, 200); } public int getItemCount() { switch (RvType) { case BREATH: return Math.max(breathVideos.size(), 0); case WATCH: return Math.max(watchVideos.size(), 0); } return 0; } static class ViewHolder extends RecyclerView.ViewHolder { TextView webView_text; WebView webView; public ViewHolder(@NonNull View itemView) { super(itemView); webView_text = itemView.findViewById(R.id.webview_text); webView = itemView.findViewById(R.id.webview); } } }
package com.shivam.healthometer.Models; public class mealModel { String mealNo, meal, macro; public mealModel() { } public mealModel(String mealNo, String meal, String macro) { this.mealNo = mealNo; this.meal = meal; this.macro = macro; } public String getMealNo() { return mealNo; } public void setMealNo(String mealNo) { this.mealNo = mealNo; } public String getMeal() { return meal; } public void setMeal(String meal) { this.meal = meal; } public String getMacro() { return macro; } public void setMacro(String macro) { this.macro = macro; } }
package com.thoughtworks.data.cart.mapper; import com.thoughtworks.data.Mapper; import com.thoughtworks.data.cart.entity.CartItemEntity; import com.thoughtworks.domain.cart.CartItem; import java.util.ArrayList; import java.util.List; /** * Created on 16-06-2018. */ class CartItemEntityListMapper implements Mapper<List<CartItemEntity>, List<CartItem>> { @Override public List<CartItem> map(final List<CartItemEntity> input) { final List<CartItem> result = new ArrayList<>(input.size()); final CartItemEntityMapper cartItemEntityMapper = new CartItemEntityMapper(); for (CartItemEntity entity : input) { result.add(cartItemEntityMapper.map(entity)); } return result; } }
package pl.edu.agh.game.settings; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import pl.edu.agh.game.logic.effects.Effect; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; /** * Created by Admin on 2015-05-10. */ public class GameSettings { private static GameSettings ourInstance = new GameSettings(); private float musicVolume = 0.2f; private float sfxVolume = 0.04f; public Music fireSound = Gdx.audio.newMusic(Gdx.files.internal("fire.mp3")); public Music poisonSound = Gdx.audio.newMusic(Gdx.files.internal("poison.mp3")); public Music fireSoundStill = Gdx.audio.newMusic(Gdx.files.internal("fire2.mp3")); private List<Effect> effectsToUpdate = new Vector<>(); private List<Effect> effectsToDelete = new Vector<>(); private HashSet<Music> musicEffects = new HashSet<>(); public List<Effect> getEffectsToUpdate() { return effectsToUpdate; } public List<Effect> getEffectsToDelete() { return effectsToDelete; } public void setMusicVolume(float musicVolume) { this.musicVolume = musicVolume; } public void setSfxVolume(float musicVolume) { this.musicVolume = musicVolume; } public float getMusicVolume(){ return musicVolume; } public float getSfxVolume(){ return sfxVolume; } public static GameSettings getInstance() { return ourInstance; } public Set<Music> getMusicEffects() { return musicEffects; } private GameSettings() { } }
package com.simple.base.components.nio.framework; import io.netty.channel.Channel; public class Request { private String sessionId; //private String path; //private int commandId; protected String command; protected Object input; private Channel ch; public Object getRequest(Class<?> cls){ return this.input; } public Object getInput(){ return this.input; } public void setInput(Object obj){ this.input = obj; } public String getSession(){ return this.sessionId; } public String getCommand(){ return this.command; } public Channel getChannel(){ return this.ch; } public void setChannel(Channel ch){ this.ch = ch; } public void setCommand(String command){ this.command = command; //this.path = String.valueOf(id); } /*public void setRequestPath(String path){ this.path = path; } public String getRequestPath(){ return this.path; } */ public void setSession(String session){ this.sessionId = session; } }
/** (Statistics: compute mean and standard deviation) In business applications, you are often asked to compute the mean and * standard deviation of data. The mean is simply the average of the numbers. * The standard deviation is a statistic that tells you how tightly all the various data are clustered * around the mean in a set of data. For example, what is the average age of the students in a class? How close are the ages? If all the students are the same age, the deviation is 0. Write a program that prompts the user to enter ten numbers, and displays the mean and standard deviations of these numbers using the following formula:*/ import java.util.Scanner; public class Problem5_45 { public static void main(String[] args) { Scanner input = new Scanner(System.in); double mean, deviation, number; mean = deviation = 0; //Prompt the user to enter ten numbers System.out.print("Enter ten numbers: "); //Compute mean and standard deviation for(int i = 1; i <= 10; i++) { number = input.nextDouble(); mean += number; deviation += Math.pow(number, 2); } deviation = Math.sqrt((deviation - (Math.pow(mean, 2) / 10)) / (10 - 1)); mean /= 10; //Display results System.out.println("The mean is " +mean); System.out.printf("The standard deviation is %.5f", deviation); } }
package com.jayqqaa12.mobilesafe.engine.antivirus; import com.jayqqaa12.abase.core.AbaseEngine; public class AntivirusEngine extends AbaseEngine { }
package com.mysql.cj.protocol.x; import com.google.protobuf.GeneratedMessageV3; import com.google.protobuf.Message; import com.mysql.cj.CharsetMapping; import com.mysql.cj.Constants; import com.mysql.cj.Messages; import com.mysql.cj.Session; import com.mysql.cj.TransactionEventHandler; import com.mysql.cj.conf.HostInfo; import com.mysql.cj.conf.PropertyDefinitions; import com.mysql.cj.conf.PropertyKey; import com.mysql.cj.conf.PropertySet; import com.mysql.cj.conf.RuntimeProperty; import com.mysql.cj.exceptions.AssertionFailedException; import com.mysql.cj.exceptions.CJCommunicationsException; import com.mysql.cj.exceptions.CJConnectionFeatureNotAvailableException; import com.mysql.cj.exceptions.CJOperationNotSupportedException; import com.mysql.cj.exceptions.ConnectionIsClosedException; import com.mysql.cj.exceptions.ExceptionFactory; import com.mysql.cj.exceptions.ExceptionInterceptor; import com.mysql.cj.exceptions.SSLParamsException; import com.mysql.cj.exceptions.WrongArgumentException; import com.mysql.cj.protocol.AbstractProtocol; import com.mysql.cj.protocol.ColumnDefinition; import com.mysql.cj.protocol.ExportControlled; import com.mysql.cj.protocol.Message; import com.mysql.cj.protocol.MessageListener; import com.mysql.cj.protocol.MessageReader; import com.mysql.cj.protocol.MessageSender; import com.mysql.cj.protocol.Protocol; import com.mysql.cj.protocol.ProtocolEntity; import com.mysql.cj.protocol.ProtocolEntityFactory; import com.mysql.cj.protocol.ResultBuilder; import com.mysql.cj.protocol.ResultStreamer; import com.mysql.cj.protocol.Resultset; import com.mysql.cj.protocol.ServerCapabilities; import com.mysql.cj.protocol.ServerSession; import com.mysql.cj.protocol.SocketConnection; import com.mysql.cj.protocol.a.NativeSocketConnection; import com.mysql.cj.result.DefaultColumnDefinition; import com.mysql.cj.result.Field; import com.mysql.cj.result.LongValueFactory; import com.mysql.cj.result.ValueFactory; import com.mysql.cj.util.SequentialIdLease; import com.mysql.cj.util.StringUtils; import com.mysql.cj.x.protobuf.Mysqlx; import com.mysql.cj.x.protobuf.MysqlxConnection; import com.mysql.cj.x.protobuf.MysqlxDatatypes; import com.mysql.cj.x.protobuf.MysqlxNotice; import com.mysql.cj.x.protobuf.MysqlxResultset; import com.mysql.cj.x.protobuf.MysqlxSession; import com.mysql.cj.x.protobuf.MysqlxSql; import com.mysql.cj.xdevapi.PreparableStatement; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.stream.Collectors; public class XProtocol extends AbstractProtocol<XMessage> implements Protocol<XMessage> { private static int RETRY_PREPARE_STATEMENT_COUNTDOWN = 100; private MessageReader<XMessageHeader, XMessage> reader; private MessageSender<XMessage> sender; private Closeable managedResource; private ResultStreamer currentResultStreamer; XServerSession serverSession = null; Boolean useSessionResetKeepOpen = null; public String defaultSchemaName; private Map<String, Object> clientCapabilities = new HashMap<>(); private boolean supportsPreparedStatements = true; private int retryPrepareStatementCountdown = 0; private SequentialIdLease preparedStatementIds = new SequentialIdLease(); private ReferenceQueue<PreparableStatement<?>> preparableStatementRefQueue = new ReferenceQueue<>(); private Map<Integer, PreparableStatement.PreparableStatementFinalizer> preparableStatementFinalizerReferences = new TreeMap<>(); private Map<Class<? extends GeneratedMessageV3>, ProtocolEntityFactory<? extends ProtocolEntity, XMessage>> messageToProtocolEntityFactory = new HashMap<>(); private String currUser; private String currPassword; private String currDatabase; public void init(Session sess, SocketConnection socketConn, PropertySet propSet, TransactionEventHandler trManager) { super.init(sess, socketConn, propSet, trManager); this.messageBuilder = new XMessageBuilder(); this.authProvider = new XAuthenticationProvider(); this.authProvider.init(this, propSet, null); this.useSessionResetKeepOpen = null; this.messageToProtocolEntityFactory.put(MysqlxResultset.ColumnMetaData.class, new FieldFactory("latin1")); this.messageToProtocolEntityFactory.put(MysqlxNotice.Frame.class, new NoticeFactory()); this.messageToProtocolEntityFactory.put(MysqlxResultset.Row.class, new XProtocolRowFactory()); this.messageToProtocolEntityFactory.put(MysqlxResultset.FetchDoneMoreResultsets.class, new FetchDoneMoreResultsFactory()); this.messageToProtocolEntityFactory.put(MysqlxResultset.FetchDone.class, new FetchDoneEntityFactory()); this.messageToProtocolEntityFactory.put(MysqlxSql.StmtExecuteOk.class, new StatementExecuteOkFactory()); this.messageToProtocolEntityFactory.put(Mysqlx.Ok.class, new OkFactory()); } public ServerSession getServerSession() { return this.serverSession; } public void sendCapabilities(Map<String, Object> keyValuePair) { keyValuePair.forEach((k, v) -> ((XServerCapabilities)getServerSession().getCapabilities()).setCapability(k, v)); this.sender.send(((XMessageBuilder)this.messageBuilder).buildCapabilitiesSet(keyValuePair)); readQueryResult(new OkBuilder()); } public void negotiateSSLConnection(int packLength) { if (!ExportControlled.enabled()) throw new CJConnectionFeatureNotAvailableException(); if (!((XServerCapabilities)this.serverSession.getCapabilities()).hasCapability(XServerCapabilities.KEY_TLS)) throw new CJCommunicationsException("A secure connection is required but the server is not configured with SSL."); this.reader.stopAfterNextMessage(); Map<String, Object> tlsCapabilities = new HashMap<>(); tlsCapabilities.put(XServerCapabilities.KEY_TLS, Boolean.valueOf(true)); sendCapabilities(tlsCapabilities); try { this.socketConnection.performTlsHandshake(null); } catch (SSLParamsException|com.mysql.cj.exceptions.FeatureNotAvailableException|IOException e) { throw new CJCommunicationsException(e); } try { if (this.socketConnection.isSynchronous()) { this.sender = new SyncMessageSender(this.socketConnection.getMysqlOutput()); this.reader = new SyncMessageReader(this.socketConnection.getMysqlInput()); } else { ((AsyncMessageSender)this.sender).setChannel(this.socketConnection.getAsynchronousSocketChannel()); this.reader.start(); } } catch (IOException e) { throw new XProtocolError(e.getMessage(), e); } } public void beforeHandshake() { this.serverSession = new XServerSession(); try { if (this.socketConnection.isSynchronous()) { this.sender = new SyncMessageSender(this.socketConnection.getMysqlOutput()); this.reader = new SyncMessageReader(this.socketConnection.getMysqlInput()); this.managedResource = this.socketConnection.getMysqlSocket(); } else { this.sender = new AsyncMessageSender(this.socketConnection.getAsynchronousSocketChannel()); this.reader = new AsyncMessageReader(this.propertySet, this.socketConnection); this.reader.start(); this.managedResource = this.socketConnection.getAsynchronousSocketChannel(); } } catch (IOException e) { throw new XProtocolError(e.getMessage(), e); } this.serverSession.setCapabilities(readServerCapabilities()); String attributes = (String)this.propertySet.getStringProperty(PropertyKey.xdevapiConnectionAttributes).getValue(); if (attributes == null || !attributes.equalsIgnoreCase("false")) { Map<String, String> attMap = getConnectionAttributesMap("true".equalsIgnoreCase(attributes) ? "" : attributes); this.clientCapabilities.put(XServerCapabilities.KEY_SESSION_CONNECT_ATTRS, attMap); } RuntimeProperty<PropertyDefinitions.XdevapiSslMode> xdevapiSslMode = this.propertySet.getEnumProperty(PropertyKey.xdevapiSSLMode); if (xdevapiSslMode.isExplicitlySet()) this.propertySet.getEnumProperty(PropertyKey.sslMode).setValue(PropertyDefinitions.SslMode.valueOf(((PropertyDefinitions.XdevapiSslMode)xdevapiSslMode.getValue()).toString())); RuntimeProperty<String> sslTrustStoreUrl = this.propertySet.getStringProperty(PropertyKey.xdevapiSSLTrustStoreUrl); if (sslTrustStoreUrl.isExplicitlySet()) this.propertySet.getStringProperty(PropertyKey.trustCertificateKeyStoreUrl).setValue(sslTrustStoreUrl.getValue()); RuntimeProperty<String> sslTrustStoreType = this.propertySet.getStringProperty(PropertyKey.xdevapiSSLTrustStoreType); if (sslTrustStoreType.isExplicitlySet()) this.propertySet.getStringProperty(PropertyKey.trustCertificateKeyStoreType).setValue(sslTrustStoreType.getValue()); RuntimeProperty<String> sslTrustStorePassword = this.propertySet.getStringProperty(PropertyKey.xdevapiSSLTrustStorePassword); if (sslTrustStorePassword.isExplicitlySet()) this.propertySet.getStringProperty(PropertyKey.trustCertificateKeyStorePassword).setValue(sslTrustStorePassword.getValue()); RuntimeProperty<PropertyDefinitions.SslMode> sslMode = this.propertySet.getEnumProperty(PropertyKey.sslMode); if (sslMode.getValue() == PropertyDefinitions.SslMode.PREFERRED) sslMode.setValue(PropertyDefinitions.SslMode.REQUIRED); boolean verifyServerCert = (sslMode.getValue() == PropertyDefinitions.SslMode.VERIFY_CA || sslMode.getValue() == PropertyDefinitions.SslMode.VERIFY_IDENTITY); String trustStoreUrl = (String)this.propertySet.getStringProperty(PropertyKey.trustCertificateKeyStoreUrl).getValue(); RuntimeProperty<String> xdevapiTlsVersions = this.propertySet.getStringProperty(PropertyKey.xdevapiTlsVersions); if (xdevapiTlsVersions.isExplicitlySet()) { if (sslMode.getValue() == PropertyDefinitions.SslMode.DISABLED) throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, "Option '" + PropertyKey.xdevapiTlsVersions .getKeyName() + "' can not be specified when SSL connections are disabled."); if (((String)xdevapiTlsVersions.getValue()).trim().isEmpty()) throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, "At least one TLS protocol version must be specified in '" + PropertyKey.xdevapiTlsVersions .getKeyName() + "' list."); String[] tlsVersions = ((String)xdevapiTlsVersions.getValue()).split("\\s*,\\s*"); List<String> tryProtocols = Arrays.asList(tlsVersions); ExportControlled.checkValidProtocols(tryProtocols); this.propertySet.getStringProperty(PropertyKey.enabledTLSProtocols).setValue(xdevapiTlsVersions.getValue()); } RuntimeProperty<String> xdevapiTlsCiphersuites = this.propertySet.getStringProperty(PropertyKey.xdevapiTlsCiphersuites); if (xdevapiTlsCiphersuites.isExplicitlySet()) { if (sslMode.getValue() == PropertyDefinitions.SslMode.DISABLED) throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, "Option '" + PropertyKey.xdevapiTlsCiphersuites .getKeyName() + "' can not be specified when SSL connections are disabled."); this.propertySet.getStringProperty(PropertyKey.enabledSSLCipherSuites).setValue(xdevapiTlsCiphersuites.getValue()); } if (!verifyServerCert && !StringUtils.isNullOrEmpty(trustStoreUrl)) { StringBuilder msg = new StringBuilder("Incompatible security settings. The property '"); msg.append(PropertyKey.xdevapiSSLTrustStoreUrl.getKeyName()).append("' requires '"); msg.append(PropertyKey.xdevapiSSLMode.getKeyName()).append("' as '"); msg.append(PropertyDefinitions.SslMode.VERIFY_CA).append("' or '"); msg.append(PropertyDefinitions.SslMode.VERIFY_IDENTITY).append("'."); throw new CJCommunicationsException(msg.toString()); } if (this.clientCapabilities.size() > 0) try { sendCapabilities(this.clientCapabilities); } catch (XProtocolError e) { if (e.getErrorCode() != 5002 && !e.getMessage().contains(XServerCapabilities.KEY_SESSION_CONNECT_ATTRS)) throw e; this.clientCapabilities.remove(XServerCapabilities.KEY_SESSION_CONNECT_ATTRS); } if (xdevapiSslMode.getValue() != PropertyDefinitions.XdevapiSslMode.DISABLED) negotiateSSLConnection(0); } private Map<String, String> getConnectionAttributesMap(String attStr) { Map<String, String> attMap = new HashMap<>(); if (attStr != null) { if (attStr.startsWith("[") && attStr.endsWith("]")) attStr = attStr.substring(1, attStr.length() - 1); if (!StringUtils.isNullOrEmpty(attStr)) { String[] pairs = attStr.split(","); for (String pair : pairs) { String[] kv = pair.split("="); String key = kv[0].trim(); String value = (kv.length > 1) ? kv[1].trim() : ""; if (key.startsWith("_")) throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("Protocol.WrongAttributeName")); if (attMap.put(key, value) != null) throw (WrongArgumentException)ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("Protocol.DuplicateAttribute", new Object[] { key })); } } } attMap.put("_platform", Constants.OS_ARCH); attMap.put("_os", Constants.OS_NAME + "-" + Constants.OS_VERSION); attMap.put("_client_name", "MySQL Connector/J"); attMap.put("_client_version", "8.0.19"); attMap.put("_client_license", "GPL"); attMap.put("_runtime_version", Constants.JVM_VERSION); attMap.put("_runtime_vendor", Constants.JVM_VENDOR); return attMap; } public XProtocol(String host, int port, String defaultSchema, PropertySet propertySet) { this.currUser = null; this.currPassword = null; this.currDatabase = null; this.defaultSchemaName = defaultSchema; RuntimeProperty<Integer> connectTimeout = propertySet.getIntegerProperty(PropertyKey.connectTimeout); RuntimeProperty<Integer> xdevapiConnectTimeout = propertySet.getIntegerProperty(PropertyKey.xdevapiConnectTimeout); if (xdevapiConnectTimeout.isExplicitlySet() || !connectTimeout.isExplicitlySet()) connectTimeout.setValue(xdevapiConnectTimeout.getValue()); SocketConnection socketConn = ((Boolean)propertySet.getBooleanProperty(PropertyKey.xdevapiUseAsyncProtocol).getValue()).booleanValue() ? new XAsyncSocketConnection() : (SocketConnection)new NativeSocketConnection(); socketConn.connect(host, port, propertySet, null, null, 0); init((Session)null, socketConn, propertySet, (TransactionEventHandler)null); } public XProtocol(HostInfo hostInfo, PropertySet propertySet) { this.currUser = null; this.currPassword = null; this.currDatabase = null; String host = hostInfo.getHost(); if (host == null || StringUtils.isEmptyOrWhitespaceOnly(host)) host = "localhost"; int port = hostInfo.getPort(); if (port < 0) port = 33060; this.defaultSchemaName = hostInfo.getDatabase(); RuntimeProperty<Integer> connectTimeout = propertySet.getIntegerProperty(PropertyKey.connectTimeout); RuntimeProperty<Integer> xdevapiConnectTimeout = propertySet.getIntegerProperty(PropertyKey.xdevapiConnectTimeout); if (xdevapiConnectTimeout.isExplicitlySet() || !connectTimeout.isExplicitlySet()) connectTimeout.setValue(xdevapiConnectTimeout.getValue()); SocketConnection socketConn = ((Boolean)propertySet.getBooleanProperty(PropertyKey.xdevapiUseAsyncProtocol).getValue()).booleanValue() ? new XAsyncSocketConnection() : (SocketConnection)new NativeSocketConnection(); socketConn.connect(host, port, propertySet, null, null, 0); init((Session)null, socketConn, propertySet, (TransactionEventHandler)null); } public void connect(String user, String password, String database) { this.currUser = user; this.currPassword = password; this.currDatabase = database; beforeHandshake(); this.authProvider.connect(null, user, password, database); } public void changeUser(String user, String password, String database) { this.currUser = user; this.currPassword = password; this.currDatabase = database; this.authProvider.changeUser(null, user, password, database); } public void afterHandshake() { initServerSession(); } public void configureTimezone() {} public void initServerSession() { configureTimezone(); send(this.messageBuilder.buildSqlStatement("select @@mysqlx_max_allowed_packet"), 0); ColumnDefinition metadata = readMetadata(); long count = ((Long)(new XProtocolRowInputStream(metadata, this, null)).next().getValue(0, (ValueFactory)new LongValueFactory(this.propertySet))).longValue(); readQueryResult(new StatementExecuteOkBuilder()); setMaxAllowedPacket((int)count); } public void readAuthenticateOk() { try { XMessage mess = (XMessage)this.reader.readMessage(null, 4); if (mess != null && mess.getNotices() != null) for (Notice notice : mess.getNotices()) { if (notice instanceof Notice.XSessionStateChanged) switch (((Notice.XSessionStateChanged)notice).getParamType().intValue()) { case 11: getServerSession().setThreadId(((Notice.XSessionStateChanged)notice).getValue().getVUnsignedInt()); } } } catch (IOException e) { throw new XProtocolError(e.getMessage(), e); } } public byte[] readAuthenticateContinue() { try { MysqlxSession.AuthenticateContinue msg = (MysqlxSession.AuthenticateContinue)((XMessage)this.reader.readMessage(null, 3)).getMessage(); byte[] data = msg.getAuthData().toByteArray(); if (data.length != 20) throw AssertionFailedException.shouldNotHappen("Salt length should be 20, but is " + data.length); return data; } catch (IOException e) { throw new XProtocolError(e.getMessage(), e); } } public boolean hasMoreResults() { try { XMessageHeader header; if ((header = (XMessageHeader)this.reader.readHeader()).getMessageType() == 16) { this.reader.readMessage(null, header); if (((XMessageHeader)this.reader.readHeader()).getMessageType() == 14) return false; return true; } return false; } catch (IOException e) { throw new XProtocolError(e.getMessage(), e); } } public <T extends com.mysql.cj.QueryResult> T readQueryResult(ResultBuilder<T> resultBuilder) { try { boolean done = false; while (!done) { XMessageHeader header = (XMessageHeader)this.reader.readHeader(); XMessage mess = (XMessage)this.reader.readMessage(null, header); Class<? extends GeneratedMessageV3> msgClass = (Class)mess.getMessage().getClass(); if (Mysqlx.Error.class.equals(msgClass)) throw new XProtocolError((Mysqlx.Error)Mysqlx.Error.class.cast(mess.getMessage())); if (!this.messageToProtocolEntityFactory.containsKey(msgClass)) throw new WrongArgumentException("Unhandled msg class (" + msgClass + ") + msg=" + mess.getMessage()); List<Notice> notices; if ((notices = mess.getNotices()) != null) notices.stream().forEach(resultBuilder::addProtocolEntity); done = resultBuilder.addProtocolEntity((ProtocolEntity)((ProtocolEntityFactory)this.messageToProtocolEntityFactory.get(msgClass)).createFromMessage(mess)); } return (T)resultBuilder.build(); } catch (IOException e) { throw new XProtocolError(e.getMessage(), e); } } public boolean hasResults() { try { return (((XMessageHeader)this.reader.readHeader()).getMessageType() == 12); } catch (IOException e) { throw new XProtocolError(e.getMessage(), e); } } public void drainRows() { try { XMessageHeader header; while ((header = (XMessageHeader)this.reader.readHeader()).getMessageType() == 13) this.reader.readMessage(null, header); } catch (XProtocolError e) { this.currentResultStreamer = null; throw e; } catch (IOException e) { this.currentResultStreamer = null; throw new XProtocolError(e.getMessage(), e); } } public static Map<String, Integer> COLLATION_NAME_TO_COLLATION_INDEX = new HashMap<>(); static { for (int i = 0; i < CharsetMapping.COLLATION_INDEX_TO_COLLATION_NAME.length; i++) COLLATION_NAME_TO_COLLATION_INDEX.put(CharsetMapping.COLLATION_INDEX_TO_COLLATION_NAME[i], Integer.valueOf(i)); } public ColumnDefinition readMetadata() { try { List<MysqlxResultset.ColumnMetaData> fromServer = new LinkedList<>(); while (true) { fromServer.add((MysqlxResultset.ColumnMetaData)((XMessage)this.reader.readMessage(null, 12)).getMessage()); if (((XMessageHeader)this.reader.readHeader()).getMessageType() != 12) { ArrayList<Field> metadata = new ArrayList<>(fromServer.size()); ProtocolEntityFactory<Field, XMessage> fieldFactory = (ProtocolEntityFactory<Field, XMessage>)this.messageToProtocolEntityFactory.get(MysqlxResultset.ColumnMetaData.class); fromServer.forEach(col -> metadata.add(fieldFactory.createFromMessage(new XMessage((Message)col)))); return (ColumnDefinition)new DefaultColumnDefinition(metadata.<Field>toArray(new Field[0])); } } } catch (IOException e) { throw new XProtocolError(e.getMessage(), e); } } public ColumnDefinition readMetadata(Field f, Consumer<Notice> noticeConsumer) { try { List<MysqlxResultset.ColumnMetaData> fromServer = new LinkedList<>(); while (((XMessageHeader)this.reader.readHeader()).getMessageType() == 12) { XMessage mess = (XMessage)this.reader.readMessage(null, 12); List<Notice> notices; if (noticeConsumer != null && (notices = mess.getNotices()) != null) notices.stream().forEach(noticeConsumer::accept); fromServer.add((MysqlxResultset.ColumnMetaData)mess.getMessage()); } ArrayList<Field> metadata = new ArrayList<>(fromServer.size()); metadata.add(f); ProtocolEntityFactory<Field, XMessage> fieldFactory = (ProtocolEntityFactory<Field, XMessage>)this.messageToProtocolEntityFactory.get(MysqlxResultset.ColumnMetaData.class); fromServer.forEach(col -> metadata.add(fieldFactory.createFromMessage(new XMessage((Message)col)))); return (ColumnDefinition)new DefaultColumnDefinition(metadata.<Field>toArray(new Field[0])); } catch (IOException e) { throw new XProtocolError(e.getMessage(), e); } } public XProtocolRow readRowOrNull(ColumnDefinition metadata, Consumer<Notice> noticeConsumer) { try { XMessageHeader header; if ((header = (XMessageHeader)this.reader.readHeader()).getMessageType() == 13) { XMessage mess = (XMessage)this.reader.readMessage(null, header); List<Notice> notices; if (noticeConsumer != null && (notices = mess.getNotices()) != null) notices.stream().forEach(noticeConsumer::accept); XProtocolRow res = new XProtocolRow((MysqlxResultset.Row)mess.getMessage()); res.setMetadata(metadata); return res; } return null; } catch (XProtocolError e) { this.currentResultStreamer = null; throw e; } catch (IOException e) { this.currentResultStreamer = null; throw new XProtocolError(e.getMessage(), e); } } public boolean supportsPreparedStatements() { return this.supportsPreparedStatements; } public boolean readyForPreparingStatements() { if (this.retryPrepareStatementCountdown == 0) return true; this.retryPrepareStatementCountdown--; return false; } public int getNewPreparedStatementId(PreparableStatement<?> preparableStatement) { if (!this.supportsPreparedStatements) throw new XProtocolError("The connected MySQL server does not support prepared statements."); int preparedStatementId = this.preparedStatementIds.allocateSequentialId(); this.preparableStatementFinalizerReferences.put(Integer.valueOf(preparedStatementId), new PreparableStatement.PreparableStatementFinalizer(preparableStatement, this.preparableStatementRefQueue, preparedStatementId)); return preparedStatementId; } public void freePreparedStatementId(int preparedStatementId) { if (!this.supportsPreparedStatements) throw new XProtocolError("The connected MySQL server does not support prepared statements."); this.preparedStatementIds.releaseSequentialId(preparedStatementId); this.preparableStatementFinalizerReferences.remove(Integer.valueOf(preparedStatementId)); } public boolean failedPreparingStatement(int preparedStatementId, XProtocolError e) { freePreparedStatementId(preparedStatementId); if (e.getErrorCode() == 1461) { this.retryPrepareStatementCountdown = RETRY_PREPARE_STATEMENT_COUNTDOWN; return true; } if (e.getErrorCode() == 1047 && this.preparableStatementFinalizerReferences.isEmpty()) { this.supportsPreparedStatements = false; this.retryPrepareStatementCountdown = 0; this.preparedStatementIds = null; this.preparableStatementRefQueue = null; this.preparableStatementFinalizerReferences = null; return true; } return false; } protected void newCommand() { if (this.currentResultStreamer != null) try { this.currentResultStreamer.finishStreaming(); } finally { this.currentResultStreamer = null; } if (this.supportsPreparedStatements) { Reference<? extends PreparableStatement<?>> ref; while ((ref = this.preparableStatementRefQueue.poll()) != null) { PreparableStatement.PreparableStatementFinalizer psf = (PreparableStatement.PreparableStatementFinalizer)ref; psf.clear(); try { this.sender.send(((XMessageBuilder)this.messageBuilder).buildPrepareDeallocate(psf.getPreparedStatementId())); readQueryResult(new OkBuilder()); } catch (XProtocolError e) { if (e.getErrorCode() != 5110) throw e; } finally { freePreparedStatementId(psf.getPreparedStatementId()); } } } } public <M extends Message, R extends com.mysql.cj.QueryResult> R query(M message, ResultBuilder<R> resultBuilder) { send((Message)message, 0); R res = readQueryResult(resultBuilder); if (ResultStreamer.class.isAssignableFrom(res.getClass())) this.currentResultStreamer = (ResultStreamer)res; return res; } public <M extends Message, R extends com.mysql.cj.QueryResult> CompletableFuture<R> queryAsync(M message, ResultBuilder<R> resultBuilder) { newCommand(); CompletableFuture<R> f = new CompletableFuture<>(); MessageListener<XMessage> l = new ResultMessageListener<>(this.messageToProtocolEntityFactory, resultBuilder, f); this.sender.send((XMessage)message, f, () -> this.reader.pushMessageListener(l)); return f; } public boolean isOpen() { return (this.managedResource != null); } public void close() throws IOException { try { send(this.messageBuilder.buildClose(), 0); readQueryResult(new OkBuilder()); } catch (Exception exception) { try { if (this.managedResource == null) throw new ConnectionIsClosedException(); this.managedResource.close(); this.managedResource = null; } catch (IOException ex) { throw new CJCommunicationsException(ex); } } finally { try { if (this.managedResource == null) throw new ConnectionIsClosedException(); this.managedResource.close(); this.managedResource = null; } catch (IOException ex) { throw new CJCommunicationsException(ex); } } } public boolean isSqlResultPending() { try { XMessageHeader header; switch ((header = (XMessageHeader)this.reader.readHeader()).getMessageType()) { case 12: return true; case 16: this.reader.readMessage(null, header); break; } return false; } catch (IOException e) { throw new XProtocolError(e.getMessage(), e); } } public void setMaxAllowedPacket(int maxAllowedPacket) { this.sender.setMaxAllowedPacket(maxAllowedPacket); } public void send(Message message, int packetLen) { newCommand(); this.sender.send(message); } public ServerCapabilities readServerCapabilities() { try { this.sender.send(((XMessageBuilder)this.messageBuilder).buildCapabilitiesGet()); return new XServerCapabilities((Map<String, MysqlxDatatypes.Any>)((MysqlxConnection.Capabilities)((XMessage)this.reader.readMessage(null, 2)).getMessage()) .getCapabilitiesList().stream().collect(Collectors.toMap(MysqlxConnection.Capability::getName, MysqlxConnection.Capability::getValue))); } catch (IOException|AssertionFailedException e) { throw new XProtocolError(e.getMessage(), e); } } public void reset() { newCommand(); this.propertySet.reset(); if (this.useSessionResetKeepOpen == null) try { send(((XMessageBuilder)this.messageBuilder).buildExpectOpen(), 0); readQueryResult(new OkBuilder()); this.useSessionResetKeepOpen = Boolean.valueOf(true); } catch (XProtocolError e) { if (e.getErrorCode() != 5168 && e.getErrorCode() != 5160) throw e; this.useSessionResetKeepOpen = Boolean.valueOf(false); } if (this.useSessionResetKeepOpen.booleanValue()) { send(((XMessageBuilder)this.messageBuilder).buildSessionResetKeepOpen(), 0); readQueryResult(new OkBuilder()); } else { send(((XMessageBuilder)this.messageBuilder).buildSessionResetAndClose(), 0); readQueryResult(new OkBuilder()); if (this.clientCapabilities.containsKey(XServerCapabilities.KEY_SESSION_CONNECT_ATTRS)) { Map<String, Object> reducedClientCapabilities = new HashMap<>(); reducedClientCapabilities.put(XServerCapabilities.KEY_SESSION_CONNECT_ATTRS, this.clientCapabilities .get(XServerCapabilities.KEY_SESSION_CONNECT_ATTRS)); if (reducedClientCapabilities.size() > 0) sendCapabilities(reducedClientCapabilities); } this.authProvider.changeUser(null, this.currUser, this.currPassword, this.currDatabase); } if (this.supportsPreparedStatements) { this.retryPrepareStatementCountdown = 0; this.preparedStatementIds = new SequentialIdLease(); this.preparableStatementRefQueue = new ReferenceQueue<>(); this.preparableStatementFinalizerReferences = new TreeMap<>(); } } public ExceptionInterceptor getExceptionInterceptor() { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public void changeDatabase(String database) { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public String getPasswordCharacterEncoding() { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public boolean versionMeetsMinimum(int major, int minor, int subminor) { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public XMessage readMessage(XMessage reuse) { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public XMessage checkErrorMessage() { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public XMessage sendCommand(Message queryPacket, boolean skipCheck, int timeoutMillis) { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public <T extends ProtocolEntity> T read(Class<T> requiredClass, ProtocolEntityFactory<T, XMessage> protocolEntityFactory) throws IOException { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public <T extends ProtocolEntity> T read(Class<Resultset> requiredClass, int maxRows, boolean streamResults, XMessage resultPacket, boolean isBinaryEncoded, ColumnDefinition metadata, ProtocolEntityFactory<T, XMessage> protocolEntityFactory) throws IOException { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public void setLocalInfileInputStream(InputStream stream) { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public InputStream getLocalInfileInputStream() { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public String getQueryComment() { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } public void setQueryComment(String comment) { throw (CJOperationNotSupportedException)ExceptionFactory.createException(CJOperationNotSupportedException.class, "Not supported"); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\protocol\x\XProtocol.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
/** * */ package net.miguel; /** * @author Mikel * */ public class SoldatEspecial extends Soldat { /** * numero deu. */ private final int cinc = 5; /** * constructor. * @param im imatge d'aquest soldat. */ public SoldatEspecial(final String im) { super(im); setVides(cinc); setForลกa(cinc); } }
/* * 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 caja; /** * * @author Usuario */ public class Caja { private int pesoMaximo; private int nPieza5=0; private int nPieza3=0; public Caja(int pesoMaximo,int nPieza5, int nPieza3){ this.pesoMaximo=pesoMaximo; } public int calcularPeso(){ int peso= nPieza5*5+nPieza3*3; return peso; } boolean insertar (int kilos, int numP){ boolean exito=false; if(kilos*numP<= pesoMaximo){ if(kilos==5) nPieza5+=numP; else nPieza3+=numP; exito=true; System.out.println("Insercion con exito"); } if (exito==false)System.out.println("Insercion fallida:no se realizarรก ningun cambio"); return exito; } boolean eliminar (int kilos, int numP){ boolean exito=false; if(calcularPeso()-(kilos*numP)>0){ if(kilos==5) nPieza5-=numP; else nPieza3-=numP; exito=true; System.out.println("Insercion con exito"); } if (exito==false)System.out.println("Insercion fallida:no se realizarรก ningun cambio"); return exito; } }
/* * 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 es.usc.grei.aos.ejercicio2.ws; import es.usc.grei.aos.ejercicio2.dao.CdDAO; import es.usc.grei.aos.ejercicio2.dao.ClienteDAO; import es.usc.grei.aos.ejercicio2.model.Cd; import es.usc.grei.aos.ejercicio2.model.Cliente; import es.usc.grei.aos.ejercicio2.model.Page; import es.usc.grei.aos.ejercicio2.model.WSResult; import java.net.URI; import java.util.ArrayList; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; /** * * @author Cristina */ @Path("/") public class CdResource { @GET @Path("cd/{codigo}") @Produces(MediaType.APPLICATION_JSON) public Cd getCd(@PathParam("codigo") Long codigo) { CdDAO dao = new CdDAO(); Cd cd = dao.getCd(codigo); if (cd == null) { throw new NotFoundException(); } return cd; } @GET @Path("cds") @Produces(MediaType.APPLICATION_JSON) public Page getCDs(@QueryParam("interprete") String interprete, @DefaultValue("0") @QueryParam("pageNumber") int pageNumber, @DefaultValue("5") @QueryParam("pageSize") int pageSize) { Page page = new Page(); CdDAO dao = new CdDAO(); if (!"".equals(interprete)) { page = dao.findCdByArtist(interprete, pageNumber, pageSize); } else { page = dao.getAll(pageNumber, pageSize); } return page; } @POST @Path("cd") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createCD(@Context UriInfo uriInfo, Cd cd) { CdDAO dao = new CdDAO(); try { dao.create(cd); return Response.created(URI.create(uriInfo.getAbsolutePath().toString() + "/" + cd.getCodigo())).entity(new WSResult(true)).build(); } catch (Exception e) { return Response.status(Response.Status.CONFLICT).entity(new WSResult(true)).build(); } } @PUT @Path("cd") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateCD(@Context UriInfo uriInfo, Cd cd) { CdDAO dao = new CdDAO(); try { getCd(cd.getCodigo()); cd = dao.update(cd); return Response.ok().entity(new WSResult(true)).build(); } catch (Exception e) { throw new NotFoundException(); } } @DELETE @Path("cd/{codigo}") public Response deleteCD(@PathParam("codigo") Long codigo) { CdDAO dao = new CdDAO(); try { dao.delete(codigo); return Response.noContent().build(); } catch (Exception e) { return Response.status(Response.Status.NOT_FOUND).build(); } } @DELETE @Path("cds") public Response deleteCDs() { CdDAO dao = new CdDAO(); try { dao.deleteAll(); return Response.noContent().build(); } catch (Exception e) { throw new NotFoundException(); } } }
package com.spbsu.flamestream.example.bl.index.validators; import com.spbsu.flamestream.example.bl.index.InvertedIndexValidator; import com.spbsu.flamestream.example.bl.index.model.WikipediaPage; import com.spbsu.flamestream.example.bl.index.model.WordBase; import com.spbsu.flamestream.example.bl.index.model.WordIndexAdd; import com.spbsu.flamestream.example.bl.index.model.WordIndexRemove; import com.spbsu.flamestream.example.bl.index.utils.IndexItemInLong; import com.spbsu.flamestream.example.bl.index.utils.WikipeadiaInput; import org.testng.Assert; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * User: Artem * Date: 19.12.2017 */ public class SmallDumpValidator extends InvertedIndexValidator.Stub { @Override public Stream<WikipediaPage> input() { return WikipeadiaInput.dumpStreamFromResources("wikipedia/test_index_small_dump.xml"); } @Override public void assertCorrect(Stream<WordBase> output) { final List<WordBase> outputList = new ArrayList<>(); output.forEach(outputList::add); Assert.assertEquals(outputList.size(), 3481); { //assertions for word "isbn" final String isbn = stem("isbn"); Assert.assertTrue(outputList.stream() .filter(wordContainer -> isbn.equals(wordContainer.word())) .filter(wordContainer -> wordContainer instanceof WordIndexAdd) .anyMatch(indexAdd -> Arrays.equals(((WordIndexAdd) indexAdd).positions(), new long[]{ IndexItemInLong.createPagePosition(7, 2534, 1), IndexItemInLong.createPagePosition(7, 2561, 1) }))); Assert.assertTrue(outputList.stream() .filter(wordContainer -> isbn.equals(wordContainer.word())) .filter(wordContainer -> wordContainer instanceof WordIndexRemove) .allMatch(indexRemove -> ((WordIndexRemove) indexRemove).start() == IndexItemInLong.createPagePosition(7, 2534, 1) && ((WordIndexRemove) indexRemove).range() == 2)); Assert.assertTrue(outputList.stream() .filter(wordContainer -> isbn.equals(wordContainer.word())) .filter(wordContainer -> wordContainer instanceof WordIndexAdd) .anyMatch(indexAdd -> Arrays.equals(((WordIndexAdd) indexAdd).positions(), new long[]{ IndexItemInLong.createPagePosition(7, 2561, 2) }))); } { //assertions for word "ะฒัั‚ะฐะฒะบะฐ" final String vstavka = stem("ะฒัั‚ะฐะฒะบะฐ"); Assert.assertTrue(outputList.stream() .filter(wordContainer -> vstavka.equals(wordContainer.word())) .filter(wordContainer -> wordContainer instanceof WordIndexAdd) .allMatch(indexAdd -> Arrays.equals(((WordIndexAdd) indexAdd).positions(), new long[]{ IndexItemInLong.createPagePosition(7, 2515, 2) }))); Assert.assertTrue(outputList.stream() .filter(wordContainer -> vstavka.equals(wordContainer.word())) .noneMatch(wordContainer -> wordContainer instanceof WordIndexRemove)); } { //assertions for word "ัะนะดะธะฝั‚ะฐั" final String eidintas = stem("ัะนะดะธะฝั‚ะฐั"); Assert.assertTrue(outputList.stream() .filter(wordContainer -> eidintas.equals(wordContainer.word())) .filter(wordContainer -> wordContainer instanceof WordIndexAdd) .anyMatch(indexAdd -> Arrays.equals(((WordIndexAdd) indexAdd).positions(), new long[]{ IndexItemInLong.createPagePosition(7, 2516, 1) }))); Assert.assertTrue(outputList.stream() .filter(wordContainer -> eidintas.equals(wordContainer.word())) .filter(wordContainer -> wordContainer instanceof WordIndexRemove) .allMatch(indexRemove -> ((WordIndexRemove) indexRemove).start() == IndexItemInLong.createPagePosition(7, 2516, 1) && ((WordIndexRemove) indexRemove).range() == 1)); Assert.assertTrue(outputList.stream() .filter(wordContainer -> eidintas.equals(wordContainer.word())) .filter(wordContainer -> wordContainer instanceof WordIndexAdd) .anyMatch(indexAdd -> Arrays.equals(((WordIndexAdd) indexAdd).positions(), new long[]{ IndexItemInLong.createPagePosition(7, 2517, 2) }))); } } @Override public int expectedOutputSize() { return 3481; //experimentally computed } }
package com.example.photorecognition.uploadphoto.ui.dashboard; public class message { private String title; private String time; public message(String title,String time){ this.title=title; this.time=time; } public String getTitle(){ return title; } public String getTime(){ return time; } }
package com.scs.awt; public class PointF { public float x, y; public PointF() { this(0, 0); } public PointF(float x, float y) { this.x = x; this.y = y; } public float length() { return (float)Math.sqrt(x * x + y * y); } public void normalizeLocal() { float len = length(); if (len != 0) { x /= len; y /= len; } } }
package com.revolut.service; import com.revolut.web.dto.AccountDTO; import com.revolut.web.dto.TransactionResultDTO; import javax.validation.constraints.NotNull; import java.math.BigDecimal; public interface AccountService { /** * Create new account * @param account * @return created Account */ AccountDTO createAccount(@NotNull AccountDTO account); /** * Delete account * @param accountId account identifier * @throws com.revolut.service.exception.AccountNotFoundException * @return deleted account or <b>null</b> */ AccountDTO deleteAccount(@NotNull Long accountId); /** * Find account by id * @param accountId * @throws com.revolut.service.exception.AccountNotFoundException * @return */ AccountDTO findAccount(@NotNull Long accountId); /** * Transfer money between accounts * @param creditAccountId accountId to withdraw money * @param debitAccountId accountId to add money * @param amount amount * @throws com.revolut.service.exception.AccountNotFoundException * @throws com.revolut.service.exception.AccountLockedException * @throws com.revolut.service.exception.InsufficientFundsAccountException * @return result of transaction */ TransactionResultDTO makeTransaction(Long creditAccountId, Long debitAccountId, BigDecimal amount); }
module Fourth { }
package datastructure; import org.junit.Test; import static org.junit.Assert.*; /** * Created by zhoubo on 2017/5/16. */ public class MatrixTest { @Test public void multiply() throws Exception { int[][] a = new int[][] {{1, 1, 1}, {2, 2, 2,}, {3, 3, 3}, {4, 4, 4}}; int[][] b = new int[][] {{1, 1, 1, 1,}, {2, 2, 2, 2}, {3, 3, 3, 3}}; Matrix matrix = new Matrix(); int[][] c = matrix.multiply(a, b); for (int i = 0; i < c.length; i++) { for (int j = 0; j < c[i].length; j++) { System.out.print(c[i][j] + " "); } System.out.println(); } } }
package com.handsome.qhb.bean; import java.io.Serializable; /** * Created by zhang on 2016/3/3. */ public class Product implements Serializable { private int pid; private String pname; private float price; private String introduce; private int sortId; private String picture; private String flag; private int num; public int getPid() { return pid; } public String getPname() { return pname; } public float getPrice() { return price; } public String getIntroduce() { return introduce; } public int getSortId() { return sortId; } public String getPicture() { return picture; } public String getFlag() { return flag; } public void setPid(int pid) { this.pid = pid; } public void setPname(String pname) { this.pname = pname; } public void setPrice(float price) { this.price = price; } public void setIntroduce(String introduce) { this.introduce = introduce; } public void setSortId(int sortId) { this.sortId = sortId; } public void setPicture(String picture) { this.picture = picture; } public void setFlag(String flag) { this.flag = flag; } public Product(){ } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public Product(int pid,String pname,float price,String introduce,int sortId,String picture,String flag ){ this.pid = pid; this.pname = pname; this.price = price; this.introduce = introduce; this.sortId = sortId; this.picture = picture; this.flag = flag; } @Override public String toString() { return "Product{" + "pid=" + pid + ", pname='" + pname + '\'' + ", price=" + price + ", introduce='" + introduce + '\'' + ", sortId=" + sortId + ", picture='" + picture + '\'' + ", flag='" + flag + '\'' + ", num=" + num + '}'; } }
package com.tencent.d.b.f; import android.content.Context; import com.tencent.d.b.c.a; import com.tencent.d.b.c.b; public class b$a { public b vml = new b((byte) 0); public final b$a Hq(int i) { this.vml.fdx = i; return this; } public final b$a acG(String str) { this.vml.pIu = str; return this; } public final b$a hK(Context context) { this.vml.mContext = context; return this; } public final b$a a(a aVar) { this.vml.jgQ = aVar; return this; } public final b$a a(b bVar) { this.vml.vmk = bVar; return this; } }
package com.vacay.vacayandroid; public class Constants { public static final String EVENT_NAME = "EVENT_NAME"; public static final String EVENT_PRICE = "EVENT_PRICE"; public static final String EVENT_DESCRIPTION = "EVENT_DESCRIPTION"; public static final String EVENT_CITY = "EVENT_CITY"; public static final String EVENT_WEBSITE = "EVENT_WEBSITE"; public static final String EVENT_IMAGE = "EVENT_IMAGE"; public static final String EVENT_ICON = "EVENT_ICON"; public static final String LA = "Los Angeles"; public static final String NY = "New York City"; public static final String SF = "San Francisco"; public static final String CITY = "CITY"; public static final String USE_PRICE = "USE_PRICE"; public static final String CHEAP = "CHEAP"; public static final String MEDIUM = "MEDIUM"; public static final String EXPENSIVE = "EXPENSIVE"; }
package tools.controller; import java.util.List; import java.util.ArrayList; import tools.model.Kahoot; import tools.view.PopupDisplay; public class Controller { private List<Kahoot> myKahoots; private PopupDisplay popup; public Controller() { myKahoots = new ArrayList<Kahoot>(); popup = new PopupDisplay(); } public void start() { Kahoot myFirstKahoot = new Kahoot(); myKahoots.add(myFirstKahoot); fillTheList(); showTheList(); } private void fillTheList() { Kahoot tenwaystoDie = new Kahoot("Ryan", 10, "The Ten Ways to Die"); Kahoot hurtMe = new Kahoot("Billy", 15, "HurtMe"); myKahoots.add(tenwaystoDie); myKahoots.add(hurtMe); } private void showTheList() { String currentCreator = ""; for (int index = 0; index < myKahoots.size();index += 1) { currentCreator = myKahoots.get(index).getCreator(); Kahoot currentKahoot = myKahoots.get(index); String creator = currentKahoot.getCreator(); popup.displayText(myKahoots.get(index).toString()); if (currentCreator.equals("nobody")) { for (int loop = 0; loop < 5; loop+= 1) { popup.displayText("wow nobody does a lot"); } } } for (int currentLetterIndex = 0; currentLetterIndex < currentCreator.length(); currentLetterIndex +=1) { popup.displayText(currentCreator.substring(currentLetterIndex, currentLetterIndex + 1)); } String topic = currentKahoot.getTopic(); for (int letter = currentKahoot.getTopic().length() - 1; letter >= 0 ; letter -= 1 ) { popup.displayText(topic.substring(letter, letter + 1)); } } private void changeTheList() { popup.displayText("Thee current list size is: " + myKahoots.size()); Kahoot removed = myKahoots.remove(3); popup.displayText(" I remove the kahoot by " + removed.getCreator()); popup.displayText("The list now has: " + myKahoots.size() + "items inside."); myKahoots.add(0,removed); popup.displayText("The list is still: " + myKahoots.size() + " items big."); removed = myKahoots.set(2, new Kahoot()); popup.displayText("The kahoot by" + removed.getCreator() + " was replaced with on by: " + myKahoots.get(2).getCreator()); } private void BurnTheList() { popup.displayText("Lets list the world: " + myKahoots.size()); Kahoot removed = myKahoots.remove(0); popup.displayText("Waiting is fun..." + removed.getCreator()); } public PopupDisplay getPopup() { return popup; } public ArrayList<Kahoot> getMyKahoot() { return (ArrayList<Kahoot>) myKahoots; } public int finndMax(ArrayList<List>myList) { int max = 0; for ( int index = 0; index < myList.size(); index ++) { if (myList.get(index).length() < min) { min = myList.get(index).length(); } } return min; } }
package salah.zakatApp; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import salah.zakatApp.numeroraire.MoneyZakatPanel; public class Main { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setTitle("Test version"); frame.setSize(900,600); //setBounds(100, 80, 900, 600); //setExtendedState(JFrame.MAXIMIZED_BOTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setIconImage(new ImageIcon("images/zakat.png").getImage()); JPanel mainPanel = new JPanel(); mainPanel.setLayout(null); frame.setContentPane(mainPanel); frame.setVisible(true); // CALL THE FIRST PANEL : new FirstPanel(frame, mainPanel); } }
package co.nos.noswallet.base; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.disposables.SerialDisposable; abstract public class BasePresenter<View extends BaseView> { private CompositeDisposable compositeDisposable = new CompositeDisposable(); private SerialDisposable serialDisposable = new SerialDisposable(); protected View view; public void attachView(View view) { this.view = view; } public void onDestroy() { compositeDisposable.clear(); } public void addDisposable(Disposable disposable) { compositeDisposable.add(disposable); } public void setDisposable(Disposable disposable) { serialDisposable.set(disposable); } public void cancelSerialDisposable() { serialDisposable.dispose(); } }
package fr.lteconsulting.training.moviedb.servlet; import fr.lteconsulting.training.moviedb.ejb.GestionFabricants; import fr.lteconsulting.training.moviedb.model.Fabricant; import fr.lteconsulting.training.moviedb.outil.Session; import fr.lteconsulting.training.moviedb.outil.Vues; import javax.ejb.EJB; 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.util.HashMap; import java.util.List; import java.util.Map; @WebServlet("/fabricants") public class FabricantsServlet extends HttpServlet { @EJB private GestionFabricants gestionFabricants; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<Fabricant> fabricants = gestionFabricants.findAll(); Map<Integer, Long> nbProduitsParFabricant = new HashMap<>(); for (Fabricant fabricant : fabricants) { nbProduitsParFabricant.put(fabricant.getId(), gestionFabricants.getNbProduitParFabricantId(fabricant.getId())); } Vues.afficherFabricants(req, resp, fabricants, nbProduitsParFabricant); } }
package pl.rogalik.client.controller.game; import pl.rogalik.client.MainContext; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.stage.Stage; public class GameOverController { @FXML private Label message; @FXML private Button menu; @FXML private Button login; private Stage dialogStage; private boolean isStillPlaying; @FXML private void initialize() { menu.defaultButtonProperty().bind(menu.focusedProperty()); login.defaultButtonProperty().bind(login.focusedProperty()); this.message.setText(MainContext.getContext().getChosenHero().getName() + " zostaล‚ pokonany!"); login.setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { isStillPlaying = false; this.dialogStage.hide(); } }); menu.setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { isStillPlaying = true; this.dialogStage.hide(); } }); } public void setDialogStage(Stage dialogStage) { this.dialogStage = dialogStage; } boolean getIsStillPlaying() {return isStillPlaying; } }
package com.example.crypsis.customkeyboard; import android.annotation.TargetApi; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.inputmethodservice.InputMethodService; import android.inputmethodservice.Keyboard; import android.inputmethodservice.KeyboardView; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.provider.Settings; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import com.example.crypsis.customkeyboard.presenter.SearchPresenter; import com.example.crypsis.customkeyboard.presenter.SearchPresenterImpl; import com.example.crypsis.customkeyboard.retrofit.SearchInteractorImpl; import com.example.crypsis.customkeyboard.retrofit.SearchModel; import com.example.crypsis.customkeyboard.retrofit.SearchService; import com.jakewharton.rxbinding.widget.RxTextView; import com.jakewharton.rxbinding.widget.TextViewTextChangeEvent; import com.squareup.picasso.Picasso; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import butterknife.Bind; import butterknife.ButterKnife; import rx.Observer; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.subscriptions.CompositeSubscription; import timber.log.Timber; /** * Created by crypsis on 16/11/16. */ public class SimpleIME extends InputMethodService implements KeyboardView.OnKeyboardActionListener, RecyclerAdapter.RecyclerAdapterListener, SearchView { @Bind(R.id.search_layout) LinearLayout searchLayout; @Bind(R.id.searchProgressBar) ProgressBar mProgressBar; @Bind(R.id.search) EditText searchText; @Bind(R.id.keyboard) KeyboardView kv; private Keyboard keyboard; @Bind(R.id.searchResultLayout) RelativeLayout mSearchResultLayout; @Bind(R.id.recyclerview) RecyclerView myList; SearchPresenter mSearchPresenter; List<SearchModel> mSearchModelList; CompositeSubscription mCompositeSubscription; private boolean search = false; private boolean caps = false; View view; RecyclerAdapter recyclerAdapter; private Subscription _subscription; @Override public View onCreateInputView() { view = getLayoutInflater().inflate(R.layout.search_layout,null); ButterKnife.bind(this,view); myList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); mSearchModelList = new ArrayList<>(); recyclerAdapter = new RecyclerAdapter(this); myList.setAdapter(recyclerAdapter); /*searchText.addTextChangedListener(this);*/ mSearchPresenter = new SearchPresenterImpl(this, new SearchInteractorImpl(SearchService.createSearchService())); subscribeDebounce(); kv = (KeyboardView) view.findViewById(R.id.keyboard); keyboard = new Keyboard(this, R.xml.qwerty); kv.setKeyboard(keyboard); kv.setOnKeyboardActionListener(this); return view; } boolean isNotNullOrEmpty(String string){ if(string!=null && string.length()>0) { return true; } else return false; } void subscribeDebounce(){ mCompositeSubscription = new CompositeSubscription(); _subscription = RxTextView.textChangeEvents(searchText) .debounce(1000, TimeUnit.MILLISECONDS)// default Scheduler is Computation .filter(changes -> isNotNullOrEmpty(searchText.getText().toString())) .observeOn(AndroidSchedulers.mainThread()) .subscribe(_getSearchObserver()); mCompositeSubscription.add(_subscription); // adding debounce subscription } @Override public void onKey(int primaryCode, int[] keyCodes) { InputConnection ic = getCurrentInputConnection(); playClick(primaryCode); if(search){ switch(primaryCode){ case Keyboard.KEYCODE_DELETE : int length = searchText.getText().length(); if (length > 0) { searchText.getText().delete(length - 1, length); } break; case Keyboard.KEYCODE_SHIFT: caps = !caps; keyboard.setShifted(caps); kv.invalidateAllKeys(); break; case Keyboard.KEYCODE_DONE: /*ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));*/ break; case Keyboard.KEYCODE_MODE_CHANGE: InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (mgr != null) { mgr.showInputMethodPicker(); } break; default: if(primaryCode==-3){ search = !search; searchLayout.setVisibility(View.GONE); mSearchResultLayout.setVisibility(View.GONE); searchText.setText(null); myList.setVisibility(View.GONE); mCompositeSubscription.unsubscribe(); List<Keyboard.Key> keys = keyboard.getKeys(); for (Keyboard.Key key : keys) { if (key.codes[0] == -3) { Log.e("hello", String.valueOf(key.codes[0])); key.icon = getResources().getDrawable(android.R.drawable.ic_menu_search); } } kv.invalidateAllKeys(); }else{ char code = (char)primaryCode; if(Character.isLetter(code) && caps){ code = Character.toUpperCase(code); } /* ic.commitText(String.valueOf(code),1);*/ searchText.append(String.valueOf(code)); } } }else{ switch(primaryCode){ case Keyboard.KEYCODE_DELETE : ic.deleteSurroundingText(1, 0); break; case Keyboard.KEYCODE_SHIFT: caps = !caps; keyboard.setShifted(caps); kv.invalidateAllKeys(); break; case Keyboard.KEYCODE_DONE: ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)); break; case Keyboard.KEYCODE_MODE_CHANGE: InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (mgr != null) { mgr.showInputMethodPicker(); } break; default: if(primaryCode==-3){ search = !search; searchLayout.setVisibility(View.VISIBLE); List<Keyboard.Key> keys = keyboard.getKeys(); for (Keyboard.Key key : keys) { if (key.codes[0] == -3) { Log.e("hello", String.valueOf(key.codes[0])); key.icon = getResources().getDrawable(android.R.drawable.ic_menu_close_clear_cancel); } } kv.invalidateAllKeys(); if(_subscription.isUnsubscribed()){ subscribeDebounce(); } }else{ char code = (char)primaryCode; if(Character.isLetter(code) && caps){ code = Character.toUpperCase(code); } ic.commitText(String.valueOf(code),1); } } } } @Override public void onPress(int primaryCode) { } @Override public void onRelease(int primaryCode) { } @Override public void onText(CharSequence text) { } @Override public void swipeDown() { } @Override public void swipeLeft() { } @Override public void swipeRight() { } @Override public void swipeUp() { } @Override public void onDestroy() { super.onDestroy(); mCompositeSubscription.unsubscribe(); } private void playClick(int keyCode){ AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE); switch(keyCode){ case 32: am.playSoundEffect(AudioManager.FX_KEYPRESS_SPACEBAR); break; case Keyboard.KEYCODE_DONE: case 10: am.playSoundEffect(AudioManager.FX_KEYPRESS_RETURN); break; case Keyboard.KEYCODE_DELETE: am.playSoundEffect(AudioManager.FX_KEYPRESS_DELETE); break; default: am.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD); } } boolean im=false; @Override public void ola(String url) { /*InputConnection ic = getCurrentInputConnection(); ic.commitText(url,1);*/ Log.e("ola", "ola"); /*getCurrentApplicationName();*/ String url1 = "http://fyf.tac-cdn.net/images/products/large/BF216-11KM.jpg"; String url2 = "http://static.prvd.com/siteimages/PFC_C_TIL_233x380_OTH16_SIT_03A_PIR699.jpg"; shareItem(url1,url); /*if(!im){ shareItem(url1,url); im=true; }else{ shareItem(url2,url); im=false; }*/ } /*@Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { recyclerAdapter.setAdapter(String.valueOf(charSequence)); myList.setVisibility(View.VISIBLE); } @Override public void afterTextChanged(Editable editable) { }*/ private Observer<TextViewTextChangeEvent> _getSearchObserver() { return new Observer<TextViewTextChangeEvent>() { @Override public void onCompleted() { Timber.d("--------- onComplete"); } @Override public void onError(Throwable e) { Timber.e(e, "--------- Woops on error!"); Log.e("Dang error", "check your logs"); } @Override public void onNext(TextViewTextChangeEvent onTextChangeEvent) { /*_log(format("Searching for %s", onTextChangeEvent.text().toString()));*/ searchValue(onTextChangeEvent.text().toString()); } }; } private void searchValue(String text) { if (_isCurrentlyOnMainThread()) { /*_logs.add(0, logMsg + " (main thread) "); _adapter.clear(); _adapter.addAll(_logs);*/ Log.e("Searching for", text); // calling api mSearchPresenter.getSearchResult(mCompositeSubscription,text); //clear previous result mSearchModelList = new ArrayList<>(); mSearchResultLayout.setVisibility(View.VISIBLE); } else { /*_logs.add(0, logMsg + " (NOT main thread) ");*/ // You can only do below stuff on main thread. new Handler(Looper.getMainLooper()).post(() -> { /* _adapter.clear(); _adapter.addAll(_logs);*/ }); } } private boolean _isCurrentlyOnMainThread() { return Looper.myLooper() == Looper.getMainLooper(); } @Override public void showProgressBar() { mProgressBar.setVisibility(View.VISIBLE); myList.setVisibility(View.GONE); } @Override public void hideProgressBar() { mProgressBar.setVisibility(View.GONE); myList.setVisibility(View.VISIBLE); } @Override public void searchError(String error) { mProgressBar.setVisibility(View.GONE); recyclerAdapter.setAdapter(searchText.getText().toString()); myList.setVisibility(View.VISIBLE); Log.e("error",error); } @Override public void searchSuccess(List<SearchModel> searchModelList) { Log.e("end_result","result"); } public void shareItem(String url, String detail) { /*Picasso.with(getApplicationContext()).load(url).into(new com.squareup.picasso.Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { Intent i = new Intent(Intent.ACTION_SEND); i.setType("image*//*"); i.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(bitmap)); i.createChooser(i,"Share"); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } });*/ if(!isAirplaneModeOn(this)){ //Picasso Code Picasso.with(getApplicationContext()).load(url).into(new com.squareup.picasso.Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { Intent i = new Intent(Intent.ACTION_SEND); i.setType("*/*"); i.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(bitmap)); i.putExtra(Intent.EXTRA_TEXT, "Hey look this product you will like it: "+ detail); i.createChooser(i,"Share with"); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }); }else{ //do something else? Log.e("Airoplane", "mode on"); } } public Uri getLocalBitmapUri(Bitmap bmp) { Uri bmpUri = null; try { File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".jpeg"); FileOutputStream out = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.PNG, 100, out); out.close(); bmpUri = Uri.fromFile(file); } catch (IOException e) { e.printStackTrace(); } return bmpUri; } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public static boolean isAirplaneModeOn(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0; } else { return Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0; } } void getCurrentApplicationName(){ ActivityManager activityManager = (ActivityManager) SimpleIME.this.getSystemService( Context.ACTIVITY_SERVICE ); List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); for(ActivityManager.RunningAppProcessInfo appProcess : appProcesses){ if(appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){ Log.i("Foreground App", appProcess.processName); Log.i("Foreground app name", String.valueOf(appProcess.processName.contains("whatsapp"))); } } } }
package com.liyu.server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /** * @author liyu * @date 2019/9/5 15:24 * @description ๆœๅŠกๆณจๅ†ŒๅฏๅŠจ็ฑป */ @SpringBootApplication @EnableEurekaServer public class ServerApplication { public static void main(String[] args) { SpringApplication.run(ServerApplication.class); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.acceleratorcms.tags2; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.acceleratorcms.data.CmsPageRequestContextData; import de.hybris.platform.acceleratorservices.util.HtmlElementHelper; import de.hybris.platform.cms2.model.contents.components.AbstractCMSComponentModel; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.jsp.PageContext; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @UnitTest public class CMSContentSlotTagUnitTest { final String CSS_CLASS = "ASDF_CLASS"; final String DYNAMIC_CSS_CLASS = "DYNAMIC_CLASS"; final String ATTR_KEY = "attrkey"; final String ATTR_VAL = "attrvalue"; final String UID = "ASDF_UID"; final CMSContentSlotTag t = new CMSContentSlotTag(); final CMSContentSlotTag spy = Mockito.spy(t); final CmsPageRequestContextData contextData = Mockito.mock(CmsPageRequestContextData.class); final PageContext pageContext = Mockito.mock(PageContext.class); final AbstractCMSComponentModel currentComponent = Mockito.mock(AbstractCMSComponentModel.class); @Before public void setUp() { spy.htmlElementHelper = new HtmlElementHelper(); spy.setPageContext(pageContext); spy.currentComponent = currentComponent; spy.cmsDynamicAttributeServices = Collections.emptyList(); Mockito.when(currentComponent.getUid()).thenReturn(UID); Mockito.when(pageContext.getAttribute("contentSlot", PageContext.REQUEST_SCOPE)).thenReturn(null); Mockito.when(spy.getElementCssClass()).thenReturn(CSS_CLASS); spy.currentCmsPageRequestContextData = contextData; } @Test public void testGetElementAttributeWithLiveEdit() { spy.dynamicAttributes = null; Mockito.when(Boolean.valueOf(contextData.isLiveEdit())).thenReturn(Boolean.TRUE); Assert.assertEquals(spy.getElementAttributes().get("class"), CSS_CLASS); } @Test public void testGetElementAttributeWithoutLiveEdit() { spy.dynamicAttributes = null; Mockito.when(Boolean.valueOf(contextData.isLiveEdit())).thenReturn(Boolean.FALSE); Assert.assertEquals(spy.getElementAttributes().get("class"), CSS_CLASS); } @Test public void testGetElementAttributeWithDynamicAttrsNoLiveEdit() { final HashMap<String, String> attrs = new HashMap<>(); attrs.put("class", DYNAMIC_CSS_CLASS); attrs.put(ATTR_KEY, ATTR_VAL); spy.dynamicAttributes = attrs; Mockito.when(Boolean.valueOf(contextData.isLiveEdit())).thenReturn(Boolean.FALSE); final Map<String, String> mergedAttributes = spy.getElementAttributes(); final List<String> classes = Arrays.asList(mergedAttributes.get("class").split(" ")); Assert.assertTrue(classes.contains(CSS_CLASS)); Assert.assertTrue(classes.contains(DYNAMIC_CSS_CLASS)); Assert.assertEquals(mergedAttributes.get(ATTR_KEY), ATTR_VAL); } @Test public void testGetElementAttributeWithDynamicAttrsYesLiveEdit() { final HashMap<String, String> attrs = new HashMap<>(); attrs.put("class", DYNAMIC_CSS_CLASS); attrs.put(ATTR_KEY, ATTR_VAL); spy.dynamicAttributes = attrs; Mockito.when(Boolean.valueOf(contextData.isLiveEdit())).thenReturn(Boolean.TRUE); final Map<String, String> mergedAttributes = spy.getElementAttributes(); final List<String> classes = Arrays.asList(mergedAttributes.get("class").split(" ")); Assert.assertTrue(classes.contains(CSS_CLASS)); Assert.assertTrue(classes.contains(DYNAMIC_CSS_CLASS)); Assert.assertEquals(mergedAttributes.get(ATTR_KEY), ATTR_VAL); } }
/* * Copyright 2012 Google Inc. * * 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.google.android.apps.mytracks; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection; import com.nogago.bb10.tracks.R; import android.app.Activity; import android.os.Handler; import android.os.RemoteException; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; /** * Track controller for record, pause, resume, and stop. * * @author Jimmy Shih */ public class TrackController { private static final String TAG = TrackController.class.getSimpleName(); private static final int ONE_SECOND = 1000; private final Activity activity; private final TrackRecordingServiceConnection trackRecordingServiceConnection; private final Handler handler; private View containerView; // private final TextView statusTextView; // private final TextView totalTimeTextView; private ImageButton recordImageButton; // private ImageButton markerImageButton; private ImageButton stopImageButton; private boolean alwaysShow; private boolean isRecording; private boolean isPaused; private long totalTime = 0; // the timestamp for the toal time private long totalTimeTimestamp = 0; // A runnable to update the total time. private final Runnable updateTotalTimeRunnable = new Runnable() { public void run() { if (isRecording && !isPaused) { // totalTimeTextView.setText(StringUtils.formatElapsedTimeWithHour(System.currentTimeMillis() // - totalTimeTimestamp + totalTime)); handler.postDelayed(this, ONE_SECOND); } } }; public TrackController(Activity activity, TrackRecordingServiceConnection trackRecordingServiceConnection, boolean alwaysShow, OnClickListener recordListener, OnClickListener stopListener) { // , // OnClickListener // markerListener) // { this.activity = activity; this.trackRecordingServiceConnection = trackRecordingServiceConnection; this.alwaysShow = alwaysShow; handler = new Handler(); // statusTextView = (TextView) // activity.findViewById(R.id.track_controller_status); // totalTimeTextView = (TextView) // activity.findViewById(R.id.track_controller_total_time); View view = null; try { view = (View) activity.findViewById(R.id.track_controller_container); } catch (NullPointerException ne1) { view = null; } if (view != null) containerView = view; try { view = (View) activity.findViewById(R.id.listBtnBarRecord); } catch (NullPointerException ne1) { view = null; } if (view != null) { recordImageButton = (ImageButton) view; recordImageButton.setOnClickListener(recordListener); } else recordImageButton = null; try { view = (View) activity.findViewById(R.id.listBtnBarStop); } catch (NullPointerException ne1) { view = null; } if (view != null) { stopImageButton = (ImageButton) view; stopImageButton.setOnClickListener(stopListener); } else stopImageButton = null; // Buttons not visible /* * if(markerListener != null) { markerImageButton = (ImageButton) * activity.findViewById(R.id.listBtnBarMarker); * markerImageButton.setOnClickListener(markerListener); } else { * markerImageButton=null; } */ } public void update(boolean recording, boolean paused) { isRecording = recording; isPaused = paused; // containerView.setVisibility(alwaysShow || isRecording ? View.VISIBLE : // View.GONE); if (!alwaysShow && !isRecording) { stop(); return; } if(recordImageButton != null) { recordImageButton.setImageResource(isRecording && !isPaused ? R.drawable.ic_pause : R.drawable.ic_record); recordImageButton.setContentDescription(activity .getString(isRecording && !isPaused ? R.string.icon_pause_recording : R.string.icon_record_track)); } /* * LayoutParams lp = recordImageButton.getLayoutParams(); lp.width=144; * lp.height=81; recordImageButton.setLayoutParams(lp); * recordImageButton.setScaleType(ScaleType.CENTER); */ if(stopImageButton != null) { stopImageButton.setImageResource(isRecording ? R.drawable.ic_stop_1 : R.drawable.ic_stop_0); stopImageButton.setEnabled(isRecording); } /* * lp = stopImageButton.getLayoutParams(); lp.width=144; lp.height=81; * stopImageButton.setLayoutParams(lp); * stopImageButton.setScaleType(ScaleType.CENTER); */ /* * statusTextView.setVisibility(isRecording ? View.VISIBLE : * View.INVISIBLE); if (isRecording) { * statusTextView.setTextColor(activity.getResources().getColor( isPaused ? * android.R.color.white : R.color.red)); statusTextView.setText(isPaused ? * R.string.generic_paused : R.string.generic_recording); } */ stop(); /* * totalTime = isRecording ? getTotalTime() : 0L; * totalTimeTextView.setText(StringUtils * .formatElapsedTimeWithHour(totalTime)); if (isRecording && !isPaused) { * totalTimeTimestamp = System.currentTimeMillis(); * handler.postDelayed(updateTotalTimeRunnable, ONE_SECOND); } */ /* * if(markerImageButton != null) { * markerImageButton.setImageResource(isRecording ? R.drawable.ic_marker : * R.drawable.ic_upload); markerImageButton.setContentDescription(activity * .getString(isRecording ? R.string.icon_marker : R.string.icon_upload)); } */ } /** * Stops the timer. */ public void stop() { handler.removeCallbacks(updateTotalTimeRunnable); } /** * Gets the total time for the current recording track. */ private long getTotalTime() { ITrackRecordingService trackRecordingService = trackRecordingServiceConnection .getServiceIfBound(); try { return trackRecordingService != null ? trackRecordingService.getTotalTime() : 0L; } catch (RemoteException e) { Log.e(TAG, "exception", e); return 0L; } } }
package a4adept; public class MutableFrame2D implements Frame2D { static final Pixel DEFAULT_INIT_PIXEL = new ColorPixel(0.0, 0.0, 0.0); private Pixel[][] pixels; public MutableFrame2D(int width, int height) { if ((width <= 0) || (height <= 0)) { throw new IllegalFrame2DGeometryException(); } pixels = new Pixel[width][height]; for (int x=0; x<width; x++) { for (int y=0; y<height; y++) { pixels[x][y] = DEFAULT_INIT_PIXEL; } } } @Override public int getWidth() { return pixels.length; } @Override public int getHeight() { return pixels[0].length; } @Override public Pixel getPixel(int x, int y) { check_coordinates(x,y); return pixels[x][y]; } @Override public Frame2D setPixel(int x, int y, Pixel p) { check_coordinates(x,y); if (p == null) { throw new RuntimeException("Null pixel error"); } pixels[x][y] = p; return this; } @Override public Frame2D lighten(double factor) { check_factor(factor); for (int x=0; x< getWidth(); x++) { for (int y=0; y<getHeight(); y++) { pixels[x][y] = pixels[x][y].lighten(factor); } } return this; } @Override public Frame2D darken(double factor) { check_factor(factor); for (int x=0; x< getWidth(); x++) { for (int y=0; y<getHeight(); y++) { pixels[x][y] = pixels[x][y].darken(factor); } } return this; } @Override public GrayFrame2D toGrayFrame() { GrayFrame2D gray_frame = new MutableGrayFrame2D(getWidth(), getHeight()); for (int x=0; x< getWidth(); x++) { for (int y=0; y<getHeight(); y++) { gray_frame.setPixel(x, y, getPixel(x, y)); } } return gray_frame; } private boolean check_coordinates(int x, int y) { if (x < 0 || x >= getWidth()) { throw new RuntimeException("x is out of bounds"); } if (y < 0 || y >= getHeight()) { throw new RuntimeException("y is out of bounds"); } return true; } private static boolean check_factor(double factor) { if (factor < 0) { throw new RuntimeException("Factor can not be less than 0.0"); } else if (factor > 1.0) { throw new RuntimeException("Factor can not be greater than 1.0"); } return true; } }
package com.jiuzhe.app.hotel.constants; public class CommonConstant { public static final int SUCCESS = 0; public static final int FAIL = -1; public static final int ID_EMPTY = 100000; public static final int OUT_DATA_EMPTY = 100001; public static final int IN_DATA_ERR = 100002; public static final int TOO_MANY_ORDER = 100101; public static final int REPEAT_ORDER = 100102; public static final int PRICE_ERROR = 100103; public static final int PAID_CANCEL_TIME = 100104; public static final int RESERVER = 100108; //ไธๆ˜ฏ้œ€่ฆ็š„็Šถๆ€ public static final int ERR_STATUS = 100107; //ๅ†ฅ็ญ‰ๆ€งๅˆคๅฎš public static final int EXISTED = 100105; //ๅ†ฅ็ญ‰ๆ€งๅˆคๅฎš public static final int UNEXISTED = 100106; //ๅ‚ๆ•ฐไธบ็ฉบ public static final int QUERY = 201; public static final String OK = "OK"; public static final String ERR = "Error"; public static final String FAILED = "Failed"; public static final String STATUS = "status"; }
package framework.factories; import framework.dto.TransactionDTO; import framework.entities.Transaction; public interface ITransactionFactory extends IFactory<TransactionDTO, Transaction> { @Override public Transaction create(TransactionDTO dto); }
package com.refunited.security; import java.security.MessageDigest; public class EncryptionManager { private static final String ALGORITHM = "SHA-256"; private static final char ZERO = '0'; /** * Method that generates a hash based on a String value * @param password the string to be hashed. * */ public static String generateHash(String password){ MessageDigest digest = null; String hash = ""; try { digest = MessageDigest.getInstance(ALGORITHM); digest.update(password.getBytes()); hash = bytesToHexString(digest.digest()); } catch (Exception ex) { ex.printStackTrace(); } return hash; } /** * Method that converts from bytes to a String representation of the same bytes in hexa. * @param bytes the bytes for conversion * */ private static String bytesToHexString(byte[] bytes) { StringBuffer sbHex = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sbHex.append(ZERO); } sbHex.append(hex); } return sbHex.toString(); } }
package com.gsrikar.roomconnectiontest.room; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Insert; import java.util.List; @Dao public interface PersonDao { @Insert() void insert(List<PersonEntity> personEntity); }
package org.ms.iknow.service.type; public class StatementEntry { String parentName; String relationId; String childName; public String getParentName() { return this.parentName; } public void setParentName(String parentName) { this.parentName = parentName; } public String getRelationId() { return relationId; } public void setRelationId(String relationId) { this.relationId = relationId; } public String getChildName() { return this.childName; } public void setChildName(String childName) { this.childName = childName; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("parent =" + this.parentName + "\n"); sb.append("relation=" + this.relationId + "\n"); sb.append("child =" + this.childName); return sb.toString(); } }
package com.example.jinliyu.shoppingapp_1.data; /** * Created by jinliyu on 4/14/18. */ public class Category { String name; String image; String cid; String description; public Category(String name, String image, String cid, String description) { this.name = name; this.image = image; this.cid = cid; this.description = description; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } }
/******************************************************************************* * Copyright (c) 2016 Chen Chao(cnfree2000@hotmail.com). * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Chen Chao - initial API and implementation *******************************************************************************/ package org.sf.feeling.mars.mpc.ui.market.client; import org.sf.feeling.decompiler.update.tester.OperationTester; public class MarsDecompilerMarketplace { public static boolean isInteresting( ) { try { Class.forName( "org.eclipse.epp.mpc.ui.Operation" ); //$NON-NLS-1$ if ( OperationTester.supportMars( ) ) return true; else return false; } catch ( ClassNotFoundException e ) { return false; } } }
package com.supconit.kqfx.web.util; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public final class CollectionUtils { private CollectionUtils() { } public static <T> Collection<T> diff(Collection<T> c1, Collection<T> c2) { if (c1 == null || c1.size() == 0 || c2 == null || c2.size() == 0) { return c1; } Collection<T> difference = new ArrayList<T>(); for (T item : c1) { if (!c2.contains(item)) { difference.add(item); } } return difference; } public static <T> boolean isEmpty(Collection<T> c) { if (c == null || c.size() == 0) { return true; } for (Iterator<T> iter = c.iterator(); iter.hasNext();) { if (iter.next() != null) { return false; } } return true; } }
package com.holmes.leecode; /** * ไธคๆ•ฐ็›ธๅŠ  * https://leetcode-cn.com/problems/add-two-numbers/ * * @author Administrator */ public class AddTwoNumbers { public static void main(String[] args) { new AddTwoNumbers(); } public AddTwoNumbers() { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(0); ListNode node3 = new ListNode(1); node1.next = node2; node2.next = node3; ListNode node4 = new ListNode(9); ListNode node5 = new ListNode(9); ListNode node6 = new ListNode(8); ListNode node7 = new ListNode(9); node4.next = node5; node5.next = node6; node6.next = node7; ListNode node = addTwoNumbers(node1, node4); while (node != null) { System.out.println(node.val); node = node.next; } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode result = null; ListNode currentNode = null; ListNode a = l1; ListNode b = l2; int carry = 0; while (null != a || null != b) { int sum = (null == a ? 0 : a.val) + (null == b ? 0 : b.val) + carry; carry = sum >= 10 ? 1 : 0; sum = sum >= 10 ? sum - 10 : sum; ListNode p = new ListNode(sum); if (null == result) { result = p; currentNode = p; } else { currentNode.next = p; currentNode = p; } a = (null == a ? null : a.next); b = (null == b ? null : b.next); } if(carry == 1) { currentNode.next = new ListNode(carry); } return result; } }
package com.rishi.baldawa.iq; import org.junit.Test; import static com.rishi.baldawa.iq.model.ListNodeDataFactory.l; import static org.junit.Assert.assertEquals; public class LinkedListIsPalindromeTest { @Test public void isPalindrome() throws Exception { assertEquals(new LinkedListIsPalindrome().isPalindrome(l(1, 3, 0, 2)), false); assertEquals(new LinkedListIsPalindrome().isPalindrome(l(1, 2, 3, 4, 5, 6, 7)), false); assertEquals(new LinkedListIsPalindrome().isPalindrome(l(1, 2, 3, 4, 3, 2, 1)), true); assertEquals(new LinkedListIsPalindrome().isPalindrome(l(1, 2, 3, 3, 2, 1)), true); } }
package se.slashat.slashat.adapter; import java.io.Serializable; import se.slashat.slashat.R; import se.slashat.slashat.model.Personal; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; public class PersonAdapter extends AbstractArrayAdapter<Personal> implements Serializable { private static final long serialVersionUID = 1L; private Personal person; public PersonAdapter(Context context, int layoutResourceId, Personal[] data) { super(context, layoutResourceId, data); this.context = context; this.layoutResourceId = layoutResourceId; this.person = data[0]; } static class PersonHolder extends Holder { TextView name; ImageView email; ImageView twitter; ImageView homepage; TextView bio; ImageView photo; } @Override public PersonHolder createHolder(View row) { PersonHolder holder = new PersonHolder(); holder.photo = (ImageView) row.findViewById(R.id.photo); holder.name = (TextView) row.findViewById(R.id.name); holder.email = (ImageView) row.findViewById(R.id.email); holder.twitter = (ImageView) row.findViewById(R.id.twitter); holder.homepage = (ImageView) row.findViewById(R.id.browser); holder.bio = (TextView) row.findViewById(R.id.bio); return holder; } @Override public boolean isClickable() { return false; } @Override public OnClickListener createOnClickListener(Personal t) { return new OnClickListener() { @Override public void onClick(View v) { } }; } @Override public void setDataOnHolder(Holder holder, final Personal t) { PersonHolder ph = (PersonHolder) holder; ph.name.setText(person.getName()); setTwitterClickListener(t, ph); setEmailClickListener(t, ph); setHomepageClickListener(t, ph); ph.bio.setText(person.getBio()); ph.photo.setImageResource(person.getImg()); } private void setHomepageClickListener(final Personal t, PersonHolder ph) { ph.homepage.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { openBrowserIntent(t); } }); } private void setEmailClickListener(final Personal t, PersonHolder ph) { ph.email.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { openEmailIntent(t); } }); } private void setTwitterClickListener(final Personal t, PersonHolder ph) { ph.twitter.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { openTwitterIntent(t); } }); } private void openTwitterIntent(final Personal t) { try { // TODO: Can all twitter clients be targeted? // Looks like every different client has it's own way to open it // correctly. Tried with twitter:// but got errors that no // application was found. context.getPackageManager() .getPackageInfo("com.twitter.android", 0); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setClassName("com.twitter.android", "com.twitter.android.ProfileActivity"); intent.putExtra("screen_name", t.getTwitter()); context.startActivity(intent); } catch (NameNotFoundException e) { // Fall back to browser context.startActivity(new Intent(Intent.ACTION_VIEW, Uri .parse("https://twitter.com/" + t.getTwitter()))); } } private void openEmailIntent(final Personal t) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { t.getEmail() }); // TODO: The chooser shows more than just email clients. context.startActivity(Intent.createChooser(intent, "Vรคlj applikation att skicka mail med")); } private void openBrowserIntent(Personal t) { context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(t .getHomepage()))); } }
package com.roadtube.fragment.tab; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.roadtube.R; import com.roadtube.adapter.FriendListAdapter; import com.roadtube.model.Friends; import com.roadtube.utils.SimpleDividerItemDecoration; import java.util.ArrayList; /** * Created by Tony on 5/14/2017. */ public class FriendsFragment extends Fragment { private String TAG = FriendsFragment.class.getSimpleName(); private ArrayList<Friends> friendList; private RecyclerView recyclerView; private FriendListAdapter mAdapter; private Context context; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout resource that'll be returned View rootView = inflater.inflate(R.layout.fragment_tab_friends, container, false); context = getActivity().getApplicationContext(); recyclerView = (RecyclerView) rootView.findViewById(R.id.list); friendList = new ArrayList<>(); Friends cr = new Friends(); cr.setId("1"); cr.setName("Tao"); cr.setEmail("test@gmail.com"); cr.setAvatar("https://pickaface.net/gallery/avatar/unr_dani_170519_0448_z72x5.png"); cr.setUserId("1"); cr.setMessengerId("1"); //cr.setTimestamp(messengerObj.getString("created_at")); friendList.add(cr); Friends cr1 = new Friends(); cr1.setId("1"); cr1.setName("Tao"); cr1.setEmail("test@gmail.com"); cr1.setAvatar("https://pickaface.net/gallery/avatar/unr_dani_170519_0448_z72x5.png"); cr1.setUserId("1"); cr1.setMessengerId("1"); //cr.setTimestamp(messengerObj.getString("created_at")); friendList.add(cr1); mAdapter = new FriendListAdapter(getActivity(), friendList); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); recyclerView.addItemDecoration(new SimpleDividerItemDecoration( context )); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(mAdapter); return rootView; } @Override public void onResume() { super.onResume(); //Toast.makeText(context, "onResume():", Toast.LENGTH_SHORT).show(); } @Override public void onPause() { super.onPause(); //Toast.makeText(context, "onPause():", Toast.LENGTH_SHORT).show(); } }
package model; public class Guerrilheiro extends Inimigo { public Guerrilheiro() { super(); this.setEstrategia(8); this.setForca(8); this.setInteligencia(5); } }
package ua.lviv.iot.uklon.domain; import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "order_state") public class OrderState { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; @Column(name = "state") private String state; public OrderState() { } public OrderState(Integer id, String state) { this.id = id; this.state = state; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof OrderState)) return false; OrderState that = (OrderState) o; return id.equals(that.id) && state.equals(that.state); } @Override public int hashCode() { return Objects.hash(id, state); } @Override public String toString() { return "OrderState{" + "id=" + id + ", state='" + state + '\'' + '}'; } }
package com.cjava.spring.util; /** * Clase utilitaria para la aplicacion. * @author Jean Ramal Alvarez * @since 31 August 2012 * @version 1.0 * */ import java.text.MessageFormat; import java.util.ResourceBundle; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class WebUtil { private WebUtil() { } public static void keepMessages() { getFacesContextCurrentInstance().getExternalContext().getFlash() .setKeepMessages(true); } /** * Metodo que obtiene una instancia de FacesContext. * * @return FacesContext. * */ public static FacesContext getFacesContextCurrentInstance() { return FacesContext.getCurrentInstance(); } /** * Metodo que obtiene el request de la instancia de FacesContext. * * @return HttpServletRequest. * */ public static HttpServletRequest getRequest() { return (HttpServletRequest) getFacesContextCurrentInstance() .getExternalContext().getRequest(); } /** * Metodo que obtiene el response de la instancia de FacesContext. * * @return HttpServletResponse. * */ public static HttpServletResponse getResponse() { return (HttpServletResponse) getFacesContextCurrentInstance() .getExternalContext().getResponse(); } /** * Metodo que obtiene la direccion ip. * * @return String. * */ public static String getRemoteAddr() { return ((HttpServletRequest) getFacesContextCurrentInstance() .getExternalContext().getRequest()).getRemoteAddr(); } /** * Metodo que obtiene la direccion ip. * * @return String. * */ public static String getRemoteHost() { return ((HttpServletRequest) getFacesContextCurrentInstance() .getExternalContext().getRequest()).getRemoteHost(); } /** * Metodo que obtiene un objeto de la session. * * @param objectName * nombre del objeto, tipo String. * @return Object. * * */ public static Object getAttribute(String objectName) { return getRequest().getSession(false).getAttribute(objectName); } /** * Metodo que elimina la sesion. * */ public static void invalidate() { ((HttpSession) getFacesContextCurrentInstance().getExternalContext() .getSession(false)).invalidate(); } /** * Metodo que obtiene el mensaje en base al codigo. * * @param key * codigo del mensaje, tipo String. * @param args * argumentos , tipo String. * @return mensaje. * */ public static String getMensaje(String key, String... args) { try { FacesContext context = getFacesContextCurrentInstance(); ResourceBundle res = context.getApplication().getResourceBundle( context, "mensaje"); MessageFormat format = new MessageFormat( (String) res.getObject(key)); return format.format(args); } catch (Exception e) { e.printStackTrace(); return null; } } }
package tim.prune.function.srtm; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; /** * Class to get the URLs of the SRTM tiles * using the srtmtiles.dat file */ public abstract class TileFinder { /** URL prefix for all tiles */ private static final String URL_PREFIX = "https://dds.cr.usgs.gov/srtm/version2_1/SRTM3/"; /** Directory names for each continent */ private static final String[] CONTINENTS = {"", "Eurasia", "North_America", "Australia", "Islands", "South_America", "Africa"}; /** * Get the Urls for the given list of tiles * @param inTiles list of Tiles to get * @return array of URLs */ public static URL[] getUrls(ArrayList<SrtmTile> inTiles) { if (inTiles == null || inTiles.size() < 1) {return null;} URL[] urls = new URL[inTiles.size()]; // Read dat file into array byte[] lookup = readDatFile(); if (lookup == null) { System.err.println("Build error: resource srtmtiles.dat missing!"); return null; } for (int t=0; t<inTiles.size(); t++) { SrtmTile tile = inTiles.get(t); // Get byte from lookup array int idx = (tile.getLatitude() + 59)*360 + (tile.getLongitude() + 180); try { int dir = lookup[idx]; if (dir > 0) { try { urls[t] = new URL(URL_PREFIX + CONTINENTS[dir] + "/" + tile.getTileName()); } catch (MalformedURLException e) {} // ignore error, url stays null } } catch (ArrayIndexOutOfBoundsException e) {} // ignore error, url stays null } return urls; } /** * Read the dat file and get the contents * @return byte array containing file contents */ private static byte[] readDatFile() { InputStream in = null; try { // Need absolute path to dat file in = TileFinder.class.getResourceAsStream("/tim/prune/function/srtm/srtmtiles.dat"); if (in != null) { byte[] buffer = new byte[in.available()]; in.read(buffer); in.close(); return buffer; } } catch (java.io.IOException e) { System.err.println("Exception trying to read srtmtiles.dat : " + e.getMessage()); } finally { try { in.close(); } catch (Exception e) {} // ignore } return null; } }
package com.vilio.plms.service.base; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.vilio.plms.dao.LoginInfoDao; import com.vilio.plms.dao.MessageReceiveDao; import com.vilio.plms.dao.MessageSendDao; import com.vilio.plms.glob.Fields; import com.vilio.plms.glob.ReturnCode; import com.vilio.plms.pojo.LoginInfo; import com.vilio.plms.pojo.MessageReceive; import com.vilio.plms.pojo.MessageSend; import com.vilio.plms.util.CommonUtil; import com.vilio.plms.util.DateUtil; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.text.SimpleDateFormat; import java.util.*; /** * Created by dell on 2017/5/31/0031. */ @Service public class MessageService { @Resource MessageSendDao messageSendDao; @Resource MessageReceiveDao messageReceiveDao; // @Resource // NlbsPendingUserDistributorMapper nlbsPendingUserDistributorMapper; @Resource RemoteMpsService remoteMpsService; @Resource LoginInfoDao loginInfoDao; private static Logger logger = Logger.getLogger(MessageService.class); /** * ๆ’ๅ…ฅๆ–ฐๆถˆๆฏ * @param paramMap * @return * @throws Exception */ public int insertMessage(Map paramMap) throws Exception { // Map msgSendParamMap = new HashMap(); // // //Step 1 ่Žทๅ–ๅ‚ๆ•ฐ // String userNo = paramMap.get(Fields.PARAM_USER_NO) == null ? "" : paramMap.get(Fields.PARAM_USER_NO).toString();//ไธ€่ˆฌๆŒ‡ๅฝ“ๅ‰็™ปๅฝ•็”จๆˆท // String status = paramMap.get(Fields.PARAM_MSG_STATUS) == null ? "" : paramMap.get(Fields.PARAM_MSG_STATUS).toString();//ไธ€่ˆฌๆŒ‡ๆถˆๆฏ็Šถๆ€ // String msgModelCode = paramMap.get(Fields.PARAM_MSG_MSG_MODEL_CODE) == null ? "" : paramMap.get(Fields.PARAM_MSG_MSG_MODEL_CODE).toString();//ๆถˆๆฏๆจก็‰ˆ // //ไปฅไธ‹ๅ‚ๆ•ฐไธŽๆถˆๆฏๆœฌ่บซๆ— ๅ…ณ๏ผŒ้ƒฝๅฐ†ๆ”พๅ…ฅinternalParam้‡Œ // Map internalParamMap = new HashMap(); // String serialNo = paramMap.get(Fields.PARAM_SERIAL_NO) == null ? "" : paramMap.get(Fields.PARAM_SERIAL_NO).toString();//ไธ€่ˆฌๆŒ‡ๆถˆๆฏๅ…ณ่”็š„่ฎขๅ•ๅบๅˆ—ๅท // String msgType = paramMap.get(Fields.PARAM_MSG_MSG_TYPE) == null ? "" : paramMap.get(Fields.PARAM_MSG_MSG_TYPE).toString();// // String keyWords = paramMap.get(Fields.PARAM_MSG_KEY_WORDS) == null ? "" : paramMap.get(Fields.PARAM_MSG_KEY_WORDS).toString();// // internalParamMap.put(Fields.PARAM_SERIAL_NO, serialNo); // internalParamMap.put(Fields.PARAM_MSG_MSG_TYPE, msgType); // if(Constants.INTERNAL_MSG_TYPE_003.equals(msgType)) { // internalParamMap.put(Fields.PARAM_MSG_KEY_WORDS, ""); // } else { // internalParamMap.put(Fields.PARAM_MSG_KEY_WORDS, keyWords); // } // //Step 1.1 ๆ‰พๅˆฐๅฝ“ๅ‰็”จๆˆท // LoginInfo loginInfo = loginInfoDao.queryNlbsUserByUserNo(userNo); // // //Step 2 ๆ‰พๆถˆๆฏๆจก็‰ˆ๏ผŒ่ฐƒ็”จไธๅ…่ฎธๅ‡บ็Žฐ็ฉบๅ€ผ๏ผŒไธไฝœ้ž็ฉบๆ ก้ชŒ // MessageModel messageModel = MessageModel.getMessageModelByCode(msgModelCode); // //Step 3 ๆ•ด็†ๆถˆๆฏๆ‰€้œ€ๅ…ฌๆœ‰ๅ‚ๆ•ฐ // String title = messageModel.getTitle(); // String content = MessageModelConfig.getContextProperty(msgModelCode);//ๆญคๆ—ถ่Žทๅ–็š„ๅชๆ˜ฏๆจก็‰ˆ๏ผŒ็ญ‰ๅพ…ๅŽ็ปญๆ•ด็†ๅ‚ๆ•ฐๅŽ่กฅๅ…จ // String userName = ""; // String distributorCode = ""; // String distributorName = ""; // if(loginInfo != null){ // userName = loginInfo.getFullName(); // distributorCode = loginInfo.getDistributorCode(); // distributorName = loginInfo.getDistributorName(); // } // String internalParamStr = JSONObject.fromObject(internalParamMap).toString(); // List<Map<String, Object>> receiverList = new ArrayList<Map<String, Object>>(); // // switch (messageModel){ // case MSG_001: // //Step 3.1 ่กฅๅ…จๆถˆๆฏๅ†…ๅฎน๏ผŒๆจกๆฟ001๏ผŒๅชๆœ‰1ไธชๅ‚ๆ•ฐ // content = String.format(content, keyWords); // //Step 3.2 ่Žทๅ–ๆŽฅๆ”ถ่€…ๅˆ—่กจ // if(loginInfo != null){ // receiverList = nlbsPendingUserDistributorMapper.getUserListByDistributorCode(loginInfo.getDistributorCode()); // } // break; // case MSG_002: // //Step 3.1 ่กฅๅ…จๆถˆๆฏๅ†…ๅฎน๏ผŒๆจกๆฟ002๏ผŒๅชๆœ‰1ไธชๅ‚ๆ•ฐ // content = String.format(content, keyWords); // NlbsInquiryApply nlbsInquiryApply = nlbsInquiryApplyMapper.getBeanBySerialNo(serialNo); // if (nlbsInquiryApply != null) { // Map userMap = new HashMap(); // userMap.put(Fields.PARAM_USER_NO, nlbsInquiryApply.getUserId()); // userMap.put(Fields.PARAM_USER_NAME, nlbsInquiryApply.getUserFullName()); // receiverList.add(userMap); // } // //Step 3.2 ่Žทๅ–ๆŽฅๆ”ถ่€…ๅˆ—่กจ // if(loginInfo != null){ // receiverList = nlbsPendingUserDistributorMapper.getUserListByDistributorCode(loginInfo.getDistributorCode()); // } // break; // case MSG_003: // //Step 3.1 ่กฅๅ…จๆถˆๆฏๅ†…ๅฎน๏ผŒๆจกๆฟ003๏ผŒๅชๆœ‰2ไธชๅ‚ๆ•ฐ // content = String.format(content, userName, keyWords); // //Step 3.2 ่Žทๅ–ๆŽฅๆ”ถ่€…ๅˆ—่กจ // if(loginInfo != null){ // receiverList = nlbsPendingUserDistributorMapper.getUserListByDistributorCode(loginInfo.getDistributorCode()); // } // if(receiverList != null) { // Map currentUserMap = new HashMap(); // currentUserMap.put(Fields.PARAM_USER_NO, userNo); // currentUserMap.put(Fields.PARAM_USER_NAME, userName); // receiverList.remove(currentUserMap);//็งป้™คๅฝ“ๅ‰็”จๆˆท // } // break; // } // //Step 4 ๅˆคๆ–ญๆŽฅๆ”ถ่€…ๅˆ—่กจ--ๅฆ‚ๆžœไธบ็ฉบ๏ผŒๅˆ™ๆ— ้œ€ไฟๅญ˜ // if(receiverList != null && receiverList.size() > 0){ // for(Map userMap : receiverList){ // String code = CommonUtil.getCurrentTimeStr("MS-", ""); // userMap.put(Fields.PARAM_CODE, code); // } // //Step 4.1 ๆ•ด็†ๅญ˜ๅ‚จๆ•ฐๆฎๅบ“็š„ๆถˆๆฏๅฏน่ฑกๅ‚ๆ•ฐ // msgSendParamMap.put(Fields.PARAM_MSG_TITLE, title); // msgSendParamMap.put(Fields.PARAM_MSG_CONTENT, content); // msgSendParamMap.put(Fields.PARAM_USER_NO, userNo); // msgSendParamMap.put(Fields.PARAM_USER_NAME, userName); // msgSendParamMap.put(Fields.PARAM_MSG_SENDER_COMPANY_CODE, distributorCode); // msgSendParamMap.put(Fields.PARAM_MSG_SENDER_COMPANY_NAME, distributorName); // msgSendParamMap.put(Fields.PARAM_MSG_INTERNAL_PARAM, internalParamStr); // msgSendParamMap.put(Fields.PARAM_MSG_STATUS, status); // msgSendParamMap.put(Fields.PARAM_MSG_RECEIVER_USER_LIST, receiverList); // // nlbsMessageSendMapper.getInsertPrmMap(msgSendParamMap); // } // // //Step 5 ๆŠŠๅฝ“ๅ‰ๆถˆๆฏๆ•ด็†ๅŽ๏ผŒๅ‘้€ๅˆฐMPS // try{ // if(receiverList != null && receiverList.size() > 0){ // Map remoteMpsMap = new HashMap(); // remoteMpsMap.put("functionNo", "HH000801"); // remoteMpsMap.put("type", "Instation"); // remoteMpsMap.put("title", title); // remoteMpsMap.put("content", content); // remoteMpsMap.put("senderCompanyCode", distributorCode); // remoteMpsMap.put("senderCompanyName", distributorName); // remoteMpsMap.put("senderDepartmentCode", ""); // remoteMpsMap.put("senderDepartmentName", ""); // remoteMpsMap.put("senderIdentityId", userNo); // remoteMpsMap.put("senderName", userName); // remoteMpsMap.put("senderSystem", "nlbs"); // remoteMpsMap.put(Fields.PARAM_MSG_INTERNAL_PARAM, internalParamStr); // // List<Map> receiverUserList = new ArrayList<Map>(); // for(Map map : receiverList){ // Map tempReceiverMap = new HashMap(); // tempReceiverMap.put("code", map.get(Fields.PARAM_CODE)); // tempReceiverMap.put("receiverCompanyCode", map.get(Fields.PARAM_DISTRIBUTRO_CODE)); // tempReceiverMap.put("receiverCompanyName", map.get(Fields.PARAM_DISTRIBUTRO_NAME)); // tempReceiverMap.put("receiverDepartmentCode", ""); // tempReceiverMap.put("receiverDepartmentName", ""); // tempReceiverMap.put("receiverIdentityId", map.get(Fields.PARAM_USER_NO)); // tempReceiverMap.put("receiverSystem", "nlbs"); // tempReceiverMap.put("receiverName", map.get(Fields.PARAM_USER_NAME)); // receiverUserList.add(tempReceiverMap); // } // remoteMpsMap.put("receiveUserList", receiverUserList); // remoteMpsService.callService(remoteMpsMap); // } // // }catch (Exception e){ // logger.error("ๅ‘้€ๆถˆๆฏๅˆฐๆถˆๆฏไธญๅฟƒ๏ผˆmps๏ผ‰็š„ๆ—ถๅ€™๏ผŒๅ‘็”Ÿไบ†ๆ•…้šœ----------"); // } return 0; } /** * ไฟฎๆ”นๅ‘้€ๅ‡บ็š„ๆถˆๆฏ๏ผŒ้ป˜่ฎคไฟฎๆ”นๆถˆๆฏ็Šถๆ€ไปฅๅŠๅ›žๅ†™ * <ไธๆ”ฏๆŒๆ‰น้‡> * @param paramMap * @return * @throws Exception */ @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public Map modifySendMessage(Map paramMap) throws Exception { Map<String, Object> resultMap = new HashMap(); String serialNo = null != paramMap.get(Fields.PARAM_MSG_SERIAL_NO) ? paramMap.get(Fields.PARAM_MSG_SERIAL_NO).toString() : null; String code = null != paramMap.get(Fields.PARAM_CODE) ? paramMap.get(Fields.PARAM_CODE).toString() : null; String status = null != paramMap.get(Fields.PARAM_MSG_STATUS) ? paramMap.get(Fields.PARAM_MSG_STATUS).toString() : "1";//1ไปฃ่กจๅทฒๆˆๅŠŸๅ‘้€ๅˆฐๆถˆๆฏไธญๅฟƒ MessageSend nlbsMessage = new MessageSend(); nlbsMessage.setSerialNo(serialNo); nlbsMessage.setCode(code); nlbsMessage.setStatus(status); messageSendDao.updateStatusByCode(nlbsMessage); resultMap.put(Fields.PARAM_MESSAGE_ERR_CODE, ReturnCode.SUCCESS_CODE); resultMap.put(Fields.PARAM_MESSAGE_ERR_MESG, "ๆˆๅŠŸไฟฎๆ”น๏ผˆๆ›ดๆ–ฐ๏ผ‰ๆถˆๆฏ๏ผ"); return resultMap; } /** * ๆŸฅ่ฏขๆถˆๆฏๅˆ—่กจ๏ผˆๅซๅˆ†้กต๏ผ‰ * @param paramMap * @return * @throws Exception */ public Map queryMessageList(Map paramMap) throws Exception { //Step 1 ่Žทๅ–ๅฟ…่ฆๅ‚ๆ•ฐ Map<String, Object> resultMap = new HashMap(); List<Map> returnNlbsMessageMapList = new ArrayList<Map>(); String userNo = null != paramMap.get(Fields.PARAM_USER_NO) ? paramMap.get(Fields.PARAM_USER_NO).toString() : null; String content = null != paramMap.get(Fields.PARAM_MSG_CONTENT) ? paramMap.get(Fields.PARAM_MSG_CONTENT).toString() : null; Integer pageNo = null != paramMap.get(Fields.PARAM_PAGE_NO) ? new Integer(paramMap.get(Fields.PARAM_PAGE_NO).toString()) : 1; Integer pageSize = null != paramMap.get(Fields.PARAM_PAGE_SIZE) ? new Integer(paramMap.get(Fields.PARAM_PAGE_SIZE).toString()) : 10; //Step 2 ่ฎพ็ฝฎ่ฟ‡ๆปคๅ‚ๆ•ฐ๏ผŒไพ›ๆŸฅ่ฏขๆˆ–ๆกไปถๆŸฅ่ฏขไฝฟ็”จ MessageReceive nlbsMessageReceive = new MessageReceive(); nlbsMessageReceive.setReceiverIdentityId(userNo); nlbsMessageReceive.setContent(content); PageHelper.startPage(pageNo, pageSize); List<MessageReceive> nlbsMessageList = messageReceiveDao.selectMessageList(nlbsMessageReceive); PageInfo pageInfo = new PageInfo(nlbsMessageList); //Step 3 ๆ•ด็†ๅ‡บๅ‚ for(MessageReceive nmr : nlbsMessageList){ Map tempMessageMap = new HashMap(); tempMessageMap.put(Fields.PARAM_MSG_SERIAL_NO, nmr.getSerialNo()); tempMessageMap.put(Fields.PARAM_MSG_TITLE, nmr.getTitle()); tempMessageMap.put(Fields.PARAM_MSG_CONTENT, nmr.getContent()); tempMessageMap.put(Fields.PARAM_MSG_SENDER_NAME, nmr.getSenderName()); tempMessageMap.put(Fields.PARAM_MSG_CREATE_TIME, DateUtil.formatDateForDisplay(nmr.getCreateTime())); tempMessageMap.put(Fields.PARAM_MSG_STATUS, nmr.getStatus()); tempMessageMap.put(Fields.PARAM_MSG_INTERNAL_PARAM, nmr.getInternalParam()); returnNlbsMessageMapList.add(tempMessageMap); } resultMap.put(Fields.PARAM_MESSAGE_LIST, returnNlbsMessageMapList); resultMap.put(Fields.PARAM_PAGES, pageInfo.getPages() + ""); resultMap.put(Fields.PARAM_TOTAL, pageInfo.getTotal() + ""); resultMap.put(Fields.PARAM_CURRENT_PAGE, pageInfo.getPageNum() + ""); resultMap.put(Fields.PARAM_MESSAGE_ERR_CODE, ReturnCode.SUCCESS_CODE); resultMap.put(Fields.PARAM_MESSAGE_ERR_MESG, "ๆˆๅŠŸ่Žทๅ–ๆถˆๆฏๅˆ—่กจ๏ผ"); return resultMap; } /** * ไฟฎๆ”นๆŽฅๆ”ถๅˆฐ็š„ๆถˆๆฏ๏ผŒ้ป˜่ฎคไฟฎๆ”นๆถˆๆฏ็Šถๆ€ไธบๅทฒ่ฏป๏ผŒ * <ไป…ๆ”ฏๆŒๆ‰น้‡> * @param paramMap * @return * @throws Exception */ @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public Map modifyReceiveMessage(Map paramMap) throws Exception { Map<String, Object> resultMap = new HashMap(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String readChannel = null != paramMap.get(Fields.PARAM_MSG_READ_CHANNEL) ? paramMap.get(Fields.PARAM_MSG_READ_CHANNEL).toString() : "pcweb"; String status = null != paramMap.get(Fields.PARAM_MSG_STATUS) ? paramMap.get(Fields.PARAM_MSG_STATUS).toString() : "1";//1ไปฃ่กจๅทฒ่ฏป List<Map> serialNoList = null != paramMap.get(Fields.PARAM_SERIAL_NO_LIST) ? (List<Map>) paramMap.get(Fields.PARAM_SERIAL_NO_LIST) : new ArrayList<>(); for(Map serialNoMap : serialNoList){ String serialNo = serialNoMap.get(Fields.PARAM_SERIAL_NO) == null ? null : serialNoMap.get(Fields.PARAM_SERIAL_NO).toString(); if(StringUtils.isBlank(serialNo)){ continue; } MessageReceive nlbsMessage = new MessageReceive(); nlbsMessage.setSerialNo(serialNo); nlbsMessage.setReadTime(sdf.parse(sdf.format(new Date()))); nlbsMessage.setReadChannel(readChannel); nlbsMessage.setStatus(status); messageReceiveDao.updateStatusAndChannelBySerialNo(nlbsMessage); } resultMap.put(Fields.PARAM_MESSAGE_ERR_CODE, ReturnCode.SUCCESS_CODE); resultMap.put(Fields.PARAM_MESSAGE_ERR_MESG, "ๆˆๅŠŸไฟฎๆ”น๏ผˆๆ›ดๆ–ฐ๏ผ‰ๆถˆๆฏ๏ผ"); return resultMap; } /** * ๆŽฅๆ”ถๆถˆๆฏ๏ผŒๅนถไฟๅญ˜่‡ณๆ•ฐๆฎๅบ“ไธญ * * @param paramMap * @return * @throws Exception */ @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public Map receiveMessage(Map paramMap) throws Exception { Map<String, Object> resultMap = new HashMap(); List<Map> messageList = (ArrayList<Map>) paramMap.get(Fields.PARAM_MESSAGE_LIST); if(messageList != null && messageList.size() > 0) { for(Map m : messageList) { MessageReceive plmsMessage = new MessageReceive(); String code = CommonUtil.getCurrentTimeStr(Fields.RECEIVE_MESSAGE_CODE_PREFIX, Fields.RECEIVE_MESSAGE_CODE_SUFFIX); plmsMessage.setCode(code); plmsMessage.setTitle((String) m.get(Fields.PARAM_MSG_TITLE)); plmsMessage.setContent((String) m.get(Fields.PARAM_MSG_CONTENT)); plmsMessage.setSerialNo((String) m.get(Fields.PARAM_MSG_SERIAL_NO)); plmsMessage.setSenderCompanyCode((String) m.get(Fields.PARAM_MSG_SENDER_COMPANY_CODE)); plmsMessage.setSenderCompanyName((String) m.get(Fields.PARAM_MSG_SENDER_COMPANY_NAME)); plmsMessage.setSenderDepartmentCode((String) m.get(Fields.PARAM_MSG_SENDER_DEPARTMENT_CODE)); plmsMessage.setSenderDepartmentName((String) m.get(Fields.PARAM_MSG_SENDER_DEPARTMENT_NAME)); plmsMessage.setSenderIdentityId((String) m.get(Fields.PARAM_MSG_SENDER_IDENTITY_ID)); plmsMessage.setSenderName((String) m.get(Fields.PARAM_MSG_SENDER_NAME)); plmsMessage.setReceiverIdentityId((String) m.get(Fields.PARAM_MSG_RECEIVER_USER_ID)); plmsMessage.setInternalParam((String) m.get(Fields.PARAM_MSG_INTERNAL_PARAM)); messageReceiveDao.savePlmsMessageReceive(plmsMessage); } resultMap.put(Fields.PARAM_MESSAGE_ERR_CODE, ReturnCode.SUCCESS_CODE); resultMap.put(Fields.PARAM_MESSAGE_ERR_MESG, "ๆˆๅŠŸๆŽฅๆ”ถๆถˆๆฏ๏ผ"); return resultMap; } resultMap.put(Fields.PARAM_MESSAGE_ERR_CODE, ReturnCode.MSG_EMPTY_RECEIVE); resultMap.put(Fields.PARAM_MESSAGE_ERR_MESG, "ๆŽฅๆ”ถๆถˆๆฏไธบ็ฉบ๏ผ"); return resultMap; } }
package ru.kappers.convert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.junit.MockitoJUnitRunner; import ru.kappers.model.dto.leon.MarketLeonDTO; import ru.kappers.model.leonmodels.MarketLeon; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; @RunWith(MockitoJUnitRunner.class) public class MarketLeonDTOToMarketLeonConverterTest { @InjectMocks private MarketLeonDTOToMarketLeonConverter converter; @Test public void convertMustReturnNullIfParameterIsNull() { assertThat(converter.convert(null), is(nullValue())); } @Test public void convert() { final List<MarketLeonDTO> dtoList = Arrays.asList( MarketLeonDTO.builder() .id(1L) .name("name 1") .open(true) .build(), MarketLeonDTO.builder() .id(2L) .name("name 2") .open(false) .build() ); for (MarketLeonDTO dto : dtoList) { final MarketLeon result = converter.convert(dto); assertThat(result, is(notNullValue())); assertThat(result.getId(), is(dto.getId())); assertThat(result.getName(), is(dto.getName())); assertThat(result.isOpen(), is(dto.isOpen())); } } }
/** * * @author juansedo, LizOriana1409 */ class Algoritmos { /** * PUNTO 1.1 * Devuelve la subsecuencia comรบn mรกs larga entre dos strings dados. * a - Primer string * b - Segundo string */ public static String lcsdyn(String a, String b) { lcsdyn(a,b,""); } public static String lcsdyn(String a, String b, String output) { if (a.length() == 0 || b.length() == 0) { return ""; } for (int i = 0; i < a.length(); i++) { String snip_a = a.substring(i, i+1); int pos_in_b = b.indexOf(snip_a); /*Si el carรกcter de a estรก en b*/ if (pos_in_b >= 0) { /*Creamos una cadena de carรกcteres de cada carรกcter de a relativo a b*/ String str = snip_a + lcsdyn(a.substring(i+1), b.substring(pos_in_b + 1), ""); /*Va modificando el valor de output hasta encontrar el string mรกs grande*/ if (str.length() > output.length()) output = str; } else { /*Cambia de carรกcter en a*/ return lcsdyn(a.substring(i+1), b, output); } } } /** * PUNTO 1.2 * Devuelve el nรบmero de formas en las que se pueden ubicar * rectรกngulos de 2x1 en un espacio de 2xn. * * @param n Ancho del espacio donde se guardan los rectรกngulos. */ public int formas (int n) { return (n <= 2)? n: formas(n-1) + formas(n-2); } }
/* * Copyright (C) 2001 - 2015 Marko Salmela, http://fuusio.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fuusio.api.util; public class Insets { public int mBottom; public int mLeft; public int mRight; public int mTop; public Insets() { this(0, 0, 0, 0); } public Insets(final int top, final int left, final int bottom, final int right) { mTop = top; mLeft = left; mBottom = bottom; mRight = right; } public Insets(final Insets source) { mTop = source.mTop; mLeft = source.mLeft; mBottom = source.mBottom; mRight = source.mRight; } public final int getBottom() { return mBottom; } public void setBottom(final int bottom) { mBottom = bottom; } public final int getLeft() { return mLeft; } public void setLeft(final int left) { mLeft = left; } public int getRight() { return mRight; } public void setRight(final int right) { mRight = right; } public final int getTop() { return mTop; } public void setTop(final int top) { mTop = top; } public void set(final int top, final int left, final int bottom, final int right) { mTop = top; mLeft = left; mBottom = bottom; mRight = right; } public void set(final Insets insets) { mTop = insets.mTop; mLeft = insets.mLeft; mBottom = insets.mBottom; mRight = insets.mRight; } }
package snake; import snake.exception.CollisionException; import snake.util.Direction; public interface Snake extends Tile { void move(Direction direction) throws CollisionException; void move(Direction direction, int times) throws CollisionException; }
package avex.golem; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import com.mongodb.MongoClient; import com.stripe.model.CustomerCollection; import avex.models.Customer; import avex.models.Order; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import org.bson.types.ObjectId; import org.json.simple.parser.JSONParser; public class AVEXDB { @SuppressWarnings("deprecation") public List<BasicDBObject> GetAthletes() { int i = 1; // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { List<BasicDBObject> athleteList = new ArrayList<>(); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollection = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); DBCursor cursor = athleteCollection.find(); while (cursor.hasNext()) { BasicDBObject athlete = (BasicDBObject) cursor.next(); athleteList.add(athlete); i++; } System.out.println("Received "+ i + " athletes"); mongoClient.close(); System.out.println("Got Athlete List Successfully"); return athleteList; } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); return null; } } public BasicDBObject GetUser(String customerid){ BasicDBObject results = new BasicDBObject(); // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { System.out.println("Get User: " + customerid); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection customerCollection = db.getCollection("customers"); System.out.println("Collection customers selected successfully"); results = (BasicDBObject) customerCollection.findOne(new BasicDBObject().append("_id", new ObjectId(customerid))); mongoClient.close(); System.out.println("Got Customer Information Successfully"); return results; } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); return null; } } public boolean SaveUser(BasicDBObject user,BasicDBObject updatePosition, BasicDBObject transactionHistory){ // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection customersCollect = db.getCollection("customers"); System.out.println("Collection customers selected successfully"); BasicDBObject queryFind = new BasicDBObject(); queryFind.append("_id", new ObjectId(user.getString("_id"))); if(!updatePosition.isEmpty()){ customersCollect.update(queryFind, updatePosition); } if(!transactionHistory.isEmpty()){ customersCollect.update(queryFind, transactionHistory); } mongoClient.close(); System.out.println("Saved Customer Successfully"); return true; } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); return false; } } public boolean UpdateOrder(String orderid,BasicDBObject updateOrder){ // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection ordersCollect = db.getCollection("orders"); System.out.println("Collection orders selected successfully"); BasicDBObject queryFind = new BasicDBObject(); queryFind.append("_id", new ObjectId(orderid)); if(!updateOrder.isEmpty()){ BasicDBObject order = new BasicDBObject(); order.append("$set", updateOrder); ordersCollect.update(queryFind, order); } System.out.println("Saved Order Successfully"); mongoClient.close(); return true; } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); return false; } } public boolean CreateNewOrder(BasicDBObject newOrder){ // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection ordersCollect = db.getCollection("orders"); System.out.println("Collection orders selected successfully"); ordersCollect.insert(newOrder); mongoClient.close(); System.out.println("Created Order Successfully"); return true; } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); return false; } } public void CompleteAthleteQueue(String athleteID){ // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { System.out.println("Get Athlete Queue: " + athleteID); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollection = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); athleteCollection.update(new BasicDBObject().append("_id", new ObjectId(athleteID)), new BasicDBObject().append("$inc", new BasicDBObject().append("currentqueue", 1))); System.out.println("Update CurrentQueue successfully"); mongoClient.close(); } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); } } public boolean SaveAthlete(BasicDBObject athlete,BasicDBObject price, BasicDBObject shares, BasicDBObject order, BasicDBObject pricehistory){ // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { System.out.println("Save Athlete Data: " + athlete); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollect = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); BasicDBObject queryFindAthlete = new BasicDBObject(); queryFindAthlete.append("_id", new ObjectId(athlete.getString("_id"))); if(!price.isEmpty()){ athleteCollect.update(queryFindAthlete, price); } if(!shares.isEmpty()){ athleteCollect.update(queryFindAthlete, shares); } if(!order.isEmpty()){ athleteCollect.update(queryFindAthlete, order); } if(!pricehistory.isEmpty()){ athleteCollect.update(queryFindAthlete, pricehistory); } mongoClient.close(); System.out.println("Saved Athlete successfully"); return true; } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); return false; } } public BasicDBObject GetSettings(){ BasicDBObject results = new BasicDBObject(); // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection settingsCollect = db.getCollection("settings"); System.out.println("Collection settings selected successfully"); results = (BasicDBObject) settingsCollect.findOne(); System.out.println("Received Settings Successfully"); mongoClient.close(); } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); } return results; } public BasicDBObject GetAthleteByID(String athleteID){ BasicDBObject results = new BasicDBObject(); // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { System.out.println("Get Athlete By ID: " + athleteID); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollect = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); BasicDBObject queryFindAthlete = new BasicDBObject(); queryFindAthlete.append("_id", new ObjectId(athleteID)); results = (BasicDBObject) athleteCollect.findOne(queryFindAthlete); mongoClient.close(); } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); } System.out.println("Got Athlete By Athlete ID successfully"); return results; } public List<BasicDBObject> GetOrdersByAthleteId(int actiontype, String athleteID,int extathleteID){ List<BasicDBObject> results = new ArrayList<>(); // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { List<BasicDBObject> obj = new ArrayList<BasicDBObject>(); List<BasicDBObject> obj1 = new ArrayList<BasicDBObject>(); obj1.add(new BasicDBObject().append("athleteid", athleteID)); obj1.add(new BasicDBObject().append("extathleteid", extathleteID)); BasicDBObject athleteFind = new BasicDBObject(); athleteFind.put("$or",obj1); obj.add(athleteFind); obj.add(new BasicDBObject().append("recordstatus", new BasicDBObject().append("$ne", 3))); obj.add(new BasicDBObject().append("recordstatus", new BasicDBObject().append("$ne", 4))); //ActionType 1 equals Buy Order if(actiontype == 1){ obj.add(new BasicDBObject().append("actiontype", "sell")); System.out.println("Get Sell Orders for AthleteID: " + athleteID); } //ActionType 2 equals Sell Order else if(actiontype == 2){ obj.add(new BasicDBObject().append("actiontype", "buy")); System.out.println("Get Buy Orders for AthleteID: " + athleteID); } BasicDBObject andQuery = new BasicDBObject(); andQuery.put("$and", obj); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection ordersCollection = db.getCollection("orders"); System.out.println("Collection orders selected successfully"); DBCursor cursor = ordersCollection.find(andQuery).sort(new BasicDBObject().append("recordstatusdate", -1)); while (cursor.hasNext()) { BasicDBObject order = (BasicDBObject) cursor.next(); results.add(order); } System.out.println("Received orders by athlete successfully"); mongoClient.close(); return results; } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); return null; } } public long GetUserQueuePosition(String athleteID){ long results = 0; // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { System.out.println("Get Customer Queue Position for AthleteID: " + athleteID); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollection = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); BasicDBObject x = (BasicDBObject) athleteCollection.findAndModify(new BasicDBObject().append("_id", new ObjectId(athleteID)), new BasicDBObject().append("$inc", new BasicDBObject().append("nextqueue", 1))); results = x.getLong("nextqueue"); System.out.println("CUSTOMER POSITION: " + results); mongoClient.close(); return results; } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); return -1; } } public Boolean CurrentQueue(long userposition,String athleteID){ // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { System.out.println("Get Current Queue Position for AthleteID: " + athleteID); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollection = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); BasicDBObject x = (BasicDBObject) athleteCollection.findOne(new BasicDBObject().append("_id", new ObjectId(athleteID))); System.out.println("CURRENT QUEUE:" + x.getLong("currentqueue")); System.out.println("USER QUEUE:" + userposition); if(userposition == x.getLong("currentqueue")){ System.out.println("READY FOR PROCESSING"); mongoClient.close(); return true; } else{ System.out.println("NOT READY YET FOR PROCESSING"); mongoClient.close(); return false; } } catch(Exception ex) { mongoClient.close(); System.out.println("Class: AVEXDB - Method: CurrentQueue- Exception: " + ex.getMessage()); System.out.println("Class: AVEXDB - Method: CurrentQueue- Stack Trace: " + ex.getStackTrace()); return false; } } @SuppressWarnings("deprecation") public List<BasicDBObject> GetOrders() { int i = 1; // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { List<BasicDBObject> ordersList = new ArrayList<>(); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection ordersCollection = db.getCollection("orders"); System.out.println("Collection orders selected successfully"); BasicDBObject queryFindOrders = new BasicDBObject(); queryFindOrders.append("recordstatus", new BasicDBObject("$ne", 3)); queryFindOrders.append("recordstatus", new BasicDBObject("$ne", 4)); DBCursor cursor = ordersCollection.find(queryFindOrders); while (cursor.hasNext()) { BasicDBObject order = (BasicDBObject) cursor.next(); ordersList.add(order); i++; } System.out.println("Received "+ i + " orders"); mongoClient.close(); return ordersList; } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); return null; } } @SuppressWarnings({ "deprecation", "rawtypes" }) public void SendAthleteValuetoDB(Map<Integer,BasicDBObject> athletes) { // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollect = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); Iterator it = athletes.entrySet().iterator(); while (it.hasNext()) { BasicDBObject query = new BasicDBObject(); Map.Entry pair = (Map.Entry)it.next(); query.append("athleteid", pair.getKey()); BasicDBObject setNewValue = new BasicDBObject().append("$push", new BasicDBObject().append("athletevalues", pair.getValue())); BasicDBObject availablity = new BasicDBObject().append("$set", new BasicDBObject().append("isavailable", true)); athleteCollect.update(query, setNewValue); athleteCollect.update(query, availablity); System.out.println(pair.getKey() + " = " + pair.getValue()); it.remove(); // avoids a ConcurrentModificationException } mongoClient.close(); } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); } } @SuppressWarnings("deprecation") public void GetAthleteQuote(int athleteID,String playerName) { System.out.println("Get Athlete Quote for AthleteID: " + athleteID); // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollect = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); BasicDBObject queryFindAthlete = new BasicDBObject(); queryFindAthlete.append("athleteid", athleteID); boolean findQuote = true; String name = playerName.replaceAll("[-+.^:,'\\s+]",""); while (findQuote) { BasicDBObject queryQuote = new BasicDBObject(); String quote = Shuffle(name).substring(0, 4).toUpperCase(); queryQuote.append("quote", quote); if (athleteCollect.find(queryQuote).count() <= 0) { BasicDBObject setNewQuote = new BasicDBObject().append("$set", new BasicDBObject().append("quote", quote)); athleteCollect.update(queryFindAthlete, setNewQuote); BasicDBObject findInfo = (BasicDBObject) athleteCollect.findOne(queryFindAthlete); System.out.println(findInfo.toString()); break; } } mongoClient.close(); } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); } } @SuppressWarnings("deprecation") public void UpdateCurrentPrice(int athleteID, DBObject value){ // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try{ System.out.println("Update Current Price for AthleteID: " + athleteID); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollect = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); BasicDBObject queryFindAthlete = new BasicDBObject(); queryFindAthlete.append("athleteid", athleteID); BasicDBObject athleteObject = (BasicDBObject) athleteCollect.findOne(queryFindAthlete); if (athleteObject != null) { Double currentPrice = Double.valueOf(String.valueOf(value.get("currentprice"))); BasicDBObject setPrice = new BasicDBObject().append("$set", new BasicDBObject().append("currentprice", currentPrice)); BasicDBObject priceHistory = new BasicDBObject().append("price",currentPrice); priceHistory.append("isathletevalueprice", true); priceHistory.append("recordstatusdate", new Date()); priceHistory.append("recordstatus", 1); BasicDBObject setHistory = new BasicDBObject().append("$push", new BasicDBObject().append("pricehistory", priceHistory)); athleteCollect.update(queryFindAthlete, setPrice); athleteCollect.update(queryFindAthlete, setHistory); } mongoClient.close(); } catch(Exception ex) { mongoClient.close(); System.out.println("Method:UpdateCurrentPrice Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); } } @SuppressWarnings("deprecation") public void AthleteUnavailable(int athleteID){ // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try{ System.out.println("Update Current Price for AthleteID: " + athleteID); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollect = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); BasicDBObject queryFindAthlete = new BasicDBObject(); queryFindAthlete.append("athleteid", athleteID); BasicDBObject athleteObject = (BasicDBObject) athleteCollect.findOne(queryFindAthlete); if (athleteObject != null) { BasicDBObject availablity = new BasicDBObject().append("$set", new BasicDBObject().append("isavailable", false)); athleteCollect.update(queryFindAthlete, availablity); } mongoClient.close(); } catch(Exception ex) { mongoClient.close(); System.out.println("Method:UpdateCurrentPrice Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); } } @SuppressWarnings("deprecation") public void UpdateTeamByAthlete(int athleteID, int teamID) { System.out.println("Update Team By Athlete for AthleteID: " + athleteID); // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollect = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); DBCollection teamCollect = db.getCollection("teams"); System.out.println("Collection teams selected successfully"); BasicDBObject queryFindAthlete = new BasicDBObject(); queryFindAthlete.append("athleteid", athleteID); BasicDBObject queryFindTeam = new BasicDBObject(); queryFindTeam.append("teamid", teamID); BasicDBObject teamObject = (BasicDBObject) teamCollect.findOne(queryFindTeam); if (teamObject != null) { BasicDBObject setTeam = new BasicDBObject().append("$set", new BasicDBObject().append("team", teamObject)); athleteCollect.update(queryFindAthlete, setTeam); } mongoClient.close(); } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); } } @SuppressWarnings("deprecation") public void GetAthleteIPO(int athleteID,String quote,int numberofshares, int orderseq){ // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { System.out.println("Get Athlete IPO for AthleteID: " + athleteID); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollect = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); DBCollection orderCollect = db.getCollection("orders"); System.out.println("Collection orders selected successfully"); BasicDBObject queryFindAthlete = new BasicDBObject(); queryFindAthlete.append("athleteid", athleteID); queryFindAthlete.append("listorders", new BasicDBObject("$exists", false)); if (athleteCollect.find(queryFindAthlete).count() >= 0) { queryFindAthlete = new BasicDBObject(); queryFindAthlete.append("athleteid", athleteID); BasicDBObject athleteIPO = new BasicDBObject().append("orderid",orderseq); athleteIPO.append("actiontype", "sell"); athleteIPO.append("quantity", numberofshares); athleteIPO.append("recordstatusdate", new Date()); athleteIPO.append("recordstatus", 1); athleteIPO.append("extathleteid", athleteID); BasicDBObject setOrders = new BasicDBObject().append("$push", new BasicDBObject().append("listorders", athleteIPO)); BasicDBObject setAthleteValue = new BasicDBObject(); setAthleteValue.append("availableshares", numberofshares); setAthleteValue.append("isavailable", true); setAthleteValue.append("isresellable", false); setOrders.append("$inc", new BasicDBObject().append("orderseq", 1)); setOrders.append("$set", setAthleteValue); athleteCollect.update(queryFindAthlete, setOrders); orderCollect.insert(athleteIPO); BasicDBObject findInfo = (BasicDBObject) athleteCollect.findOne(queryFindAthlete); System.out.println(findInfo.toString()); } mongoClient.close(); } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); } } private String Shuffle(String input){ List<Character> characters = new ArrayList<Character>(); for(char c:input.toCharArray()){ characters.add(c); } StringBuilder output = new StringBuilder(input.length()); while(characters.size()!=0){ int randPicker = (int)(Math.random()*characters.size()); output.append(characters.remove(randPicker)); } return output.toString(); } public void UpdateAthleteImage(String athlete, BasicDBObject value){ // To connect to mongodb server MongoClient mongoClient = new MongoClient(Program.DATABASE_CONNECTION , Program.DATABASE_PORT ); try { System.out.println("Save Athlete Data: " + athlete); // Now connect to your databases DB db = mongoClient.getDB(Program.DATABASE_NAME); System.out.println("Connect to database successfully"); //boolean auth = db.authenticate(myUserName, myPassword); //System.out.println("Authentication: "+auth); DBCollection athleteCollect = db.getCollection("athletes"); System.out.println("Collection athletes selected successfully"); BasicDBObject queryFindAthlete = new BasicDBObject(); queryFindAthlete.append("_id", new ObjectId(athlete)); if(!value.isEmpty()){ athleteCollect.update(queryFindAthlete, value); } mongoClient.close(); System.out.println("Saved Athlete successfully"); } catch(Exception ex) { mongoClient.close(); System.out.println("Exception: " + ex.getMessage()); System.out.println("Stack Trace: " + ex.getStackTrace()); } } }
package com.autentia.elkexample.test; import com.autentia.elkexample.Application; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.test.OutputCapture; public class ApplicationTest { @Rule public OutputCapture outputCapture = new OutputCapture(); @Test public void testDefaultSettings() throws Exception { assertEquals(0, SpringApplication.exit(SpringApplication .run(Application.class, "duration=1"))); String output = this.outputCapture.toString(); assertTrue("Wrong output: " + output, output.contains("completed with the following parameters")); } }
package com.pointburst.jsmusic.ui; import android.app.Dialog; import android.app.Notification; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.widget.RemoteViews; import android.widget.Toast; import com.android.volley.*; import com.pointburst.jsmusic.R; import com.pointburst.jsmusic.constant.ApiEvent; import com.pointburst.jsmusic.constant.Constants; import com.pointburst.jsmusic.model.Album; import com.pointburst.jsmusic.model.Media; import com.pointburst.jsmusic.model.Result; import com.pointburst.jsmusic.network.ServiceResponse; import com.pointburst.jsmusic.network.VolleyGenericRequest; import com.pointburst.jsmusic.network.VolleyHelper; import com.pointburst.jsmusic.parser.BaseParser; import com.pointburst.jsmusic.parser.IParser; import com.pointburst.jsmusic.utils.Logger; import com.pointburst.jsmusic.utils.StringUtils; /** * Created by FARHAN on 12/27/2014. */ abstract public class BaseActivity extends FragmentActivity implements Response.Listener, Response.ErrorListener, View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /** * Helper method to make Http get data from server. * * @param url request url * @param eventType request event type * @param requestObject Object used to uniquely identify the response */ public boolean fetchData(String url, final int eventType,IParser parser,Object requestObject,Response.Listener responseListener,Response.ErrorListener errorListener,Context ctx,boolean isLoaderRequired) { boolean returnVal = false; String cachedResponse = getJSONForRequest(eventType); final IParser parser1 = parser == null ? new BaseParser() : parser; if (StringUtils.isNullOrEmpty(cachedResponse)) { Logger.print("request " + url + ""); VolleyGenericRequest req = new VolleyGenericRequest(url, responseListener, errorListener, ctx); req.setRequestData(requestObject); req.setEvent(eventType); req.setParser(parser1); //TODO req.setRequestTimeOut(Constants.API_TIMEOUT); VolleyHelper.getInstance(this).addRequestInQueue(req); } else { final String tempResponse = cachedResponse; runOnUiThread(new Runnable() { @Override public void run() { // Log.d("BaseActivity fetchData", "found response in cache for eventType " + eventType); onResponse(parser1.parseData(eventType, tempResponse)); //TODO execute it on Non UI Thread } }); } return returnVal; } private ProgressDialog mProgressDialog; /** * Shows a simple native progress dialog<br/> * Subclass can override below two methods for custom dialogs- <br/> * 1. showProgressDialog <br/> * 2. removeProgressDialog * * @param bodyText */ public void showProgressDialog(String bodyText) { if (isFinishing()) { return; } if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(BaseActivity.this); mProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mProgressDialog.setCancelable(false); mProgressDialog.setOnKeyListener(new Dialog.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_CAMERA || keyCode == KeyEvent.KEYCODE_SEARCH) { return true; // } return false; } }); } mProgressDialog.setMessage(bodyText); if (!mProgressDialog.isShowing()) { mProgressDialog.show(); } } /** * Removes the simple native progress dialog shown via showProgressDialog <br/> * Subclass can override below two methods for custom dialogs- <br/> * 1. showProgressDialog <br/> * 2. removeProgressDialog */ public void removeProgressDialog() { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } } /** * Utility function for displaying progress dialog * */ public void showProgressDialog() { showProgressDialog("Loading..."); } /** * Utility function for showing common error dialog. * * @param message */ public void showToast(String message) { if (TextUtils.isEmpty(message)) { message = "Something went wrong"; } Toast.makeText(this,message,Toast.LENGTH_SHORT).show(); } /** * Helper function to obtain cached json data based on event type * * @param eventType * @return */ public String getJSONForRequest(int eventType) { String request = null; switch (eventType) { case ApiEvent.GET_ALBUM_EVENT: request = Constants.MEDIA_RESULT; break; default: } SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); if (preferences.contains(request)) { return preferences.getString(request, ""); } return ""; } @Override public void onErrorResponse(VolleyError error) { removeProgressDialog(); ServiceResponse responseObj = new ServiceResponse(); responseObj.setResponseCode(ServiceResponse.ERROR); /*int statusCode = error.networkResponse.statusCode; NetworkResponse response = error.networkResponse; Log.d("testerror",""+statusCode+" "+response.data);*/ // Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button. // For AuthFailure, you can re login with user credentials. // For ClientError, 400 & 401, Errors happening on client side when sending api request. // In this case you can check how client is forming the api and debug accordingly. // For ServerError 5xx, you can do retry or handle accordingly. if( error instanceof NetworkError) { responseObj.setErrorMessage("Network Connection is not available."); } else if( error instanceof ServerError) { responseObj.setErrorMessage("Server Error"); } else if( error instanceof AuthFailureError) { responseObj.setErrorMessage("Auth Error"); } else if( error instanceof ParseError) { responseObj.setErrorMessage("Parsing Error"); } else if( error instanceof NoConnectionError) { responseObj.setErrorMessage("No connection could be established."); } else if( error instanceof TimeoutError) { responseObj.setErrorMessage("Network Connection Time out"); } updateUi(responseObj); } @Override public void onResponse(Object response) { removeProgressDialog(); updateUi((ServiceResponse)response); } public void updateUi(ServiceResponse response){ } }
package com.tdp.pasrasapp; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.tdp.bean.BeanActividad; import com.tdp.bean.BeanUsuario; import com.tdp.util.Constants; import com.tdp.util.RequestAsynctask; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.ParseException; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.os.Build; public class ActividadPrincipal extends Activity { Button btningresar; EditText txtusu; EditText txtcla; TextView txtnuevousu; final BeanUsuario be = new BeanUsuario(); RequestAsynctask request; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.prlogueo); btningresar = (Button)findViewById(R.id.btningreso); txtusu = (EditText)findViewById(R.id.correoUsuario); txtcla = (EditText)findViewById(R.id.claveUsuario); txtnuevousu = (TextView)findViewById(R.id.txtnuevo); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); request = new RequestAsynctask(this); btningresar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //http://tallerandroid.cesar-pillihuaman.com/index.php/user/buscar/mromero@gmail.com/abcd if (!txtusu.getText().toString().equals("") && !txtcla.equals("") ){ /* String url = Constants.API + Constants.APIsection + Constants.apiCorreoUsuario + txtusu.getText().toString() + Constants.apiClaveUsuario + txtcla.getText().toString(); */ String url = Constants.API + "index.php/user/buscar/" + txtusu.getText().toString() + "/" + txtcla.getText().toString() ; System.out.println("URL : "+url); request.validaUsuario(url); //Toast.makeText(getApplicationContext(), "Ingreso Correctamente", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(), "Ingrese los datos correctamente", Toast.LENGTH_SHORT).show(); } } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void mostrarMenuPrincipal (BeanUsuario poBusu){ System.out.println("APELIIDOSSSS: +++" + poBusu.getIdusuario() ); int codTipo= 0; codTipo = poBusu.getCod_tip(); if(codTipo == 1 ){//va a la pantalla de coordinadores Intent intent = new Intent(ActividadPrincipal.this,MainPlanificacion.class); Bundle bun = new Bundle(); bun.putString("idUsuario", "" + poBusu.getIdusuario() ); // asignamos al intent los parametros a enviar intent.putExtra("beanusuario", bun); // cambiamos de activity startActivity(intent); }else{ //va a la pantalla ver actividades y registrar hh reales Intent intent = new Intent(ActividadPrincipal.this,MainRegistrarPlanific.class); Bundle bun = new Bundle(); bun.putString("idUsuario", "" + poBusu.getIdusuario() ); bun.putString("codTipo", "" + poBusu.getCod_tip() ); // asignamos al intent los parametros a enviar intent.putExtra("beanUsuarioCola", bun); // cambiamos de activity startActivity(intent); } } public void validacionTerminada(String jsonResult) { Log.d("VALIDA",jsonResult); try { JSONArray respJSON = new JSONArray(jsonResult); if ( respJSON != null ) { //RECIIMOS DATOS DEL USUARIO Y GENERAMOS UN REGISTRO EN SQLITE //JSONObject dato = jsonData.getJSONObject(Constants.APIdata); int n = respJSON.length(); for (int i = 0; i < n; i++) { JSONObject dato = respJSON.getJSONObject(i); be.setApellidos(dato.getString(Constants.APIdataAPEUSUARIO)); be.setCorreo(dato.getString(Constants.APIdataCORREOUSUARIO)); be.setNombre(dato.getString(Constants.APIdataNOMBREUSUARIO)); be.setIdusuario(Integer.parseInt(dato.getString("id"))); be.setCod_tip(Integer.parseInt(dato.getString("codTipo"))); } /* JSONObject jsonData = new JSONObject (jsonResult); if (jsonData.getString(Constants.APIresponse).equals(Constants.apiVarErrorOK)) { //RECIIMOS DATOS DEL USUARIO Y GENERAMOS UN REGISTRO EN SQLITE JSONObject dato = jsonData.getJSONObject(Constants.APIdata); be.setApellidos(dato.getString(Constants.APIdataAPEUSUARIO)); be.setCorreo(dato.getString(Constants.APIdataCORREOUSUARIO)); be.setNombre(dato.getString(Constants.APIdataNOMBREUSUARIO)); be.setIdusuario(Integer.parseInt(dato.getString(Constants.APIdataIDUSUARIO))); be.setCod_tip(Integer.parseInt(dato.getString("codTipo"))); System.out.println("APELIIDOSSSS: +++"+be.getApellidos()); */ mostrarMenuPrincipal(be); }else{ Toast.makeText(this, "Error revise sus datos", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }
package com.podarbetweenus.Activities; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.podarbetweenus.Adapter.AdminMesageAdapter; import com.podarbetweenus.Adapter.TeacherMessageAdapter; import com.podarbetweenus.BetweenUsConstant.Constant; import com.podarbetweenus.Entity.LoginDetails; import com.podarbetweenus.R; import com.podarbetweenus.Services.DataFetchService; import com.podarbetweenus.Utility.AppController; import org.json.JSONObject; /** * Created by Gayatri on 3/16/2016. */ public class AdminSentMessage extends Activity implements AdapterView.OnItemClickListener{ //UI Variable //ListView ListView lv_admin_sentmessage_list; //TExtView TextView tv_no_record; //ProgressDialog ProgressDialog progressDialog; String usl_id,clt_id,board_name,org_id,version_name,school_name,admin_name,check = "1",detail_msg,sender_name, date,subject,toUslId,pmuId,stud_id,academic_year,attachment_name,attachment_path; String ShowViewMessagesMethod_name = "ViewAdminMessageDetails"; int pageNo = 1,notificationId,notificationID=1,viewTeacherMessageListSize,tab_position; int pageSize = 200; DataFetchService dft; LoginDetails login_details; AdminMesageAdapter teacherMessageAdapter; @Override protected void onCreate(Bundle savedInstanceState) { Log.d("<<Inside","AdminSentMessage"); super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.admin_sendmessage_layout); findViews(); init(); getIntentId(); //Call ws of Send Messages callWsSendMessages(clt_id,usl_id,check,pageNo,pageSize); } private void getIntentId() { Intent intent = getIntent(); usl_id = intent.getStringExtra("usl_id"); clt_id = intent.getStringExtra("clt_id"); school_name = intent.getStringExtra("School_name"); admin_name = intent.getStringExtra("Admin_name"); version_name = intent.getStringExtra("version_name"); org_id = intent.getStringExtra("org_id"); academic_year = intent.getStringExtra("academic_year"); AppController.versionName = version_name; board_name = intent.getStringExtra("board_name"); } private void init() { dft= new DataFetchService(this); login_details = new LoginDetails(); progressDialog = Constant.getProgressDialog(this); lv_admin_sentmessage_list.setOnItemClickListener(this); } private void callWsSendMessages(String clt_id,String usl_id,String check,int pageNo,int pageSize) { if(dft.isInternetOn()==true) { if (!progressDialog.isShowing()) { progressDialog.show(); } } else{ progressDialog.dismiss(); } dft.getAdminMessages(clt_id, usl_id, check, pageNo, pageSize, ShowViewMessagesMethod_name, Request.Method.POST, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } try { login_details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class); if (login_details.Status.equalsIgnoreCase("1")) { tv_no_record.setVisibility(View.GONE); // getListView().setVisibility(View.VISIBLE); lv_admin_sentmessage_list.setVisibility(View.VISIBLE); setUIDataDataForList(); } else { lv_admin_sentmessage_list.setVisibility(View.GONE); tv_no_record.setVisibility(View.VISIBLE); tv_no_record.setText("No Records Found"); } } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //Show error or whatever... Log.d("LoginActivity", "ERROR.._---" + error.getCause()); } }); } private void setUIDataDataForList() { teacherMessageAdapter = new AdminMesageAdapter(AdminSentMessage.this,login_details.ViewMessageResult,notificationId,clt_id,usl_id,school_name,academic_year,org_id,admin_name,board_name,version_name); lv_admin_sentmessage_list.setAdapter(teacherMessageAdapter); } private void findViews() { //TExtView tv_no_record = (TextView) findViewById(R.id.tv_no_record); //ListView lv_admin_sentmessage_list = (ListView) findViewById(R.id.lv_admin_sentmessage_list); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { try { AppController.SendMessageLayout = "false"; detail_msg = login_details.ViewMessageResult.get(position).pmg_Message; sender_name = login_details.ViewMessageResult.get(position).Fullname; date = login_details.ViewMessageResult.get(position).pmg_date; subject = login_details.ViewMessageResult.get(position).pmg_subject; stud_id = login_details.ViewMessageResult.get(position).stu_id; toUslId = login_details.ViewMessageResult.get(position).usl_ID; pmuId = login_details.ViewMessageResult.get(position).pmu_ID; attachment_name = login_details.ViewMessageResult.get(position).pmg_file_name; attachment_path = login_details.ViewMessageResult.get(position).pmg_file_path; Intent detail_msg_intent = new Intent(AdminSentMessage.this, AdminDetailMessage.class); detail_msg_intent.putExtra("Detail Message", detail_msg); detail_msg_intent.putExtra("Sender Name", sender_name); detail_msg_intent.putExtra("Date", date); detail_msg_intent.putExtra("clt_id", clt_id); detail_msg_intent.putExtra("usl_id", usl_id); detail_msg_intent.putExtra("School_name", school_name); detail_msg_intent.putExtra("Admin_name", admin_name); detail_msg_intent.putExtra("version_name", AppController.versionName); detail_msg_intent.putExtra("board_name", board_name); detail_msg_intent.putExtra("Subject", subject); detail_msg_intent.putExtra("Attachment Name",attachment_name); detail_msg_intent.putExtra("Attachment Path",attachment_path); detail_msg_intent.putExtra("stud_id", stud_id); detail_msg_intent.putExtra("academic_year", academic_year); detail_msg_intent.putExtra("toUslId", toUslId); detail_msg_intent.putExtra("Pmu_Id", pmuId); detail_msg_intent.putExtra("org_id", org_id); startActivity(detail_msg_intent); } catch (Exception e){ e.printStackTrace(); } } @Override public void onBackPressed() { //super.onBackPressed(); Intent back = new Intent(AdminSentMessage.this,AdminProfileActivity.class); AppController.OnBackpressed = "false"; AppController.AdminSentMessage = "false"; AppController.clt_id = clt_id; AppController.usl_id = usl_id; AppController.Board_name = board_name; back.putExtra("clt_id", AppController.clt_id); back.putExtra("msd_ID",AppController.msd_ID); back.putExtra("msd_ID",AppController.msd_ID); back.putExtra("usl_id",AppController.usl_id); back.putExtra("board_name",board_name); back.putExtra("School_name", school_name); back.putExtra("Admin_name", admin_name); back.putExtra("org_id",org_id); back.putExtra("academic_year",academic_year); back.putExtra("version_name",AppController.versionName); back.putExtra("verion_code",AppController.versionCode); startActivity(back); } }