text
stringlengths
10
2.72M
package seedu.address.logic.commands.deliveryman; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.commons.core.Messages.MESSAGE_DELIVERYMEN_LISTED_OVERVIEW; import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.address.testutil.TypicalDeliverymen.CHIKAO; import static seedu.address.testutil.TypicalDeliverymen.MANIKA; import static seedu.address.testutil.TypicalDeliverymen.RAJUL; import static seedu.address.testutil.TypicalDeliverymen.getTypicalDeliverymenList; import static seedu.address.testutil.TypicalOrders.getTypicalOrderBook; import static seedu.address.testutil.user.TypicalUsers.getTypicalUsersList; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import seedu.address.logic.CommandHistory; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.model.deliveryman.DeliverymanNameContainsKeywordsPredicate; /** * Contains integration tests (interaction with the Model) for {@code DeliverymanFindCommandTest}. */ public class DeliverymanFindCommandTest { // TODO: Add deliveryman into Model Manager after merge private Model model = new ModelManager(getTypicalOrderBook(), getTypicalUsersList(), getTypicalDeliverymenList(), new UserPrefs()); private Model expectedModel = new ModelManager(getTypicalOrderBook(), getTypicalUsersList(), getTypicalDeliverymenList(), new UserPrefs()); private CommandHistory commandHistory = new CommandHistory(); @Test public void equals() { DeliverymanNameContainsKeywordsPredicate firstPredicate = new DeliverymanNameContainsKeywordsPredicate(Collections.singletonList("first")); DeliverymanNameContainsKeywordsPredicate secondPredicate = new DeliverymanNameContainsKeywordsPredicate(Collections.singletonList("second")); DeliverymanFindCommand findFirstOrderCommand = new DeliverymanFindCommand(firstPredicate); DeliverymanFindCommand findSecondOrderCommand = new DeliverymanFindCommand(secondPredicate); // same object -> returns true assertTrue(findFirstOrderCommand.equals(findFirstOrderCommand)); // same values -> returns true DeliverymanFindCommand findFirstOrderCommandCopy = new DeliverymanFindCommand(firstPredicate); assertTrue(findFirstOrderCommand.equals(findFirstOrderCommandCopy)); // different types -> returns false assertFalse(findFirstOrderCommand.equals(1)); // null -> returns false assertFalse(findFirstOrderCommand.equals(null)); // different common -> returns false assertFalse(findFirstOrderCommand.equals(findSecondOrderCommand)); } @Test public void execute_zeroKeywords_noDeliverymanFound() { String expectedMessage = String.format(MESSAGE_DELIVERYMEN_LISTED_OVERVIEW, 0); DeliverymanNameContainsKeywordsPredicate predicate = preparePredicate(" "); DeliverymanFindCommand commandName = new DeliverymanFindCommand(predicate); expectedModel.updateFilteredDeliverymenList(predicate); assertCommandSuccess(commandName, model, commandHistory, expectedMessage, expectedModel); assertEquals(Collections.emptyList(), model.getFilteredDeliverymenList()); } @Test public void execute_multipleKeywords_multipleDeliverymanFound() { String expectedMessage = String.format(MESSAGE_DELIVERYMEN_LISTED_OVERVIEW, 3); DeliverymanNameContainsKeywordsPredicate predicate = preparePredicate("Chi Monuela Rajul"); DeliverymanFindCommand command = new DeliverymanFindCommand(predicate); expectedModel.updateFilteredDeliverymenList(predicate); assertCommandSuccess(command, model, commandHistory, expectedMessage, expectedModel); assertEquals(Arrays.asList(CHIKAO, MANIKA, RAJUL), model.getFilteredDeliverymenList()); } /** * Parses {@code userInput} into a {@code NameContainsKeywordsPredicate}. */ private DeliverymanNameContainsKeywordsPredicate preparePredicate(String userInput) { return new DeliverymanNameContainsKeywordsPredicate(Arrays.asList(userInput.split("\\s+"))); } }
/* * Watr. Android application * Copyright (c) 2020 Linus Willner, Panu Eronen and Markus Hartikainen. * Licensed under the MIT license. */ package com.watr.app.datastore.room.hydration; import android.content.Context; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Multi-threaded Room database query executor. * * @author linuswillner * @version 1.0.0 */ @Database( entities = {HydrationEntity.class}, version = 1, exportSchema = false) @TypeConverters({TypeConversionUtils.class}) public abstract class HydrationDatabase extends RoomDatabase { private static final int THREAD_COUNT = 4; // Create multi-threaded write executor static final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); // Define singleton instance and thread count private static volatile HydrationDatabase INSTANCE; /** * Gets the global Room database instance. * * @param context Application context * @return {@link HydrationDatabase} */ static HydrationDatabase getDatabase(final Context context) { if (INSTANCE == null) { synchronized (HydrationDatabase.class) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder( context.getApplicationContext(), HydrationDatabase.class, "hydration_database") .build(); } } } return INSTANCE; } // Init DAO public abstract HydrationDao hydrationDao(); }
package user.web; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.log4j.Logger; import tool.PropertyOper; import user.User; /** * User * Servlet控制层:负责从前台收取数据,检查用户session登录,根据url调用相应的业务方法,收取业务方法返回的数据并发送给对应的前端页面, * 存储用户登录信息到session * */ /* @WebServlet("/UserServ") */ public class UserServ extends HttpServlet { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(UserServ.class); /** * 上传内存阈值(文件缓冲区的大小) */ private static final int MEMORY_THRESHOLD = Integer .parseInt(PropertyOper.GetValueByKey("souvenirs.properties", "MEMORY_THRESHOLD"), 16); /** * 上传文件的最大大小 */ private static final int MAX_FILE_SIZE = Integer .parseInt(PropertyOper.GetValueByKey("souvenirs.properties", "MAX_FILE_SIZE"), 16); /** * 可接收的二进制流的最大大小 */ private static final int MAX_REQUEST_SIZE = Integer .parseInt(PropertyOper.GetValueByKey("souvenirs.properties", "MAX_REQUEST_SIZE"), 16); /** * @see HttpServlet#HttpServlet() */ public UserServ() { super(); // TODO Auto-generated constructor stub } /** * {@link Servlet#init(ServletConfig)} */ public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub } /** * User Servlet 控制层获取-分发方法。用户的登出直接在servlet中进行,没有再写业务方法。 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) <br> */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HttpSession session = request.getSession(true); UserManager um = UserManager.getInstance(); Map<String, String> para = new HashMap<String, String>(); Enumeration<?> paraNames = request.getParameterNames(); // Put all parameters from request into a Map transferred to // UserManager while (paraNames.hasMoreElements()) { String paraName = (String) paraNames.nextElement(); String[] paraValues = request.getParameterValues(paraName); String paraValue = paraValues[0]; para.put(paraName, new String(paraValue.getBytes("iso8859-1"), "UTF-8")); } System.out.println(session + " " + para); para.put("login_username", session.getAttribute("username") == null ? "" : (String) session.getAttribute("username")); para.put("login_user_id", session.getAttribute("user_id") == null ? "" : (String) session.getAttribute("user_id")); para.put("login_password", session.getAttribute("password") == null ? "" : (String) session.getAttribute("password")); para.put("login_verifycode_name", session.getAttribute("login_verifycode_name") == null ? "" : (String) session.getAttribute("login_verifycode_name")); para.put("register_verifycode_name", session.getAttribute("register_verifycode_name") == null ? "" : (String) session.getAttribute("register_verifycode_name")); Map<String, Object> result = new HashMap<>(); // Obtain operation url String query_url = request.getServletPath(); query_url = query_url.substring(query_url.lastIndexOf('/') + 1); // Call specific method according to query_url if (query_url.contentEquals("register")) { // Register a new user result = um.register(para); } else if (query_url.contentEquals("login")) { // Check validation of user login information result = um.login(para); } else if (query_url.contentEquals("setting")) { // Check validation of user login information result = um.displaySetting(para); } else if (query_url.contentEquals("logout")) { // Let session invalidate session.invalidate(); logger.info("User(id=<" + para.get("login_user_id") + ">) logout."); response.sendRedirect("index.jsp"); return; } else { // Invalid query_url, redirect to index.jsp result.put("DispatchURL", "index.jsp"); } for (Entry<String, Object> entry : result.entrySet()) { request.setAttribute(entry.getKey(), entry.getValue()); } // If login succeeded, put user information into session if (result.containsKey("login_user_id") && result.containsKey("login_username") && result.containsKey("login_password")) { session.setAttribute("username", result.get("login_username")); session.setAttribute("password", result.get("login_password")); session.setAttribute("user_id", result.get("login_user_id")); session.setAttribute("user", result.get("login_user")); } // Store verify code in session if (result.containsKey("VerifyCode")) session.setAttribute("login_verifycode_name", result.get("VerifyCode")); // Forward or Redirect result to assigned page String dispatchURL = (String) result.get("DispatchURL"); if (result.containsKey("Redirect") && (boolean) result.get("Redirect")) { response.sendRedirect(dispatchURL); } else { RequestDispatcher dispatcher = request.getRequestDispatcher(dispatchURL); dispatcher.forward(request, response); } } /** * 调用doGet方法 * @see #doGet(HttpServletRequest, HttpServletResponse) * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // Obtain operation url String query_url = request.getServletPath(); query_url = query_url.substring(query_url.lastIndexOf('/') + 1); if (query_url.contentEquals("updateSettings")){ HttpSession session = request.getSession(true); // If login information is wrong, redirect to index.jsp in order to // login in again logger.debug(session + " " + session.getAttribute("username") + " " + session.getAttribute("password")); if (!UserManager.checkLogin(session.getAttribute("user_id"), session.getAttribute("username"), session.getAttribute("password"))) { session.invalidate(); response.sendRedirect("loginfail.jsp"); } else { // 检测是否为多媒体上传 if (!ServletFileUpload.isMultipartContent(request)) { // 如果不是则停止 PrintWriter writer = response.getWriter(); writer.println("Error: Form type must be 'enctype=multipart/form-data'"); writer.flush(); return; } // 配置上传参数 DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中 factory.setSizeThreshold(MEMORY_THRESHOLD); // 设置临时存储目录 factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // 设置最大文件上传值 upload.setFileSizeMax(MAX_FILE_SIZE); // 设置最大请求值 (包含文件和表单数据) upload.setSizeMax(MAX_REQUEST_SIZE); Map<String, String> para = new HashMap<>(); Map<String, Object> result = null; UserManager um = UserManager.getInstance(); FileItem file_item = null; try { // 解析请求的内容提取文件数据 List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // 迭代表单数据 for (FileItem item : formItems) { if (item.isFormField()) { String key = item.getFieldName(); String val = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8"); para.put(key, val); } else { // Store file handler file_item = item; } } } // Send user_id as primary key of user to manager object para.put("login_user_id", session.getAttribute("user_id") == null ? "" : (String) session.getAttribute("user_id")); para.put("login_password", session.getAttribute("password") == null ? "" : (String) session.getAttribute("password")); // Send parameters and file handler to UploadManager result =um.updateSettings(para, file_item); if (result.containsKey("new_password")) { session.setAttribute("password", result.get("new_password")); } if (result.containsKey("new_username")) { session.setAttribute("username", result.get("new_username")); ((User)session.getAttribute("user")).setUsername((String)result.get("new_username")); } } catch (Exception ex) { ex.printStackTrace(); request.setAttribute("Error", ex.getMessage()); } for (Entry<String, Object> entry : result.entrySet()) { request.setAttribute(entry.getKey(), entry.getValue()); } // Forward or redirect to assigned page String dispatchURL = result.containsKey("DispatchURL") ? (String) result.get("DispatchURL") : "index.jsp"; if (result.containsKey("Is_redirect")) response.sendRedirect(dispatchURL); else { RequestDispatcher dispatcher = request.getRequestDispatcher(dispatchURL); dispatcher.forward(request, response); } } } else doGet(request, response); } }
package com.karya.dao; import java.util.List; import com.karya.model.HolidayList001MB; import com.karya.model.LeaveApp001MB; import com.karya.model.LeaveBlockList001MB; import com.karya.model.LeaveType001MB; public interface ILeaveDao { public void addLeaveApp(LeaveApp001MB leaveapp001MB); public List<LeaveApp001MB> listleaveapps(); public LeaveApp001MB getleaveapp(int lvappId); public void deleteleaveapp(int lvappId); //Leave Type public void addLeaveType(LeaveType001MB leavetype001MB); public List<LeaveType001MB> listleavetype(); public LeaveType001MB getleavetype(int lvtypeId); public void deleteleavetype(int lvtypeId); //Holiday List public void addholidayList(HolidayList001MB holidaylist001MB); public List<HolidayList001MB> listholidays(); public HolidayList001MB getholidaylist(int hlistId); public void deleteholiday(int hlistId); //Leave Block List public void addleaveblock(LeaveBlockList001MB leaveblocklist001MB); public List<LeaveBlockList001MB> listleaveblock(); public LeaveBlockList001MB getblocklist(int lvblockId); public void deleteleaveblock(int lvblockId); }
package com.ctg.itrdc.janus.rpc.protocol; import java.util.List; import com.ctg.itrdc.janus.common.Constants; import com.ctg.itrdc.janus.common.URL; import com.ctg.itrdc.janus.common.extension.ExtensionLoader; import com.ctg.itrdc.janus.rpc.Exporter; import com.ctg.itrdc.janus.rpc.Filter; import com.ctg.itrdc.janus.rpc.Invocation; import com.ctg.itrdc.janus.rpc.Invoker; import com.ctg.itrdc.janus.rpc.Protocol; import com.ctg.itrdc.janus.rpc.Result; import com.ctg.itrdc.janus.rpc.RpcException; /** * 过滤器Protocol,处理系统的调用过滤链filter。根据系统注册的filter,进行filter的调用处理。 * * 将filter按照级别的优先排列起来,级别高的先调用,级别低的后调用,最后是invoker本身的调用。 * * filter(highest order)->filter(high order)....->filter(low order)...->invoker * * filter链处理分两种:<br/> * 1. export时,通过查找group为provider的filter链 <br/> * 2. refer时,通过查找group为consumer的filter链 * * @author Administrator */ public class ProtocolFilterWrapper implements Protocol { private final Protocol protocol; public ProtocolFilterWrapper(Protocol protocol) { if (protocol == null) { throw new IllegalArgumentException("protocol == null"); } this.protocol = protocol; } public int getDefaultPort() { return protocol.getDefaultPort(); } public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { if (Constants.REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) { return protocol.export(invoker); } return protocol.export(buildInvokerChain(invoker, Constants.SERVICE_FILTER_KEY, Constants.PROVIDER)); } public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) { return protocol.refer(type, url); } return buildInvokerChain(protocol.refer(type, url), Constants.REFERENCE_FILTER_KEY, Constants.CONSUMER); } public void destroy() { protocol.destroy(); } /** * 构建invoker调用的filter链 * * @param invoker * @param key * @param group * @return */ private static <T> Invoker<T> buildInvokerChain(final Invoker<T> invoker, String key, String group) { Invoker<T> last = invoker; List<Filter> filters = ExtensionLoader.getExtensionLoader(Filter.class) .getActivateExtension(invoker.getUrl(), key, group); if (filters.size() == 0) { return last; } for (int i = filters.size() - 1; i >= 0; i--) { final Filter filter = filters.get(i); final Invoker<T> next = last; last = new Invoker<T>() { public Class<T> getInterface() { return invoker.getInterface(); } public URL getUrl() { return invoker.getUrl(); } public boolean isAvailable() { return invoker.isAvailable(); } public Result invoke(Invocation invocation) throws RpcException { return filter.invoke(next, invocation); } public void destroy() { invoker.destroy(); } @Override public String toString() { return invoker.toString(); } }; } return last; } }
package com.example.hawxthy.erebos; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import static junit.framework.TestCase.assertNotNull; /** * Created by HAWXTHY on 24.11.2015. */ @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21, manifest = "src/main/AndroidManifest.xml") public class MainActivityTest { private MainActivity activity; @Before public void setup() { activity = Robolectric.buildActivity(MainActivity.class).create().get(); } @Test public void checkActivityNotNull() throws Exception { assertNotNull(activity); } }
/** * */ package com.fidel.dummybank.controllers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.fidel.dummybank.common.CommUtils; import com.fidel.dummybank.common.Constants; import com.fidel.dummybank.model.CustomerInfo; import com.fidel.dummybank.model.MerchantInfo; import com.fidel.dummybank.model.PayLoad; import com.fidel.dummybank.service.AccountService; import com.fidel.dummybank.service.CustomerService; import com.fidel.dummybank.service.MerchantService; import com.fidel.dummybank.service.SmsSender; /** * @author Swapnil * */ @Controller @RequestMapping(path = "/api/v1") public class PaymentController { @Autowired private CustomerService customerService; @Autowired private AccountService accountService; @Autowired private MerchantService merchantService; @Autowired private SmsSender sender; // logger Logger logger = LoggerFactory.getLogger(PaymentController.class); @PostMapping(path = "/charge") public String charge(@ModelAttribute("pay-load") PayLoad payLoad, Model model) { CustomerInfo custDetails = customerService.findUserByMobNo(payLoad.getMobileNo()); if (custDetails == null) // view to render return "init_credentials"; // view to render return "confirm"; } @PostMapping(path = "/net-pay") public String netPay(@RequestParam(name = "bnk", required = false) String bnk, @RequestParam(name = "othr-bnk", required = false) String othrBnk, PayLoad payLoad, Model model, HttpServletRequest request, HttpServletResponse response) { // mobile number & email check if (payLoad.getMobileNo() == null && payLoad.getEmail() == null) { payLoad.setReqType(Constants.CNCL); model.addAttribute("payload", payLoad); model.addAttribute(Constants.STATUS, Constants.ERROR); model.addAttribute(Constants.MESSAGE, "User data mismatch."); // view to render return "error-request"; } // get customer id from database String uniqCustId = customerService.getUniqCustId(payLoad); // customer id empty check if (uniqCustId.isEmpty()) { payLoad.setReqType(Constants.CNCL); model.addAttribute("payload", payLoad); model.addAttribute(Constants.STATUS, Constants.ERROR); model.addAttribute(Constants.MESSAGE, "User not registered with bank."); return "error-request"; } // get merchant details MerchantInfo mrInfo = merchantService.findById(Integer.parseInt(bnk)); if (mrInfo.getmId() == null) { payLoad.setReqType(Constants.CNCL); model.addAttribute("payload", payLoad); model.addAttribute(Constants.STATUS, Constants.ERROR); model.addAttribute(Constants.MESSAGE, "Merchant not found."); // view to render return "error-request"; } // response preparation model.addAttribute("mrData", mrInfo); model.addAttribute("processUrl", "/api/v1/process-payment"); payLoad.setCustId(uniqCustId); model.addAttribute("payload", payLoad); model.addAttribute("data", customerService.finaById(uniqCustId)); model.addAttribute("curDate", CommUtils.getDateTime()); // view to render return "net-payment"; } @PostMapping(path = "/process-payment") public String processPayment(@RequestParam("status") String status, PayLoad payLoad, Model model, HttpServletRequest request, HttpServletResponse response) { if (status.equals("cancel")) { payLoad.setReqType(Constants.CNCL); model.addAttribute("payload", payLoad); model.addAttribute(Constants.STATUS, Constants.ERROR); model.addAttribute(Constants.MESSAGE, "Payment Error"); // view to render return "net-pay-status"; } String message = "Payment Successful!"; status = "success"; if (!accountService.updateBalance(payLoad)) { payLoad.setReqType(Constants.CNCL); model.addAttribute("payload", payLoad); model.addAttribute(Constants.STATUS, Constants.ERROR); model.addAttribute(Constants.MESSAGE, "Payment Error"); // view to render return "net-pay-status"; } model.addAttribute("payload", payLoad); model.addAttribute("status", status); model.addAttribute("message", message); try { sender.send(payLoad.getMobileNo(), accountService.findById(payLoad.getCustId()), payLoad); } catch (Exception e) { logger.info(e.getMessage()); } // view to render return "net-pay-status"; } @GetMapping(path = "/paymentStatus") public String paymentStatus(@RequestParam("status") String status, @RequestParam("message") String message, PayLoad payLoad, Model model, HttpServletRequest request, HttpServletResponse response) { model.addAttribute("status", status); model.addAttribute("message", message); model.addAttribute("payload", payLoad); return "redirect:https://localhost:8084/wallet/txnStatus?status=" + status + "&message=" + message + "&" + payLoad.toString(); // return "redirect:http://localhost:8084/wallet/txnStatus?status=" + status + // "&message=" + message + "&" // + payLoad.toString(); } }
import java.util.*; class Min_max{ public static void main(String args[]){ Scanner s=new Scanner(System.in); System.out.print("Enter Size of Array: "); int size=s.nextInt(); int i,temp,j; int num[]=new int[size]; System.out.println("Enter Numbers"); for(i=0;i<(size);i++){ num[i]=s.nextInt(); } for(i=0;i<(size-1);i++){ for(j=i+1;j<(size);j++){ if(num[i]>num[j]){ temp=num[j]; num[j]=num[i]; num[i]=temp; } } } System.out.println("Minimum Number "+num[0]); System.out.print("Minimum Number "+num[size-1]); } }
/* * 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. */ import java.awt.GridLayout; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javax.swing.JOptionPane; import java.security.SecureRandom; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import javafx.scene.input.MouseEvent; /** * * @author shoaib */ public class FXMLDocumentController implements Initializable { @FXML public GridLayout table; @FXML public TextField t1; @FXML public TextField t2; @FXML public TextField t3; @FXML public TextField t4; @FXML public TextField t5; @FXML public TextField t6; @FXML public TextField t7; @FXML public TextField t8; @FXML public TextField t9; public boolean playerTurn=true; public boolean playerWon=false; public boolean computerWon=false; public boolean check=false; @FXML public void handleText(MouseEvent event) { String text=((TextField)event.getSource()).getText(); if(text.equals("")){ check=false; if(playerTurn==true){ ((TextField)event.getSource()).setText("X"); playerTurn=false; checkWin(); if(!check){ computerTurn(); checkWin(); } playerTurn=true; } /* else { ((TextField)event.getSource()).setText("O"); playerTurn=true; checkWin(); }*/ } } @FXML public void checkWin(){ if(t1.getText().equals("X")){ if(t2.getText().equals("X")){ if(t3.getText().equals("X")){ playerWon=true; check=playerWon; computerWon=false; } } } if(t1.getText().equals("X")){ if(t5.getText().equals("X")){ if(t9.getText().equals("X")){ playerWon=true; check=playerWon; computerWon=false; } } } if(t1.getText().equals("X")){ if(t4.getText().equals("X")){ if(t7.getText().equals("X")){ playerWon=true; check=playerWon; computerWon=false; } } } if(t2.getText().equals("X")){ if(t5.getText().equals("X")){ if(t8.getText().equals("X")){ playerWon=true; check=playerWon; computerWon=false; } } } if(t3.getText().equals("X")){ if(t5.getText().equals("X")){ if(t7.getText().equals("X")){ playerWon=true; check=playerWon; computerWon=false; } } } if(t3.getText().equals("X")){ if(t6.getText().equals("X")){ if(t9.getText().equals("X")){ playerWon=true; check=playerWon; computerWon=false; } } } if(t4.getText().equals("X")){ if(t5.getText().equals("X")){ if(t6.getText().equals("X")){ playerWon=true; check=playerWon; computerWon=false; } } } if(t7.getText().equals("X")){ if(t8.getText().equals("X")){ if(t9.getText().equals("X")){ playerWon=true; check=playerWon; computerWon=false; } } } if(t1.getText().equals("O")){ if(t2.getText().equals("O")){ if(t3.getText().equals("O")){ playerWon=false; computerWon=true; } } } if(t1.getText().equals("O")){ if(t5.getText().equals("O")){ if(t9.getText().equals("O")){ playerWon=false; computerWon=true; } } } if(t1.getText().equals("O")){ if(t4.getText().equals("O")){ if(t7.getText().equals("O")){ playerWon=false; computerWon=true; } } } if(t2.getText().equals("O")){ if(t5.getText().equals("O")){ if(t8.getText().equals("O")){ playerWon=false; computerWon=true; } } } if(t3.getText().equals("O")){ if(t5.getText().equals("O")){ if(t7.getText().equals("O")){ playerWon=false; computerWon=true; } } } if(t3.getText().equals("O")){ if(t6.getText().equals("O")){ if(t9.getText().equals("O")){ playerWon=false; computerWon=true; } } } if(t4.getText().equals("O")){ if(t5.getText().equals("O")){ if(t6.getText().equals("O")){ playerWon=false; computerWon=true; } } } if(t7.getText().equals("O")){ if(t8.getText().equals("O")){ if(t9.getText().equals("O")){ playerWon=false; computerWon=true; } } } if((!t1.getText().equals(""))&&(!t2.getText().equals(""))&&(!t3.getText().equals("")) &&(!t4.getText().equals(""))&&(!t5.getText().equals(""))&&(!t6.getText().equals("")) &&(!t7.getText().equals(""))&&(!t8.getText().equals(""))&&(!t9.getText().equals(""))){ JOptionPane.showMessageDialog(null,"DRAW"); String msg=JOptionPane.showInputDialog("Do You Want to PlayAgain?(Y/N)"); switch(msg){ case "y": case"Y": t1.setText(""); t2.setText(""); t3.setText(""); t4.setText(""); t5.setText(""); t6.setText(""); t7.setText(""); t8.setText(""); t9.setText(""); playerTurn=true; playerWon=false; computerWon=false; check=true; break; case "n": case"N": JOptionPane.showMessageDialog(null,"thanks for Playing.. :)"); System.exit(0); break; } } if(playerWon==true||computerWon==true){ JOptionPane.showMessageDialog(null,"player 1 Won: "+playerWon+"player 2 Won: "+computerWon,"Result",JOptionPane.PLAIN_MESSAGE); String ans=JOptionPane.showInputDialog("Do You Want to PlayAgain?(Y/N)"); switch(ans){ case "y": case"Y": t1.setText(""); t2.setText(""); t3.setText(""); t4.setText(""); t5.setText(""); t6.setText(""); t7.setText(""); t8.setText(""); t9.setText(""); playerTurn=true; playerWon=false; computerWon=false; check=true; break; case "n": case"N": JOptionPane.showMessageDialog(null,"thanks for Playing.. :)"); System.exit(0); break; } } } public void computerTurn(){ SecureRandom ran=new SecureRandom(); boolean value=false; while(!value){ int n=ran.nextInt(8)+1; switch(n){ case 1: if(t1.getText().equals("")){ t1.setText("O"); value=true; } break; case 2: if(t2.getText().equals("")){ t2.setText("O"); value=true; } break; case 3: if(t3.getText().equals("")){ t3.setText("O"); value=true; } break; case 4: if(t4.getText().equals("")){ t4.setText("O"); value=true; } break; case 5: if(t5.getText().equals("")){ t5.setText("O"); value=true; } break; case 6: if(t6.getText().equals("")){ t6.setText("O"); value=true; } break; case 7: if(t7.getText().equals("")){ t7.setText("O"); value=true; } break; case 8: if(t8.getText().equals("")){ t8.setText("O"); value=true; } break; case 9: if(t9.getText().equals("")){ t9.setText("O"); value=true; } break; } } } @Override public void initialize(URL url, ResourceBundle rb) { // TODO } }
/** * MIT License * <p> * Copyright (c) 2017-2018 nuls.io * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package network.nerve.converter.rpc.call; import io.nuls.core.exception.NulsException; import io.nuls.core.model.StringUtils; import io.nuls.core.rpc.info.Constants; import io.nuls.core.rpc.model.ModuleE; import network.nerve.converter.constant.ConverterConstant; import network.nerve.converter.model.bo.Chain; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import static network.nerve.converter.constant.ConverterConstant.*; /** * @author: Loki * @date: 2020/10/10 */ public class QuotationCall { /** * 根据喂价key获取最终喂价 * @param chain * @param oracleKey * @return */ public static BigDecimal getPriceByOracleKey(Chain chain, String oracleKey) { /********************* 测试用 ***************************/ /*if("ETH_PRICE".equals(oracleKey)){ return new BigDecimal("1800.6417"); } else if (ORACLE_KEY_NVT_PRICE.equals(oracleKey)){ return new BigDecimal("0.0135"); } else if ("BNB_PRICE".equals(oracleKey)){ return new BigDecimal("306.3948"); } else if ("HT_PRICE".equals(oracleKey)){ return new BigDecimal("7.0541"); } else if ("OKT_PRICE".equals(oracleKey)){ return new BigDecimal("24.6444"); } else if ("ONE_PRICE".equals(oracleKey)){ return new BigDecimal("0.3431331"); } else if ("MATIC_PRICE".equals(oracleKey)){ return new BigDecimal("0.7412"); } else if ("KCS_PRICE".equals(oracleKey)){ return new BigDecimal("14.2687"); } else if ("TRX_PRICE".equals(oracleKey)){ return new BigDecimal("0.07095"); } else if ("CRO_PRICE".equals(oracleKey)){ return new BigDecimal("0.1991"); } else if ("AVAX_PRICE".equals(oracleKey)){ return new BigDecimal("34.43"); } else if ("FTM_PRICE".equals(oracleKey)){ return new BigDecimal("0.3648"); } else if ("METIS_PRICE".equals(oracleKey)){ return new BigDecimal("29.8957"); } else if ("IOTX_PRICE".equals(oracleKey)){ return new BigDecimal("0.03262"); } else if ("KLAY_PRICE".equals(oracleKey)){ return new BigDecimal("0.4146"); } else if ("BCH_PRICE".equals(oracleKey)){ return new BigDecimal("207.26"); } else if ("NULS_PRICE".equals(oracleKey)){ return new BigDecimal("0.2035"); } else if ("KAVA_PRICE".equals(oracleKey)){ return new BigDecimal("0.752"); } else if ("ETHW_PRICE".equals(oracleKey)){ return new BigDecimal("3.409"); } else if ("LGCY_PRICE".equals(oracleKey)){ return new BigDecimal("0.0001815"); } else if ("REI_PRICE".equals(oracleKey)){ return new BigDecimal("0.1993"); } else if ("EOS_PRICE".equals(oracleKey)){ return new BigDecimal("0.7366"); }*/ /************************************************/ try { Map<String, Object> params = new HashMap(ConverterConstant.INIT_CAPACITY_4); params.put(Constants.VERSION_KEY_STR, ConverterConstant.RPC_VERSION); params.put(Constants.CHAIN_ID, chain.getChainId()); params.put("key", oracleKey); HashMap map = (HashMap) BaseCall.requestAndResponse(ModuleE.QU.abbr, "qu_final_quotation", params); String price = map.get("price").toString(); if (StringUtils.isBlank(price)) { return null; } return new BigDecimal(price); } catch (NulsException e) { e.printStackTrace(); } return null; } }
package jForce.springhotelreservation.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.*; import jForce.springhotelreservation.exception.NoAvailableRoomsException; import jForce.springhotelreservation.model.Booking; import jForce.springhotelreservation.model.HotelRoom; import jForce.springhotelreservation.repository.BookingRepository; import jForce.springhotelreservation.repository.HotelRoomRepository; import jForce.springhotelreservation.service.BookingService; import java.time.LocalDate; import java.util.List; /** * Created by Paweł Troć on 2018-01-06. */ @CrossOrigin(origins = "http://localhost:4200") @RestController public class BookingController { @Autowired private BookingService bookingService; @GetMapping("/bookRoom") @ResponseBody public String bookHotelRoom(@RequestParam(value = "roomSize") int roomSize, @RequestParam(value = "startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate, @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) throws NoAvailableRoomsException { bookingService.bookHotelRoom(roomSize, startDate, endDate); return "OK"; } @DeleteMapping("/cancelBooking") @ResponseBody public String cancelBooking(@RequestParam(value = "id") Long bookingId) { bookingService.cancelBooking(bookingId); return "OK"; } @GetMapping("/getAllBookings") public List<Booking> getAllBookings() { return bookingService.getAllBookings(); } }
package be.sparmentier.discovery.spring; /** * Created by Simon Parmentier on 9/05/16. * Interface to test Factory pattern and beans */ public interface Shape { void getShape(); }
package org.giddap.dreamfactory.cc150; import org.giddap.dreamfactory.leetcode.commons.ListNode; public class Q0202FindNthNodeFromTheEnd { public ListNode findKthNodeFromEnd(ListNode root, int k) { ListNode fast = root; int i = 1; while (i < k) { fast = fast.next; i++; if (fast == null) { fast = root; } } ListNode slow = root; while (fast != null && fast.next != null) { fast = fast.next; slow = slow.next; } return slow; } public ListNode findKthNodeFromEndRecursively(ListNode root, int k) { findKthNodeFromEndRecursivelyHelper(root, k); return kthNodeFromTheEnd; } private ListNode kthNodeFromTheEnd = null; private int findKthNodeFromEndRecursivelyHelper(ListNode node, int k) { if (node == null) { return 0; } if (node.next == null) { return 1; } int orderFromTheEnd = 1 + findKthNodeFromEndRecursivelyHelper(node.next, k); if (orderFromTheEnd == k) { kthNodeFromTheEnd = node; } return orderFromTheEnd; } }
package be.dpms.medwan.common.model.vo.occupationalmedicine; import be.mxs.common.model.vo.IIdentifiable; import java.io.Serializable; /** * Created by IntelliJ IDEA. * User: MichaŽl * Date: 16-juin-2003 * Time: 9:15:23 */ public class RiskCodeVO implements Serializable, IIdentifiable { public Integer riskCodeId; public String code; public String messageKey; public String nl; public String fr; public String defaultVisible; public String language; public RiskCodeVO(Integer riskCodeId, String code, String messageKey) { this.riskCodeId = riskCodeId; this.code = code; this.messageKey = messageKey; } public RiskCodeVO(Integer riskCodeId, String code, String messageKey, String nl, String fr, String defaultVisible,String language) { this.riskCodeId = riskCodeId; this.code = code; this.messageKey = messageKey; this.nl=nl; this.fr=fr; this.defaultVisible=defaultVisible; this.language=language; } public String getLabel(){ if (language.equalsIgnoreCase("N")){ if (nl==null || nl.equals("")){ return messageKey; } else{ return nl; } } else { if (fr==null || fr.equals("")){ return messageKey; } else{ return fr; } } } public String getLabel(String language){ if (language.equalsIgnoreCase("N")){ if (nl==null || nl.equals("")){ return messageKey; } else{ return nl; } } else { if (fr==null || fr.equals("")){ return messageKey; } else{ return fr; } } } public String getNl(){ return nl; } public String getFr(){ return fr; } public String getDefaultVisible(){ return defaultVisible; } public Integer getRiskCodeId() { return riskCodeId; } public String getCode() { return code; } public String getMessageKey() { return messageKey; } public void setRiskCodeId(Integer riskCodeId) { this.riskCodeId = riskCodeId; } public void setCode(String code) { this.code = code; } public void setMessageKey(String messageKey) { this.messageKey = messageKey; } public boolean equals(Object o){ boolean equal = false; if (o instanceof RiskCodeVO) { RiskCodeVO riskCodeVO = (RiskCodeVO) o; if (riskCodeVO.getRiskCodeId().equals(this.getRiskCodeId())) equal = true; } return equal; } public int hashCode() { return riskCodeId.hashCode(); } }
package com.vitorapp.dspesquisa.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.vitorapp.dspesquisa.entities.Record; @Repository public interface RecordRepository extends JpaRepository<Record , Long> { }
package pl.edu.agh.to2.models; public class Call { private String callRaw; private CallType callType = CallType.COMMAND; public Call(String callRaw) { this.callRaw = callRaw; } public Call(String callRaw, CallType callType) { this.callRaw = callRaw; this.callType = callType; } public String getCallRaw() { return callRaw; } public CallType getCallType() { return callType; } public String toString() { return callRaw; } }
package com.example.bob.health_helper.Me.adapter; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.bob.health_helper.R; import butterknife.BindView; import butterknife.ButterKnife; public class WeekDayGridAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private String[] weekDayList={"日","一","二","三","四","五","六"}; private int selected=0; public WeekDayGridAdapter(int selected){ this.selected=selected; } static class WeekDayItemViewHolder extends RecyclerView.ViewHolder{ @BindView(R.id.weekday_item) TextView weekDayText; public WeekDayItemViewHolder(@NonNull View itemView) { super(itemView); ButterKnife.bind(this,itemView); } } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_reminder_weekday,viewGroup,false); WeekDayItemViewHolder holder=new WeekDayItemViewHolder(view); return holder; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) { WeekDayItemViewHolder holder=(WeekDayItemViewHolder)viewHolder; holder.weekDayText.setText(weekDayList[i]); if((selected>>i)%2==1) holder.weekDayText.setSelected(true); else holder.weekDayText.setSelected(false); holder.weekDayText.setOnClickListener(view->{ if(view.isSelected()){//取消 selected-=(1<<i); if(selected<=0){ selected+=(1<<i); return; } holder.weekDayText.setTextColor(view.getContext().getResources().getColor(R.color.colorTextPrimaryMoreLight)); view.setSelected(false); }else{//选中 selected+=(1<<i); holder.weekDayText.setTextColor(view.getContext().getResources().getColor(R.color.colorOrange)); view.setSelected(true); } }); } @Override public int getItemCount() { return weekDayList.length; } public int getSelected(){ return selected; } }
package model; import util.DateUtil; import util.LocalDateAdapter; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.io.Serializable; import java.time.LocalDate; import java.time.Month; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import static util.DateUtil.NOW; import static util.DateUtil.of; @XmlAccessorType(XmlAccessType.FIELD) public class Place implements Serializable { private static final long serialVersionUID = 1L; private Link homePage; private List<WorkPosition> workPositions = new ArrayList<>(); public Place() { } public Place(String name, String url, WorkPosition... workPositions) { this(new Link(name, url), Arrays.asList(workPositions)); } public Place(Link homePage, List<WorkPosition> workPositions) { this.homePage = homePage; this.workPositions = workPositions; } public Link getHomePage() { return homePage; } public List<WorkPosition> getWorkPositions() { return workPositions; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Place place = (Place) o; return Objects.equals(homePage, place.homePage) && Objects.equals(workPositions, place.workPositions); } @Override public int hashCode() { return Objects.hash(homePage, workPositions); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(homePage).append('\n'); for (WorkPosition wp : workPositions) { sb.append(wp.toString()).append('\n'); } return sb.toString(); } @XmlAccessorType(XmlAccessType.FIELD) public static class WorkPosition implements Serializable { private static final long serialVersionUID = 1L; private String title; private String description; @XmlJavaTypeAdapter(LocalDateAdapter.class) private LocalDate startDate; @XmlJavaTypeAdapter(LocalDateAdapter.class) private LocalDate endDate; public WorkPosition() { } public WorkPosition(String title, String description, int startYear, Month startMonth) { this(title, description, DateUtil.of(startYear, startMonth), NOW); } public WorkPosition(String title, String description, int startYear, Month startMonth, int endYear, Month endMonth) { this(title, description, of(startYear, startMonth), of(endYear, endMonth)); } public WorkPosition(String title, String description, LocalDate startDate, LocalDate endDate) { Objects.requireNonNull(startDate, "startDate must not be null"); Objects.requireNonNull(endDate, "endDate must not be null"); Objects.requireNonNull(title, "title must not be null"); this.title = title; this.description = description != null ? description : ""; this.startDate = startDate; this.endDate = endDate; } public String getTitle() { return title; } public String getDescription() { return description; } public LocalDate getStartDate() { return startDate; } public LocalDate getEndDate() { return endDate; } @Override public String toString() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM"); return formatter.format(startDate) + " - " + formatter.format(endDate) + " " + title + '\n' + description; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WorkPosition that = (WorkPosition) o; return Objects.equals(title, that.title) && Objects.equals(description, that.description) && Objects.equals(startDate, that.startDate) && Objects.equals(endDate, that.endDate); } @Override public int hashCode() { return Objects.hash(title, description, startDate, endDate); } } }
package com.sasi.collections; import java.util.function.Consumer; public class Filter implements Consumer { static void filter(Integer i ) { if(i==1) { System.out.println(i); } } @Override public void accept(Object i) { if((int)i==1) { System.out.println(i); } } static void add(Integer i ) { System.out.println(i+7); } }
package net.mv.dao; import javax.persistence.*; //tell the compiler that this can be persisted @Entity public class Animal { /* @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="STUD_ID") private long sid; */ @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="ANIMAL_ID") private long ANIMAL_ID; @Column(name="NAME") private String NAME; @Column(name="DIET") private String DIET; @Column(name="AGE") private int AGE; @Column(name="OWNER") private String OWNER; @Column(name="LIMBS") private int LIMBS; @Column(name="TYPE") private String TYPE; public String getName() { return NAME; } public void setName(String name) { this.NAME = name; } public String getDiet() { return DIET; } public void setDiet(String diet) { this.DIET = diet; } public int getAge() { return AGE; } public void setAge(int age) { this.AGE = age; } public String getOwner() { return OWNER; } public void setOwner(String owner) { this.OWNER = owner; } public int getLimbs() { return LIMBS; } public void setLimbs(int appendages) { this.LIMBS = appendages; } public String getType() { return TYPE; } public void setType(String environment) { this.TYPE = environment; } public long getANIMAL_ID() { return ANIMAL_ID; } public void setANIMAL_ID(long aNIMAL_ID) { ANIMAL_ID = aNIMAL_ID; } @Override public String toString() { return "Animal [ANIMAL_ID=" + ANIMAL_ID + ", NAME=" + NAME + ", DIET=" + DIET + ", AGE=" + AGE + ", OWNER=" + OWNER + ", LIMBS=" + LIMBS + ", TYPE=" + TYPE + "]"; } }
package hopamchuan; import org.hibernate.NonUniqueResultException; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import util.HibernateUtils; /** * Description * * @author minhho242 on 4/11/15. */ public class SongDAO { private static final Logger LOGGER = LoggerFactory.getLogger(SongDAO.class); public static SongDTO getSongBySourceSongId(String sourceSongId) { try { Session session = HibernateUtils.getSessionFactory().openSession(); return (SongDTO) session.createQuery("FROM SongDTO as song where song.sourceSongId = :sourceSongId").setParameter("sourceSongId", sourceSongId).uniqueResult(); } catch (NonUniqueResultException e) { LOGGER.error("Not unique sourceSongId {}", sourceSongId, e); return null; } } public static boolean checkExistedBySourceSongId(String sourceSongId) { return getSongBySourceSongId(sourceSongId) != null; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.function.client; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntPredicate; import java.util.function.Predicate; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import io.micrometer.observation.contextpropagation.ObservationThreadLocalAccessor; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.SignalType; import reactor.util.context.Context; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatusCode; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.client.reactive.ClientHttpRequest; import org.springframework.http.client.reactive.ClientHttpResponse; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; import org.springframework.web.reactive.function.BodyExtractor; import org.springframework.web.reactive.function.BodyInserter; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.util.UriBuilder; import org.springframework.web.util.UriBuilderFactory; /** * The default implementation of {@link WebClient}, * as created by the static factory methods. * * @author Rossen Stoyanchev * @author Brian Clozel * @author Sebastien Deleuze * @since 5.0 * @see WebClient#create() * @see WebClient#create(String) */ final class DefaultWebClient implements WebClient { private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() + ".uriTemplate"; private static final Mono<ClientResponse> NO_HTTP_CLIENT_RESPONSE_ERROR = Mono.error( () -> new IllegalStateException("The underlying HTTP client completed without emitting a response.")); private static final DefaultClientRequestObservationConvention DEFAULT_OBSERVATION_CONVENTION = new DefaultClientRequestObservationConvention(); private final ExchangeFunction exchangeFunction; @Nullable private final ExchangeFilterFunction filterFunctions; private final UriBuilderFactory uriBuilderFactory; @Nullable private final HttpHeaders defaultHeaders; @Nullable private final MultiValueMap<String, String> defaultCookies; @Nullable private final Consumer<RequestHeadersSpec<?>> defaultRequest; private final List<DefaultResponseSpec.StatusHandler> defaultStatusHandlers; private final ObservationRegistry observationRegistry; @Nullable private final ClientRequestObservationConvention observationConvention; private final DefaultWebClientBuilder builder; DefaultWebClient(ExchangeFunction exchangeFunction, @Nullable ExchangeFilterFunction filterFunctions, UriBuilderFactory uriBuilderFactory, @Nullable HttpHeaders defaultHeaders, @Nullable MultiValueMap<String, String> defaultCookies, @Nullable Consumer<RequestHeadersSpec<?>> defaultRequest, @Nullable Map<Predicate<HttpStatusCode>, Function<ClientResponse, Mono<? extends Throwable>>> statusHandlerMap, ObservationRegistry observationRegistry, @Nullable ClientRequestObservationConvention observationConvention, DefaultWebClientBuilder builder) { this.exchangeFunction = exchangeFunction; this.filterFunctions = filterFunctions; this.uriBuilderFactory = uriBuilderFactory; this.defaultHeaders = defaultHeaders; this.defaultCookies = defaultCookies; this.observationRegistry = observationRegistry; this.observationConvention = observationConvention; this.defaultRequest = defaultRequest; this.defaultStatusHandlers = initStatusHandlers(statusHandlerMap); this.builder = builder; } private static List<DefaultResponseSpec.StatusHandler> initStatusHandlers( @Nullable Map<Predicate<HttpStatusCode>, Function<ClientResponse, Mono<? extends Throwable>>> handlerMap) { return (CollectionUtils.isEmpty(handlerMap) ? Collections.emptyList() : handlerMap.entrySet().stream() .map(entry -> new DefaultResponseSpec.StatusHandler(entry.getKey(), entry.getValue())) .toList()); } @Override public RequestHeadersUriSpec<?> get() { return methodInternal(HttpMethod.GET); } @Override public RequestHeadersUriSpec<?> head() { return methodInternal(HttpMethod.HEAD); } @Override public RequestBodyUriSpec post() { return methodInternal(HttpMethod.POST); } @Override public RequestBodyUriSpec put() { return methodInternal(HttpMethod.PUT); } @Override public RequestBodyUriSpec patch() { return methodInternal(HttpMethod.PATCH); } @Override public RequestHeadersUriSpec<?> delete() { return methodInternal(HttpMethod.DELETE); } @Override public RequestHeadersUriSpec<?> options() { return methodInternal(HttpMethod.OPTIONS); } @Override public RequestBodyUriSpec method(HttpMethod httpMethod) { return methodInternal(httpMethod); } private RequestBodyUriSpec methodInternal(HttpMethod httpMethod) { return new DefaultRequestBodyUriSpec(httpMethod); } @Override public Builder mutate() { return new DefaultWebClientBuilder(this.builder); } private static Mono<Void> releaseIfNotConsumed(ClientResponse response) { return response.releaseBody().onErrorResume(ex2 -> Mono.empty()); } private static <T> Mono<T> releaseIfNotConsumed(ClientResponse response, Throwable ex) { return response.releaseBody().onErrorResume(ex2 -> Mono.empty()).then(Mono.error(ex)); } private class DefaultRequestBodyUriSpec implements RequestBodyUriSpec { private final HttpMethod httpMethod; @Nullable private URI uri; @Nullable private HttpHeaders headers; @Nullable private MultiValueMap<String, String> cookies; @Nullable private BodyInserter<?, ? super ClientHttpRequest> inserter; private final Map<String, Object> attributes = new LinkedHashMap<>(4); @Nullable private Function<Context, Context> contextModifier; @Nullable private Consumer<ClientHttpRequest> httpRequestConsumer; DefaultRequestBodyUriSpec(HttpMethod httpMethod) { this.httpMethod = httpMethod; } @Override public RequestBodySpec uri(String uriTemplate, Object... uriVariables) { attribute(URI_TEMPLATE_ATTRIBUTE, uriTemplate); return uri(uriBuilderFactory.expand(uriTemplate, uriVariables)); } @Override public RequestBodySpec uri(String uriTemplate, Map<String, ?> uriVariables) { attribute(URI_TEMPLATE_ATTRIBUTE, uriTemplate); return uri(uriBuilderFactory.expand(uriTemplate, uriVariables)); } @Override public RequestBodySpec uri(String uriTemplate, Function<UriBuilder, URI> uriFunction) { attribute(URI_TEMPLATE_ATTRIBUTE, uriTemplate); return uri(uriFunction.apply(uriBuilderFactory.uriString(uriTemplate))); } @Override public RequestBodySpec uri(Function<UriBuilder, URI> uriFunction) { return uri(uriFunction.apply(uriBuilderFactory.builder())); } @Override public RequestBodySpec uri(URI uri) { this.uri = uri; return this; } private HttpHeaders getHeaders() { if (this.headers == null) { this.headers = new HttpHeaders(); } return this.headers; } private MultiValueMap<String, String> getCookies() { if (this.cookies == null) { this.cookies = new LinkedMultiValueMap<>(3); } return this.cookies; } @Override public DefaultRequestBodyUriSpec header(String headerName, String... headerValues) { for (String headerValue : headerValues) { getHeaders().add(headerName, headerValue); } return this; } @Override public DefaultRequestBodyUriSpec headers(Consumer<HttpHeaders> headersConsumer) { headersConsumer.accept(getHeaders()); return this; } @Override public DefaultRequestBodyUriSpec accept(MediaType... acceptableMediaTypes) { getHeaders().setAccept(Arrays.asList(acceptableMediaTypes)); return this; } @Override public DefaultRequestBodyUriSpec acceptCharset(Charset... acceptableCharsets) { getHeaders().setAcceptCharset(Arrays.asList(acceptableCharsets)); return this; } @Override public DefaultRequestBodyUriSpec contentType(MediaType contentType) { getHeaders().setContentType(contentType); return this; } @Override public DefaultRequestBodyUriSpec contentLength(long contentLength) { getHeaders().setContentLength(contentLength); return this; } @Override public DefaultRequestBodyUriSpec cookie(String name, String value) { getCookies().add(name, value); return this; } @Override public DefaultRequestBodyUriSpec cookies(Consumer<MultiValueMap<String, String>> cookiesConsumer) { cookiesConsumer.accept(getCookies()); return this; } @Override public DefaultRequestBodyUriSpec ifModifiedSince(ZonedDateTime ifModifiedSince) { getHeaders().setIfModifiedSince(ifModifiedSince); return this; } @Override public DefaultRequestBodyUriSpec ifNoneMatch(String... ifNoneMatches) { getHeaders().setIfNoneMatch(Arrays.asList(ifNoneMatches)); return this; } @Override public RequestBodySpec attribute(String name, Object value) { this.attributes.put(name, value); return this; } @Override public RequestBodySpec attributes(Consumer<Map<String, Object>> attributesConsumer) { attributesConsumer.accept(this.attributes); return this; } @SuppressWarnings("deprecation") @Override public RequestBodySpec context(Function<Context, Context> contextModifier) { this.contextModifier = (this.contextModifier != null ? this.contextModifier.andThen(contextModifier) : contextModifier); return this; } @Override public RequestBodySpec httpRequest(Consumer<ClientHttpRequest> requestConsumer) { this.httpRequestConsumer = (this.httpRequestConsumer != null ? this.httpRequestConsumer.andThen(requestConsumer) : requestConsumer); return this; } @Override public RequestHeadersSpec<?> bodyValue(Object body) { this.inserter = BodyInserters.fromValue(body); return this; } @Override public <T, P extends Publisher<T>> RequestHeadersSpec<?> body( P publisher, ParameterizedTypeReference<T> elementTypeRef) { this.inserter = BodyInserters.fromPublisher(publisher, elementTypeRef); return this; } @Override public <T, P extends Publisher<T>> RequestHeadersSpec<?> body(P publisher, Class<T> elementClass) { this.inserter = BodyInserters.fromPublisher(publisher, elementClass); return this; } @Override public RequestHeadersSpec<?> body(Object producer, Class<?> elementClass) { this.inserter = BodyInserters.fromProducer(producer, elementClass); return this; } @Override public RequestHeadersSpec<?> body(Object producer, ParameterizedTypeReference<?> elementTypeRef) { this.inserter = BodyInserters.fromProducer(producer, elementTypeRef); return this; } @Override public RequestHeadersSpec<?> body(BodyInserter<?, ? super ClientHttpRequest> inserter) { this.inserter = inserter; return this; } @Override @Deprecated public RequestHeadersSpec<?> syncBody(Object body) { return bodyValue(body); } @Override public ResponseSpec retrieve() { return new DefaultResponseSpec( this.httpMethod, initUri(), exchange(), DefaultWebClient.this.defaultStatusHandlers); } @Override public <V> Mono<V> exchangeToMono(Function<ClientResponse, ? extends Mono<V>> responseHandler) { return exchange().flatMap(response -> { try { return responseHandler.apply(response) .flatMap(value -> releaseIfNotConsumed(response).thenReturn(value)) .switchIfEmpty(Mono.defer(() -> releaseIfNotConsumed(response).then(Mono.empty()))) .onErrorResume(ex -> releaseIfNotConsumed(response, ex)); } catch (Throwable ex) { return releaseIfNotConsumed(response, ex); } }); } @Override public <V> Flux<V> exchangeToFlux(Function<ClientResponse, ? extends Flux<V>> responseHandler) { return exchange().flatMapMany(response -> { try { return responseHandler.apply(response) .concatWith(Flux.defer(() -> releaseIfNotConsumed(response).then(Mono.empty()))) .onErrorResume(ex -> releaseIfNotConsumed(response, ex)); } catch (Throwable ex) { return releaseIfNotConsumed(response, ex); } }); } @SuppressWarnings("deprecation") @Override public Mono<ClientResponse> exchange() { ClientRequestObservationContext observationContext = new ClientRequestObservationContext(); ClientRequest.Builder requestBuilder = initRequestBuilder(); return Mono.deferContextual(contextView -> { Observation observation = ClientHttpObservationDocumentation.HTTP_REACTIVE_CLIENT_EXCHANGES.observation(observationConvention, DEFAULT_OBSERVATION_CONVENTION, () -> observationContext, observationRegistry); observationContext.setCarrier(requestBuilder); observation .parentObservation(contextView.getOrDefault(ObservationThreadLocalAccessor.KEY, null)) .start(); ExchangeFilterFunction filterFunction = new ObservationFilterFunction(observationContext); if (filterFunctions != null) { filterFunction = filterFunctions.andThen(filterFunction); } ClientRequest request = requestBuilder.build(); observationContext.setUriTemplate((String) request.attribute(URI_TEMPLATE_ATTRIBUTE).orElse(null)); observationContext.setRequest(request); Mono<ClientResponse> responseMono = filterFunction.apply(exchangeFunction) .exchange(request) .checkpoint("Request to " + this.httpMethod.name() + " " + this.uri + " [DefaultWebClient]") .switchIfEmpty(NO_HTTP_CLIENT_RESPONSE_ERROR); if (this.contextModifier != null) { responseMono = responseMono.contextWrite(this.contextModifier); } final AtomicBoolean responseReceived = new AtomicBoolean(); return responseMono .doOnNext(response -> responseReceived.set(true)) .doOnError(observationContext::setError) .doFinally(signalType -> { if (signalType == SignalType.CANCEL && !responseReceived.get()) { observationContext.setAborted(true); } observation.stop(); }) .contextWrite(context -> context.put(ObservationThreadLocalAccessor.KEY, observation)); }); } private ClientRequest.Builder initRequestBuilder() { if (defaultRequest != null) { defaultRequest.accept(this); } ClientRequest.Builder builder = ClientRequest.create(this.httpMethod, initUri()) .headers(this::initHeaders) .cookies(this::initCookies) .attributes(attributes -> attributes.putAll(this.attributes)); if (this.httpRequestConsumer != null) { builder.httpRequest(this.httpRequestConsumer); } if (this.inserter != null) { builder.body(this.inserter); } return builder; } private URI initUri() { return (this.uri != null ? this.uri : uriBuilderFactory.expand("")); } private void initHeaders(HttpHeaders out) { if (!CollectionUtils.isEmpty(defaultHeaders)) { out.putAll(defaultHeaders); } if (!CollectionUtils.isEmpty(this.headers)) { out.putAll(this.headers); } } private void initCookies(MultiValueMap<String, String> out) { if (!CollectionUtils.isEmpty(defaultCookies)) { out.putAll(defaultCookies); } if (!CollectionUtils.isEmpty(this.cookies)) { out.putAll(this.cookies); } } } private static class DefaultResponseSpec implements ResponseSpec { private static final Predicate<HttpStatusCode> STATUS_CODE_ERROR = HttpStatusCode::isError; private static final StatusHandler DEFAULT_STATUS_HANDLER = new StatusHandler(STATUS_CODE_ERROR, ClientResponse::createException); private final HttpMethod httpMethod; private final URI uri; private final Mono<ClientResponse> responseMono; private final List<StatusHandler> statusHandlers = new ArrayList<>(1); private final int defaultStatusHandlerCount; DefaultResponseSpec(HttpMethod httpMethod, URI uri, Mono<ClientResponse> responseMono, List<StatusHandler> defaultStatusHandlers) { this.httpMethod = httpMethod; this.uri = uri; this.responseMono = responseMono; this.statusHandlers.addAll(defaultStatusHandlers); this.statusHandlers.add(DEFAULT_STATUS_HANDLER); this.defaultStatusHandlerCount = this.statusHandlers.size(); } @Override public ResponseSpec onStatus(Predicate<HttpStatusCode> statusCodePredicate, Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) { Assert.notNull(statusCodePredicate, "StatusCodePredicate must not be null"); Assert.notNull(exceptionFunction, "Function must not be null"); int index = this.statusHandlers.size() - this.defaultStatusHandlerCount; // Default handlers always last this.statusHandlers.add(index, new StatusHandler(statusCodePredicate, exceptionFunction)); return this; } @Override public ResponseSpec onRawStatus(IntPredicate statusCodePredicate, Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) { return onStatus(toStatusCodePredicate(statusCodePredicate), exceptionFunction); } private static Predicate<HttpStatusCode> toStatusCodePredicate(IntPredicate predicate) { return value -> predicate.test(value.value()); } @Override public <T> Mono<T> bodyToMono(Class<T> elementClass) { Assert.notNull(elementClass, "Class must not be null"); return this.responseMono.flatMap(response -> handleBodyMono(response, response.bodyToMono(elementClass))); } @Override public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> elementTypeRef) { Assert.notNull(elementTypeRef, "ParameterizedTypeReference must not be null"); return this.responseMono.flatMap(response -> handleBodyMono(response, response.bodyToMono(elementTypeRef))); } @Override public <T> Flux<T> bodyToFlux(Class<T> elementClass) { Assert.notNull(elementClass, "Class must not be null"); return this.responseMono.flatMapMany(response -> handleBodyFlux(response, response.bodyToFlux(elementClass))); } @Override public <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> elementTypeRef) { Assert.notNull(elementTypeRef, "ParameterizedTypeReference must not be null"); return this.responseMono.flatMapMany(response -> handleBodyFlux(response, response.bodyToFlux(elementTypeRef))); } @Override public <T> Mono<ResponseEntity<T>> toEntity(Class<T> bodyClass) { return this.responseMono.flatMap(response -> WebClientUtils.mapToEntity(response, handleBodyMono(response, response.bodyToMono(bodyClass)))); } @Override public <T> Mono<ResponseEntity<T>> toEntity(ParameterizedTypeReference<T> bodyTypeRef) { return this.responseMono.flatMap(response -> WebClientUtils.mapToEntity(response, handleBodyMono(response, response.bodyToMono(bodyTypeRef)))); } @Override public <T> Mono<ResponseEntity<List<T>>> toEntityList(Class<T> elementClass) { return this.responseMono.flatMap(response -> WebClientUtils.mapToEntityList(response, handleBodyFlux(response, response.bodyToFlux(elementClass)))); } @Override public <T> Mono<ResponseEntity<List<T>>> toEntityList(ParameterizedTypeReference<T> elementTypeRef) { return this.responseMono.flatMap(response -> WebClientUtils.mapToEntityList(response, handleBodyFlux(response, response.bodyToFlux(elementTypeRef)))); } @Override public <T> Mono<ResponseEntity<Flux<T>>> toEntityFlux(Class<T> elementType) { return this.responseMono.flatMap(response -> handlerEntityFlux(response, response.bodyToFlux(elementType))); } @Override public <T> Mono<ResponseEntity<Flux<T>>> toEntityFlux(ParameterizedTypeReference<T> elementTypeRef) { return this.responseMono.flatMap(response -> handlerEntityFlux(response, response.bodyToFlux(elementTypeRef))); } @Override public <T> Mono<ResponseEntity<Flux<T>>> toEntityFlux(BodyExtractor<Flux<T>, ? super ClientHttpResponse> bodyExtractor) { return this.responseMono.flatMap(response -> handlerEntityFlux(response, response.body(bodyExtractor))); } @Override public Mono<ResponseEntity<Void>> toBodilessEntity() { return this.responseMono.flatMap(response -> WebClientUtils.mapToEntity(response, handleBodyMono(response, Mono.<Void>empty())) .flatMap(entity -> response.releaseBody() .onErrorResume(WebClientUtils.WRAP_EXCEPTION_PREDICATE, exceptionWrappingFunction(response)) .thenReturn(entity)) ); } private <T> Mono<T> handleBodyMono(ClientResponse response, Mono<T> body) { body = body.onErrorResume(WebClientUtils.WRAP_EXCEPTION_PREDICATE, exceptionWrappingFunction(response)); Mono<T> result = applyStatusHandlers(response); return (result != null ? result.switchIfEmpty(body) : body); } private <T> Publisher<T> handleBodyFlux(ClientResponse response, Flux<T> body) { body = body.onErrorResume(WebClientUtils.WRAP_EXCEPTION_PREDICATE, exceptionWrappingFunction(response)); Mono<T> result = applyStatusHandlers(response); return (result != null ? result.flux().switchIfEmpty(body) : body); } private <T> Mono<? extends ResponseEntity<Flux<T>>> handlerEntityFlux(ClientResponse response, Flux<T> body) { ResponseEntity<Flux<T>> entity = new ResponseEntity<>( body.onErrorResume(WebClientUtils.WRAP_EXCEPTION_PREDICATE, exceptionWrappingFunction(response)), response.headers().asHttpHeaders(), response.statusCode()); Mono<ResponseEntity<Flux<T>>> result = applyStatusHandlers(response); return (result != null ? result.defaultIfEmpty(entity) : Mono.just(entity)); } private <T> Function<Throwable, Mono<? extends T>> exceptionWrappingFunction(ClientResponse response) { return t -> response.createException().flatMap(ex -> Mono.error(ex.initCause(t))); } @Nullable private <T> Mono<T> applyStatusHandlers(ClientResponse response) { HttpStatusCode statusCode = response.statusCode(); for (StatusHandler handler : this.statusHandlers) { if (handler.test(statusCode)) { Mono<? extends Throwable> exMono; try { exMono = handler.apply(response); exMono = exMono.flatMap(ex -> releaseIfNotConsumed(response, ex)); exMono = exMono.onErrorResume(ex -> releaseIfNotConsumed(response, ex)); } catch (Throwable ex2) { exMono = releaseIfNotConsumed(response, ex2); } Mono<T> result = exMono.flatMap(Mono::error); return result.checkpoint(statusCode + " from " + this.httpMethod + " " + getUriToLog(this.uri) + " [DefaultWebClient]"); } } return null; } private static URI getUriToLog(URI uri) { if (StringUtils.hasText(uri.getQuery())) { try { uri = new URI(uri.getScheme(), uri.getHost(), uri.getPath(), null); } catch (URISyntaxException ex) { // ignore } } return uri; } private static class StatusHandler { private final Predicate<HttpStatusCode> predicate; private final Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction; public StatusHandler(Predicate<HttpStatusCode> predicate, Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) { this.predicate = predicate; this.exceptionFunction = exceptionFunction; } public boolean test(HttpStatusCode status) { return this.predicate.test(status); } public Mono<? extends Throwable> apply(ClientResponse response) { return this.exceptionFunction.apply(response); } } } private static class ObservationFilterFunction implements ExchangeFilterFunction { private final ClientRequestObservationContext observationContext; ObservationFilterFunction(ClientRequestObservationContext observationContext) { this.observationContext = observationContext; } @Override public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) { return next.exchange(request).doOnNext(this.observationContext::setResponse); } } }
package ch06homework.Ex17; public class Example { public static void main(String[] args) { Person p1 = new Person("123-123132","계백"); System.out.println(p1.NATION); System.out.println(p1.ssn); System.out.println(p1.name); //p1.NATION = "usa"; //p1.ssn = "515151-1515155"; final 필드는 값 수정 불가 p1.name="을지문덕"; } }
package com.practice.qa.testcases; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class SelectCalenderByJS { public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "C:\\Selenium Drivers\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("http://www.spicejet.com/"); WebElement date = driver.findElement(By.id("ctl00_mainContent_view_date1")); String dateVal = "07-08-2018"; selectDateByJS(driver, date, dateVal); } public static void selectDateByJS(WebDriver driver, WebElement element, String dateVal) { JavascriptExecutor js = ((JavascriptExecutor)driver); js.executeScript("arguments[0].setAttribute('value','"+dateVal+"');",element); } }
package com.nowcoder.community; import com.nowcoder.community.dao.MessageMapper; import com.nowcoder.community.entity.Message; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import java.util.Date; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration(classes = CommunityApplication.class) public class MessageMapperTest { @Autowired private MessageMapper messageMapper; @Test public void testMessageMapper(){ // List<Message> list =messageMapper.getSessionNewestMessageList(111,0,10); // System.out.println(list); // // int count = messageMapper.getSessionCount(111); // System.out.println(count); // // int count1 =messageMapper.getMessageCount("111_112"); // System.out.println(count1); // // List<Message> list1=messageMapper.getMessageList(null,0,100); // System.out.println(list1); // // int count2 = messageMapper.getMessageUnReadCount(111,"111_112"); // System.out.println(count2); Message message = new Message(); message.setContent("56465464"); message.setToId(45); message.setCreateTime(new Date()); message.setFromId(1); message.setStatus(1); message.setConversationId("f1d5f145df"); messageMapper.insertMessage(message); } }
package com.example.administrator.panda_channel_app.MVP_Framework.module.panda_report; import android.content.Context; import com.example.administrator.panda_channel_app.MVP_Framework.base.BasePresenter; import com.example.administrator.panda_channel_app.MVP_Framework.base.BaseView; import com.example.administrator.panda_channel_app.MVP_Framework.modle.entity.PandaReportBean; import com.example.administrator.panda_channel_app.MVP_Framework.modle.entity.PandaRepoterBean; /** * Created by Administrator on 2017/7/11 0011. */ public interface panda_reportContract { interface View extends BaseView<Presenter> { void setPullupRefresh(); void setHeadListentoevents(); void setXRecyclerViewListentoevents(); void setPandaRepoterBean(PandaRepoterBean PandaRepoterBean); void showMessage(String msg); void setPandaReportBean(PandaReportBean pandaReportBean); void showMessageTwo(String msg); } interface Presenter extends BasePresenter{ void Addthenumber( String path,String primary_id,String serviceId); void setJump(Context context,Class tClass,String url,String img); } }
package br.com.fatec.tcc.rotasegura.roadMap; import com.google.gson.annotations.Expose; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Leg { private Distance distance; private Duration duration; private String end_address; private EndLocation end_location; private String start_address; private StartLocation start_location; private List<Step> steps = new ArrayList<Step>(); private List<Object> trafficSpeedEntry = new ArrayList<Object>(); private List<ViaWaypoint> viaWaypoint = new ArrayList<ViaWaypoint>(); private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * * @return * The distance */ public Distance getDistance() { return distance; } /** * * @param distance * The distance */ public void setDistance(Distance distance) { this.distance = distance; } /** * * @return * The duration */ public Duration getDuration() { return duration; } /** * * @param duration * The duration */ public void setDuration(Duration duration) { this.duration = duration; } /** * * @return * The endAddress */ public String getEndAddress() { return end_address; } /** * * @param end_address * The end_address */ public void setEndAddress(String end_address) { this.end_address = end_address; } /** * * @return * The endLocation */ public EndLocation getEndLocation() { return end_location; } /** * * @param end_location * The end_location */ public void setEndLocation(EndLocation end_location) { this.end_location = end_location; } /** * * @return * The startAddress */ public String getStartAddress() { return start_address; } /** * * @param start_address * The start_address */ public void setStartAddress(String start_address) { this.start_address = start_address; } /** * * @return * The startLocation */ public StartLocation getStartLocation() { return start_location; } /** * * @param start_location * The start_location */ public void setStartLocation(StartLocation start_location) { this.start_location = start_location; } /** * * @return * The steps */ public List<Step> getSteps() { return steps; } /** * * @param steps * The steps */ public void setSteps(List<Step> steps) { this.steps = steps; } /** * * @return * The trafficSpeedEntry */ public List<Object> getTrafficSpeedEntry() { return trafficSpeedEntry; } /** * * @param trafficSpeedEntry * The traffic_speed_entry */ public void setTrafficSpeedEntry(List<Object> trafficSpeedEntry) { this.trafficSpeedEntry = trafficSpeedEntry; } /** * * @return * The viaWaypoint */ public List<ViaWaypoint> getViaWaypoint() { return viaWaypoint; } /** * * @param viaWaypoint * The via_waypoint */ public void setViaWaypoint(List<ViaWaypoint> viaWaypoint) { this.viaWaypoint = viaWaypoint; } public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
package com.qt.functionsPage.controller; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.qt.quartz.service.QuartzJobService; import com.qt.util.HttpRequest; import com.qt.util.WriterLog; import com.qt.util.WxJsSdk; @Controller public class GpsController { @Autowired private QuartzJobService quartzJobService; private Map<String, String> result; private String latitude; private String longitude; private Map<String, String> address; public Map<String, String> getResult() { return result; } public void setLatitude(String latitude) { this.latitude = latitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public Map<String, String> getAddress() { return address; } private String openId; public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String execute(){ result = new WxJsSdk().wxJsSdk(quartzJobService,"http://qtwxbp.duapp.com/myQt_index/gps?openId="+openId); return "success"; } public String searchLoc(){ tencentApi(); return "success"; } /** * 百度地图逆地址解析API */ // private void baiduApi(){ // address = new HashMap<String, String>(); // String url = "http://api.map.baidu.com/geoconv/v1/"; // String param = "coords="+latitude+","+longitude+"&ak=25227afb68e7c8a60138de19c5c4b2de&from=3"; // try { // JSONObject json = new JSONObject(HttpRequest.sendGet(url, param)).getJSONArray("result").getJSONObject(0); // latitude = json.get("x").toString(); // longitude = json.get("y").toString(); // url = "http://api.map.baidu.com/geocoder/v2/"; // param = "ak=25227afb68e7c8a60138de19c5c4b2de&location="+latitude+","+longitude+"&output=json&pois=1"; // json = new JSONObject(HttpRequest.sendGet(url, param)).getJSONObject("result"); // JSONObject addrJson = json.getJSONObject("addressComponent"); // address.put("address", addrJson.get("province").toString() + addrJson.get("city").toString() // + addrJson.get("district").toString() + addrJson.get("street").toString()); // address.put("pois", json.get("pois").toString()); // } catch (JSONException e) { // WriterLog.writerLog("gps json error"); // } // } /** * 百度查询周边自定义地点 */ public void baiduNearby(){ address = new HashMap<String, String>(); String url = "http://api.map.baidu.com/geosearch/v3/nearby"; String param = "ak=25227afb68e7c8a60138de19c5c4b2de&geotable_id=94133&location="+longitude+","+latitude+"&radius=1000"; JSONObject json; try { json = new JSONObject(HttpRequest.sendGet(url, param)); address.put("pois", json.get("contents").toString()); } catch (JSONException e) { WriterLog.writerLog("gps json error"); } } /** * 腾讯地图逆地址解析API */ private void tencentApi(){ // latitude = "39.983424"; // longitude = "116.322987"; address = new HashMap<String, String>(); String url = "http://apis.map.qq.com/ws/geocoder/v1/"; String param = "location="+latitude+","+longitude+"&key=IAJBZ-PB4HV-5RZPL-UKVJP-ITD2Q-MPB5M&get_poi=1"; try { JSONObject json = new JSONObject(HttpRequest.sendGet(url, param)).getJSONObject("result"); JSONObject addrJson = json.getJSONObject("address_component"); address.put("address", addrJson.get("province").toString() + addrJson.get("city").toString() + addrJson.get("district").toString() + addrJson.get("street").toString()); address.put("pois", json.get("pois").toString()); } catch (JSONException e) { WriterLog.writerLog("gps json error"); } } /** * 腾讯搜索周边接口 */ public void tencentNearby(){ String url = "http://apis.map.qq.com/ws/place/v1/search"; //nearby(lat,lon,半径),keyword=关键字(需要encodeURI编码),page_size=分页数,page_index=页码,orderby=排序 String param = "boundary=nearby("+latitude+","+longitude+",1000)&keyword=&page_size=20&page_index=1&orderby=_distance&key=IAJBZ-PB4HV-5RZPL-UKVJP-ITD2Q-MPB5M"; String json = HttpRequest.sendGet(url, param); System.out.println(json); } public static void main(String[] args) { GpsController gps = new GpsController(); gps.searchLoc(); } }
/* * Test 19 * * Testiamo ora l'operatore ||. */ class HelloWorld { static public void main(String[] argv) { boolean a; int x=10; int b=15; int c=17; int d=13; a=(x<b) || (c>d); System.out.println(a); // stampo true. } }
package com.peihua.interceptor; import com.peihua.pojo.User; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginInterceptor implements HandlerInterceptor { /*前置处理*/ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); /*拿到用户信息*/ User user = (User) session.getAttribute("user"); if(user == null){//为空: 不放行 request.setAttribute("erroyy","还没有登录"); request.setAttribute("loginerror","请先登录"); request.getRequestDispatcher("index.jsp").forward(request,response); return false; } return true; /* if (user != null){ return true; }else { request.getRequestDispatcher("index.jsp").forward(request,response); return false; }*/ } }
package org.ordogene.cli; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.ordogene.cli.errorHandle.ErrorHandle; import org.ordogene.file.utils.ApiJsonResponse; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.mock.http.client.MockClientHttpResponse; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(MockitoJUnitRunner.class) public class ErrorHandleTest { @Mock private RestTemplate restTemplate; @InjectMocks private Commands commands; private static final ObjectMapper mapper = new ObjectMapper(); @Test(expected = HttpClientErrorException.class) public void handleError401Test() throws IOException { ApiJsonResponse ajr = new ApiJsonResponse(null,0,"TestError : CLIENT_ERROR",null,null); String strBody = mapper.writeValueAsString(ajr); InputStream is = new ByteArrayInputStream(strBody.getBytes(StandardCharsets.UTF_8)); ClientHttpResponse errorHttpResponse = new MockClientHttpResponse(is, HttpStatus.BAD_REQUEST); ErrorHandle eh = new ErrorHandle(); eh.handleError(errorHttpResponse); } @Test(expected = HttpServerErrorException.class) public void handleError500Test() throws IOException { ApiJsonResponse ajr = new ApiJsonResponse(null, 0, "TestError : SERVER_ERROR", null, null); String strBody = mapper.writeValueAsString(ajr); InputStream is = new ByteArrayInputStream(strBody.getBytes(StandardCharsets.UTF_8)); ClientHttpResponse errorHttpResponse = new MockClientHttpResponse(is, HttpStatus.INTERNAL_SERVER_ERROR); ErrorHandle eh = new ErrorHandle(); eh.handleError(errorHttpResponse); } @Test(expected = RestClientException.class) public void handleErrorNoHandledTest() throws IOException { ApiJsonResponse ajr = new ApiJsonResponse(null, 0, "TestError : Carabistouille_Error", null, null); String strBody = mapper.writeValueAsString(ajr); InputStream is = new ByteArrayInputStream(strBody.getBytes(StandardCharsets.UTF_8)); ClientHttpResponse errorHttpResponse = new MockClientHttpResponse(is, HttpStatus.CHECKPOINT); ErrorHandle eh = new ErrorHandle(); eh.handleError(errorHttpResponse); } }
package com.example.demo.service; import com.example.demo.dto.Product; import com.example.demo.util.RedisSerializer; import com.example.demo.util.stats.RecordTime; import com.example.demo.util.stats.TimeParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * Service to store and fetch data from Redis. */ @Service public class RedisService { @Autowired public JedisPool jedisPool; @Autowired RedisSerializer redisSerializer; /** * Store String value to Redis * @param key * @param value * @return */ public String storeValue(String key, String value) { try { Jedis jd = jedisPool.getResource(); jd.set(key, value); jd.incr("count"); return jd.get(key); } catch (Exception d) { return "Error Occure" + d.getMessage(); } } /** * Fetch String value from Redis * @param key * @return */ public String getValue(String key) { try { Jedis jd = jedisPool.getResource(); jd.incr("count"); String redisvalue = jd.get(key); String value = redisvalue == null ? "" : redisvalue; return value; } catch (Exception e) { return "Error Occure"; } } /** * Fetch List of keys value from Redis * @return */ public Set<String> getKeys() { try { Jedis jd = jedisPool.getResource(); return jd.keys("*"); } catch (Exception e) { return new TreeSet<>(); } } /** * To count no of times the set and get of string method is called. this return integer count from key "count" * @return */ @RecordTime public String getCount() { try { Jedis jd = jedisPool.getResource(); String redisvalue = jd.get("count"); checkingParamAnotation(redisvalue); return redisvalue; } catch (Exception e) { return "Error Occure"; } } /** * To store product into Redis. We need to serialize object for storing it into Redis * @param product * @return * @throws Exception */ @RecordTime public Product addProduct(Product product) throws Exception{ Jedis jd = jedisPool.getResource(); jd.set(redisSerializer.convertToByte("recentProductList") , redisSerializer.convertToByte(product)); return product; } /** * fetching Product object from Redis. Need to deSerialize byte into Product object * @param key * @return * @throws Exception */ @RecordTime public Product getProduct(String key) throws Exception{ key = key != null ? key : "recentProductList"; Jedis jd = jedisPool.getResource(); byte[] bytes = jd.get(redisSerializer.convertToByte(key)); return (Product)redisSerializer.convertToObject(bytes); } @RecordTime private void checkingParamAnotation(@TimeParam(value = "str") String str) { System.out.println("Executed Filed param : " + str); } }
package com.example.thread; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by zhaoningqiang on 16/7/8. */ public class CountdownLatchTest { public static void main(String[] args) throws InterruptedException { CountDownLatch start = new CountDownLatch(1); CountDownLatch end = new CountDownLatch(3); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0 ; i < 3; i++){ Runnable runnable = new Runnable() { @Override public void run() { try { System.out.println(Thread.currentThread().getName()+" 正在等待 "+start.getCount()); start.await(); Thread.sleep((long) (Math.random()*10000)); System.out.println(Thread.currentThread().getName()+"  已经到达 "+start.getCount()); end.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }; executorService.execute(runnable); } executorService.shutdown(); Thread.sleep((long) (Math.random()*10000)); System.out.println(Thread.currentThread().getName()+"  马上发布命令 "+end.getCount()); start.countDown(); System.out.println(Thread.currentThread().getName()+"  等待发布发布结果 "+end.getCount()); end.await(); System.out.println(Thread.currentThread().getName()+"  发布结果 "+end.getCount()); } }
package UI.Sends; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; import javax.mail.Message; import javax.swing.JFrame; import javax.swing.WindowConstants; import Util.Email.EmailDataManager; import DataInfo.EmailMessage; import DataInfo.EnumType; public class SendedUITest extends JFrame { // SendedUI sendUI = null; public SendedUITest(EmailMessage message) { super("zimenglan - send email UI"); sendUI = new SendedUI(message); // sendUI.setBackground(Color.yellow); this.add(sendUI, BorderLayout.CENTER); // 设置大小 this.setSize(new Dimension( EnumType.ACC_JSCROLLPANE_WIDTH, EnumType.ACC_JSCROLLPANE_HEIGHT)); // 禁止拉动窗口大小 setResizable(EnumType.Sended_UI_IS_RESIZE); // 居中窗口 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2); // 设置可见 this.setVisible(true); // 关闭窗口 setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } public static void main(String[] args) { // login EmailDataManager.DefaultLogin(); SendedUITest st = new SendedUITest(new EmailMessage()); // st.setBackground(Color.red); } }
package us.spring.dayary.common.tool; public class XSS { public static String xssShield(String str) { str = str.replaceAll("&", "&amp;"); str = str.replaceAll("<", "&lt;"); str = str.replaceAll(">", "&gt;"); str = str.replaceAll("\"", "&quot;"); str = str.replaceAll("\'", "&apos;"); str = str.replaceAll(" ", "&nbsp;"); str = str.replaceAll("\n", "<br>"); return str; } }
package com.javawebtutor.Controllers; import com.javawebtutor.Models.Users; import com.javawebtutor.Utilities.HibernateUtil; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.PasswordField; import org.hibernate.Session; import org.hibernate.SessionFactory; import java.io.IOException; public class ActivatePasswordController extends Controller{ SessionFactory factory = HibernateUtil.getSessionFactory(); Session session = factory.getCurrentSession(); @FXML private PasswordField password; public void activatePassword(ActionEvent event) throws IOException { System.out.println(password.getText()); session.getTransaction().begin(); Users u = session.get(Users.class, LogInController.loggedUserId); u.setPasswordActivated(1); u.setPassword(password.getText()); System.out.println(u.toString()); session.getTransaction().commit(); session.close(); logOut(event); } public void backButton(ActionEvent event) throws IOException { changeScene(event, "/LogInScene.fxml"); } }
/** * */ package net.sf.taverna.t2.component.ui.menu.component; import static java.awt.GridBagConstraints.BOTH; import static java.awt.GridBagConstraints.WEST; import static javax.swing.JOptionPane.ERROR_MESSAGE; import static javax.swing.JOptionPane.OK_CANCEL_OPTION; import static javax.swing.JOptionPane.OK_OPTION; import static javax.swing.JOptionPane.showConfirmDialog; import static javax.swing.JOptionPane.showMessageDialog; import static net.sf.taverna.t2.component.ui.serviceprovider.ComponentServiceIcon.getIcon; import static org.apache.log4j.Logger.getLogger; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JPanel; import javax.swing.border.TitledBorder; import net.sf.taverna.t2.component.api.Component; import net.sf.taverna.t2.component.api.RegistryException; import net.sf.taverna.t2.component.api.Version; import net.sf.taverna.t2.component.ui.panel.ComponentChoiceMessage; import net.sf.taverna.t2.component.ui.panel.ComponentChooserPanel; import net.sf.taverna.t2.component.ui.panel.ProfileChoiceMessage; import net.sf.taverna.t2.lang.observer.Observable; import net.sf.taverna.t2.lang.observer.Observer; import org.apache.log4j.Logger; /** * @author alanrw * */ public class ComponentMergeAction extends AbstractAction { private static final long serialVersionUID = 6791184757725253807L; private static final Logger logger = getLogger(ComponentMergeAction.class); private static final String MERGE_COMPONENT = "Merge component..."; public ComponentMergeAction() { super(MERGE_COMPONENT, getIcon()); } @Override public void actionPerformed(ActionEvent arg0) { JPanel overallPanel = new JPanel(); overallPanel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); ComponentChooserPanel source = new ComponentChooserPanel(); source.setBorder(new TitledBorder("Source component")); gbc.insets = new Insets(0, 5, 0, 5); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = WEST; gbc.fill = BOTH; gbc.gridwidth = 2; gbc.weightx = 1; overallPanel.add(source, gbc); final ComponentChooserPanel target = new ComponentChooserPanel(); target.setBorder(new TitledBorder("Target component")); gbc.gridy++; overallPanel.add(target, gbc); source.addObserver(new Observer<ComponentChoiceMessage>() { @Override public void notify(Observable<ComponentChoiceMessage> sender, ComponentChoiceMessage message) throws Exception { ProfileChoiceMessage profileMessage = new ProfileChoiceMessage( message.getComponentFamily().getComponentProfile()); target.notify(null, profileMessage); } }); int answer = showConfirmDialog(null, overallPanel, "Merge Component", OK_CANCEL_OPTION); if (answer == OK_OPTION) doMerge(source.getChosenComponent(), target.getChosenComponent()); } private void doMerge(Component sourceComponent, Component targetComponent) { if (sourceComponent == null) { showMessageDialog(null, "Unable to determine source component", "Component Merge Problem", ERROR_MESSAGE); return; } else if (targetComponent == null) { showMessageDialog(null, "Unable to determine target component", "Component Merge Problem", ERROR_MESSAGE); return; } else if (sourceComponent.equals(targetComponent)) { showMessageDialog(null, "Cannot merge a component with itself", "Component Merge Problem", ERROR_MESSAGE); return; } try { Version sourceVersion = sourceComponent.getComponentVersionMap() .get(sourceComponent.getComponentVersionMap().lastKey()); targetComponent.addVersionBasedOn(sourceVersion.getDataflow(), "Merge from " + sourceComponent.getFamily().getName() + ":" + sourceComponent.getName()); } catch (RegistryException e) { logger.error("failed to merge component", e); showMessageDialog(null, "Failed to merge component: " + e, "Component Merge Problem", ERROR_MESSAGE); } } }
package com.class3601.social.models; import com.class3601.social.common.Messages; public class Friend { private String friendIdPrimarKey; private String id; private String friendid; private String status; public Friend() { setId(Messages.UNKNOWN); setFriendid(Messages.UNKNOWN); setStatus(Messages.UNKNOWN); } public void updateFromFriend(Friend friend) { setFriendIdPrimarKey(friend.getFriendIdPrimarKey()); setId(friend.getId()); setStatus(friend.getStatus()); } public Friend copy() { Friend friend = new Friend(); friend.updateFromFriend(this); return friend; } public boolean equals(Friend friend) { return getFriendIdPrimarKey().equals(friend.getFriendIdPrimarKey()); } public String getFriendIdPrimarKey() { return friendIdPrimarKey; } public void setFriendIdPrimarKey(String friendIdPrimarKey) { this.friendIdPrimarKey = friendIdPrimarKey; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFriendid() { return friendid; } public void setFriendid(String friendid) { this.friendid = friendid; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
import java.util.*; import java.io.*; import java.math.*; class Solution { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); // the number of temperatures to analyse in.nextLine(); String temps = in.nextLine(); // the n temperatures expressed as integers ranging from -273 to 5526 int[] arr = new int[n]; if (n == 0) System.out.println(0); else { for (int i = 0; i < n; i++) { if (temps.indexOf(" ") != -1) { arr[i] = Integer.parseInt(temps.substring(0, temps.indexOf(" "))); temps = temps.substring(temps.indexOf(" ") + 1, temps.length()); } else { arr[i] = Integer.parseInt(temps); temps = ""; } } int max = 0; for (int i = 0; i < n; i++) { if (Math.abs(arr[i]) < Math.abs(arr[max]) || (Math.abs(arr[i]) == Math.abs(arr[max]) && arr[i] > 0)) max = i; } System.out.println(arr[max]); } } }
package eulen.po; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import funciones.Screenshooter; public class LoginEulenPO { private WebDriver driver; @FindBy(id = "iniciarSesion") private WebElement iniciarSesion; @FindBy(xpath = "//img[@alt='Logo de EULEN']") private WebElement icono; public LoginEulenPO(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } public void assertPage() { Assert.assertEquals("Logo de EULEN", icono.getAttribute("alt")); //System.out.println("verficar" + icono.getAttribute("alt")); } public void inicio() { Screenshooter.takeScreenshot("Capturas\\loginNew\\LOGIN", driver); iniciarSesion.click(); } }
package falcons.client; import java.io.File; import java.io.IOException; import falcons.client.controller.ClientMasterController; import falcons.client.controller.DataMasterController; import falcons.client.network.ClientConnection; import falcons.client.network.SystemClientPlugin; import falcons.plugin.AbstractPluginData; import falcons.plugin.PluginCall; import falcons.utils.LibraryEvent; public class Client { private ClientMasterController controller; private DataMasterController dataController; private ClientConnection connection = null; private boolean connected = false; /** * Default constructor. */ public Client(){ controller = new ClientMasterController(); dataController = new DataMasterController(); } /** * Called by the Client-object when actionPerformed is called from the * ClientView. Determines which type of action was performed and asks the * correct sub-controller to handle it. * * @param e * The ClientEvent associated with the action that the View was * asking for. */ public void actionPerformed(LibraryEvent e){ controller.actionPerformed(e); } /** * Returns the data associated with a LibraryEvent. * @param e The LibraryEvent to return the data from. * @return A general objcet containing the data. */ public Object getData(LibraryEvent e){ return dataController.getData(e); } /** * Fetches a {@link ClientConnection} which starts a connection to the server. * @return True if the connection is completed. */ public boolean connect(){ connection = ClientConnection.getInstance(); connected = true; return connected; } /** * Closes the {@link ClientConnection} which disconnects from the server. * @return Returns true if the disconnection is succesful. */ public boolean disconnect(){ SystemClientPlugin.getInstance().disconnect(); try{ connection.closeConnection(); }catch(Exception e){ e.printStackTrace(); } connected = false; return !connected; } /** * Checks if there is an established connection. * @return True if there is an connection established, otherwise false. */ public boolean connected(){ return connected; } }
package sop.filegen.generator.impl; import java.io.File; import java.io.OutputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRExporter; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.export.JRCsvExporter; import net.sf.jasperreports.engine.export.JRTextExporter; import net.sf.jasperreports.engine.export.JRTextExporterParameter; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.JRXlsExporterParameter; import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter; import net.sf.jasperreports.engine.util.JRLoader; /** * @Author: LCF * @Date: 2020/1/8 17:54 * @Package: sop.filegen.generator.impl */ @SuppressWarnings("deprecation") public class JrReportEngine { private static DataSource ds; private static JrReportEngine engine; private Map<String, String> jasperFiles = Collections.synchronizedMap(new HashMap<String, String>()); private String reportPath; public static JrReportEngine getInstance() { if (engine == null) { engine = new JrReportEngine(); engine.setDataSource(ds); engine.setReportPath(System.getProperty("rrr.config.path")); //engine.compileAllTemplates(); } return engine; } public Map<String, String> getJasperFiles() { return jasperFiles; } public String getReportPath() { return reportPath; } public void setReportPath(String reportPath) { this.reportPath = reportPath; } public DataSource getDataSource() { return ds; } public void setDataSource(DataSource dataSource) { ds = dataSource; } public void compileAllTemplates() { JrReportCompiler.compileAllTemplates(reportPath, jasperFiles); } private JasperPrint fillSQLReport(String mainReport, Map<String, Object> params) throws Exception { //JrReportCompiler.compileToFileWhenNeccessary(this.getReportPath(),this.jasperFiles, mainReport); //Assert.isTrue(jasperFiles.containsKey(mainReport), "report can not be able to locate. "+ mainReport); String jasperFile = JrReportEngine.class.getClassLoader().getResource("reportsTemplates").getPath() + "//" + mainReport + ".jasper"; JrReportFiller filler = new JrReportFiller(this.getDataSource()); return filler.fillReport(jasperFile, params); } public String exportPdfWithSQL(String mainReport, Map<String, Object> params, String outFile) throws Exception { JasperExportManager.exportReportToPdfFile(fillSQLReport(mainReport, params), outFile); return outFile; } public OutputStream exportPdfWithSQL(String mainReport, Map<String, Object> model, OutputStream outputStream) throws Exception { JasperExportManager.exportReportToPdfStream(fillSQLReport(mainReport, model), outputStream); return outputStream; } public String exportXlsWithSQL(String mainReport, Map<String, Object> params, String outFile) throws Exception { JRXlsExporter exporter = new JRXlsExporter(); JasperPrint jasperPrint = fillSQLReport(mainReport, params); /*Add remove empty space rows for style of report*/ exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, true); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new File(outFile)); exporter.exportReport(); return outFile; } public String exportXlsxWithSQL(String mainReport, Map<String, Object> params, String outFile) throws Exception { JRXlsxExporter exporter = new JRXlsxExporter(); JasperPrint jasperPrint = fillSQLReport(mainReport, params); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new File(outFile)); exporter.exportReport(); return outFile; } public OutputStream exportXlsxWithSQL(String mainReport, Map<String, Object> params, OutputStream outputStream) throws Exception { JRXlsxExporter exporter = new JRXlsxExporter(); JasperPrint jasperPrint = fillSQLReport(mainReport, params); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE, outputStream); exporter.exportReport(); return outputStream; } public OutputStream exportCsvWithSQL(String mainReport, Map<String, Object> params, OutputStream outputStream) throws Exception { JRCsvExporter exporter = new JRCsvExporter(); JasperPrint jasperPrint = fillSQLReport(mainReport, params); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE, outputStream); exporter.exportReport(); return outputStream; } public String exportCsvWithSQL(String mainReport, Map<String, Object> params, String outFile) throws Exception { JRCsvExporter exporter = new JRCsvExporter(); JasperPrint jasperPrint = fillSQLReport(mainReport, params); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new File(outFile)); exporter.exportReport(); return outFile; } // public OutputStream exportTxtWithSQL(String mainReport, Map<String, Object> params, OutputStream outputStream) throws Exception { JRTextExporter exporter = new JRTextExporter(); JasperPrint jasperPrint = fillSQLReport(mainReport, params); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE, outputStream); exporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 200); exporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 300); exporter.exportReport(); return outputStream; } public String exportTxtWithSQL(String mainReport, Map<String, Object> params, String outFile) throws Exception { JRTextExporter exporter = new JRTextExporter(); JasperPrint jasperPrint = fillSQLReport(mainReport, params); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new File(outFile)); exporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 200); exporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 300); exporter.exportReport(); return outFile; } // public String exportXlsxWithJRDatasource(String mainReport, Map<String, Object> params, JRDataSource jrds, String outFile) throws Exception { JRXlsxExporter exporter = new JRXlsxExporter(); return exportFileWithJRDatasource(exporter, mainReport, params, jrds, outFile); } public String exportXlsWithJRDatasource(String mainReport, Map<String, Object> params, JRDataSource jrds, String outFile) throws Exception { JRXlsExporter exporter = new JRXlsExporter(); /*Add remove empty space rows for style of report*/ exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, true); return exportFileWithJRDatasource(exporter, mainReport, params, jrds, outFile); } public String exportTxtWithJRDatasource(String mainReport, Map<String, Object> params, JRDataSource jrds, String outFile) throws Exception { JRTextExporter exporter = new JRTextExporter(); exporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 200); exporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 300); return exportFileWithJRDatasource(exporter, mainReport, params, jrds, outFile); } public String exportCsvWithJRDatasource(String mainReport, Map<String, Object> params, JRDataSource jrds, String outFile) throws Exception { JRCsvExporter exporter = new JRCsvExporter(); return exportFileWithJRDatasource(exporter, mainReport, params, jrds, outFile); } @SuppressWarnings("rawtypes") private String exportFileWithJRDatasource(JRExporter exporter, String mainReport, Map<String, Object> params, JRDataSource jrds, String outFile) throws Exception { //JrReportCompiler.compileToFileWhenNeccessary(this.getReportPath(),this.jasperFiles, mainReport); //Assert.isTrue(jasperFiles.containsKey(mainReport), "report can not be able to locate. "+ mainReport); //File sourceFile = new File(jasperFiles.get(mainReport)); String jasperFile = JrReportEngine.class.getClassLoader().getResource("reportsTemplates").getPath() + "//" + mainReport + ".jasper"; File sourceFile = new File(jasperFile); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(sourceFile); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, jrds); return exportToFile(jasperPrint, exporter, mainReport, params, jrds, outFile); } @SuppressWarnings("rawtypes") private String exportToFile(JasperPrint jasperPrint, JRExporter exporter, String mainReport, Map<String, Object> params, JRDataSource jrds, String outFile) throws Exception { exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new File(outFile)); exporter.exportReport(); return outFile; } public String exportPdfWithJRDatasource(String mainReport, Map<String, Object> params, JRDataSource jrds, String outFile) throws Exception { //JrReportCompiler.compileToFileWhenNeccessary(this.getReportPath(),this.jasperFiles, mainReport); //Assert.isTrue(jasperFiles.containsKey(mainReport), "report can not be able to locate. "+ mainReport); //File sourceFile = new File(jasperFiles.get(mainReport)); String jasperFile = JrReportEngine.class.getClassLoader().getResource("reportsTemplates").getPath() + "//" + mainReport + ".jasper"; File sourceFile = new File(jasperFile); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(sourceFile); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, jrds); JasperExportManager.exportReportToPdfFile(jasperPrint, outFile); return outFile; } public OutputStream exportPdfWithJRDatasource(String mainReport, Map<String, Object> params, JRDataSource jrds, OutputStream outputStream) throws Exception { //JrReportCompiler.compileToFileWhenNeccessary(this.getReportPath(),this.jasperFiles, mainReport); //Assert.isTrue(jasperFiles.containsKey(mainReport), "report can not be able to locate. "+ mainReport); //File sourceFile = new File(jasperFiles.get(mainReport)); String jasperFile = JrReportEngine.class.getClassLoader().getResource("reportsTemplates").getPath() + "//" + mainReport + ".jasper"; File sourceFile = new File(jasperFile); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(sourceFile); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, jrds); JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream); return outputStream; } public String exportHtmlWithJRDatasource(String mainReport, Map<String, Object> params, JRDataSource jrds, String outFile) throws Exception { //JrReportCompiler.compileToFileWhenNeccessary(this.getReportPath(),this.jasperFiles, mainReport); //Assert.isTrue(jasperFiles.containsKey(mainReport), "report can not be able to locate. "+ mainReport); //File sourceFile = new File(jasperFiles.get(mainReport)); String jasperFile = JrReportEngine.class.getClassLoader().getResource("reportsTemplates").getPath() + "//" + mainReport + ".jasper"; File sourceFile = new File(jasperFile); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(sourceFile); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, jrds); JasperExportManager.exportReportToHtmlFile(jasperPrint, outFile); return outFile; } public String exportHtmlWithSQL(String mainReport, Map<String, Object> params, String outFile) throws Exception { JasperExportManager.exportReportToHtmlFile(fillSQLReport(mainReport, params), outFile); return outFile; } }
package com.itheima.day_03.sleep; public class PassengerA extends Person { @Override public void sleep() { System.out.println("PassengerA is sleeping"); } }
package vue; import java.net.URL; import dao.Requete; import model.Main; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class Vue { public static Stage parentWindow; public static String NumCompte; public Vue(String VueName,Stage arg0,String NumCompte) throws Exception { if ( arg0 != null ) parentWindow = arg0; this.NumCompte = NumCompte; parentWindow.setTitle(VueName+" - BanqueClient"); final URL fxml = getClass().getResource("/vue/"+VueName+".fxml"); final FXMLLoader fxmlLoader = new FXMLLoader(fxml); final VBox nodeParent = (VBox) fxmlLoader.load(); Scene scene = new Scene(nodeParent); setStyleSheets(scene,VueName); Main.parentWindow.setScene(scene); Main.parentWindow.show(); } public void setStyleSheets(Scene scene, String vue) { scene.getStylesheets().add("/vue/form.css"); if (vue.equals("Compte")) { scene.getStylesheets().add("/vue/listview.css"); } } }
package com.yecoo.util; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.Random; import java.util.StringTokenizer; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; /** * 公用方法 * @author zhoujd */ public class StrUtils { /** * 写入日志 * @param classname * @param obj * @creadate 2012-3-31 */ public static final void WriteLog(String classname, Object obj) { Logger logger = Logger.getLogger(classname); logger.error(obj); } /** * 将sourceStr转换为指定长度输出,用‘0’补足 * @param sourceStr * @param strLen * @return String * @creadate 2012-3-31 */ public static String getLenStr(String sourceStr, int strLen) { String FullStr = "0000000000"; String rstStr = ""; rstStr = FullStr.substring(0, strLen - sourceStr.length()) + sourceStr; return rstStr; } /** * NULL转为"" * @param sourceStr * @return String * @creadate 2012-3-31 */ public static String nullToStr(String sourceStr) { if ((sourceStr == null) || sourceStr.equals("") || sourceStr.equals("null")) { sourceStr = ""; } return sourceStr; } public static String nullToStr(Object sourceStr, String defaultStr) { if ((sourceStr == null) || sourceStr.equals("") || sourceStr.equals("null")) { sourceStr = defaultStr; } return sourceStr.toString(); } /** * NULL转为"" * @param sourceStr1 * @return String * @creadate 2012-3-31 */ public static String nullToStr(Object sourceStr1) { String sourceStr = sourceStr1 + ""; if ((sourceStr == null) || sourceStr.equals("") || sourceStr.equals("null")) { sourceStr = ""; } return sourceStr; } /** * 执行javascript操作,把内容显示到页面上 * @param response * @param showContent * @creadate 2012-3-31 */ public static void printToPage(HttpServletResponse response, String showContent) { try { response.setContentType("text/html;charset=UTF-8"); response.getWriter().print(showContent); } catch (IOException e) { e.printStackTrace(); } } /** * 去除字符串line中的&nbsp;、全角空格、半角空格 * @param line * @return String * @creadate 2012-3-31 */ public static String replaceBlank(String line) { String sResult = ""; line = line.trim(); for (int i = 0; i < line.length(); i++) { String str1 = line.substring(i, i + 1); byte[] hjl = str1.getBytes(); if (hjl[0] != 63) { // 如果不是&nbsp; if (hjl.length == 2) { // 长度等于2说明是全角字符 if (!(hjl[0] == -95 && hjl[1] == -95)) { // 如果不是全角空格 sResult = sResult + str1; // 如果不是全角空格,则连接就可以了 } } else if (hjl.length == 1) { // 说明是半角字符 sResult = sResult + str1; // 直接连接就可以了 } } } return sResult; } /** * 去除字符串line中的数字、“.”、"-"以外的字符 * @param line * @return String * @creadate 2012-3-31 */ public static String matchNumber(String line) { String sResult = ""; line = line.trim(); for (int i = 0; i < line.length(); i++) { String str1 = line.substring(i, i + 1); if (str1.equals("-") || str1.equals(".")) { sResult = sResult + str1; } else { byte[] hj = str1.getBytes(); // 若字符为0到9的数字 if ((hj[0] >= 48 && hj[0] <= 57)) { sResult = sResult + str1; } } } return sResult; } /** * 将列表转换成以splitStr分隔的字符串 * @param list * @param splitStr * @return String * @creadate 2012-3-31 */ public static String listToStr(List<String> list, String splitStr) { String sFields = ""; try { if (!list.isEmpty()) { sFields = (String) list.get(0); for (int i = 1; i < list.size(); i++) { sFields = sFields + splitStr + (String) list.get(i); } } } catch (Exception e) { sFields = "error"; StrUtils.WriteLog("StrUtils.implode()", e); } return sFields; } /** * 将数组转换成以splitStr分隔的字符串 * @param str * @param splitStr * @return String * @creadate 2012-3-31 */ public static String ArrayToStr(String[] str, String splitStr) { String sFields = ""; try { if (str != null) { for (int i = 0; i < str.length; i++) { if (!"".equals(StrUtils.nullToStr(str[i]))) { sFields += splitStr + StrUtils.nullToStr(str[i]); } } if (!sFields.equals("")) { sFields = sFields.substring(splitStr.length()); } } } catch (Exception e) { StrUtils.WriteLog("StrUtils.implode()", e); } return sFields; } /** * 将list转换成string[] * @param list * @return string[] */ public static String[] listToStrs(List<Object> list) { String[] sArr = new String[list.size()]; try { for (int i = 0; i < list.size(); i++) { sArr[i] = (String) list.get(i); } } catch (Exception e) { StrUtils.WriteLog("StrUtils.listToStr()", e); } return sArr; } /** * 将字符串分割成字符串数组 * @param str 被分割字符串 * @param div 分割字符串 * @return 字符串数组 */ public static String[] strToArray(String str, String div) { ArrayList<String> array = new ArrayList<String>(); StringTokenizer fenxi = new StringTokenizer(str, div); while (fenxi.hasMoreTokens()) { String s1 = fenxi.nextToken(); array.add(s1); } String[] result = new String[array.size()]; for (int i = 0; i < result.length; i++) result[i] = (String) array.get(i); return result; } /** * 根据random()与字典字符串产生随机字符串 * @param length 字串长度 * @return 随机字符串 */ // 定义私有变量 private static Random randGen = null; private static char[] numbersAndLetters = null; private static Object initLock = new Object(); public static final String randomString(int length) { if (length < 1) { return null; } if (randGen == null) { synchronized (initLock) { if (randGen == null) { randGen = new Random(); numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") .toCharArray(); } } } char[] randBuffer = new char[length]; for (int i = 0; i < length; i++) { randBuffer[i] = numbersAndLetters[randGen.nextInt(71)]; } return new String(randBuffer); } /** * 封装SQL,获取分页SQL * @param sSQL * @param iCurrentPage 当前页 * @param iPageSize 每页数 * @return String * @creadate 2012-3-31 */ public static String getMultiPageSQL(String sSQL, int iCurrentPage, int iPageSize) { String sReturn = ""; try { sReturn = "SELECT * FROM (" + "SELECT ROWNUM AS FTEMP_INDEX,TEMP_TABLE_A.* FROM " + "(" + sSQL + ") TEMP_TABLE_A " + "WHERE ROWNUM<=" + iCurrentPage * iPageSize + ") TEMP_TABLE_B " + "WHERE TEMP_TABLE_B.FTEMP_INDEX>" + (iCurrentPage - 1) * iPageSize; } catch (Exception e) { StrUtils.WriteLog("StrUtils.getMultiPageSQL()", e); } finally { } return sReturn; } /** * 判断是否是字符是否数值型函数 * @param str 字符 * @return boolean */ public static boolean CheckFloat(String str) { try { Double.parseDouble(str); return true; } catch (Exception ex) { return false; } } /** * 编码 * @param value * @return String * @creadate 2012-3-22 */ public static String encode(String value) { String sReturn = ""; try { if (value == null) { return sReturn; } sReturn = java.net.URLEncoder.encode(value, "UTF-8"); } catch (Exception e) { StrUtils.WriteLog("StrUtils.encode()", e); } return sReturn; } /** * 解码 * @param value * @return String * @creadate 2012-3-22 */ public static String decode(String value) { String sReturn = ""; try { if (value == null) return sReturn; sReturn = java.net.URLDecoder.decode(value, "UTF-8"); } catch (Exception e) { StrUtils.WriteLog("StrUtils.encode()", e); } return sReturn; } /** * XML字符转义 * @param str * @return String */ public static String changeStrXML(String str) { str = nullToStr(str); str = str.replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll( "&", "&amp;").replaceAll("'", "&apos;").replaceAll("\"", "&quot;"); return str; } /** * 取得服务配置信息 * @return Properties * @creadate 2012-3-31 */ public static Properties getServerProperties() { Properties osPro = System.getProperties(); String UserDir = ""; InputStream is = null; try { // 获取当前用户的工作目录 UserDir = osPro.getProperty("user.dir"); is = new FileInputStream(UserDir + "/project_server.ini"); osPro.load(is); is.close(); } catch (Exception e) { StrUtils.WriteLog("StrUtils.getServerProperties()", e); } finally { if (is != null) { try { is.close(); } catch (Exception ignore) { } } } return osPro; } /** * 字符串类型转Date类型 * @param date_str * @return Date "yyyy-MM-dd" * @creadate 2012-3-31 */ public static Date strToDate(String date_str) { try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); ParsePosition pos = new ParsePosition(0); java.util.Date current = formatter.parse(date_str, pos); return current; } catch (NullPointerException e) { return null; } } /** * 日期格式化,返回字符串类型 * @param date * @return String "yyyy-MM-dd" * @creadate 2012-3-31 */ public static String DateToStr(java.util.Date date) { try { return (new SimpleDateFormat("yyyy-MM-dd")).format(date); } catch (NullPointerException e) { return null; } } /** * 获取当前时间 * @return String * @creadate 2012-3-22 */ public static String getSysdate() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(new Date()); } /** * 获取当前时间 * @param format 日期格式 * @return String * @creadate 2012-3-22 */ public static String getSysdate(String format) { if("".equals(nullToStr(format))) { format = "yyyy-MM-dd"; } SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(new Date()); } /** * 获取编码 * @param parentNo父级编码 * @param noclumn 编码字段 * @param tabname 表名 * @return */ public static String getNO(String parentNo, String noclumn, String tabname) { DbUtils dbUtils = new DbUtils(); String no = parentNo; StringBuffer sql = new StringBuffer(""); sql.append("SELECT IFNULL(MAX(SUBSTR(").append(noclumn).append(", -2)), 0) + 1 FROM ").append(tabname) .append(" WHERE ").append(noclumn).append(" like '" + parentNo + "__'"); no += StringUtils.leftPad(dbUtils.execQuerySQL(sql.toString()), 2,"0"); return no; } /** * 获取单据编码 * @param btype 单据类型 * @param noclumn 编码字段 * @param tabname 表名 * @return */ public static String getNewNO(String btype, String noclumn, String tabname) { DbUtils dbUtils = new DbUtils(); String sysdate = StrUtils.getSysdate("yyyyMMdd"); String no = btype + "-" + sysdate + "-"; StringBuffer sql = new StringBuffer(""); sql.append("SELECT IFNULL(MAX(SUBSTR(").append(noclumn).append(", -3)), 0) + 1 FROM ").append(tabname) .append(" WHERE ").append(noclumn).append(" like '" + no + "%'"); no += StringUtils.leftPad(dbUtils.execQuerySQL(sql.toString()), 3,"0"); return no; } }
/* * @(#) DbifInfo.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ims.chubdblinfo; import com.esum.wp.ims.chubdblinfo.base.BaseChubDblInfo; /** * * @author heowon@esumtech.com * @version $Revision: 1.2 $ $Date: 2009/01/15 09:23:12 $ */ public class ChubDblInfo extends BaseChubDblInfo { private static final long serialVersionUID = 1L; // DataBase Flag private String dbType; // for paging private Integer currentPage; private Integer itemCountPerPage; private Integer totalCount; private Integer minIndex; private Integer maxIndex; public Integer getMinIndex() { return minIndex; } public void setMinIndex(Integer minIndex) { this.minIndex = minIndex; } public Integer getMaxIndex() { return maxIndex; } public void setMaxIndex(Integer maxIndex) { this.maxIndex = maxIndex; } private String mode; private Integer index; private String formName; private String fieldName; // private java.util.List dbifInfoDetailList = null; private String langType; private String rootPath; public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getFormName() { return formName; } public void setFormName(String formName) { this.formName = formName; } //public java.util.List getDbifInfoDetailList() { // return dbifInfoDetailList; // } // // public void setDbifInfoDetailList(java.util.List dbifInfoDetailList) { // this.dbifInfoDetailList = dbifInfoDetailList; // } public Integer getIndex() { return index; } public void setIndex(Integer index) { this.index = index; } public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } /*[CONSTRUCTOR MARKER BEGIN]*/ public ChubDblInfo () { super(); } /** * Constructor for primary key */ public ChubDblInfo (java.lang.String interfaceId) { super(interfaceId); } /*[CONSTRUCTOR MARKER END]*/ protected void initialize () { super.initialize(); } /** * @return Returns the currentPage. */ public Integer getCurrentPage() { return currentPage; } /** * @param currentPage The currentPage to set. */ public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } /** * @return Returns the itemCountPerPage. */ public Integer getItemCountPerPage() { return itemCountPerPage; } /** * @param itemCountPerPage The itemCountPerPage to set. */ public void setItemCountPerPage(Integer itemCountPerPage) { this.itemCountPerPage = itemCountPerPage; } /** * @return Returns the totalItemCount. */ public Integer getTotalCount() { return totalCount; } /** * @param totalItemCount The totalItemCount to set. */ public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public String getDbType() { return dbType; } public void setDbType(String dbType) { this.dbType = dbType; } public String getLangType() { return langType; } public void setLangType(String langType) { this.langType = langType; } public String getRootPath() { return rootPath; } public void setRootPath(String rootPath) { this.rootPath = rootPath; } }
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.tags; import jakarta.servlet.jsp.JspException; import jakarta.servlet.jsp.PageContext; import jakarta.servlet.jsp.tagext.TagSupport; import jakarta.servlet.jsp.tagext.TryCatchFinally; import org.springframework.beans.PropertyAccessor; import org.springframework.lang.Nullable; /** * <p>The {@code <nestedPath>} tag supports and assists with nested beans or * bean properties in the model. Exports a "nestedPath" variable of type String * in request scope, visible to the current page and also included pages, if any. * * <p>The BindTag will auto-detect the current nested path and automatically * prepend it to its own path to form a complete path to the bean or bean property. * * <p>This tag will also prepend any existing nested path that is currently set. * Thus, you can nest multiple nested-path tags. * * <table> * <caption>Attribute Summary</caption> * <thead> * <tr> * <th>Attribute</th> * <th>Required?</th> * <th>Runtime Expression?</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td>path</td> * <td>true</td> * <td>true</td> * <td>Set the path that this tag should apply. E.g. 'customer' to allow bind * paths like 'address.street' rather than 'customer.address.street'.</td> * </tr> * </tbody> * </table> * * @author Juergen Hoeller * @since 1.1 */ @SuppressWarnings("serial") public class NestedPathTag extends TagSupport implements TryCatchFinally { /** * Name of the exposed variable within the scope of this tag: "nestedPath". */ public static final String NESTED_PATH_VARIABLE_NAME = "nestedPath"; @Nullable private String path; /** Caching a previous nested path, so that it may be reset. */ @Nullable private String previousNestedPath; /** * Set the path that this tag should apply. * <p>E.g. "customer" to allow bind paths like "address.street" * rather than "customer.address.street". * @see BindTag#setPath */ public void setPath(@Nullable String path) { if (path == null) { path = ""; } if (path.length() > 0 && !path.endsWith(PropertyAccessor.NESTED_PROPERTY_SEPARATOR)) { path += PropertyAccessor.NESTED_PROPERTY_SEPARATOR; } this.path = path; } /** * Return the path that this tag applies to. */ @Nullable public String getPath() { return this.path; } @Override public int doStartTag() throws JspException { // Save previous nestedPath value, build and expose current nestedPath value. // Use request scope to expose nestedPath to included pages too. this.previousNestedPath = (String) this.pageContext.getAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE); String nestedPath = (this.previousNestedPath != null ? this.previousNestedPath + getPath() : getPath()); this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME, nestedPath, PageContext.REQUEST_SCOPE); return EVAL_BODY_INCLUDE; } /** * Reset any previous nestedPath value. */ @Override public int doEndTag() { if (this.previousNestedPath != null) { // Expose previous nestedPath value. this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME, this.previousNestedPath, PageContext.REQUEST_SCOPE); } else { // Remove exposed nestedPath value. this.pageContext.removeAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE); } return EVAL_PAGE; } @Override public void doCatch(Throwable throwable) throws Throwable { throw throwable; } @Override public void doFinally() { this.previousNestedPath = null; } }
package ru.job4j.array; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class MatrixTest { @Test public void whenMultipleTableWithThreeThenMultipleTable() { Matrix matrix = new Matrix(); int[][] resultArray = matrix.multiple(3); int[][] expectArray = { {1, 2, 3}, {2, 4, 6}, {3, 6, 9} }; assertThat(resultArray, is(expectArray)); } @Test public void whenMultipleTableWithFiveThenMultipleTable() { Matrix matrix = new Matrix(); int[][] resultArray = matrix.multiple(5); int[][] expectArray = { {1, 2, 3, 4, 5}, {2, 4, 6, 8, 10}, {3, 6, 9, 12, 15}, {4, 8, 12, 16, 20}, {5, 10, 15, 20, 25} }; } }
package com.esum.framework.security.pki.x509; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyFactory; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.PublicKey; import java.security.Security; import java.security.cert.CRLException; import java.security.cert.CertPath; import java.security.cert.CertPathValidator; import java.security.cert.CertPathValidatorException; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateNotYetValidException; import java.security.cert.PKIXParameters; import java.security.cert.TrustAnchor; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Set; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import org.apache.commons.io.IOUtils; import org.bouncycastle.util.encoders.Base64; import com.esum.framework.common.util.ClassUtil; import com.esum.framework.security.pki.keystore.KeyPairType; public class X509CertUtil { private static final String X509_CERT_TYPE = "X.509"; public static final String PKCS7_ENCODING = "PKCS7"; /** Begin certificate for PEM encoding */ private static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----"; /** End certificate for PEM encoding */ private static final String END_CERT = "-----END CERTIFICATE-----"; /** The maximum length of lines in printable encoded certificates */ private static final int CERT_LINE_LENGTH = 64; public static X509Certificate[] getX509CertificateList(KeyStore keyStore, String alias) throws KeyStoreException, CertificateException { X509Certificate[] x509CertList = null; if (keyStore.isKeyEntry(alias)) // If entry is key entry x509CertList = convertCertsToX509Certs(keyStore.getCertificateChain(alias)); else {// If entry is trust entry x509CertList = new X509Certificate[1]; x509CertList[0] = convertCertsToX509Certs(keyStore.getCertificate(alias)); } return x509CertList; } private static X509Certificate[] convertCertsToX509Certs(Certificate[] certList) throws CertificateException { X509Certificate[] x509CertList = new X509Certificate[certList.length]; for (int i = 0; i < certList.length; i++) x509CertList[i] = convertCertsToX509Certs(certList[i]); return x509CertList; } public static X509Certificate convertCertsToX509Certs(Certificate cert) throws CertificateException { // We could request BC here in order to gain support for certs // with > 2048 bit RSA keys also on Java 1.4. But unless there's // a way to eg. read JKS keystores containing such certificates // on Java 1.4 (think eg. importing such CA certs), that would // just help the user shoot herself in the foot... CertificateFactory certFactory = CertificateFactory.getInstance(X509_CERT_TYPE); ByteArrayInputStream inStream = null; try{ inStream = new ByteArrayInputStream(cert.getEncoded()); return (X509Certificate)certFactory.generateCertificate(inStream); }finally{ IOUtils.closeQuietly(inStream); } } public static X509Certificate[] orderX509CertChain(X509Certificate[] certList) { int idx = 0; X509Certificate[] tmpCertList = (X509Certificate[]) certList.clone(); X509Certificate[] orderedCertList = new X509Certificate[certList.length]; X509Certificate issuerCert = null; // Find Root CA for (int i = 0; i < tmpCertList.length; i++) { X509Certificate cert = tmpCertList[i]; if (cert.getIssuerDN().equals(cert.getSubjectDN())) { issuerCert = cert; orderedCertList[idx] = issuerCert; idx++; } } // If not exist the ROOT CA, return the argumented Certificate List if (issuerCert == null) { return certList; } while (true) { boolean foundNextCert = false; for (int i = 0; i < tmpCertList.length; i++) { X509Certificate cert = tmpCertList[i]; if (cert.getIssuerDN().equals(issuerCert.getSubjectDN()) && cert != issuerCert) { issuerCert = cert; orderedCertList[idx] = issuerCert; idx++; foundNextCert = true; break; } } if (!foundNextCert) break; } // Resize array tmpCertList = new X509Certificate[idx]; System.arraycopy(orderedCertList, 0, tmpCertList, 0, idx); // Reverse the order of the array orderedCertList = new X509Certificate[idx]; for (int i = 0; i < idx; i++) orderedCertList[i] = tmpCertList[tmpCertList.length - 1 - i]; return orderedCertList; } public static int getCertificateKeyLength(X509Certificate cert) throws NoSuchAlgorithmException, InvalidKeySpecException, GeneralSecurityException { PublicKey pubKey = cert.getPublicKey(); String algorithm = pubKey.getAlgorithm(); if (algorithm.equals(KeyPairType.RSA)) { KeyFactory keyFact = KeyFactory.getInstance(algorithm, "BC"); RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(pubKey, RSAPublicKeySpec.class); BigInteger modulus = keySpec.getModulus(); return modulus.toString(2).length(); } else if (algorithm.equals(KeyPairType.DSA)) { KeyFactory keyFact = KeyFactory.getInstance(algorithm, "BC"); DSAPublicKeySpec keySpec = (DSAPublicKeySpec)keyFact.getKeySpec(pubKey, DSAPublicKeySpec.class); BigInteger prime = keySpec.getP(); return prime.toString(2).length(); } else throw new GeneralSecurityException("Could not get certificate's public key's keysize. Unrecognised algorithm '" + algorithm + "'."); } public static X509Certificate getHeadCert(KeyStore keyStore, String alias) throws KeyStoreException, CertificateException { X509Certificate cert = null; if (keyStore.isKeyEntry(alias)) cert = orderX509CertChain(convertCertsToX509Certs(keyStore.getCertificateChain(alias)))[0]; else cert = convertCertsToX509Certs(keyStore.getCertificate(alias)); return cert; } public static byte[] getCertEncodedDER(X509Certificate cert) throws CertificateEncodingException { return cert.getEncoded(); } public static byte[] getCertEncodedPEM(X509Certificate cert) throws CertificateEncodingException { String rawEncodedData = new String(Base64.encode(cert.getEncoded())); // Certificate encodng is bounded by a header and footer String data = BEGIN_CERT + "\n"; // Limit line lengths between header and footer for (int i = 0; i < rawEncodedData.length(); i += CERT_LINE_LENGTH) { int lineLength = -1 ; if ((i + CERT_LINE_LENGTH) > rawEncodedData.length()) lineLength = rawEncodedData.length() - i; else lineLength = CERT_LINE_LENGTH; data += rawEncodedData.substring(i, i + lineLength) + "\n"; } data += END_CERT + "\n"; return data.getBytes(); } public static byte[] getCertEncodedPkcs7(X509Certificate cert) throws CertificateException { return getCertListEncodedPkcs7(new X509Certificate[] {cert}); } public static byte[] getCertListEncodedPkcs7(X509Certificate[] certList) throws CertificateException { return getCertListEncoded(certList, PKCS7_ENCODING); } private static byte[] getCertListEncoded(X509Certificate[] certList, String encoding) throws CertificateException { CertificateFactory certFactory = CertificateFactory.getInstance(X509_CERT_TYPE); return certFactory.generateCertPath(Arrays.asList(certList)).getEncoded(encoding); } public static X509Certificate getCertificate(byte[] cert) throws CertificateException { CertificateFactory certFactory = CertificateFactory.getInstance(X509_CERT_TYPE); InputStream certInput = new ByteArrayInputStream(cert); try { return (X509Certificate)certFactory.generateCertificate(certInput); } finally { IOUtils.closeQuietly(certInput); } } public static Collection<X509Certificate> getCertificates(byte[] cert) throws CertificateException { CertificateFactory certFactory = CertificateFactory.getInstance(X509_CERT_TYPE); InputStream certInput = new ByteArrayInputStream(cert); try { return (Collection<X509Certificate>) certFactory.generateCertificates(new ByteArrayInputStream(cert)); } finally { IOUtils.closeQuietly(certInput); } } public static void checkValidation(X509Certificate cert, boolean isDSIGUsage, boolean isENCUsage) throws CertificateExpiredException, CertificateNotYetValidException, CertPathValidatorException, CertificateException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException, KeyStoreException, IOException { checkValidation(cert, null, null, isDSIGUsage, isENCUsage, false); } public static void checkValidation(X509Certificate cert, String certPathFile, String certPathPassword, boolean isDSIGUsage, boolean isENCUsage) throws CertificateExpiredException, CertificateNotYetValidException, CertPathValidatorException, CertificateException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException, KeyStoreException, IOException { checkValidation(cert, certPathFile, certPathPassword, isDSIGUsage, isENCUsage, false); } public static void checkValidation(X509Certificate cert, String certPathFile, String certPathPassword, boolean isDSIGUsage, boolean isENCUsage, boolean useCRL) throws CertificateExpiredException, CertificateNotYetValidException, CertPathValidatorException, CertificateException, IOException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException, KeyStoreException { cert.checkValidity(); checkCertPath(cert, certPathFile, certPathPassword); // CRL Distribution Point try { if (useCRL && isRevoked(cert)) throw new CertificateException("This certifcate is revoked."); } catch (CRLException e) { throw new CertificateException("CRL Check Error!! -" + e.getMessage()); } // Key Usage : "Digital Signature", "nonRepudation" if (isDSIGUsage) { checkDSIGUsage(cert); } // Key Usage : "Key Encipherment" if (isENCUsage) { checkENCUsage(cert); } } private static void checkCertPath(X509Certificate cert, String certPathFile, String certPathPassword) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException, CertPathValidatorException { if (certPathFile != null) { try { if (Security.getProvider("BC") == null) { Class<?> bcProvClass = ClassUtil.forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); Provider bcProv = (Provider) bcProvClass.newInstance(); Security.addProvider(bcProv); } } catch (ClassNotFoundException e) { throw new CertificateException("Class Not Found!! -" + e.getMessage()); } catch (InstantiationException e) { throw new CertificateException("Instantiation Error!! -" + e.getMessage()); } catch (IllegalAccessException e) { throw new CertificateException("Illegal Access Error!! -" + e.getMessage()); } KeyStore keyStore = KeyStore.getInstance("JKS"); FileInputStream fileInStream = null; try { fileInStream = new FileInputStream(certPathFile); keyStore.load(fileInStream, certPathPassword.toCharArray()); } finally { IOUtils.closeQuietly(fileInStream); fileInStream = null; } List<Certificate> certChain = new ArrayList<Certificate>(); certChain.add(cert); getCertList(certChain, keyStore, cert.getIssuerDN().toString()); X509Certificate rootCert = (X509Certificate)certChain.get(certChain.size() - 1); Set<TrustAnchor> trust = Collections.singleton(new TrustAnchor(rootCert, null)); PKIXParameters params = new PKIXParameters(trust); params.setRevocationEnabled(false); CertificateFactory certFact = CertificateFactory.getInstance("X.509"); CertPath certPath = certFact.generateCertPath(certChain); CertPathValidator certPathValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType(), "BC"); certPathValidator.validate(certPath, params); } } private static void getCertList(List<Certificate> certChain, KeyStore keyStore, String issuer) throws KeyStoreException { Enumeration<String> e = keyStore.aliases(); while(e.hasMoreElements()) { String alias = (String)e.nextElement(); X509Certificate trustCert = (X509Certificate)keyStore.getCertificate(alias); if (trustCert.getSubjectDN().toString().equals(issuer)) { certChain.add(trustCert); if (!trustCert.getSubjectDN().toString().equals(trustCert.getIssuerDN().toString())) { getCertList(certChain, keyStore, trustCert.getIssuerDN().toString()); } } } } private static boolean hasCRLHttpServer(String crlInfo) { return crlInfo.indexOf("http://") != -1 ? true : false; } private static String extractUrl(String crlInfo) { if (hasCRLHttpServer(crlInfo)) return crlInfo.substring(crlInfo.indexOf("http://")); else return crlInfo.substring(crlInfo.indexOf("ldap://")); } private static String getHost(String url) { int idx1 = url.indexOf("://"); int idx2 = url.indexOf("/", idx1 + 3); return url.substring(0, idx2); } private static String getPath(String url) { int idx1 = url.indexOf("://"); int idx2 = url.indexOf("/", idx1 + 3); return url.substring(idx2 + 1); } /** * (CRL) * * @param cert X509Certificate * @return boolean * @throws CRLException * @throws IOException * @throws CertificateException */ private static boolean isRevoked(X509Certificate cert) throws CRLException, IOException, CertificateException { String crlInfo = new String(cert.getExtensionValue("2.5.29.31")); String crlServer = extractUrl(crlInfo); CertificateFactory certBCFactory = CertificateFactory.getInstance("X.509"); if (hasCRLHttpServer(crlInfo)) { X509CRL crl = null; try { URL url = new URL(crlServer); crl = (X509CRL)certBCFactory.generateCRL(url.openStream()); } catch (MalformedURLException e) { throw new CRLException("URL Error!! -" + e.getMessage()); } catch (IOException e) { throw new CRLException("URL Error!! -" + e.getMessage()); } return crl.isRevoked(cert); } else { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, getHost(crlServer)); ByteArrayInputStream is = null; try { DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(getPath(crlServer)); is = new ByteArrayInputStream((byte[])attrs.get("certificateRevocationList").get()); } catch (NamingException e) { throw new IOException("LDAP Error!! -" + e.getMessage()); } finally { IOUtils.closeQuietly(is); } X509CRL crl = (X509CRL)certBCFactory.generateCRL(is); return crl.isRevoked(cert); } } private static void checkDSIGUsage(X509Certificate cert) throws CertificateException { boolean[] keyUsageList = cert.getKeyUsage(); if (keyUsageList == null) { throw new CertificateException("Key Usage is empty. Please check the Key Usage field."); } if (!keyUsageList[0]) { throw new CertificateException("Digital Signature Certificate Error!! The digitalSignature field is not set."); } if (!keyUsageList[1]) { throw new CertificateException("Digital Signature Certificate Error!! The nonRepudiation field is not set."); } } private static void checkENCUsage(X509Certificate cert) throws CertificateException { boolean[] keyUsageList = cert.getKeyUsage(); if (keyUsageList == null) { throw new CertificateException("Key Usage is empty. Please check the Key Usage field."); } if (!keyUsageList[2]) { throw new CertificateException("Encryption Certificate Error!! The keyEncipherment field is not set."); } } }
package com.example.qunxin.erp.activity; import android.Manifest; import android.app.Activity; import android.app.Dialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.example.qunxin.erp.ActivityManager; import com.example.qunxin.erp.BaseActivity; import com.example.qunxin.erp.R; import com.example.qunxin.erp.UserBaseDatus; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by qunxin on 2019/8/6. */ public class SettingsActivity extends BaseActivity { CircleImageView showImageView; TextView cancelLoginBtn; private View backBtn; TextView phoneNumTex; TextView nameText; TextView passWorldText; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings); initView(); showImageView.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { showQuan(); Intent intent = new Intent(); /* 开启Pictures画面Type设定为image */ intent.setType("image/*"); /* 使用Intent.ACTION_GET_CONTENT这个Action */ intent.setAction(Intent.ACTION_GET_CONTENT); /* 取得相片后返回本画面 */ startActivityForResult(intent, 2); } }); if(readImage()!=null){ showImageView.setImageBitmap(readImage()); } cancelLoginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = getSharedPreferences("baseData", Activity.MODE_PRIVATE).edit(); editor.putBoolean("login",false); editor.commit(); finish(); Intent intent=new Intent(SettingsActivity.this,LoginActivity.class); startActivity(intent); ActivityManager.getInstance().finishActivitys(); } }); backBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); SharedPreferences read = getSharedPreferences("baseData", Activity.MODE_PRIVATE); nameText.setText(read.getString("userName","")); phoneNumTex.setText(read.getString("phoneNumber","")); } void initView(){ showImageView = (CircleImageView)findViewById(R.id.headBitmpa); cancelLoginBtn=findViewById(R.id.cancle_login); backBtn=findViewById(R.id.settings_back); phoneNumTex=findViewById(R.id.settings_phone); nameText=findViewById(R.id.settings_name); passWorldText=findViewById(R.id.passWold); } // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (resultCode == RESULT_OK) { // Uri uri = data.getData(); // // ContentResolver cr = this.getContentResolver(); // try { // Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); // CircleImageView imageView = (CircleImageView) findViewById(R.id.headBitmpa); // /* 将Bitmap设定到ImageView */ // // imageView.setImageBitmap(bitmap); // // ByteArrayOutputStream baos=new ByteArrayOutputStream(); // bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos); // bitmap.recycle(); // // if(saveImage(baos.toByteArray())){ // Log.d("hhhhh", "onActivityResult: 成功"); // }else { // Log.d("hhhhh", "onActivityResult: 失败"); // } // // } catch (IOException e) { // Log.e("Exception", e.getMessage(),e); // } // } // super.onActivityResult(requestCode, resultCode, data); // // } String picPath; protected void onActivityResult(int requestCode, int resultCode, Intent data) { /* Bitmap bitmap=null; if(requestCode == 2){//相册 if (resultCode == RESULT_OK) { Uri uri = data.getData(); String pathOfPicture = getAbsoluteImagePath(uri); System.out.println("ok=============================" + pathOfPicture); Log.e("uri", uri.getHost()); ContentResolver cr = this.getContentResolver(); InputStream is = null; try { is = cr.openInputStream(uri); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } bitmap = BitmapFactory.decodeStream(is); } } if(bitmap!=null){ showImageView.setImageBitmap(bitmap); try{ ByteArrayOutputStream baos=new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos); saveImage(baos.toByteArray()); }catch (Exception e){ } } */ if (resultCode == Activity.RESULT_OK) { /** * 当选择的图片不为空的话,在获取到图片的途径 */ Uri uri = data.getData(); Log.e("tag", "uri = " + uri); try { String[] pojo = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, pojo, null, null, null); if (cursor != null) { ContentResolver cr = this.getContentResolver(); int colunm_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String path = cursor.getString(colunm_index); /*** * * 这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了, * * 这样的话,我们判断文件的后缀名 如果是图片格式的话,那么才可以 */ if (path.endsWith("jpg") || path.endsWith("png")) { picPath = path; Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); showImageView.setImageBitmap(bitmap); addImage(); if(bitmap!=null){ try{ ByteArrayOutputStream baos=new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos); saveImage(baos.toByteArray()); }catch (Exception e){ } } } else { alert(); } } else { alert(); } } catch (Exception e) { } } } public static final int EXTERNAL_STORAGE_REQ_CODE = 10 ; void showQuan(){ int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // 请求权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_REQ_CODE); } } private void alert() { Dialog dialog = new AlertDialog.Builder(this).setTitle("提示") .setMessage("您选择的不是有效的图片") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { picPath = null; } }).create(); dialog.show(); } protected String getAbsoluteImagePath(Uri uri) { String[] proj = { MediaStore.Images.Media.DATA }; @SuppressWarnings("deprecation") Cursor cursor = this.getContentResolver().query(uri, proj, null, null, null); int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } public Boolean saveImage(byte[] bytes) { try { FileOutputStream outputStream = openFileOutput("head.jpg", MODE_PRIVATE); outputStream.write(bytes); outputStream.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } } //读取本地文件 public Bitmap readImage(){ try { FileInputStream fis = openFileInput("head.jpg"); byte[] bytes=new byte[fis.available()]; fis.read(bytes); fis.close(); return BitmapFactory.decodeByteArray(bytes,0,bytes.length); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } //上传图片到服务器上 String avatar=""; void addImage(){ String userId="1";//业务类型 String signa= UserBaseDatus.getInstance().getSign(); final Map<String, String> params = new HashMap<String, String>(); params.put("userId", userId); params.put("signa", signa); final Map<String, File> files = new HashMap<String, File>(); File file=new File(picPath); files.put("file", file); final String strUrl = UserBaseDatus.getInstance().url+"api/app/user/updateAvatar"; new Thread(new Runnable() { @Override public void run() { try { final String request =UserBaseDatus.getInstance().post(strUrl, params, files); Log.d("requestaaa", request); JSONObject jsonObject=new JSONObject(request); avatar=jsonObject.getString("data"); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } }
package com.kidscademy.apiservice.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.kidscademy.apiservice.model.PhysicalTrait; import js.dom.Document; import js.dom.EList; import js.dom.Element; import js.lang.BugError; import js.util.Strings; public class AnimaliaPhysicalTraitsParser implements Parser<List<PhysicalTrait>> { @Override public List<PhysicalTrait> parse(Document document) { List<PhysicalTrait> traits = new ArrayList<>(); EList traitElements = document.findByCssClass("s-char-char__wrap"); if (traitElements.isEmpty()) { traitElements = document .findByXPath("//DIV[@class='s-char-char__block']/DIV[@class='row']/DIV[@class='col-6']"); } for (Element traitElement : traitElements) { EList children = traitElement.getChildren(); String traitName = name(children.item(0).getText()); String traitValue = children.item(1).getText(); String[] valueParts = parts(traitValue); Meta meta = null; try { switch (valueParts.length) { case 1: meta = new Meta("SCALAR", 1.0); traits.add(new PhysicalTrait(traitName, parseDouble(valueParts[0], meta), meta.quantity)); break; case 2: meta = meta(valueParts[1]); traits.add(new PhysicalTrait(traitName, parseDouble(valueParts[0], meta), meta.quantity)); break; case 3: meta = meta(valueParts[2]); traits.add(new PhysicalTrait(traitName, parseDouble(valueParts[0], meta), parseDouble(valueParts[1], meta), meta.quantity)); break; } } catch (NumberFormatException ignore) { // on number format error ignore trait element // possible cause is 'UNKNOWN' value, for example for population size } } return traits; } private static String[] parts(String value) { value = value.toUpperCase(); value = value.replace("BELOW ", ""); value = value.replace("ABOVE ", ""); value = value.replace(" TO ", "-"); return Strings.split(value, '-', ' ').toArray(new String[0]); } private static Map<String, String> NAME = new HashMap<>(); static { NAME.put("Population size", "population.size"); NAME.put("Life Span", "lifespan"); NAME.put("TOP SPEED", "speed.full"); NAME.put("HEIGHT", "height"); NAME.put("WEIGHT", "weight"); NAME.put("LENGTH", "length"); } private static String name(String name) { String normalizedName = NAME.get(name); if (normalizedName == null) { throw new BugError("Not handled name |%s|.", name); } return normalizedName; } private static Map<String, Meta> META = new HashMap<>(); static { META.put("YRS", new Meta("TIME", 31556952.0)); META.put("YEARS", new Meta("TIME", 31556952.0)); META.put("KM/H", new Meta("SPEED", 1.0 / 3.6)); META.put("MPH", new Meta("SPEED", 1.0 / 2.23693629)); META.put("G", new Meta("MASS", 0.001)); META.put("KG", new Meta("MASS", 1.0)); META.put("T", new Meta("MASS", 1000)); META.put("MM", new Meta("LENGTH", 0.001)); META.put("CM", new Meta("LENGTH", 0.01)); META.put("M", new Meta("LENGTH", 1.0)); META.put("THOU", new Meta("SCALAR", 1000.0)); META.put("MLN", new Meta("SCALAR", 1000000.0)); } private static Meta meta(String units) { Meta meta = META.get(units.toUpperCase()); if (meta == null) { throw new BugError("Not handled units |%s|.", units); } return meta; } private static Double parseDouble(String value, Meta meta) { return round(Double.parseDouble(value.replaceAll(",", "")) * meta.factor); } private static double round(double value) { return Math.round(value * 1000.0) / 1000.0; } private static class Meta { final String quantity; final double factor; public Meta(String quantity, double factor) { this.quantity = quantity; this.factor = factor; } } }
package bn.impl.dynbn; import java.io.PrintStream; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Vector; import bn.BNException; import bn.IBayesNode; import bn.distributions.Distribution.SufficientStatistic; import bn.dynamic.IDBNNode; import bn.impl.InternalIBayesNode; import bn.impl.dynbn.DynamicContextManager.DynamicMessageIndex; import bn.messages.Message.MessageInterfaceSet; abstract class DBNNode implements InternalIBayesNode, IDBNNode { protected DBNNode(DynamicBayesianNetwork net,String name) { this.bayesNet = net; this.name = name; } /* * General information accessors. */ @Override public String toString() { return this.name; } public final String getName() { return this.name; } public final int numParents() { return this.intraParents.size(); } public final int numTotalParents() { return this.intraParents.size()+this.interParents.size(); } public final int numChildren() { return this.intraChildren.size()+this.interChildren.size(); } public String getEdgeDefinition() { String ret = ""; Vector<Entry<DBNNode,DynamicMessageIndex>> edgeVec = new Vector<Entry<DBNNode,DynamicMessageIndex>>(this.interParents.entrySet()); Collections.sort(edgeVec,new EdgeComparer()); for(int i = 0; i < edgeVec.size(); i++) ret += edgeVec.get(i).getKey().getName()+"=>"+this.getName()+"\n"; edgeVec = new Vector<Entry<DBNNode,DynamicMessageIndex>>(this.intraParents.entrySet()); Collections.sort(edgeVec,new EdgeComparer()); for(int i = 0; i < edgeVec.size(); i++) ret += edgeVec.get(i).getKey().getName()+"->"+this.getName()+"\n"; /*for(DBNNode child : this.intraChildren.keySet()) ret += this.getName()+"->"+child.getName()+"\n"; for(DBNNode child : this.interChildren.keySet()) ret += this.getName()+"=>"+child.getName()+"\n";*/ return ret; } private static class EdgeComparer implements Comparator<Entry<DBNNode, DynamicMessageIndex>> { @Override public int compare(Entry<DBNNode, DynamicMessageIndex> o1, Entry<DBNNode, DynamicMessageIndex> o2) { return o1.getValue().compareTo(o2.getValue()); } } @Override public DynamicBayesianNetwork getNetwork() { return this.bayesNet; } /* * Abstract methods for the creation and removal of edges. Expected * to be implemented by specific node types. */ protected abstract MessageInterfaceSet<?> newChildInterface(int T) throws BNException; protected abstract DynamicMessageIndex addInterParentInterface(MessageInterfaceSet<?> mia) throws BNException; protected abstract DynamicMessageIndex addIntraParentInterface(MessageInterfaceSet<?> mia) throws BNException; protected abstract DynamicMessageIndex addInterChildInterface(MessageInterfaceSet<?> mia) throws BNException; protected abstract DynamicMessageIndex addIntraChildInterface(MessageInterfaceSet<?> mia) throws BNException; protected abstract void removeInterParentInterface(DynamicMessageIndex index) throws BNException; protected abstract void removeIntraParentInterface(DynamicMessageIndex index) throws BNException; protected abstract void removeInterChildInterface(DynamicMessageIndex index) throws BNException; protected abstract void removeIntraChildInterface(DynamicMessageIndex index) throws BNException; /* * Edge creation methods */ public void addInterChild(DBNNode child) throws BNException { if(child.bayesNet!=this.bayesNet) throw new BNException("Attempted to connect two nodes from different networks..."); if(this.interChildren.containsKey(child)) return; try { MessageInterfaceSet<?> mi = this.newChildInterface(this.bayesNet.getT()-1); DynamicMessageIndex pi = this.addInterChildInterface(mi); try { DynamicMessageIndex ci = child.addInterParentInterface(mi); this.interChildren.put(child, pi); child.interParents.put(this, ci); this.neighbors.add(child); child.neighbors.add(this); } catch(BNException e) { this.removeInterChildInterface(pi); throw new BNException(e); } } catch(BNException e) { throw new BNException("Failed to connect nodes " + this.name + " and " + child.name, e); } } public void addIntraChild(DBNNode child) throws BNException { if(child.bayesNet!=this.bayesNet) throw new BNException("Attempted to connect two nodes from different networks..."); if(this.intraChildren.containsKey(child)) return; try { MessageInterfaceSet<?> mi = this.newChildInterface(this.bayesNet.getT()); DynamicMessageIndex pi = this.addIntraChildInterface(mi); try { DynamicMessageIndex ci = child.addIntraParentInterface(mi); this.intraChildren.put(child, pi); child.intraParents.put(this, ci); this.neighbors.add(child); child.neighbors.add(this); } catch(BNException e) { this.removeIntraChildInterface(pi); throw new BNException(e); } } catch(BNException e) { throw new BNException("Failed to connect nodes " + this.name + " and " + child.name, e); } } /* * Edge removal methods. */ public void removeInterChild(DBNNode child) throws BNException { if(!this.interChildren.containsKey(child)) throw new BNException("Attempted to remove inter-child " + child.name + " from node " + this.name + " where it is not a child."); DynamicMessageIndex pi = this.interChildren.remove(child); DynamicMessageIndex ci = child.interParents.remove(this); this.removeInterChildInterface(pi); child.removeInterParentInterface(ci); child.interParents.remove(this); if(!this.intraChildren.containsKey(child)) { this.neighbors.remove(child); child.neighbors.remove(this); } } public void removeIntraChild(DBNNode child) throws BNException { if(!this.intraChildren.containsKey(child)) throw new BNException("Attempted to remove intra-child " + child.name + " from node " + this.name + " where it is not a child."); DynamicMessageIndex pi = this.intraChildren.remove(child); DynamicMessageIndex ci = child.intraParents.remove(this); this.removeIntraChildInterface(pi); child.removeIntraParentInterface(ci); child.intraParents.remove(this); if(!this.interChildren.containsKey(child)) { this.neighbors.remove(child); child.neighbors.remove(this); } } public Iterable<DBNNode> getNeighborsI() { return this.neighbors; } public final void removeAllChildren() throws BNException { Vector<DBNNode> childCopy = new Vector<DBNNode>(this.interChildren.keySet()); for(DBNNode child : childCopy) this.removeInterChild(child); childCopy = new Vector<DBNNode>(this.intraChildren.keySet()); for(DBNNode child : childCopy) this.removeIntraChild(child); } public final void removeAllParents() throws BNException { Vector<DBNNode> parentCopy = new Vector<DBNNode>(this.interParents.keySet()); for(DBNNode parent : parentCopy) parent.removeInterChild(this); parentCopy = new Vector<DBNNode>(this.intraParents.keySet()); for(DBNNode parent : parentCopy) parent.removeIntraChild(this); } /* * Children/parent edge existence checkers, both internal and external. */ public boolean hasInterChild(IDBNNode child) { return this.interChildren.containsKey(child); } public boolean hasIntraChild(IDBNNode child) { return this.intraChildren.containsKey(child); } public boolean hasInterParent(IDBNNode parent) { return this.interParents.containsKey(parent); } public boolean hasIntraParent(IDBNNode parent) { return this.intraParents.containsKey(parent); } boolean hasInterChild(DBNNode child) { return this.interChildren.containsKey(child); } boolean hasIntraChild(DBNNode child) { return this.intraChildren.containsKey(child); } public abstract void validate() throws BNException; /* * Internal and external iterators over children and parents. */ public Iterable<DBNNode> getInterChildren() { return this.interChildren.keySet(); } public Iterable<DBNNode> getInterParents() { return this.interParents.keySet(); } public Iterable<? extends IBayesNode> getChildren() { return this.intraChildren.keySet(); } public Iterable<? extends IBayesNode> getParents() { return this.intraParents.keySet(); } public Iterable<DBNNode> getChildrenI() { return this.intraChildren.keySet(); } public Iterable<DBNNode> getParentsI() { return this.intraParents.keySet(); } public Iterable<DBNNode> getIntraChildren() { return this.intraChildren.keySet(); } public Iterable<DBNNode> getIntraParents() { return this.intraParents.keySet(); } public Iterable<DBNNode> getInterParentsI() { return this.interParents.keySet(); } public Iterable<DBNNode> getIntraParentsI() { return this.intraParents.keySet(); } public Iterable<DBNNode> getInterChildrenI() { return this.interChildren.keySet(); } public Iterable<DBNNode> getIntraChildrenI() { return this.intraChildren.keySet(); } /* * Message updating methods. */ public double updateMessages() throws BNException { return updateMessages(0,this.bayesNet.getT()-1); } public final double updateMessages(int tmin, int tmax) throws BNException { double maxErr = 0; maxErr = Math.max(maxErr, this.updateMessages(tmin, tmax, this.lastPassBackward)); this.lastPassBackward = !this.lastPassBackward; return maxErr; } public final double updateMessages(int tmin, int tmax, boolean forward) throws BNException { double maxErr = 0; if(forward) for(int t = tmin; t <= tmax; t++) maxErr = Math.max(this.updateMessages(t),maxErr); else for(int t = tmax; t >= tmin; t--) maxErr = Math.max(this.updateMessages(t), maxErr); return maxErr; } protected abstract double updateMessages(int t) throws BNException; public abstract void resetMessages(); public abstract void printDistributionInfo(PrintStream ps); public void lockParameters() { this.parametersLocked = true; } public void unlockParameters() { this.parametersLocked = false; } public boolean isLocked() { return this.parametersLocked; } public final double optimizeParameters() throws BNException { if(this.parametersLocked) return 0; else return this.optimizeParametersI(); } public final double optimizeParameters(SufficientStatistic stat) throws BNException { if(this.parametersLocked) return 0; else return this.optimizeParametersI(stat); } protected abstract double optimizeParametersI() throws BNException; protected abstract double optimizeParametersI(SufficientStatistic stat) throws BNException; protected boolean parametersLocked = false; private boolean lastPassBackward = true; protected DynamicBayesianNetwork bayesNet; protected String name; protected HashSet<DBNNode> neighbors = new HashSet<DBNNode>(); protected HashMap<DBNNode,DynamicMessageIndex> interChildren = new HashMap<DBNNode, DynamicMessageIndex>(); protected HashMap<DBNNode,DynamicMessageIndex> intraChildren = new HashMap<DBNNode, DynamicMessageIndex>(); protected HashMap<DBNNode,DynamicMessageIndex> interParents = new HashMap<DBNNode, DynamicMessageIndex>(); protected HashMap<DBNNode,DynamicMessageIndex> intraParents = new HashMap<DBNNode, DynamicMessageIndex>(); }
/* * 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 de.kaojo.ejb.dto.interfaces; /** * * @author jwinter */ public interface ChatRoomChatRequest { public Long getChatRoomId(); public Long getUserId(); }
package com.Dao; import com.entity.User; import com.util.JDBCUtil; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class UserDao { private static JDBCUtil jdbcUtil = new JDBCUtil(); /** * 注册用户 */ public static int add(User user) throws SQLException { int result = 0; String sql = "insert into users values(null,?,?,?,?)"; PreparedStatement pstm = jdbcUtil.createStatement(sql); pstm.setString(1, user.getUserName()); pstm.setString(2, user.getPassword()); pstm.setString(3, user.getSex()); pstm.setString(4, user.getEmail()); result = pstm.executeUpdate(); jdbcUtil.close(); return result; } /** * 查询用户 */ public static List find() { String sql = "select * from users"; List<User> list = new ArrayList<>(); ResultSet set = null; PreparedStatement pstm = jdbcUtil.createStatement(sql); try { set = pstm.executeQuery(); while (set.next()) { Integer userId = set.getInt(1); String userName = set.getString(2); String password = set.getString(3); String sex = set.getString(4); String email = set.getString(5); User user = new User(userId, userName, password, sex, email); list.add(user); } } catch (Exception e) { e.printStackTrace(); } finally { jdbcUtil.close(set); } return list; } /** * 删除用户 */ public static int del(String id) { String sql = "delete from users where userId = ?"; int result = 0; PreparedStatement pstm = jdbcUtil.createStatement(sql); try { pstm.setInt(1, Integer.parseInt(id)); result = pstm.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { jdbcUtil.close(); } return result; } /** * 登陆查询 */ public static int login(String userName, String password) { int result = 0; String sql = "select * from users where userName = ? and password = ?"; ResultSet set = null; PreparedStatement pstm = jdbcUtil.createStatement(sql); try { pstm.setString(1, userName); pstm.setString(2, password); set = pstm.executeQuery(); while (set.next()) { result = set.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { jdbcUtil.close(set); } return result; } }
package xyz.noark.core.network; import java.lang.annotation.Annotation; /** * 处理器方法. * * @author 小流氓[176543888@qq.com] * @since 3.4 */ public interface HandlerMethod { /** * 获取这个处理器方法上的指定注解 * * @param annotationClass 注解类 * @param <T> 注解类型 * @return 如果有此类型的注解则返回,如果没有就返回null */ <T extends Annotation> T getAnnotation(Class<T> annotationClass); }
package com.CDH.myapplication.ui.fragments; import androidx.lifecycle.ViewModelProviders; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.CDH.myapplication.R; import com.CDH.myapplication.ui.Datos.DbHelper; import com.CDH.myapplication.ui.vistas.Plantillafragment1ViewModel; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class plantillafragment1 extends Fragment { private Plantillafragment1ViewModel mViewModel; DbHelper FavDB; EditText codigoTXT,fechaTXT,acargoTXT,asignadaTXT,detalleTXT,proyectoTXT; public static plantillafragment1 newInstance() { return new plantillafragment1(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View vista= inflater.inflate(R.layout.plantillafragment1_fragment, container, false); codigoTXT = (EditText) vista.findViewById(R.id.editTextCodigo); fechaTXT = (EditText) vista.findViewById(R.id.editTextDate); acargoTXT = (EditText) vista.findViewById(R.id.editTextPersona); proyectoTXT = (EditText) vista.findViewById(R.id.editTextProyecto); asignadaTXT = (EditText) vista.findViewById(R.id.editTextSuma); detalleTXT = (EditText) vista.findViewById(R.id.editTextDetalle); asignadaTXT.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { if(asignadaTXT.getText().toString().equals("")){ asignadaTXT.setText("0"); } } } }); FavDB = new DbHelper(vista.getContext()); Bundle bundle = getArguments(); if(bundle!=null){ agregabdd(getArguments().getString("codigo")); } return vista; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewModel = ViewModelProviders.of(this).get(Plantillafragment1ViewModel.class); // TODO: Use the ViewModel } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Button btn1=view.findViewById(R.id.btn1); btn1.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { /*ejecutarServicio("http://192.168.56.1/wappservice/insertar_ficha.php"); // codigoTXT = (EditText) getView().findViewById(R.id.editTextCodigo); String codigo = codigoTXT.getText().toString(); String fecha = fechaTXT.getText().toString(); String acargo = acargoTXT.getText().toString(); String proyecto = proyectoTXT.getText().toString(); String asignada = asignadaTXT.getText().toString(); String detalle = detalleTXT.getText().toString();*/ String codigo = codigoTXT.getText().toString(); Bundle bundle = new Bundle(); // Toast.makeText(getActivity(), codigoTXT.getText().toString() , Toast.LENGTH_SHORT).show(); bundle.putString("codigo", codigo); bundle.putString("numero", "1");bundle.putString("mod", "2"); agregabdd(codigo); //ejecutarServicio("http://192.168.56.1/wappservice/insertar_ficha.php"); Navigation.findNavController(v).navigate(R.id.planillaFragment2, bundle); } }); } private void agregabdd(String codigo){ String fecha = fechaTXT.getText().toString(); String acargo = acargoTXT.getText().toString(); String proyecto = proyectoTXT.getText().toString(); String asignada = asignadaTXT.getText().toString(); String detalle = detalleTXT.getText().toString(); if(FavDB.if_exist(codigo)){ SQLiteDatabase db = FavDB.getReadableDatabase(); Cursor cursor = FavDB.select_all_favorite_list(); try { while (cursor.moveToNext()) { fechaTXT.setText(cursor.getString(cursor.getColumnIndex(FavDB.FECHA))); acargoTXT.setText(cursor.getString(cursor.getColumnIndex(FavDB.ACARGO))); proyectoTXT.setText(cursor.getString(cursor.getColumnIndex(FavDB.PROYECTO))); asignadaTXT.setText(cursor.getString(cursor.getColumnIndex(FavDB.ASIGNADA))); detalleTXT.setText(cursor.getString(cursor.getColumnIndex(FavDB.DETALLE))); codigoTXT.setText(cursor.getString(cursor.getColumnIndex(FavDB.CODIGO))); } FavDB.edit_parts_one(codigo, acargo, proyecto, asignada, detalle, fecha); } finally { if (cursor != null && cursor.isClosed()) cursor.close(); db.close(); } }else{ FavDB.insertIntoTheDatabase(codigo, acargo, proyecto, asignada, detalle, fecha, "true"); } } private void ejecutarServicio(String URL){ StringRequest stringRequest=new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Toast.makeText(getActivity(), "PASO "+ codigoTXT.getText().toString(), Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getActivity(), "No Paso", Toast.LENGTH_SHORT).show(); } }){ protected Map<String, String>getParams() throws AuthFailureError{ Map<String,String> parametros=new HashMap<String, String>(); parametros.put("codigo",codigoTXT.getText().toString()); parametros.put("fecha",fechaTXT.getText().toString()); parametros.put("acargo",acargoTXT.getText().toString()); parametros.put("proyecto",proyectoTXT.getText().toString()); parametros.put("asignada",asignadaTXT.getText().toString()); parametros.put("detalle",detalleTXT.getText().toString()); return parametros; } }; RequestQueue requestQueue= Volley.newRequestQueue(this.getContext()); requestQueue.add(stringRequest); } private void buscaFactura(String URL){ JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(URL, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { JSONObject jsonObject = null; for (int i = 0; i < response.length(); i++) { try { jsonObject = response.getJSONObject(i); //codigoTXT.setText(jsonObject.getString("")); fechaTXT.setText(jsonObject.getString("")); acargoTXT.setText(jsonObject.getString("")); proyectoTXT.setText(jsonObject.getString("")); asignadaTXT.setText(jsonObject.getString("")); detalleTXT.setText(jsonObject.getString("")); } catch (JSONException e) { Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getActivity(), "Error de conexion ", Toast.LENGTH_SHORT).show(); } } ); RequestQueue requestQueue= Volley.newRequestQueue(this.getContext()); requestQueue.add(jsonArrayRequest); } }
package parties; /** * Created by Amaury on 10/04/2017. */ public class CaseStandard extends Case { public CaseStandard(int x, int y, String pseudoJoueur) { super(x, y, pseudoJoueur); this.sortie = false; } public CaseStandard(int x, int y, String pseudoJoueur, Fantome fantome) { super(x, y, pseudoJoueur, fantome); this.sortie = false; } }
package com.zl.service.impl; import com.zl.mapper.AccessoryMapper; import com.zl.pojo.AccessoryDO; import com.zl.pojo.AccessoryDOExample; import com.zl.service.AccessoryService; import com.zl.util.AjaxPutPage; import com.zl.util.AjaxResultPage; import com.zl.util.MessageException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @program: FruitSales * @description: * @author: ZhuLlin * @create: 2019-01-31 14:12 **/ @Service public class AccessoryServiceImpl implements AccessoryService { @Autowired private AccessoryMapper accessoryMapper; @Override public AjaxResultPage<AccessoryDO> listAccessoryByGardenId(AjaxPutPage<AccessoryDO> ajaxPutPage) { AjaxResultPage<AccessoryDO> result = new AjaxResultPage<AccessoryDO>(); List<AccessoryDO> list = accessoryMapper.listAccessoryByGardenId(ajaxPutPage); result.setData(list); result.setCount(accessoryMapper.listAccessoryByGardenIdCount(ajaxPutPage)); return result; } @Override public void updateAccessory(AccessoryDO accessoryDO) throws MessageException{ accessoryMapper.updateByPrimaryKeySelective(accessoryDO); } @Override public void deleteAccessory(String id) throws MessageException{ accessoryMapper.deleteByPrimaryKey(id); } @Override public void insertAccessory(AccessoryDO accessoryDO) throws MessageException{ accessoryMapper.insertSelective(accessoryDO); } }
/* * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.gs.tablasco.investigation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.List; /** * Compares results from two environments and drills down on breaks in multiple * steps until it finds the underlying data responsible for the breaks. */ public class Sherlock { private static final Logger LOGGER = LoggerFactory.getLogger(Sherlock.class); public void handle(Investigation investigation, File outputFile) { Watson watson = new Watson(outputFile); InvestigationLevel currentLevel = investigation.getFirstLevel(); List<Object> drilldownKeys = watson.assist("Initial Results", currentLevel, investigation.getRowKeyLimit()); if (drilldownKeys == null || drilldownKeys.isEmpty()) { LOGGER.info("No breaks found :)"); return; } LOGGER.info("Got " + drilldownKeys.size() + " broken drilldown keys - " + outputFile); int level = 1; while (!drilldownKeys.isEmpty() && (currentLevel = investigation.getNextLevel(drilldownKeys)) != null) { drilldownKeys = watson.assist("Investigation Level " + level + " (Top " + investigation.getRowKeyLimit() + ')', currentLevel, investigation.getRowKeyLimit()); LOGGER.info("Got " + drilldownKeys.size() + " broken drilldown keys - " + outputFile); level++; } String message = "Some tests failed. Check test results file " + outputFile.getAbsolutePath() + " for more details."; throw new AssertionError(message); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.services; import com.dao.ImplDao; import static com.dao.ImplDao.getEmf; import static com.dao.ImplDao.getEntityManagger; import com.entity.Producto; import com.entity.Proveedor; import com.entity.Tienda; import com.implDao.IProveedor; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Query; /** * * @author DAC-PC */ public class ProveedorServices extends ImplDao<Proveedor, Long> implements IProveedor,Serializable{ @Override public List<Proveedor> listarproveedor(Tienda c) { ArrayList<Proveedor> listar = new ArrayList<>(); String consulta = null; try { consulta = "FROM Proveedor c WHERE c.tienda =?1"; Query query = getEmf().createEntityManager().createQuery(consulta); query.setParameter(1, c); listar =(ArrayList<Proveedor>) query.getResultList(); return listar; } catch (Exception e) { }finally{ getEntityManagger().close(); } return listar; } @Override public Proveedor verproveedor(Long id) { Proveedor c = null; String consulta; try { consulta = "FROM Producto c WHERE c.id = ?1 "; Query query = getEmf().createEntityManager().createQuery(consulta); query.setParameter(1, id); List<Proveedor> lista =query.getResultList(); if(!lista.isEmpty()){ c = lista.get(0); } } catch (Exception e) { throw e; }finally{ getEntityManagger().close(); } return c; } }
package com.dx.visitor2; public class FeedingPet implements AnimalPet{ AnimalPet [] animalPets; public FeedingPet(){ animalPets = new AnimalPet[]{new DogPet(),new CatPet()}; } @Override public void accept(Humen humen) { for(AnimalPet pet:animalPets){ pet.accept(humen); } } }
public class Print_rows { public static void main(String[] args){ int firstarray[][] = {{8,9,10,11},{12,13,14,15}}; int secondarray[][] = {{30,31,32,33},{43},{4,5,6}}; // firstarray[0][1] = 9 //at the end, write this code System.out.println("This is the first array"); display(firstarray); System.out.println("This is the second array"); display(secondarray); } public static void display(int x[][]){ for(int i=0; i < x.length; i++){//for rows System.out.print("x("+i); System.out.print(") = "); for(int j=0; j < x[i].length ; j++){//for columns System.out.print(x[i][j]+"\t"); } System.out.println(); } } }
package com.cmi.bache24.data.remote; import android.content.Context; import android.os.CountDownTimer; import android.util.Log; import com.cmi.bache24.data.model.AttendedReport; import com.cmi.bache24.data.model.Comment; import com.cmi.bache24.data.model.Picture; import com.cmi.bache24.data.model.PushRecord; import com.cmi.bache24.data.model.Rejection; import com.cmi.bache24.data.model.Report; import com.cmi.bache24.data.model.Status; import com.cmi.bache24.data.model.User; import com.cmi.bache24.data.remote.interfaces.CommentsCallback; import com.cmi.bache24.data.remote.interfaces.IGetVersionCallback; import com.cmi.bache24.data.remote.interfaces.LoginCallback; import com.cmi.bache24.data.remote.interfaces.NewReportCallback; import com.cmi.bache24.data.remote.interfaces.RecoverPasswordCallback; import com.cmi.bache24.data.remote.interfaces.RegisterUserCallback; import com.cmi.bache24.data.remote.interfaces.RejectionsCallback; import com.cmi.bache24.data.remote.interfaces.ReportsCallback; import com.cmi.bache24.data.remote.interfaces.SingleReportCallback; import com.cmi.bache24.ui.dialog.interfaces.IStatusResponse; import com.cmi.bache24.util.Constants; import com.cmi.bache24.util.FileManager; import com.cmi.bache24.util.ReportComparator; import com.cmi.bache24.util.TroopReportComparator; import com.google.gson.Gson; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import cz.msebera.android.httpclient.Header; /** * Created by omar on 12/2/15. */ public class ServicesManager { public static final int TIMEOUT = 30 * 1000; // 30 Segundos public static void registerUser(final User user, final RegisterUserCallback callback) { AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); final String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_REGISTER; RequestParams params = new RequestParams(); params.put("usuario_usuario", user.getEmail()); params.put("usuario_nombre", user.getName()); params.put("usuario_apellido_paterno", user.getFirtsLastName()); params.put("usuario_apellido_materno", user.getSecondLastName()); params.put("usuario_telefono", user.getPhone()); params.put("usuario_correo", user.getEmail()); params.put("usuario_avatar", user.getPicture()); if (user.getRegisterType().equals(Constants.REGISTER_EMAIL)) { params.put("usuario_contrasenia", user.getPassword()); } else if (user.getRegisterType().equals(Constants.REGISTER_FACEBOOK)) { params.put("usuario_fb", user.getFbUsername()); params.put("usuario_fb_token", user.getFbToken()); params.put("usuario_hash", user.getHashToken()); } else if (user.getRegisterType().equals(Constants.REGISTER_TWITTER)) { params.put("usuario_tw", user.getTwUsername()); params.put("usuario_tw_token", user.getTwToken()); params.put("usuario_hash", user.getHashToken()); } client.post(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); printResponse(response.toString()); if (isBannedUser(response)) { if (callback != null) callback.userBanned(); // sendDebugResponse(user.getEmail(), url, "", response.toString(), user.getToken()); return; } if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) callback.onRegisterFail(getMessageForResponseCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } catch (JSONException ex) { if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else if (response.has("auth_token")) { try { user.setToken(response.getString("auth_token").toString()); if (response.has("avatar")) { user.setPicture(response.getString("avatar")); user.setPictureUrl(response.getString("avatar")); } if (callback != null) callback.onRegisterSuccess(user); } catch (JSONException ex) { if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else { callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); /*if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void loginWithUser(final User user, final LoginCallback callback) { AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); final String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_LOGIN; RequestParams params = new RequestParams(); params.put("usuario_usuario", user.getEmail() != null ? user.getEmail() : "" ); params.put("usuario_contrasenia", user.getPassword() != null ? user.getPassword() : ""); params.put("usuario_hash", user.getHashToken() != null ? user.getHashToken().replace("\n", "") : ""); params.put("usuario_fb_token", user.getFbToken() != null ? user.getFbToken() : ""); params.put("usuario_tw_token", user.getTwToken() != null ? user.getTwToken() : ""); client.post(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); printResponse(response.toString()); if (isBannedUser(response)) { if (callback != null) callback.userBanned(); // sendDebugResponse(user.getEmail(), url, "", response.toString(), user.getToken()); return; } if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) callback.loginFail(getMessageForResponseCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } catch (JSONException ex) { if (callback != null) callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else { try { User userInfo = new User(); userInfo.setName(response.getString("nombre")); userInfo.setFirtsLastName(response.getString("apellidoPa")); userInfo.setSecondLastName(response.getString("apellidoMa")); userInfo.setPhone(response.getString("telefono")); userInfo.setEmail(response.getString("correo")); userInfo.setUserType(response.getInt("tipo_usuario")); userInfo.setPicture(response.getString("avatar")); userInfo.setPictureUrl(response.getString("avatar")); userInfo.setIdDelegacion(response.getInt("delegacion")); userInfo.setToken(response.getString("auth_token")); userInfo.setHashToken(user.getHashToken() != null ? user.getHashToken().replace("\n", "") : ""); userInfo.setFbToken(user.getFbToken() != null ? user.getFbToken() : ""); userInfo.setTwToken(user.getTwToken() != null ? user.getTwToken() : ""); if (callback != null) callback.loginSuccess(userInfo); } catch (JSONException ex) { if (callback != null) callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (callback != null) callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (callback != null) callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void recoverPassword(final User user, final RecoverPasswordCallback callback) { AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); final String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_RECOVER_PASSWORD; RequestParams params = new RequestParams(); params.put("usuario_correo", user.getEmail()); client.post(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); printResponse(response.toString()); if (isBannedUser(response)) { if (callback != null) callback.userBanned(); // sendDebugResponse(user.getEmail(), url, "", response.toString(), user.getToken()); return; } if (response.has("OK")) { if (callback != null) callback.onRecoverSuccess(); } else { if (callback != null) callback.onRecoverFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (callback != null) callback.onRecoverFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (callback != null) callback.onRecoverFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onRecoverFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onRecoverFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onRecoverFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onRecoverFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onRecoverFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onRecoverFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onRecoverFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onRecoverFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onRecoverFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void registerNewReport(final User user, final Report report, final NewReportCallback callback) { AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); final String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_REGISTER_REPORT; RequestParams params = new RequestParams(); client.addHeader("token", user.getToken()); params.put("bache_longitud", report.getLongitude()); params.put("bache_latitud", report.getLatitude()); params.put("bache_descripcion", report.getDescription()); params.put("bache_vialidad_numero", report.getNumero()); params.put("bache_colonia", report.getColonia()); params.put("bache_direccion", report.getAddress()); params.put("bache_vialidad", report.getVialidad()); params.put("bache_img1", report.getPicture1()); params.put("bache_img2", report.getPicture2()); params.put("bache_img3", report.getPicture3()); params.put("bache_img4", report.getPicture4()); client.post(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); if (isBannedUser(response)) { if (callback != null) callback.userBanned(); // sendDebugResponse(user.getEmail(), url, "", response.toString(), user.getToken()); return; } if (isTokenDisabled(response)) { if (callback != null) callback.onTokenDisabled(); return; } if (response.has("OK")) { try { report.setTicket(response.getString("ID").toString().trim()); if (response.has("id_cat_delegacion")) { report.setDelegationId(response.getInt("id_cat_delegacion")); } report.setReportVersion(response.has("vialidad") ? response.getInt("vialidad") : Constants.NEW_VERSION); report.setRoadType(response.has("primaria") ? response.getInt("primaria") : Constants.ROAD_TYPE_DEFAULT); if (callback != null) callback.onSuccessRegister(response.getString("OK"), report); } catch (JSONException ex) { if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else if (response.has("ERROR")) { try { if (response.getString("ERROR").equals(Constants.NEW_REPORT_RESULT_OUT_OF_RANGE) || response.getString("ERROR").equals(Constants.NEW_REPORT_RESULT_ALREADY_REPORTED)) { report.setTicket(response.getString("ERROR").toString().trim()); if (callback != null) callback.onSuccessRegister(response.getString("ERROR"), report); } else { if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } catch (JSONException ex) { if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else { if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } private static boolean timerFinished; public static void getReports(final User user, final ReportsCallback callback) { final AsyncHttpClient client = new AsyncHttpClient(); // client.setTimeout(TIMEOUT); client.setTimeout(50000); final String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_GET_REPORTS; // final String url = "http://www.google.com:81/"; RequestParams params = new RequestParams(); client.addHeader("token", user.getToken()); timerFinished = false; final CountDownTimer timer = new CountDownTimer(30000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { client.cancelAllRequests(true); if (timerFinished) { // Log.i("BACHE_TIMEOUT", "timer already finished"); return; } // Log.i("BACHE_TIMEOUT", "timer finished = " + new Date().toString()); if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } }; // Log.i("BACHE_TIMEOUT", "timer started = " + new Date().toString()); timer.start(); client.post(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Success = " + new Date().toString()); if (isBannedUser(response)) { if (callback != null) callback.userBanned(); // sendDebugResponse(user.getEmail(), url, "", response.toString(), user.getToken()); return; } if (isTokenDisabled(response)) { if (callback != null) callback.onTokenDisabled(); return; } if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) callback.onReportsFail(getMessageForResponseCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } catch (JSONException ex) { if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else { try { List<Report> reports = new ArrayList<>(); if (response.has("OK")) { if (callback != null) callback.onReportsCallback(reports); } else { Iterator<String> iterator = response.keys(); while (iterator.hasNext()) { String key = iterator.next(); Report report = new Report(); JSONObject jsonObject = (JSONObject) response.get(key); report.setReportId(jsonObject.getString("id_bache")); report.setDate(jsonObject.getString("bache_fecha_alta")); report.setTicket(jsonObject.getString("bache_ticket")); report.setEtapaId(jsonObject.getInt("id_cat_etapa")); report.setLongitude(jsonObject.getString("bache_longitud")); report.setLatitude(jsonObject.getString("bache_latitud")); report.setDescription(jsonObject.getString("bache_descripcion")); report.setColonia(jsonObject.getString("bache_colonia")); report.setAddress(jsonObject.getString("bache_direccion")); report.setAvenidaId(jsonObject.getInt("id_cat_avenida")); if (jsonObject.has("bache_ticket_sales")) { report.setSalesForceTicket(jsonObject.getString("bache_ticket_sales")); } if (jsonObject.has("id_cat_delegacion")) { report.setDelegationId(jsonObject.getInt("id_cat_delegacion")); } report.setReportVersion(jsonObject.has("vialidad") ? jsonObject.getInt("vialidad") : Constants.NEW_VERSION); report.setCause(jsonObject.has("razon_no_aplica") ? jsonObject.getString("razon_no_aplica") : ""); report.setPictures(new ArrayList<Picture>()); if (jsonObject.has("imgs")) { JSONArray images = jsonObject.getJSONArray("imgs"); if (images.length() > 0) { for (int i = 0; i < images.length(); i++) { Picture reportPicture = new Picture(); reportPicture.setEtapaId(images.getJSONObject(i).getInt("id_cat_etapa")); reportPicture.setFoto(images.getJSONObject(i).getString("foto")); report.getPictures().add(reportPicture); } } } report.setPushHistory(new ArrayList<PushRecord>()); try { if (jsonObject.has("push_historial")) { JSONArray pushHistoryArray = jsonObject.getJSONArray("push_historial"); for (int i = 0; i < pushHistoryArray.length(); i++) { PushRecord record = new PushRecord(); record.setMessage(pushHistoryArray.getJSONObject(i).getString("push_mensaje")); record.setDate(pushHistoryArray.getJSONObject(i).getString("push_fecha_envio")); report.getPushHistory().add(record); } } } catch (Exception ex) { } reports.add(report); } Collections.sort(reports, new ReportComparator()); if (callback != null) callback.onReportsCallback(reports); } } catch (JSONException ex) { if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); timer.cancel(); timerFinished = true; if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); timer.cancel(); timerFinished = true; if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); if (isTimeOutException(throwable)) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure2 = " + new Date().toString()); if (isTimeOutException(throwable)) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure3 = " + new Date().toString()); if (isTimeOutException(throwable)) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void updateUser(final User user, final RegisterUserCallback callback) { AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); final String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_UPDATE_USER; RequestParams params = new RequestParams(); params.put("usuario_usuario", user.getEmail()); params.put("usuario_contrasenia", user.getOldPassword()); params.put("usuario_contrasenia_cambio", user.getPassword()); params.put("usuario_nombre", user.getName()); params.put("usuario_apellido_paterno", user.getFirtsLastName()); params.put("usuario_apellido_materno", user.getSecondLastName()); params.put("usuario_telefono", user.getPhone()); params.put("usuario_correo", user.getEmail()); params.put("usuario_fb", user.getFbUsername()); params.put("usuario_fb_token", user.getFbToken()); params.put("usuario_tw", user.getTwUsername()); params.put("usuario_tw_token", user.getTwToken()); params.put("usuario_hash", user.getHashToken()); params.put("usuario_avatar", user.getPicture()); client.addHeader("token", user.getToken()); client.post(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); if (isBannedUser(response)) { if (callback != null) callback.userBanned(); // sendDebugResponse(user.getEmail(), url, "", response.toString(), user.getToken()); return; } if (isTokenDisabled(response)) { if (callback != null) callback.onTokenDisabled(); return; } if (response.has("OK")) { try { if (response.has("url_foto")) user.setPictureUrl(response.getString("url_foto")); } catch (JSONException ex) { } if (callback != null) callback.onRegisterSuccess(user); } else { if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) callback.onRegisterFail(getMessageForResponseCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } catch (JSONException ex) { if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); if (callback != null) { if (callback != null) callback.onRegisterSuccess(user); } } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onRegisterFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onRegisterFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void getReportsForTroops(User user, final ReportsCallback callback) { final AsyncHttpClient client = new AsyncHttpClient(); // client.setTimeout(TIMEOUT); client.setTimeout(60 * 1000); client.setConnectTimeout(60 * 1000); client.setResponseTimeout(60 * 1000); String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_GET_TROOPS_REPORTS; RequestParams params = new RequestParams(); client.addHeader("token", user.getToken()); timerFinished = false; final CountDownTimer timer = new CountDownTimer(60000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { client.cancelAllRequests(true); if (timerFinished) { // Log.i("BACHE_TIMEOUT", "timer already finished"); return; } // Log.i("BACHE_TIMEOUT", "timer finished = " + new Date().toString()); if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } }; // Log.i("BACHE_TIMEOUT", "timer started = " + new Date().toString()); timer.start(); client.post(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Success = " + new Date().toString()); if (isTokenDisabled(response)) { if (callback != null) callback.onTokenDisabled(); return; } if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) { if (Integer.valueOf(response.getString(Constants.RESPONSE_ERROR_KEY)) == Constants.ERROR_NO_REPORTS_FOUND) { callback.onReportsFail(Constants.ERROR_NO_REPORTS_FOUND_DESCRIPTION_2); } else callback.onReportsFail(getMessageForResponseCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } } catch (JSONException ex) { if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else { try { List<Report> reports = new ArrayList<>(); if (response.has("OK")) { if (callback != null) callback.onReportsCallback(reports); } else { Iterator<String> iterator = response.keys(); SimpleDateFormat mDateFormat = new SimpleDateFormat(Constants.DATE_FORMAT); while (iterator.hasNext()) { String key = iterator.next(); Report report = new Report(); JSONObject jsonObject = (JSONObject) response.get(key); report.setReportId(jsonObject.getString("id_bache")); report.setDate(jsonObject.getString("bache_fecha_alta")); report.setTicket(jsonObject.getString("bache_ticket")); report.setEtapaId(jsonObject.getInt("id_cat_etapa")); report.setLongitude(jsonObject.getString("bache_longitud")); report.setLatitude(jsonObject.getString("bache_latitud")); report.setDescription(jsonObject.getString("bache_descripcion")); report.setColonia(jsonObject.getString("bache_colonia")); report.setAddress(jsonObject.getString("bache_direccion")); report.setOrigin(getOrigin(jsonObject.has("bache_lugar_alta") ? jsonObject.getInt("bache_lugar_alta") : Constants.REPORT_ORIGIN_APP)); if (jsonObject.has("bache_urgente")) { report.setUrgent(jsonObject.getBoolean("bache_urgente")); } report.setVialidad(jsonObject.has("bache_vialidad") ? jsonObject.getString("bache_vialidad") : ""); if (jsonObject.has("bache_secundaria")) { report.setHasPrimary(true); String primaryValue = jsonObject.getString("bache_secundaria"); if (primaryValue == null) { report.setPrimary(false); } else { report.setPrimary((primaryValue.equals(Constants.PRIMARY_YES) || primaryValue == Constants.PRIMARY_YES)); } } Date date1 = null; try { date1 = mDateFormat.parse(report.getDate()); } catch (ParseException ex) { date1 = new Date(); } if (report.isUrgent()) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); calendar.add(Calendar.HOUR_OF_DAY, -19); date1 = calendar.getTime(); } report.setCreationDate(date1); JSONObject jsonFotos = jsonObject.getJSONObject("fotos"); JSONArray images = jsonFotos.getJSONArray("imgs"); report.setPictures(new ArrayList<Picture>()); if (images.length() > 0) { for (int i = 0; i < images.length(); i++) { Picture reportPicture = new Picture(); reportPicture.setEtapaId(images.getJSONObject(i).getInt("id_cat_etapa")); reportPicture.setFoto(images.getJSONObject(i).getString("foto")); report.getPictures().add(reportPicture); } } // if (report.getEtapaId() != Constants.TROOP_REPORT_STATUS_MARK_AS_REPAIRED && // report.getEtapaId() != Constants.TROOP_REPORT_STATUS_DOES_NOT_APPLY) if (report.getEtapaId() == Constants.REPORT_STATUS_NEW || report.getEtapaId() == Constants.REPORT_STATUS_7 || report.getEtapaId() == Constants.REPORT_STATUS_ASIGNED) { reports.add(report); } } } Collections.sort(reports, new TroopReportComparator()); if (callback != null) callback.onReportsCallback(reports); } catch (JSONException ex) { if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (timerFinished) { client.cancelAllRequests(true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (timerFinished) { client.cancelAllRequests(true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelAllRequests(true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); if (timerFinished) { client.cancelAllRequests(true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelAllRequests(true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onReportsFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onReportsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void updateReportStatus(final Context context, final User user, String reportTicket, int status, final NewReportCallback callback) { final AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_UPDATE_REPORT_BY_TROOP; RequestParams params = new RequestParams(); client.addHeader("token", user.getToken()); params.put("bache_ticket", reportTicket); params.put("id_cat_etapa", status); // Log.i("BACHE_SERVICES", "updateReportStatus (set status 2) executed for ticket = " + reportTicket); final Report currentReport = new Report(); currentReport.setTicket(reportTicket); currentReport.setEtapaId(status); /*B24Debug debugObject = currentReport.debugObject(); debugObject.setReportSquadEmail(user.getEmail()); debugObject.setReportSquadToken(user.getToken()); ServicesManager.sendDebugData(debugObject);*/ // Utils.Log("ServicesManager", "updateReportStatus", "Service call for " + reportTicket); timerFinished = false; final CountDownTimer timer = new CountDownTimer(30000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { client.cancelRequests(context, true); if (timerFinished) { // Log.i("BACHE_TIMEOUT", "timer already finished"); return; } timerFinished = true; // Log.i("BACHE_TIMEOUT", "timer finished = " + new Date().toString()); if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } }; // Log.i("BACHE_TIMEOUT", "timer started = " + new Date().toString()); timer.start(); client.post(context, url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "success = " + new Date().toString()); // Utils.Log("ServicesManager", "onSuccess", "Service response " + response.toString()); /*String message = ServicesManager.getJSONStringWithParameters(currentReport.getTicket(), user.getEmail(), response != null ? response.toString() : "Response Null"); ServicesManager.sendDebugThrowableDataWithToken(currentReport, null, message, statusCode + "", user.getToken());*/ if (response.has("OK")) { try { if (response.getString("OK").equals("805") || response.getString("OK").equals("806") || response.getString("OK").equals("807")) { if (callback != null){ callback.onSuccessRegisterReport(null); } } else callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } catch (JSONException ex) { if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else { if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); // Utils.Log("ServicesManager", "onFailure", "Service response failure " + errorResponse.toString()); /*String message = ServicesManager.getJSONStringWithParameters(currentReport.getTicket(), user.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableData(currentReport, throwable, message, statusCode + "");*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); // Utils.Log("ServicesManager", "onFailure", "Service response failure " + responseString); /*String message = ServicesManager.getJSONStringWithParameters(currentReport.getTicket(), user.getEmail(), responseString != null ? responseString : "Response Null"); ServicesManager.sendDebugThrowableData(currentReport, throwable, message, statusCode + "");*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); // Utils.Log("ServicesManager", "onFailure", "Service response failure " + errorResponse.toString()); /*String message = ServicesManager.getJSONStringWithParameters(currentReport.getTicket(), user.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableData(currentReport, throwable, message, statusCode + "");*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); } }); } public static void getSingleReport(final User user, final Report report, final SingleReportCallback callback) { if (user == null) { if (callback != null) callback.reportFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); return; } AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); final String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_GET_REPORT_DETAIL; RequestParams params = new RequestParams(); client.addHeader("token", user.getToken()); params.add("bache_ticket", report.getTicket()); client.post(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); if (isBannedUser(response)) { if (callback != null) callback.userBanned(); // sendDebugResponse(user.getEmail(), url, "", response.toString(), user.getToken()); return; } if (isTokenDisabled(response)) { if (callback != null) callback.onTokenDisabled(); return; } if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) callback.reportFail(getMessageForResponseCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } catch (JSONException ex) { if (callback != null) callback.reportFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else { try { if (response.has(report.getTicket())) { Report reportResult = new Report(); JSONObject jsonObject = (JSONObject) response.get(report.getTicket()); reportResult.setReportId(jsonObject.getString("id_bache")); reportResult.setDate(jsonObject.getString("bache_fecha_alta")); reportResult.setTicket(jsonObject.getString("bache_ticket")); reportResult.setEtapaId(jsonObject.getInt("id_cat_etapa")); reportResult.setDelegationId(jsonObject.getInt("id_cat_delegacion")); reportResult.setLongitude(jsonObject.getString("bache_longitud")); reportResult.setLatitude(jsonObject.getString("bache_latitud")); reportResult.setDescription(jsonObject.getString("bache_descripcion")); reportResult.setColonia(jsonObject.getString("bache_colonia")); reportResult.setAddress(jsonObject.getString("bache_direccion")); if (jsonObject.has("id_cat_avenida")) { reportResult.setAvenidaId(jsonObject.getInt("id_cat_avenida")); } if (jsonObject.has("bache_ticket_sales")) { reportResult.setSalesForceTicket(jsonObject.getString("bache_ticket_sales")); } reportResult.setReportVersion(jsonObject.has("vialidad") ? jsonObject.getInt("vialidad") : Constants.NEW_VERSION); report.setCause(jsonObject.has("razon_no_aplica") ? jsonObject.getString("razon_no_aplica") : ""); JSONObject jsonFotos = jsonObject.getJSONObject("fotos"); JSONArray images = jsonFotos.getJSONArray("imgs"); reportResult.setPictures(new ArrayList<Picture>()); if (images.length() > 0) { for (int i = 0; i < images.length(); i++) { Picture reportPicture = new Picture(); reportPicture.setEtapaId(images.getJSONObject(i).getInt("id_cat_etapa")); reportPicture.setFoto(images.getJSONObject(i).getString("foto")); reportResult.getPictures().add(reportPicture); } } reportResult.setPushHistory(new ArrayList<PushRecord>()); try { if (jsonObject.has("push_historial")) { JSONArray pushHistoryArray = jsonObject.getJSONArray("push_historial"); for (int i = 0; i < pushHistoryArray.length(); i++) { PushRecord record = new PushRecord(); record.setMessage(pushHistoryArray.getJSONObject(i).getString("push_mensaje")); record.setDate(pushHistoryArray.getJSONObject(i).getString("push_fecha_envio")); reportResult.getPushHistory().add(record); } } } catch (Exception ex) { } if (callback != null) callback.reportSuccess(reportResult); } } catch (JSONException ex) { if (callback != null) callback.reportFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (callback != null) callback.reportFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (callback != null) callback.reportFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.reportFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.reportFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.reportFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.reportFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.reportFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.reportFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.reportFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.reportFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.reportFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void sendComments(final Comment comment, final CommentsCallback callback) { AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); final String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_SEND_COMMENTS; RequestParams params = new RequestParams(); client.addHeader("token", comment.getUser().getToken()); params.add("comentario", comment.getMessage()); params.add("bache_ticket", comment.getReport().getTicket()); client.post(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); if (isBannedUser(response)) { if (callback != null) callback.userBanned(); // sendDebugResponse(comment.getUser().getEmail(), url, "", response.toString(), comment.getUser().getToken()); return; } if (isTokenDisabled(response)) { if (callback != null) callback.onTokenDisabled(); return; } if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) callback.onSendCommentsFail(getMessageForResponseCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } catch (JSONException ex) { if (callback != null) callback.onSendCommentsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else { if (callback != null) callback.onSendCommentsSuccess(); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (callback != null) callback.onSendCommentsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (callback != null) callback.onSendCommentsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onSendCommentsFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onSendCommentsFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onSendCommentsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onSendCommentsFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onSendCommentsFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onSendCommentsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onSendCommentsFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onSendCommentsFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onSendCommentsFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void getRejectionList(User user, final RejectionsCallback callback) { AsyncHttpClient client = new AsyncHttpClient(); String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_GET_REJECTION_LIST; RequestParams params = new RequestParams(); client.addHeader("token", user.getToken()); client.post(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) callback.onFail(getMessageForResponseCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } catch (JSONException ex) { if (callback != null) callback.onFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else { } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); try { List<Rejection> rejectionList = new ArrayList<>(); if (response.length() > 0) { for (int i = 0; i < response.length(); i++) { Rejection rejection = new Rejection(); rejection.setId(response.getJSONObject(i).getInt("id_cat_motivos")); rejection.setDescription(response.getJSONObject(i).getString("cat_motivo_rechazo_descripcion")); rejectionList.add(rejection); } } if (callback != null) callback.onRejectionCallback(rejectionList); } catch (Exception ex) { if (callback != null) { callback.onFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (callback != null) callback.onFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFail(Constants.TIMEOUT_DESCRIPTION); return; } if (callback != null) callback.onFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } /// ESTE METODO ES EL ORIGINAL Y EL QUE FUNCIONA BIEN public static void sendAttendedReport(final Context context, final User currentUser, final AttendedReport attendedReport, final NewReportCallback callback) { final AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); // client.setMaxRetriesAndTimeout(1, TIMEOUT); String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_UPDATE_REPORT_BY_TROOP; RequestParams params = new RequestParams(); String bachesString = attendedReport.arregloToJson(); client.addHeader("token", attendedReport.getToken()); params.put("bache_ticket", attendedReport.getTicket()); params.put("numero_baches", attendedReport.getNoBaches()); params.put("id_cat_etapa", attendedReport.getEtapa()); params.put("arreglo_baches", bachesString); params.put("bache_img1", attendedReport.getImage1()); params.put("bache_img2", attendedReport.getImage2()); params.put("bache_img3", attendedReport.getImage3()); params.put("bache_comentarios", attendedReport.getDescripcion()); //QUITAR PARA PRODUCCION params.put("tramo", attendedReport.getStretch()); params.put("sentido", attendedReport.getOrientation()); params.put("lugarfisico", attendedReport.getPhysicalPlace()); //QUITAR PARA PRODUCCION /*B24Debug debugObject = attendedReport.debugObject(); debugObject.setReportSquadEmail(currentUser.getEmail()); ServicesManager.sendDebugData(debugObject);*/ // Log.i("BACHE_SERVICES", "sendAttendedReport executed for ticket = " + attendedReport.getTicket()); // Utils.Log("ServicesManager", "sendAttendedReport", "Service call for " + attendedReport.getTicket()); timerFinished = false; final CountDownTimer timer = new CountDownTimer(30000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { client.cancelRequests(context, true); if (timerFinished) { // Log.i("BACHE_TIMEOUT", "timer already finished"); return; } timerFinished = true; // Log.i("BACHE_TIMEOUT", "timer finished = " + new Date().toString()); if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } }; // Log.i("BACHE_TIMEOUT", "timer started = " + new Date().toString()); timer.start(); client.post(context, url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "success = " + new Date().toString()); // Utils.Log("ServicesManager", "sendAttendedReport->onSuccess", "Service response " + response.toString()); FileManager.writeLog(attendedReport.getTicket(), response != null ? response.toString() : "Response Null"); if (isTokenDisabled(response)) { if (callback != null) callback.onTokenDisabled(); return; } if (response.has("OK")) { try { if (response.getString("OK").trim().equals("807")) { if (callback != null) callback.onFailRegisterReport(Constants.REPORTE_ATTENDED); } else if (response.getString("OK").equals("805") || response.getString("OK").equals("806")) { if (callback != null){ callback.onSuccessRegisterReport(null); } } else { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode(response.getString("OK"))); } } } catch (JSONException ex) { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode("006")); } } } else if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } } catch (JSONException ex) { if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("007")); } } else { if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("008")); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; FileManager.writeLog(attendedReport.getTicket(), response != null ? response.toString() : "Response Null"); if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("005")); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; FileManager.writeLog(attendedReport.getTicket(), responseString != null ? responseString : "Response Null"); if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("004")); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); // Utils.Log("ServicesManager", "sendAttendedReport->onFailure", "Service response " + errorResponse != null ? errorResponse.toString() : ""); FileManager.writeLog(attendedReport.getTicket(), errorResponse != null ? errorResponse.toString() : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(attendedReport.getTicket(), currentUser.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableData(attendedReport, throwable, message, statusCode + "");*/ client.cancelRequests(context, true); /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); // Utils.Log("ServicesManager", "sendAttendedReport->onFailure", "Service response " + responseString); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure2 = " + new Date().toString()); FileManager.writeLog(attendedReport.getTicket(), responseString != null ? responseString.toString() : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(attendedReport.getTicket(), currentUser.getEmail(), responseString != null ? responseString : "Response Null"); ServicesManager.sendDebugThrowableData(attendedReport, throwable, message, statusCode + "");*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure3 = " + new Date().toString()); // Utils.Log("ServicesManager", "sendAttendedReport->onFailure", "Service response " + errorResponse.toString()); FileManager.writeLog(attendedReport.getTicket(), errorResponse != null ? errorResponse.toString() : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(attendedReport.getTicket(), currentUser.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableData(attendedReport, throwable, message, statusCode + "");*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void sendWrongReport(final Context context, final User currentUser, final AttendedReport attendedReport, final NewReportCallback callback) { final AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); // client.setMaxRetriesAndTimeout(1, TIMEOUT); String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_UPDATE_REPORT_BY_TROOP; RequestParams params = new RequestParams(); client.addHeader("token", attendedReport.getToken()); params.put("bache_ticket", attendedReport.getTicket()); params.put("numero_baches", attendedReport.getNoBaches()); params.put("id_cat_etapa", attendedReport.getEtapa()); params.put("bache_img1", attendedReport.getImage1()); params.put("bache_img2", attendedReport.getImage2()); params.put("bache_img3", attendedReport.getImage3()); params.put("bache_descripcion", attendedReport.getDescripcion()); params.put("razon_no_aplica", attendedReport.getCausa()); /*B24Debug debugObject = attendedReport.debugObject(); debugObject.setReportSquadEmail(currentUser.getEmail()); ServicesManager.sendDebugData(debugObject);*/ // Log.i("BACHE_SERVICES", "sendWrongReport executed for ticket = " + attendedReport.getTicket()); timerFinished = false; final CountDownTimer timer = new CountDownTimer(30000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { client.cancelRequests(context, true); if (timerFinished) { // Log.i("BACHE_TIMEOUT", "timer already finished"); return; } // Log.i("BACHE_TIMEOUT", "timer finished = " + new Date().toString()); if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } }; // Log.i("BACHE_TIMEOUT", "timer started = " + new Date().toString()); timer.start(); client.post(context, url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "success = " + new Date().toString()); FileManager.writeLog(attendedReport.getTicket(), response != null ? response.toString() : "Response Null"); if (isTokenDisabled(response)) { if (callback != null) callback.onTokenDisabled(); return; } if (response.has("OK")) { try { if (response.getString("OK").trim().equals("807")) { if (callback != null) callback.onFailRegisterReport(Constants.REPORTE_ATTENDED); } else if (response.getString("OK").equals("805") || response.getString("OK").trim().equals("806") || response.getString("OK").trim().equals("921") || response.getString("OK").trim().contains("921") || response.getString("OK").trim().contains("922")) { if (callback != null){ callback.onSuccessRegisterReport(null); } } else { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode(response.getString("OK"))); } } } catch (JSONException ex) { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode("006")); } } } else if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } } catch (JSONException ex) { if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("007")); } } else { if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("008")); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; FileManager.writeLog(attendedReport.getTicket(), response != null ? response.toString() : "Response Null"); if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("005")); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; FileManager.writeLog(attendedReport.getTicket(), responseString != null ? responseString.toString() : "Response Null"); if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("004")); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); FileManager.writeLog(attendedReport.getTicket(), errorResponse != null ? errorResponse.toString() : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(attendedReport.getTicket(), currentUser.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableData(attendedReport, throwable, message, statusCode + "");*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); FileManager.writeLog(attendedReport.getTicket(), responseString != null ? responseString : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(attendedReport.getTicket(), currentUser.getEmail(), responseString != null ? responseString : "Response Null"); ServicesManager.sendDebugThrowableData(attendedReport, throwable, message, statusCode + "");*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); FileManager.writeLog(attendedReport.getTicket(), errorResponse != null ? errorResponse.toString() : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(attendedReport.getTicket(), currentUser.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableData(attendedReport, throwable, message, statusCode + "");*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable != null) { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void getUserInfo(final User currentUser, final LoginCallback callback) { AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); // client.setMaxRetriesAndTimeout(1, TIMEOUT); client.addHeader("token", currentUser.getToken()); client.post(Constants.SERVICES_USER_INFO, null, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); if (isBannedUser(response)) { if (callback != null) callback.userBanned(); // sendDebugResponse(currentUser.getEmail(), Constants.SERVICES_USER_INFO, "", response.toString(), currentUser.getToken()); return; } if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) callback.loginFail(getMessageForResponseCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } catch (JSONException ex) { if (callback != null) callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } else { try { currentUser.setName(response.getString("nombre")); currentUser.setFirtsLastName(response.getString("apellidoPa")); currentUser.setSecondLastName(response.getString("apellidoMa")); currentUser.setPhone(response.getString("telefono")); currentUser.setEmail(response.getString("correo")); currentUser.setUserType(response.getInt("tipo_usuario")); currentUser.setPicture(response.getString("avatar")); currentUser.setPictureUrl(response.getString("avatar")); currentUser.setIdDelegacion(response.getInt("delegacion"));; if (callback != null) callback.loginSuccess(currentUser); } catch (JSONException ex) { if (callback != null) callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.loginFail(Constants.TIMEOUT_DESCRIPTION); return; } callback.loginFail(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void sendSecondaryRoadReport(final Context context, final User currentUser, //final Report currentReport, final AttendedReport currentReport, final NewReportCallback callback) { final AsyncHttpClient client = new AsyncHttpClient(); // client.setTimeout(TIMEOUT); // client.setMaxRetriesAndTimeout(1, TIMEOUT); String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_SECONDARY_ROAD; RequestParams params = new RequestParams(); client.addHeader("token", currentUser.getToken()); params.put("bache_ticket", currentReport.getTicket()); params.put("bache_img1", currentReport.getImage1()); /*B24Debug debugObject = currentReport.debugObject(); debugObject.setReportSquadEmail(currentUser.getEmail()); debugObject.setReportSquadToken(currentUser.getToken()); ServicesManager.sendDebugData(debugObject);*/ timerFinished = false; final CountDownTimer timer = new CountDownTimer(30000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { client.cancelRequests(context, true); if (timerFinished) { // Log.i("BACHE_TIMEOUT", "timer already finished"); return; } // Log.i("BACHE_TIMEOUT", "timer finished = " + new Date().toString()); if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_DESCRIPTION); return; } }; // Log.i("BACHE_TIMEOUT", "timer started = " + new Date().toString()); timer.start(); client.post(context, url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Success = " + new Date().toString()); FileManager.writeLog(currentReport.getTicket(), response != null ? response.toString() : "Response Null"); printResponse(response.toString()); if (isTokenDisabled(response)) { if (callback != null) callback.onTokenDisabled(); return; } if (response.has("OK")) { try { if (response.getString("OK").trim().equals("807")) { if (callback != null) callback.onFailRegisterReport(Constants.REPORTE_ATTENDED); } else if (response.getString("OK").equals("805") || response.getString("OK").trim().equals("806") || response.getString("OK").trim().equals("921") || response.getString("OK").trim().contains("921") || response.getString("OK").trim().contains("922")) { if (callback != null){ callback.onSuccessRegisterReport(null); } } else { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode(response.getString("OK"))); } } } catch (JSONException ex) { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode("006")); } } } else if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } } catch (JSONException ex) { if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("007")); } } else { if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("008")); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; FileManager.writeLog(currentReport.getTicket(), response != null ? response.toString() : "Response Null"); if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("005")); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; FileManager.writeLog(currentReport.getTicket(), responseString != null ? responseString.toString() : "Response Null"); if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("004")); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); FileManager.writeLog(currentReport.getTicket(), errorResponse != null ? errorResponse.toString() : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(currentReport.getTicket(), currentUser.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableDataWithToken(currentReport, throwable, message, statusCode + "", currentUser.getToken());*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("003")); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); FileManager.writeLog(currentReport.getTicket(), responseString != null ? responseString : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(currentReport.getTicket(), currentUser.getEmail(), responseString != null ? responseString : "Response Null"); ServicesManager.sendDebugThrowableDataWithToken(currentReport, throwable, message, statusCode + "", currentUser.getToken());*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("002")); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); FileManager.writeLog(currentReport.getTicket(), errorResponse != null ? errorResponse.toString() : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(currentReport.getTicket(), currentUser.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableDataWithToken(currentReport, throwable, message, statusCode + "", currentUser.getToken());*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("001")); } }); } public static void cancelReportAttention(final Context context, final User currentUser, final Report currentReport, final NewReportCallback callback) { final AsyncHttpClient client = new AsyncHttpClient(); // client.setTimeout(TIMEOUT); String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_CANCEL_REPORT_ATTENTION; RequestParams params = new RequestParams(); client.addHeader("token", currentUser.getToken()); params.put("bache_ticket", currentReport.getTicket()); /*B24Debug debugObject = currentReport.debugObject(); debugObject.setReportSquadEmail(currentUser.getEmail()); debugObject.setReportSquadToken(currentUser.getToken());*/ // ServicesManager.sendDebugData(debugObject); // Log.i("BACHE_SERVICES", "cancelReportAttention executed for ticket = " + currentReport.getTicket()); // Utils.Log("ServicesManager", "cancelReportAttention", "Service call for = " + currentReport.getTicket()); timerFinished = false; final CountDownTimer timer = new CountDownTimer(30000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { client.cancelRequests(context, true); if (timerFinished) { // Log.i("BACHE_TIMEOUT", "timer already finished"); return; } // Log.i("BACHE_TIMEOUT", "timer finished = " + new Date().toString()); if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_DESCRIPTION); return; } }; // Log.i("BACHE_TIMEOUT", "timer started = " + new Date().toString()); timer.start(); client.post(context, url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); // Utils.Log("ServicesManager", "onSuccess", "Service response = " + response.toString()); timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Success = " + new Date().toString()); FileManager.writeLog(currentReport.getTicket(), response != null ? response.toString() : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(currentReport.getTicket(), currentUser.getEmail(), response != null ? response.toString() : "Response Null"); ServicesManager.sendDebugThrowableDataWithToken(currentReport, null, message, statusCode + "", currentUser.getToken());*/ // Log.i("VALID_REPORT_ACT_LOG", "[" + currentReport.getTicket() + "] Action = Request -> " + response.toString()); if (isTokenDisabled(response)) { if (callback != null) callback.onTokenDisabled(); return; } if (response.has("OK")) { try { if (response.getString("OK").equals("805") || response.getString("OK").trim().equals("806") || response.getString("OK").trim().equals("807") || response.getString("OK").trim().equals("921") || response.getString("OK").trim().contains("921") || response.getString("OK").trim().contains("922") || response.getString("OK").trim().contains("801")) { if (callback != null){ callback.onSuccessRegisterReport(null); } } else { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode(response.getString("OK"))); } } } catch (JSONException ex) { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode("006")); } } } else if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } } catch (JSONException ex) { if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("007")); } } else { if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("008")); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (timerFinished) { client.cancelRequests(context, true); return; } FileManager.writeLog(currentReport.getTicket(), response != null ? response.toString() : "Response Null"); if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("005")); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (timerFinished) { client.cancelRequests(context, true); return; } FileManager.writeLog(currentReport.getTicket(), responseString != null ? responseString.toString() : "Response Null"); if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("004")); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); // Utils.Log("ServicesManager", "onFailure", "Service response failure = " + errorResponse.toString()); FileManager.writeLog(currentReport.getTicket(), errorResponse != null ? errorResponse.toString() : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(currentReport.getTicket(), currentUser.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableDataWithToken(currentReport, throwable, message, statusCode + "", currentUser.getToken());*/ /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION);//getMessageWithErrorCode("003")); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); // Utils.Log("ServicesManager", "onFailure", "Service response failure = " + responseString); FileManager.writeLog(currentReport.getTicket(), responseString != null ? responseString : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(currentReport.getTicket(), currentUser.getEmail(), responseString != null ? responseString : "Response Null"); ServicesManager.sendDebugThrowableDataWithToken(currentReport, throwable, message, statusCode + "", currentUser.getToken());*/ /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION);//getMessageWithErrorCode("002")); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); // Utils.Log("ServicesManager", "onFailure", "Service response failure = " + errorResponse.toString()); FileManager.writeLog(currentReport.getTicket(), errorResponse != null ? errorResponse.toString() : "Response Null"); /*String message = ServicesManager.getJSONStringWithParameters(currentReport.getTicket(), currentUser.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableDataWithToken(currentReport, throwable, message, statusCode + "", currentUser.getToken());*/ /*if (throwable != null) { if (throwable.getCause() instanceof ConnectTimeoutException) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION);//getMessageWithErrorCode("001")); } }); } public static void getLastVersion(final IGetVersionCallback callback) { AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); String url = Constants.SERVICES_GET_LAST_VERSION; client.get(url, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); if (response.has("ver")) { if (callback != null) { try { callback.versionResponse(response.get("ver").toString()); } catch (JSONException e) { e.printStackTrace(); callback.versionResponse(""); } } } else { callback.versionResponse(""); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); callback.versionResponse(""); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); callback.versionResponse(""); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); callback.versionResponse(""); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); callback.versionResponse(""); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); callback.versionResponse(""); } }); } // CONSULTA DE CATALOGOS public static void getStatesList(final IStatusResponse callback) { AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_STATUS_LIST; client.get(url, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); callback.onResponse(null); } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response);//AQUI List<Status> statusList = null; if (response != null) { statusList = new ArrayList<>(); try { for (int i = 0; i < response.length(); i++) { Status status = new Status(); status.setId(response.getJSONObject(i).getInt("id_cat_etapa")); status.setName(response.getJSONObject(i).getString("cat_etapa_descripcion")); statusList.add(status); } } catch (JSONException ex) { } } if (callback != null) { callback.onResponse(statusList); } } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); callback.onResponse(null); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); callback.onResponse(null); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); callback.onResponse(null); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); callback.onResponse(null); } }); } // NUEVOS ESTADOS 7 y 8 public static void updateReportStatusAttention(final Context context, final User currentUser, final AttendedReport attendedReport, final NewReportCallback callback) { final AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(TIMEOUT); // client.setMaxRetriesAndTimeout(1, TIMEOUT); String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_UPDATE_REPORT_BY_TROOP; RequestParams params = new RequestParams(); client.addHeader("token", attendedReport.getToken()); params.put("bache_ticket", attendedReport.getTicket()); params.put("id_cat_etapa", attendedReport.getEtapa()); params.put("bache_img1", attendedReport.getImage1()); if (attendedReport.getEtapa() == Constants.REPORT_STATUS_7) { params.put("razon_no_aplica", attendedReport.getBacheJustificacion()); params.put("bache_compromiso", attendedReport.getBacheCompromiso()); } else if (attendedReport.getEtapa() == Constants.REPORT_STATUS_8) { params.put("bache_reasignacion", attendedReport.getBacheReasignacion()); params.put("bache_comentarios", attendedReport.getDescripcion()); } /*B24Debug debugObject = attendedReport.debugObject(); debugObject.setReportSquadEmail(currentUser.getEmail()); ServicesManager.sendDebugData(debugObject);*/ timerFinished = false; final CountDownTimer timer = new CountDownTimer(30000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { client.cancelRequests(context, true); if (timerFinished) { // Log.i("BACHE_TIMEOUT", "timer already finished"); return; } // Log.i("BACHE_TIMEOUT", "timer finished = " + new Date().toString()); if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_DESCRIPTION); return; } }; // Log.i("BACHE_TIMEOUT", "timer started = " + new Date().toString()); timer.start(); client.post(context, url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "success = " + new Date().toString()); FileManager.writeLog(attendedReport.getTicket(), response != null ? response.toString() : "Response Null"); if (isTokenDisabled(response)) { if (callback != null) callback.onTokenDisabled(); return; } if (response.has("OK")) { try { if (response.getString("OK").trim().equals("807")) { if (callback != null) callback.onFailRegisterReport(Constants.REPORTE_ATTENDED); } else if (response.getString("OK").equals("805") || response.getString("OK").trim().equals("806") || response.getString("OK").trim().equals("921") || response.getString("OK").trim().contains("921") || response.getString("OK").trim().contains("922") || response.getString("OK").trim().equals("802")) { if (callback != null){ callback.onSuccessRegisterReport(null); } } else { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode(response.getString("OK"))); } } } catch (JSONException ex) { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode("006")); } } } else if (response.has(Constants.RESPONSE_ERROR_KEY)) { try { if (callback != null) { callback.onFailRegisterReport(getMessageWithErrorCode(response.getString(Constants.RESPONSE_ERROR_KEY))); } } catch (JSONException ex) { if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("007")); } } else { if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("008")); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { super.onSuccess(statusCode, headers, response); if (timerFinished) { client.cancelRequests(context, true); return; } FileManager.writeLog(attendedReport.getTicket(), response != null ? response.toString() : "Response Null"); if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("005")); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { super.onSuccess(statusCode, headers, responseString); if (timerFinished) { client.cancelRequests(context, true); return; } FileManager.writeLog(attendedReport.getTicket(), responseString != null ? responseString.toString() : "Response Null"); if (callback != null) callback.onFailRegisterReport(getMessageWithErrorCode("004")); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); // Log.i("ERROR_REUBICAR", errorResponse.toString()); FileManager.writeLog(attendedReport.getTicket(), errorResponse != null ? errorResponse.toString() : "Response Null"); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); /*String message = ServicesManager.getJSONStringWithParameters(attendedReport.getTicket(), currentUser.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableData(attendedReport, throwable, message, statusCode + "");*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); // Log.i("ERROR_REUBICAR", responseString.toString()); FileManager.writeLog(attendedReport.getTicket(), responseString != null ? responseString : "Response Null"); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); /*String message = ServicesManager.getJSONStringWithParameters(attendedReport.getTicket(), currentUser.getEmail(), responseString != null ? responseString : "Response Null"); ServicesManager.sendDebugThrowableData(attendedReport, throwable, message, statusCode + "");*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); // Log.i("ERROR_REUBICAR", errorResponse.toString()); FileManager.writeLog(attendedReport.getTicket(), errorResponse != null ? errorResponse.toString() : "Response Null"); if (timerFinished) { client.cancelRequests(context, true); return; } timer.cancel(); timerFinished = true; // Log.i("BACHE_TIMEOUT", "Failure1 = " + new Date().toString()); /*String message = ServicesManager.getJSONStringWithParameters(attendedReport.getTicket(), currentUser.getEmail(), errorResponse != null ? errorResponse.toString() : "Response Null"); ServicesManager.sendDebugThrowableData(attendedReport, throwable, message, statusCode + "");*/ /*if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } else { if (throwable != null) { if (throwable.toString().equals("java.net.SocketTimeoutException")) { if (callback != null) callback.onFailRegisterReport(Constants.AGU_DESCRIPTION); return; } } } }*/ if (isTimeOutException(throwable)) { if (callback != null) callback.onFailRegisterReport(Constants.TIMEOUT_REPORT_ATTENTION_DESCRIPTION); return; } if (callback != null) callback.onFailRegisterReport(Constants.ERROR_DATABASE_ERROR_DESCRIPTION); } }); } public static void sendFirebaseToken(final Context context, User currentUser, String firebaseToken) { AsyncHttpClient client = new AsyncHttpClient(); String url = Constants.SERVICES_SERVER_URL + Constants.SERVICES_SEND_FIREBASE_TOKEN; RequestParams params = new RequestParams(); client.addHeader("token", currentUser.getToken()); params.put("correo", currentUser.getEmail()); params.put("tokenD", firebaseToken); client.post(context, url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); Log.d("FirebaseServer", "token save successfully"); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); if (throwable != null) { throwable.printStackTrace(); } } }); } private static Report.ReportOrigin getOrigin(int parameter) { Report.ReportOrigin origin; switch (parameter) { case Constants.REPORT_ORIGIN_APP: origin = Report.ReportOrigin.APP; break; case Constants.REPORT_ORIGIN_CMS: origin = Report.ReportOrigin.CMS; break; case Constants.REPORT_ORIGIN_072_SALESFORCE: origin = Report.ReportOrigin.O72; break; case Constants.REPORT_ORIGIN_SMS: origin = Report.ReportOrigin.SMS; break; default: origin = Report.ReportOrigin.APP; break; } return origin; } private static boolean isBannedUser(JSONObject object) { try { if (object.has("ERROR")) { int responseCode = Integer.valueOf(object.getString("ERROR")); if (responseCode == Constants.ERROR_USER_BANNED) { return true; } } if (object.has("OK")) { int responseCode = Integer.valueOf(object.getString("OK")); if (responseCode == Constants.ERROR_USER_BANNED) { return true; } } } catch (Exception ex) { return false; } return false; } private static boolean isTokenDisabled(JSONObject object) { try { if (object.has("ERROR")) { int responseCode = Integer.valueOf(object.getString("ERROR")); if (responseCode == Constants.ERROR_INCORRECT_TOKEN) { //|| responseCode == Constants.ERROR_BAD_TOKEN) { return true; } } } catch (Exception ex) { } return false; } private static String getMessageForResponseCode(String responseCodeString) { String responseMessage = ""; int responseCode = Integer.valueOf(responseCodeString); switch (responseCode) { case Constants.ERROR_MISSING_DATA: responseMessage = Constants.ERROR_MISSING_DATA_DESCRIPTION; break; case Constants.ERROR_INCORRECT_DATA: responseMessage = Constants.ERROR_INCORRECT_DATA_DESCRIPTION; break; case Constants.ERROR_DATABASE_ERROR: responseMessage = Constants.ERROR_DATABASE_ERROR_DESCRIPTION; break; case Constants.ERROR_INCORRECT_TOKEN: responseMessage = ""; break; case Constants.ERROR_EMAIL_ERROR: responseMessage = Constants.ERROR_EMAIL_ERROR_DESCRIPTION; break; case Constants.ERROR_BAD_COORDINATES: responseMessage = Constants.ERROR_BAD_COORDINATES_DESCRIPTION; break; // case Constants.ERROR_BAD_TOKEN: // responseMessage = ""; // break; case Constants.ERROR_NO_REPORTS_FOUND: responseMessage = Constants.ERROR_NO_REPORTS_FOUND_DESCRIPTION; break; case Constants.ERROR_USER_PERMISION_DENIED: responseMessage = Constants.ERROR_USER_PERMISION_DENIED_DESCRIPTION; break; case Constants.ERROR_BAD_REPORT_ID: responseMessage = Constants.ERROR_BAD_REPORT_ID_DESCRIPTION; break; case Constants.ERROR_EMPTY_REPORT_ID: responseMessage = Constants.ERROR_EMPTY_REPORT_ID_DESCRIPTION; break; case Constants.ERROR_USER_ALREADY_REGISTERED: responseMessage = Constants.ERROR_USER_ALREADY_REGISTERED_DESCRIPTION; break; case Constants.ERROR_HASH_EMPTY: responseMessage = Constants.ERROR_HASH_EMPTY_DESCRIPTION; break; case Constants.ERROR_REPORT_ASSIGNATION_FAILED: responseMessage = Constants.ERROR_REPORT_ASSIGNATION_FAILED_DESCRIPTION; break; case Constants.ERROR_TROOP_STATUS: responseMessage = Constants.ERROR_TROOP_STATUS_DESCRIPTION; break; case Constants.ERROR_UPDATE_REPORT: responseMessage = Constants.ERROR_UPDATE_REPORT_DESCRIPTION; break; case Constants.ERROR_REPORT_EMPTY: responseMessage = Constants.ERROR_REPORT_EMPTY_DESCRIPTION; break; case Constants.ERROR_INVALID_USER: responseMessage = Constants.ERROR_INVALID_USER_DESCRIPTION; break; // case Constants.ERROR_REGISTER_INVALID: // responseMessage = Constants.ERROR_REGISTER_INVALID_DESCRIPTION; // break; // case Constants.ERROR_SOCIAL_NETWORK_EMPTY: // responseMessage = Constants.ERROR_SOCIAL_NETWORK_EMPTY_DESCRIPTION; // break; // case Constants.ERROR_PASSWORD_UPDATE: // responseMessage = Constants.ERROR_PASSWORD_UPDATE_DESCRIPTION; // break; case Constants.ERROR_EMAIL_ERROR_2: responseMessage = Constants.ERROR_EMAIL_ERROR_2_DESCRIPTION; break; case Constants.ERROR_USER_REGISTER: responseMessage = Constants.ERROR_USER_REGISTER_DESCRIPTION; break; case Constants.ERROR_ACCOUNT_NOT_ACTIVE: responseMessage = Constants.ERROR_ACCOUNT_NOT_ACTIVE_DESCRIPTION; break; case Constants.ERROR_USER_NOT_REGISTERED: responseMessage = Constants.ERROR_USER_NOT_REGISTERED_DESCRIPTION; default: responseMessage = Constants.ERROR_DATABASE_ERROR_DESCRIPTION; break; } return responseMessage; } public static String getMessageWithErrorCode(String responseCode) { return Constants.ERROR_GENERIC_PART_1 + " " + responseCode + Constants.ERROR_GENERIC_PART_2; } /*public static void sendDebugData(final B24Debug debugObject) { debugObject.saveEventually(); }*/ /*public static void sendDebugThrowableData(B24DebugInterface report, Throwable error, String errorDescription, String errorCode) { ServicesManager.sendDebugThrowableDataWithToken(report, error, errorDescription, errorCode, null); }*/ /*public static void sendDebugThrowableDataWithToken(B24DebugInterface report, Throwable error, String errorDescription, String errorCode, String token) { B24DebugThrowable debugObject = new B24DebugThrowable(); debugObject.setErrorDescription(errorDescription); debugObject.setErrorMessage(error != null ? error.getMessage() : ""); debugObject.setReportID(report.getReportID()); debugObject.setReportSquadToken(token != null ? token : report.getReportToken()); debugObject.saveEventually(); FlurryAgent.onError(errorCode, errorDescription, error); }*/ public static String getJSONStringWithParameters(String reportID, String email, String errorMessage) { Map <String, String> parameters = new HashMap<String, String>(); parameters.put("ReportID", reportID); parameters.put("SquadEmail", email); parameters.put("Message", errorMessage); Gson json = new Gson(); return json.toJson(parameters); } /*public static void sendDebugResponse(String email, String serviceEndPoint, String request, String response, String token) { B24DebugResponse debugObject = new B24DebugResponse(); debugObject.setEmail(email); debugObject.setServiceEndPoint(serviceEndPoint); // debugObject.setRequest(request); debugObject.setResponse(response); debugObject.setUserToken(token); Date currentDate = new Date(); DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); debugObject.setDate(dateFormat.format(currentDate)); debugObject.saveEventually(); }*/ public static void printResponse(String response) { // Log.i("SERVICE_RESPONSE", response); } private static boolean isTimeOutException(Throwable throwable) { if (throwable != null) { if (throwable.getMessage() != null) { if (throwable.getMessage().contains("timed out")) { return true; } } else { if (throwable.toString().equals("java.net.SocketTimeoutException")) { return true; } } } return false; } }
package com.example.starbucks_piece; import java.util.UUID; public class Food { private String mTitle; private int mImgPath; private UUID mId; public Food(){} public Food(String title, int imgPath){ mTitle = title; mImgPath = imgPath; } public UUID getId() { return mId; } public String getTitle() { return mTitle; } public void setTitle(String title) { mTitle = title; } public int getImgPath() { return mImgPath; } public void setImgPath(int imgPath) { mImgPath = imgPath; } }
package de.varylab.discreteconformal.uniformization; import static de.varylab.discreteconformal.adapter.HyperbolicModel.Klein; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.logging.Logger; import de.jreality.geometry.IndexedLineSetFactory; import de.jreality.math.P2; import de.jreality.math.Pn; import de.jreality.math.Rn; import de.jreality.scene.IndexedLineSet; import de.jtem.halfedge.util.HalfEdgeUtils; import de.jtem.halfedgetools.adapter.AdapterSet; import de.jtem.halfedgetools.algorithm.topology.TopologyAlgorithms; import de.varylab.discreteconformal.heds.CoEdge; import de.varylab.discreteconformal.heds.CoFace; import de.varylab.discreteconformal.heds.CoHDS; import de.varylab.discreteconformal.heds.CoVertex; import de.varylab.discreteconformal.util.CuttingUtility.CuttingInfo; import de.varylab.discreteconformal.util.NodeIndexComparator; public class SurfaceCurveUtility { private static Logger log = Logger.getLogger(SurfaceCurveUtility.class.getName()); public static IndexedLineSet createSurfaceCurves( FundamentalPolygon poly, CoHDS surface, AdapterSet aSet, int maxElements, double maxDrawDistance, boolean includePoygon, boolean includeAxes, int signature ) { List<double[][]> axesSegments = new ArrayList<double[][]>(); List<double[][]> polySegments = new ArrayList<double[][]>(); VisualizationUtility.createUniversalCover( poly, Klein, maxElements, maxDrawDistance, includePoygon, includeAxes, false, axesSegments, polySegments, null, null, null ); List<double[][][]> allCurves = new ArrayList<double[][][]>(); if (includeAxes) { for (double[][] ds : axesSegments) { List<double[][][]> I = intersectTriangulation(surface, ds, signature); allCurves.addAll(I); } } if (includePoygon) { for (double[][] ds : polySegments) { List<double[][][]> I = intersectTriangulation(surface, ds, signature); allCurves.addAll(I); } } double[][] vData = new double[allCurves.size() * 2][]; double[][] tData = new double[allCurves.size() * 2][2]; int[][] eData = new int[allCurves.size()][2]; int index = 0; for (double[][][] s : allCurves) { vData[index + 0] = s[1][0]; vData[index + 1] = s[1][1]; tData[index + 0][0] = s[0][0][0]; tData[index + 0][1] = s[0][0][1]; tData[index + 1][0] = s[0][1][0]; tData[index + 1][1] = s[0][1][1]; eData[index/2][0] = index; eData[index/2][1] = index + 1; index += 2; } IndexedLineSetFactory ilsf = new IndexedLineSetFactory(); ilsf.setVertexCount(vData.length); ilsf.setEdgeCount(eData.length); ilsf.setVertexCoordinates(vData); ilsf.setVertexTextureCoordinates(tData); ilsf.setEdgeIndices(eData); ilsf.update(); return ilsf.getIndexedLineSet(); } public static Set<Set<CoVertex>> createIntersectionVertices( FundamentalPolygon poly, CoHDS surface, CoHDS domain, CuttingInfo<CoVertex, CoEdge, CoFace> cutInfo, AdapterSet aSet, double snapTolerance, int signature ) { Set<Set<CoVertex>> result = new HashSet<Set<CoVertex>>(); List<double[][]> axesSegments = new ArrayList<double[][]>(); List<double[][]> polySegments = new ArrayList<double[][]>(); VisualizationUtility.createUniversalCover( poly, Klein, 200, 10, true, false, false, axesSegments, polySegments, null, null, null ); for (double[][] segment : polySegments) { Set<CoVertex> segmentVertices = new TreeSet<>(new NodeIndexComparator<CoVertex>()); createIntersectionVertices(segment, surface, domain, cutInfo, snapTolerance, signature, segmentVertices); result.add(segmentVertices); } return result; } public static void createIntersectionVertices( double[][] segment, boolean segmentOnly, CoHDS surface, CoHDS domain, CuttingInfo<CoVertex, CoEdge, CoFace> cutInfo, double snapTolerance, int signature, Set<CoVertex> result ) { double[] polygonLine = P2.lineFromPoints(null, segment[0], segment[1]); Rn.normalize(polygonLine, polygonLine); for (CoEdge domainEdge : domain.getPositiveEdges()) { CoVertex s = domainEdge.getStartVertex(); CoVertex t = domainEdge.getTargetVertex(); double[] st = {s.T[0] / s.T[3], s.T[1] / s.T[3], 1}; double[] tt = {t.T[0] / t.T[3], t.T[1] / t.T[3], 1}; double[][] domainSegment = {st, tt}; double[][] surfaceSegment = {s.P, t.P}; double[] domainEdgeLine = P2.lineFromPoints(null, st, tt); Rn.normalize(domainEdgeLine, domainEdgeLine); double edgeOnLine = Rn.euclideanNormSquared(Rn.crossProduct(null, polygonLine, domainEdgeLine)); if (edgeOnLine < 1E-8) { List<CoEdge> surfaceEdges = findCorrespondingSurfaceEdges(domainEdge, cutInfo, surface); for (CoEdge e : surfaceEdges) { result.add(e.getStartVertex()); result.add(e.getTargetVertex()); } continue; } double[] newDomainPoint = P2.pointFromLines(null, polygonLine, domainEdgeLine); // split only if edge is really intersected if (isOnSegment(newDomainPoint, domainSegment) && (!segmentOnly || isOnSegment(newDomainPoint, segment))) { double[] newPoint = getPointOnCorrespondingSegment(newDomainPoint, domainSegment, surfaceSegment, signature); List<CoEdge> surfaceEdges = findCorrespondingSurfaceEdges(domainEdge, cutInfo, surface); if (surfaceEdges.isEmpty()) continue; CoEdge splitEdge = null; // select intersected part boolean snap = false; for (CoEdge se : surfaceEdges) { CoVertex vs = se.getStartVertex(); CoVertex vt = se.getTargetVertex(); if (result.contains(vs) || result.contains(vt)) { log.info("snapped to cycle vertex"); snap = true; break; } double[][] pSegment = {vs.P, vt.P}; if (isOnSegment(newPoint, pSegment)) { splitEdge = se; double d1 = getDistanceBetween(newPoint, vs.P, Pn.EUCLIDEAN); double d2 = getDistanceBetween(newPoint, vt.P, Pn.EUCLIDEAN); if (d1 < snapTolerance) { result.add(vs); snap = true; } if (d2 < snapTolerance) { result.add(vt); snap = true; } break; } } if (snap) continue; if (splitEdge == null) { log.warning("no corresponding intersected edge found on surface"); continue; } CoVertex newVertex = TopologyAlgorithms.splitEdge(splitEdge); result.add(newVertex); newVertex.P = newPoint; newVertex.T = P2.imbedP2InP3(null, newDomainPoint); } } } public static void createIntersectionVertices( double[][] segment, CoHDS surface, CoHDS domain, CuttingInfo<CoVertex, CoEdge, CoFace> cutInfo, double snapTolerance, int signature, Set<CoVertex> result ) { createIntersectionVertices(segment, true, surface, domain, cutInfo, snapTolerance, signature, result); } private static List<CoEdge> findCorrespondingSurfaceEdges( CoEdge sourceEdge, CuttingInfo<CoVertex, CoEdge, CoFace> sourceCutInfo, CoHDS target ) { CoFace flSource = sourceEdge.getLeftFace(); CoFace frSource = sourceEdge.getRightFace(); if (flSource == null) { CoEdge idEdge = sourceCutInfo.edgeCutMap.get(sourceEdge); if (idEdge != null) { flSource = idEdge.getRightFace(); } } if (frSource == null) { CoEdge idEdge = sourceCutInfo.edgeCutMap.get(sourceEdge); if (idEdge != null) { frSource = idEdge.getLeftFace(); } } assert flSource != null || frSource != null; CoFace flTarget = null; CoFace frTarget = null; if (flSource != null) { flTarget = target.getFace(flSource.getIndex()); } if (frSource != null) { frTarget = target.getFace(frSource.getIndex()); } if (flTarget == null) { flTarget = frTarget; frTarget = null; } List<CoEdge> result = HalfEdgeUtils.findEdgesBetweenFaces(flTarget, frTarget); return result; } private static List<double[][][]> intersectTriangulation(CoHDS T, double[][] segment, int signature) { List<double[][][]> result = new LinkedList<double[][][]>(); for (CoFace f : T.getFaces()) { CoEdge be = f.getBoundaryEdge(); CoVertex v0 = be.getStartVertex(); CoVertex v1 = be.getNextEdge().getStartVertex(); CoVertex v2 = be.getPreviousEdge().getStartVertex(); double[] p0 = {v0.T[0] / v0.T[3], v0.T[1] / v0.T[3], 1}; double[] p1 = {v1.T[0] / v1.T[3], v1.T[1] / v1.T[3], 1}; double[] p2 = {v2.T[0] / v2.T[3], v2.T[1] / v2.T[3], 1}; double[][] ts0 = {p0, p1}; double[][] ts1 = {p1, p2}; double[][] ts2 = {p2, p0}; double[][] ps0 = {v0.P, v1.P}; double[][] ps1 = {v1.P, v2.P}; double[][] ps2 = {v2.P, v0.P}; double[] line = P2.lineFromPoints(null, segment[0], segment[1]); double[][] tri = {p0, p1, p2}; double[][] chopped = P2.chopConvexPolygonWithLine(tri, line); if (chopped == null || chopped == tri) { continue; } else { double[] c0 = null; double[] c1 = null; for (double[] p : chopped) { if (Arrays.equals(p, p0) || Arrays.equals(p, p1) || Arrays.equals(p, p2)) { continue; } if (c0 == null) { c0 = p; } else { c1 = p; } } if (c0 == null || c1 == null) { continue; } if (isOnSegment(c0, segment) && isOnSegment(c1, segment)) { double[] sp0 = v0.P; double[] sp1 = v1.P; if (isOnSegment(c0, ts0)) { sp0 = getPointOnCorrespondingSegment(c0, ts0, ps0, signature); } else if (isOnSegment(c0, ts1)) { sp0 = getPointOnCorrespondingSegment(c0, ts1, ps1, signature); } else if (isOnSegment(c0, ts2)) { sp0 = getPointOnCorrespondingSegment(c0, ts2, ps2, signature); } if (isOnSegment(c1, ts0)) { sp1 = getPointOnCorrespondingSegment(c1, ts0, ps0, signature); } else if (isOnSegment(c1, ts1)) { sp1 = getPointOnCorrespondingSegment(c1, ts1, ps1, signature); } else if (isOnSegment(c1, ts2)) { sp1 = getPointOnCorrespondingSegment(c1, ts2, ps2, signature); } double[][][] curveSegment = {{c0, c1}, {sp0, sp1}}; result.add(curveSegment); } } } return result; } static boolean isOnSegment(double[] p, double[][] s) { Pn.dehomogenize(p, p); Pn.dehomogenize(s, s); double[] ps0 = Rn.subtract(null, s[0], p); double[] ps1 = Rn.subtract(null, s[1], p); double d1 = Pn.norm(ps0, Pn.EUCLIDEAN); double d2 = Pn.norm(ps0, Pn.EUCLIDEAN); if (d1 < 0.0 || d2 < 0.0) return false; double[] s0s1 = Rn.subtract(null, s[0], s[1]); double[] cross = Rn.crossProduct(null, ps0, ps1); double dot = Rn.innerProduct(ps0, ps1); if (Rn.euclideanNorm(cross) > 1E-7) return false; if (dot > 0) return false; if (dot > Rn.euclideanNormSquared(s0s1)) return false; return true; } // static boolean isOnSegment(double[] p, double[][] s) { // double l = Pn.distanceBetween(s[0], s[1], Pn.EUCLIDEAN); // double l1 = Pn.distanceBetween(s[0], p, Pn.EUCLIDEAN); // double l2 = Pn.distanceBetween(s[1], p, Pn.EUCLIDEAN); // return Math.abs(l1 + l2 - l) < 1E-7; // } static double[] getPointOnCorrespondingSegment(double[] p, double[][] source, double[][] target, int signature) { double l = Pn.distanceBetween(source[0], source[1], signature); double l1 = Pn.distanceBetween(source[0], p, signature) / l; double l2 = Pn.distanceBetween(source[1], p, signature) / l; if (Double.isNaN(l1)) { return target[0]; } if (Double.isNaN(l2)) { return target[1]; } double[] t0d = Pn.dehomogenize(null, target[0]); double[] t1d = Pn.dehomogenize(null, target[1]); return Rn.linearCombination(null, l1, t1d, l2, t0d); } static double getDistanceBetween(double[] p1, double[] p2, int signature) { double d = Pn.distanceBetween(p1, p2, signature); if (Double.isNaN(d)) { return 0.0; } else { return d; } } }
package org.foolip.mushup; import org.musicbrainz.model.*; import org.musicbrainz.webservice.*; import org.neo4j.api.core.*; import org.neo4j.util.index.IndexService; import java.util.*; public class Replicator { private static Replicator instance; private MushArtistFactory maf; public Replicator(NeoService neo, IndexService indexService) { maf = new MushArtistFactory(neo, indexService); } public synchronized MushArtist getArtistById(UUID id, int depth) { MushArtist artist = maf.getArtistById(id); return artist; } }
package com.dbs.portal.ui.component.view; import java.util.List; import java.util.Map; import com.dbs.portal.ui.component.pagetable.IPagedTableParameter; import com.dbs.portal.ui.component.pagetable.PagedTableDataType; import com.vaadin.data.Container; public interface ITableResultView extends IResultView{ public Object[] getVisibleColumnHeader(); public List<String> getCurrentCollapseColumnHeader(); public void setSavedColumnHeader(Object[] dataId, String[] collapsedDataIdList); public Map<String, IPagedTableParameter> getPagedTableParameterMap(); public Object[] getCurrentVisibleColumn(); public String[] getCurrentVisibleColumnName(); public void activateColumn(String gorupKey); public void clearActivatedColumn(); public void setDeleteButtonEnable(boolean deleteButtonEnable); public Object[] getOriginalColumnDataId(); public String[] getOriginalColumnHeader(); public Object[] getVisibleColumns(); public Container getContainer(); public List<PagedTableDataType> getVisibleColumnDataType(); public String getFunctionName(); public List<String> getTotalColumnId(); public void sort(Object[] columnIds, boolean[] ascending); }
/* * Copyright (c) 2017-2020 Peter G. Horvath, All Rights Reserved. * * 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.github.blausql.ui; import com.github.blausql.Main; import com.github.blausql.TerminalUI; import com.github.blausql.core.Constants; import com.github.blausql.core.connection.ConnectionDefinition; import com.github.blausql.core.preferences.ConfigurationRepository; import com.github.blausql.core.preferences.ConnectionDefinitionRepository; import com.github.blausql.core.preferences.LoadException; import com.github.blausql.ui.components.ActionButton; import com.github.blausql.ui.util.DefaultErrorHandlerAction; import com.github.blausql.ui.util.HotKeySupportListener; import com.google.common.collect.ImmutableMap; import com.googlecode.lanterna.gui.Action; import com.googlecode.lanterna.gui.Window; import java.util.List; public class MainMenuWindow extends Window { public MainMenuWindow() { super(Constants.APPLICATION_BANNER); addComponent(connectToDatabaseButton); addComponent(manageConnectionButton); addComponent(setApplicationClasspathButton); addComponent(manageBookmarkedSqlFilesButton); addComponent(aboutButton); addComponent(quitApplicationButton); addWindowListener(new HotKeySupportListener( ImmutableMap.<Character, Action>builder() .put('C', connectToDatabaseButton) .put('M', manageConnectionButton) .put('B', manageBookmarkedSqlFilesButton) .put('S', setApplicationClasspathButton) .put('A', aboutButton) .put('Q', quitApplicationButton) .build(), false)); } private final ActionButton connectToDatabaseButton = new ActionButton("[C]onnect to database", new DefaultErrorHandlerAction() { public void doActionWithErrorHandler() throws LoadException { List<ConnectionDefinition> connectionDefinitions = ConnectionDefinitionRepository.getInstance().getConnectionDefinitions(); TerminalUI.showWindowCenter(new SelectConnectionForQueryWindow(connectionDefinitions)); } }); private final ActionButton manageConnectionButton = new ActionButton("[M]anage Connections", new Action() { public void doAction() { TerminalUI.showWindowCenter(new ManageConnectionsWindow()); } }); private final ActionButton setApplicationClasspathButton = new ActionButton("[S]et Classpath", new DefaultErrorHandlerAction() { public void doActionWithErrorHandler() throws LoadException { String[] classpath = ConfigurationRepository.getInstance().getClasspath(); TerminalUI.showWindowCenter(new SetClasspathWindow(classpath)); } }); private final ActionButton manageBookmarkedSqlFilesButton = new ActionButton("[B]ookmarked SQL Files", new DefaultErrorHandlerAction() { public void doActionWithErrorHandler() throws LoadException { TerminalUI.showWindowCenter(new ManageBookmarkedSqlFilesWindow()); } }); private final ActionButton aboutButton = new ActionButton("[A]bout", new Action() { public void doAction() { TerminalUI.showMessageBox("About BlauSQL", Constants.ABOUT_TEXT); } }); private final ActionButton quitApplicationButton = new ActionButton("[Q]uit Application", new Action() { public void doAction() { Main.exitApplication(0); } }); }
package com.legaoyi.protocol.down.messagebody; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.legaoyi.protocol.message.MessageBody; /** * 摄像头立即拍摄命令 * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2015-01-30 */ @Scope("prototype") @Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "8801_tjsatl" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX) public class Tjsatl_2017_8801_MessageBody extends MessageBody { private static final long serialVersionUID = -4356706548662314173L; public static final String MESSAGE_ID = "8801"; /** 通道id **/ @JsonProperty("channelId") private int channelId; /** 拍摄命令,0:表示停止拍摄,1:表示录像;其他拍照 **/ @JsonProperty("commandType") private int commandType = 2; /** 拍摄张数 **/ @JsonProperty("totalPicture") private int totalPicture; /** 拍摄间隔/录像时间 **/ @JsonProperty("executionTime") private int executionTime; /** 保存标识 **/ @JsonProperty("saveFlag") private int saveFlag; /** 分辨率 **/ @JsonProperty("resolution") private int resolution = 1; /** 质量 **/ @JsonProperty("quality") private int quality = 10; /** 亮度 **/ @JsonProperty("luminance") private int luminance; /** 对比度 **/ @JsonProperty("contrast") private int contrast; /** 饱和度 **/ @JsonProperty("saturation") private int saturation; /** 色度 **/ @JsonProperty("chromaticity") private int chromaticity; public final int getChannelId() { return channelId; } public final void setChannelId(int channelId) { this.channelId = channelId; } public final int getCommandType() { return commandType; } public final void setCommandType(int commandType) { this.commandType = commandType; } public final int getTotalPicture() { return totalPicture; } public final void setTotalPicture(int totalPicture) { this.totalPicture = totalPicture; } public final int getExecutionTime() { return executionTime; } public final void setExecutionTime(int executionTime) { this.executionTime = executionTime; } public final int getSaveFlag() { return saveFlag; } public final void setSaveFlag(int saveFlag) { this.saveFlag = saveFlag; } public final int getResolution() { return resolution; } public final void setResolution(int resolution) { this.resolution = resolution; } public final int getQuality() { return quality; } public final void setQuality(int quality) { this.quality = quality; } public final int getLuminance() { return luminance; } public final void setLuminance(int luminance) { this.luminance = luminance; } public final int getContrast() { return contrast; } public final void setContrast(int contrast) { this.contrast = contrast; } public final int getSaturation() { return saturation; } public final void setSaturation(int saturation) { this.saturation = saturation; } public final int getChromaticity() { return chromaticity; } public final void setChromaticity(int chromaticity) { this.chromaticity = chromaticity; } }
package com.citibank.ods.modules.product.fundsubscription.functionality; import java.util.Date; import java.util.List; import org.apache.commons.beanutils.BeanUtils; import org.apache.struts.action.ActionForm; import com.citibank.ods.common.functionality.BaseFnc; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO; import com.citibank.ods.common.logger.ApplicationLogger; import com.citibank.ods.common.logger.LoggerFactory; import com.citibank.ods.common.util.TableTypeEnum; import com.citibank.ods.entity.pl.valueobject.TplDataSubscptEntityVO; import com.citibank.ods.entity.pl.valueobject.TplFundMortEntityVO; import com.citibank.ods.entity.pl.valueobject.TplInfoSubscptImpEntityVO; import com.citibank.ods.modules.product.fundsubscription.form.valueobject.FundSubscriptionInvestorDataVO; import com.citibank.ods.modules.product.fundsubscription.functionality.valueobject.FundSubscriptionDetailApprovalFncVO; import com.citibank.ods.persistence.pl.dao.rdb.oracle.OracleTplDataSubscptDAO; import com.citibank.ods.persistence.pl.dao.rdb.oracle.OracleTplFundMortDAO; import com.citibank.ods.persistence.pl.dao.rdb.oracle.OracleTplInfoSubscptImpDAO; public class FundSubscriptionDetailApprovalFnc extends BaseFnc implements com.citibank.ods.common.functionality.ODSListFnc { ApplicationLogger applicationLogger = LoggerFactory.getApplicationLoggerInstance(); @Override public BaseFncVO createFncVO() { return new FundSubscriptionDetailApprovalFncVO(); } public void clearPage(BaseFncVO fncVO_) { FundSubscriptionDetailApprovalFncVO fnc = ( FundSubscriptionDetailApprovalFncVO ) fncVO_; fnc.clearErrors(); fnc.clearMessages(); fnc.setNomeCliente(null); fnc.setEvento(null); fnc.setTipoProduto(null); fnc.setNomeProduto(null); fnc.setAssunto(null); fnc.setAtestadoDivergencia(null); fnc.setBoletimReserva(null); fnc.setCcDebito(null); fnc.setCodigoCorretora(null); fnc.setCodigoFundo(null); fnc.setCodigoInvestidor(null); fnc.setComentario(null); fnc.setConhecimentoProduto(null); fnc.setCpfInvestidor(null); fnc.setCustNbr(null); fnc.setDataAbertura(null); fnc.setDataResolucaoFase(null); fnc.setDataSolucao(null); fnc.setDocumentacao(null); fnc.setFase(null); fnc.setFuncionalGerente(null); fnc.setNivelRisco(null); fnc.setNomeAprovador(null); fnc.setNomeCliente(null); fnc.setNomeFundo(null); fnc.setNomeInvestidor(null); fnc.setOta(null); fnc.setPerfilGRB(null); fnc.setProtocolo(null); fnc.setTermoTreinamento(null); fnc.setTipoTransacao(null); fnc.setValorInvestimento(null); fnc.setValorNovo(null); } @Override public void updateFormFromFncVO(ActionForm form_, BaseFncVO fncVO_) { try { BeanUtils.copyProperties(form_, fncVO_); }catch(Exception e) { applicationLogger.error("Not impeditive error in updateFormFromFncVO", e); } } @Override public void updateFncVOFromForm(ActionForm form_, BaseFncVO fncVO_) { try { BeanUtils.copyProperties(fncVO_, form_); }catch(Exception e) { applicationLogger.error("Not impeditive error in updateFncVOFromForm", e); } } public void list(BaseFncVO fncVO_) { } public void load(BaseFncVO fncVO_) { } public static void loadForApproval(BaseFncVO fncVO_){ FundSubscriptionDetailApprovalFncVO vo = ( FundSubscriptionDetailApprovalFncVO ) fncVO_; OracleTplDataSubscptDAO dao = new OracleTplDataSubscptDAO(); TplDataSubscptEntityVO d = dao.searchDataSubscrptByEnrollment(vo.getSelectedCode().replaceAll(",\\w$", ""), TableTypeEnum.MOVEMENT); vo.setAssunto(d.getSubjectText()); vo.setAtestadoDivergencia("S".equals(d.getCnfrmIncpatInd())? "Sim":"Não"); vo.setBoletimReserva("S".equals(d.getReserveInd())? "Sim":"Não"); vo.setCcDebito(com.citibank.ods.common.util.Util.stringOf(d.getAcctNbr())); vo.setCodigoCorretora(com.citibank.ods.common.util.Util.isEmpty(d.getBkrCodeText())? null: d.getBkrCodeText()); vo.setCodigoFundo(d.getFundCode()); vo.setComentario(d.getCommentText()); vo.setConhecimentoProduto(d.getProdKnwlgText()); vo.setCpfInvestidor(d.getPlyrCpfNbr()); vo.setDataAbertura(com.citibank.ods.common.util.Util.dateToString(d.getSubscptOpenDate(), "dd/MM/yyyy" )); vo.setDataResolucaoFase(com.citibank.ods.common.util.Util.dateToString(d.getPhaseRsltnDate(), "dd/MM/yyyy")); vo.setDataSolucao(com.citibank.ods.common.util.Util.dateToString(d.getSubjectSolDate(), "dd/MM/yyyy")); vo.setDocumentacao("S".equals(d.getDocumentCheckInd())? "Sim":"Não"); vo.setEvento(d.getEventText()); vo.setFase(d.getSubjectPhaseText()); vo.setNivelRisco(d.getProdRiskLvlQty()==null?null:d.getProdRiskLvlQty().toString()); vo.setNomeAprovador(d.getIncpatApprvNameText()); if (d.getAcctNbr() != null){ vo.setNomeCliente(dao.searchCustFullName(com.citibank.ods.common.util.Util.stringOf(d.getAcctNbr()))); } vo.setNomeFundo(d.getFundNameText()); vo.setNomeProduto(d.getProdNameText()); vo.setOta("S".equals(d.getStockTrfOrderInd())? "Sim":"Não"); if (!com.citibank.ods.common.util.Util.isEmpty(d.getPlyrCpfNbr())){ FundSubscriptionInvestorDataVO investorVO = dao.defInvestorNameAndCode(Long.valueOf(d.getPlyrCpfNbr().replaceAll("\\D", ""))); if (investorVO!= null){ vo.setCodigoInvestidor(investorVO.getInvestorCode()); vo.setNomeInvestidor(investorVO.getInvestorName()); } } if (d.getAcctNbr()!= null){ vo.setPerfilGRB(dao.getPerfGrb(d.getAcctNbr().longValue())); vo.setFuncionalGerente(dao.searchOffcrNbr(d.getAcctNbr().longValue())); } vo.setProtocolo(d.getEnrollment().toString()); vo.setTermoTreinamento("S".equals(d.getTrainingTermInd())? "Sim":"Não"); vo.setTipoProduto(d.getProdImpTypeCode()); vo.setTipoTransacao(d.getTransactionTypeText()); vo.setValorInvestimento(com.citibank.ods.common.util.Util.stringOf(d.getInvestimentAmt())); vo.setValorNovo(com.citibank.ods.common.util.Util.stringOf(d.getAddDiffAmt())); vo.setCanApprove(d.getLastUpdUserId() == null?false:!d.getLastUpdUserId().equals(vo.getLoggedUser().getUserID()) ); } public void validateList(BaseFncVO fncVO_) { } public static void approve(FundSubscriptionDetailApprovalFncVO vo) { OracleTplDataSubscptDAO dao = new OracleTplDataSubscptDAO(); TplDataSubscptEntityVO voInMov = dao.searchDataSubscrptByEnrollment(vo.getProtocolo(), TableTypeEnum.MOVEMENT); String userID = vo.getLoggedUser().getUserID(); String protocol = vo.getProtocolo(); if (voInMov!=null){ if ("E".equals(voInMov.getOpernTypeCode())){ dao.delete(protocol, TableTypeEnum.EFFECTIVE); dao.delete(protocol, TableTypeEnum.MOVEMENT); voInMov.setLastApprvDate(new Date()); voInMov.setLastApprvUserId(userID); voInMov.setTableType(TableTypeEnum.HISTORIC); dao.insert(voInMov); }else { FundSubscriptionImportDetailFnc.defineFund(userID, voInMov, vo.getNomeFundo(), true); insertDataSubscrpt(dao, voInMov, userID, protocol); } vo.addMessage(BaseODSFncVO.C_MESSAGE_SUCESS); } } public static void insertDataSubscrpt(OracleTplDataSubscptDAO dao, TplDataSubscptEntityVO voInMov, String userID, String protocol) { TplDataSubscptEntityVO voEffective = dao.searchDataSubscrptByEnrollment(protocol, TableTypeEnum.EFFECTIVE); if (voEffective!=null){ voInMov.setLastApprvDate(new Date()); voInMov.setLastApprvUserId(userID); voInMov.setTableType(TableTypeEnum.EFFECTIVE); voInMov.setFileImportCode(voEffective.getFileImportCode());//Necessário para que o mesmo código de importação seja mantido dao.update(voInMov); dao.delete(voInMov.getEnrollment(), TableTypeEnum.MOVEMENT); voEffective.setTableType(TableTypeEnum.HISTORIC); voEffective.setLastApprvDate(new Date()); voEffective.setLastApprvUserId(userID); dao.insert(voEffective); }else { voInMov.setLastApprvDate(new Date()); voInMov.setLastApprvUserId(userID); voInMov.setTableType(TableTypeEnum.EFFECTIVE); dao.insert(voInMov); dao.delete(voInMov.getEnrollment(), TableTypeEnum.MOVEMENT); } if (!com.citibank.ods.common.util.Util.isEmpty(voInMov.getFundNameText())){ OracleTplFundMortDAO fundDao = new OracleTplFundMortDAO(); TplFundMortEntityVO fundsEffective = fundDao.getFundsByName(voInMov.getFundNameText(), TableTypeEnum.EFFECTIVE); if (fundsEffective==null){ TplFundMortEntityVO fundsMov = fundDao.getFundsByName(voInMov.getFundNameText(), TableTypeEnum.MOVEMENT); if (fundsMov != null){ fundsMov.setLastUpdDate(new Date()); fundsMov.setLastApprvDate(new Date()); fundsMov.setLastUpdUserId(userID); fundsMov.setTableType(TableTypeEnum.EFFECTIVE); fundDao.insert(fundsMov); } } } } public static void repprove(FundSubscriptionDetailApprovalFncVO vo) { OracleTplDataSubscptDAO dao = new OracleTplDataSubscptDAO(); dao.delete(vo.getProtocolo(), TableTypeEnum.MOVEMENT); vo.addMessage(BaseODSFncVO.C_MESSAGE_SUCESS); } public static void approveimport(Long impCode, String userID){ OracleTplDataSubscptDAO dataDao = new OracleTplDataSubscptDAO(); OracleTplInfoSubscptImpDAO subDao = new OracleTplInfoSubscptImpDAO(); TplInfoSubscptImpEntityVO impSubscriptMov = subDao.searchImpSubscript(impCode, TableTypeEnum.MOVEMENT); if (impSubscriptMov!= null){//is never supposed to be null impSubscriptMov.setTableType(TableTypeEnum.EFFECTIVE); impSubscriptMov.setLastApprvDate(new Date()); impSubscriptMov.setLastApprvUserId(userID); subDao.insert(impSubscriptMov); List<TplDataSubscptEntityVO> dataSubscrpts = dataDao.searchDataSubscrptImportCode(impCode, TableTypeEnum.MOVEMENT); if (dataSubscrpts!= null){ for (TplDataSubscptEntityVO vo : dataSubscrpts){ FundSubscriptionImportDetailFnc.defineFund(userID, vo, vo.getFundNameText(), true); insertDataSubscrpt(dataDao, vo, userID, vo.getEnrollment()); } } subDao.delete(impCode, TableTypeEnum.MOVEMENT); } } }
package alien4cloud.paas.wf; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.elasticsearch.common.collect.Lists; import org.elasticsearch.common.collect.Maps; import alien4cloud.exception.AlreadyExistException; import alien4cloud.model.components.Operation; import alien4cloud.model.topology.NodeTemplate; import alien4cloud.model.topology.RelationshipTemplate; import alien4cloud.paas.plan.ToscaNodeLifecycleConstants; import alien4cloud.paas.wf.WorkflowsBuilderService.TopologyContext; import alien4cloud.paas.wf.exception.BadWorkflowOperationException; import alien4cloud.paas.wf.exception.InconsistentWorkflowException; import alien4cloud.paas.wf.util.WorkflowUtils; public abstract class AbstractWorkflowBuilder { public abstract void addNode(Workflow wf, String nodeId, TopologyContext toscaTypeFinder, boolean isCompute); public abstract void addRelationship(Workflow wf, String nodeId, NodeTemplate nodeTemplate, RelationshipTemplate RelationshipTemplate, TopologyContext toscaTypeFinder); public void removeEdge(Workflow wf, String from, String to) { AbstractStep fromStep = wf.getSteps().get(from); if (fromStep == null) { throw new InconsistentWorkflowException(String.format( "Inconsistent workflow: a step nammed '%s' can not be found while it's referenced else where ...", from)); } AbstractStep toStep = wf.getSteps().get(to); if (toStep == null) { throw new InconsistentWorkflowException(String.format( "Inconsistent workflow: a step nammed '%s' can not be found while it's referenced else where ...", to)); } fromStep.getFollowingSteps().remove(to); toStep.getPrecedingSteps().remove(from); } public void connectStepFrom(Workflow wf, String stepId, String[] stepNames) { AbstractStep to = wf.getSteps().get(stepId); if (to == null) { throw new InconsistentWorkflowException(String.format( "Inconsistent workflow: a step nammed '%s' can not be found while it's referenced else where ...", stepId)); } for (String preceding : stepNames) { AbstractStep precedingStep = wf.getSteps().get(preceding); if (precedingStep == null) { throw new InconsistentWorkflowException(String.format( "Inconsistent workflow: a step nammed '%s' can not be found while it's referenced else where ...", preceding)); } WorkflowUtils.linkSteps(precedingStep, to); } } public void connectStepTo(Workflow wf, String stepId, String[] stepNames) { AbstractStep from = wf.getSteps().get(stepId); if (from == null) { throw new InconsistentWorkflowException(String.format( "Inconsistent workflow: a step nammed '%s' can not be found while it's referenced else where ...", stepId)); } for (String following : stepNames) { AbstractStep followingStep = wf.getSteps().get(following); if (followingStep == null) { // TODO throw ex } WorkflowUtils.linkSteps(from, followingStep); } } // private Set<String> getAllChildrenHierarchy(PaaSNodeTemplate paaSNodeTemplate) { // Set<String> nodeIds = new HashSet<String>(); // recursivelyPopulateChildrenHierarchy(paaSNodeTemplate, nodeIds); // return nodeIds; // } // // private void recursivelyPopulateChildrenHierarchy(PaaSNodeTemplate paaSNodeTemplate, Set<String> nodeIds) { // nodeIds.add(paaSNodeTemplate.getId()); // List<PaaSNodeTemplate> children = paaSNodeTemplate.getChildren(); // if (children != null) { // for (PaaSNodeTemplate child : children) { // recursivelyPopulateChildrenHierarchy(child, nodeIds); // } // } // } protected AbstractStep eventuallyAddStdOperationStep(Workflow wf, AbstractStep lastStep, String nodeId, String operationName, TopologyContext topologyContext, boolean forceOperation) { NodeTemplate nodeTemplate = topologyContext.getTopology().getNodeTemplates().get(nodeId); // FIXME: should we browse hierarchy ? Operation operation = WorkflowUtils.getOperation(nodeTemplate.getType(), ToscaNodeLifecycleConstants.STANDARD, operationName, topologyContext); // for compute all std operations are added, for others, only those having artifacts if ((operation != null && operation.getImplementationArtifact() != null) || forceOperation) { lastStep = appendOperationStep(wf, lastStep, nodeId, ToscaNodeLifecycleConstants.STANDARD, operationName); } return lastStep; } protected NodeActivityStep appendStateStep(Workflow wf, AbstractStep lastStep, String nodeId, String stateName) { NodeActivityStep step = WorkflowUtils.addStateStep(wf, nodeId, stateName); WorkflowUtils.linkSteps(lastStep, step); return step; } protected NodeActivityStep insertStateStep(Workflow wf, AbstractStep lastStep, String nodeId, String stateName) { NodeActivityStep step = WorkflowUtils.addStateStep(wf, nodeId, stateName); WorkflowUtils.linkSteps(step, lastStep); return step; } protected NodeActivityStep addActivityStep(Workflow wf, String nodeId, AbstractActivity activity) { NodeActivityStep step = new NodeActivityStep(); step.setNodeId(nodeId); step.setActivity(activity); step.setName(WorkflowUtils.buildStepName(wf, step, 0)); wf.addStep(step); return step; } protected NodeActivityStep appendOperationStep(Workflow wf, AbstractStep lastStep, String nodeId, String interfaceName, String operationName) { NodeActivityStep step = WorkflowUtils.addOperationStep(wf, nodeId, interfaceName, operationName); WorkflowUtils.linkSteps(lastStep, step); return step; } protected NodeActivityStep insertOperationStep(Workflow wf, AbstractStep previousStep, String nodeId, String interfaceName, String operationName) { NodeActivityStep step = WorkflowUtils.addOperationStep(wf, nodeId, interfaceName, operationName); WorkflowUtils.linkSteps(step, previousStep); return step; } protected void unlinkSteps(AbstractStep from, AbstractStep to) { from.removeFollowing(to.getName()); to.removePreceding(from.getName()); } protected boolean isOperationStep(NodeActivityStep defaultStep, String interfaceName, String operationName) { if (defaultStep.getActivity() instanceof OperationCallActivity) { OperationCallActivity oet = (OperationCallActivity) defaultStep.getActivity(); if (oet.getInterfaceName().equals(interfaceName) && oet.getOperationName().equals(operationName)) { return true; } } return false; } /** * @param wf * @param relatedStepId if specified, the step will be added near this one (maybe before) * @param before if true, the step will be added before the relatedStepId * @param activity */ public void addActivity(Workflow wf, String relatedStepId, boolean before, AbstractActivity activity, TopologyContext topologyContext) { if (WorkflowUtils.isNativeNode(activity.getNodeId(), topologyContext)) { throw new BadWorkflowOperationException("Activity can not be added for abstract nodes"); } if (relatedStepId != null) { if (before) { // insert insertActivityStep(wf, relatedStepId, activity); } else { // append appendActivityStep(wf, relatedStepId, activity); } } else { addActivityStep(wf, activity.getNodeId(), activity); } } public void insertActivityStep(Workflow wf, String stepId, AbstractActivity activity) { AbstractStep lastStep = wf.getSteps().get(stepId); String stepBeforeId = null; if (lastStep.getPrecedingSteps() != null && lastStep.getPrecedingSteps().size() == 1) { stepBeforeId = lastStep.getPrecedingSteps().iterator().next(); } NodeActivityStep insertedStep = addActivityStep(wf, activity.getNodeId(), activity); WorkflowUtils.linkSteps(insertedStep, lastStep); if (stepBeforeId != null) { AbstractStep stepBefore = wf.getSteps().get(stepBeforeId); unlinkSteps(stepBefore, lastStep); WorkflowUtils.linkSteps(stepBefore, insertedStep); } } public void appendActivityStep(Workflow wf, String stepId, AbstractActivity activity) { AbstractStep lastStep = wf.getSteps().get(stepId); String stepAfterId = null; if (lastStep.getFollowingSteps() != null && lastStep.getFollowingSteps().size() == 1) { stepAfterId = lastStep.getFollowingSteps().iterator().next(); } NodeActivityStep insertedStep = addActivityStep(wf, activity.getNodeId(), activity); WorkflowUtils.linkSteps(lastStep, insertedStep); if (stepAfterId != null) { AbstractStep stepAfter = wf.getSteps().get(stepAfterId); unlinkSteps(lastStep, stepAfter); WorkflowUtils.linkSteps(insertedStep, stepAfter); } } public void removeStep(Workflow wf, String stepId, boolean force) { AbstractStep step = wf.getSteps().remove(stepId); if (step == null) { throw new InconsistentWorkflowException(String.format( "Inconsistent workflow: a step nammed '%s' can not be found while it's referenced else where ...", stepId)); } if (!force && step instanceof NodeActivityStep && ((NodeActivityStep) step).getActivity() instanceof DelegateWorkflowActivity) { throw new BadWorkflowOperationException("Native steps can not be removed from workflow"); } if (step.getPrecedingSteps() != null) { if (step.getFollowingSteps() != null) { // connect all preceding to all following for (String precedingId : step.getPrecedingSteps()) { AbstractStep preceding = wf.getSteps().get(precedingId); for (String followingId : step.getFollowingSteps()) { AbstractStep following = wf.getSteps().get(followingId); WorkflowUtils.linkSteps(preceding, following); } } } for (Object precedingId : step.getPrecedingSteps().toArray()) { AbstractStep preceding = wf.getSteps().get(precedingId); unlinkSteps(preceding, step); } } if (step.getFollowingSteps() != null) { for (Object followingId : step.getFollowingSteps().toArray()) { AbstractStep following = wf.getSteps().get(followingId); unlinkSteps(step, following); } } } public void renameStep(Workflow wf, String stepId, String newStepName) { if (wf.getSteps().containsKey(newStepName)) { throw new AlreadyExistException(String.format("A step nammed ''{0}'' already exists", newStepName)); } AbstractStep step = wf.getSteps().remove(stepId); step.setName(newStepName); wf.getSteps().put(newStepName, step); // now explore the links if (step.getPrecedingSteps() != null) { for (String precedingId : step.getPrecedingSteps()) { AbstractStep precedingStep = wf.getSteps().get(precedingId); precedingStep.getFollowingSteps().remove(stepId); precedingStep.getFollowingSteps().add(newStepName); } } if (step.getFollowingSteps() != null) { for (String followingId : step.getFollowingSteps()) { AbstractStep followingStep = wf.getSteps().get(followingId); followingStep.getPrecedingSteps().remove(stepId); followingStep.getPrecedingSteps().add(newStepName); } } } public void removeNode(Workflow wf, String nodeName) { AbstractStep[] steps = new AbstractStep[wf.getSteps().size()]; steps = wf.getSteps().values().toArray(steps); for (AbstractStep step : steps) { if (step instanceof NodeActivityStep && ((NodeActivityStep) step).getNodeId().equals(nodeName)) { removeStep(wf, step.getName(), true); } } } /** * When a relationship is removed, we remove all links between src and target. * <p> * TODO : a better implem should be to just remove the links that rely to this relationship. But to do this, we have to associate the link with the * relationship (when the link is created consecutively to a relationship add). * * @param wf * @param paaSTopology * @param paaSNodeTemplate * @param relationhipTarget */ public void removeRelationship(Workflow wf, String nodeId, String relationhipTarget) { Iterator<AbstractStep> steps = wf.getSteps().values().iterator(); while(steps.hasNext()) { AbstractStep step = steps.next(); if (step instanceof NodeActivityStep && ((NodeActivityStep) step).getNodeId().equals(nodeId)) { if (step.getFollowingSteps() != null) { Object[] followingStepIds = step.getFollowingSteps().toArray(); for (Object followingId : followingStepIds) { AbstractStep followingStep = wf.getSteps().get(followingId); if (followingStep instanceof NodeActivityStep && ((NodeActivityStep) followingStep).getNodeId().equals(relationhipTarget)) { unlinkSteps(step, followingStep); } } } if (step.getPrecedingSteps() != null) { Object precedings[] = step.getPrecedingSteps().toArray(); for (Object precedingId : precedings) { AbstractStep precedingStep = wf.getSteps().get(precedingId); if (precedingStep instanceof NodeActivityStep && ((NodeActivityStep) precedingStep).getNodeId().equals(relationhipTarget)) { unlinkSteps(precedingStep, step); } } } } } } /** * Swap steps means: * <ul> * <li>The connection between step and target is inverted. * <li>All step's predecessors become predecessors of target & vice versa * <li>All step's followers become followers of target & vice versa * </ul> * That's all folks ! */ public void swapSteps(Workflow wf, String stepId, String targetId) { AbstractStep step = wf.getSteps().get(stepId); AbstractStep target = wf.getSteps().get(targetId); unlinkSteps(step, target); List<AbstractStep> stepPredecessors = removePredecessors(wf, step); List<AbstractStep> stepFollowers = removeFollowers(wf, step); List<AbstractStep> targetPredecessors = removePredecessors(wf, target); List<AbstractStep> targetFollowers = removeFollowers(wf, target); associateFollowers(step, targetFollowers); associateFollowers(target, stepFollowers); associatePredecessors(step, targetPredecessors); associatePredecessors(target, stepPredecessors); WorkflowUtils.linkSteps(target, step); } private void associatePredecessors(AbstractStep step, List<AbstractStep> stepPredecessors) { for (AbstractStep predecessor : stepPredecessors) { WorkflowUtils.linkSteps(predecessor, step); } } private void associateFollowers(AbstractStep step, List<AbstractStep> stepFollowers) { for (AbstractStep follower : stepFollowers) { WorkflowUtils.linkSteps(step, follower); } } private List<AbstractStep> removePredecessors(Workflow wf, AbstractStep step) { List<AbstractStep> result = Lists.newArrayList(); if (step.getPrecedingSteps() == null || step.getPrecedingSteps().size() == 0) { return result; } Object precedings[] = step.getPrecedingSteps().toArray(); for (Object precedingId : precedings) { AbstractStep precedingStep = wf.getSteps().get(precedingId); unlinkSteps(precedingStep, step); result.add(precedingStep); } return result; } private List<AbstractStep> removeFollowers(Workflow wf, AbstractStep step) { List<AbstractStep> result = Lists.newArrayList(); if (step.getFollowingSteps() == null || step.getFollowingSteps().size() == 0) { return result; } Object followings[] = step.getFollowingSteps().toArray(); for (Object followingId : followings) { AbstractStep followingStep = wf.getSteps().get(followingId); unlinkSteps(step, followingStep); result.add(followingStep); } return result; } public void renameNode(Workflow wf, String oldName, String newName) { if (wf.getSteps() != null) { for (AbstractStep step : wf.getSteps().values()) { if (step instanceof NodeActivityStep && ((NodeActivityStep) step).getNodeId().equals(oldName)) { ((NodeActivityStep) step).setNodeId(newName); ((NodeActivityStep) step).getActivity().setNodeId(newName); } } } } public Workflow reinit(Workflow wf, TopologyContext toscaTypeFinder) { Map<String, AbstractStep> steps = Maps.newHashMap(); wf.setSteps(steps); if (toscaTypeFinder.getTopology().getNodeTemplates() != null) { // first stage : add the nodes for (Entry<String, NodeTemplate> entry : toscaTypeFinder.getTopology().getNodeTemplates().entrySet()) { String nodeId = entry.getKey(); boolean forceOperation = WorkflowUtils.isComputeOrVolume(nodeId, toscaTypeFinder); addNode(wf, nodeId, toscaTypeFinder, forceOperation); } // second stage : add the relationships for (Entry<String, NodeTemplate> entry : toscaTypeFinder.getTopology().getNodeTemplates().entrySet()) { String nodeId = entry.getKey(); if (entry.getValue().getRelationships() != null) { for (RelationshipTemplate relationshipTemplate : entry.getValue().getRelationships().values()) { addRelationship(wf, nodeId, entry.getValue(), relationshipTemplate, toscaTypeFinder); } } } } return wf; } }
package com.learn.leetcode.week4; import java.util.HashSet; import java.util.Set; /** * 给定一个整数数组,判断是否存在重复元素。 * * 如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。 */ public class SolutionContainsDuplicate { public static boolean containsDuplicate(int[] nums) { Set<Integer> s = new HashSet<>(); for (int i = 0; i < nums.length; i++) { if(s.contains(nums[i])) return false; s.add(nums[i]); } return true; } }
package bank.test.david; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.slf4j.Logger; @Component public class Receiver { private final Logger logger = (Logger) LoggerFactory.getLogger(Receiver.class); public CalcResult handleMessage(Request message) throws Exception{ try{ return new CalcResult().calculate(message.getfirstNumber(), message.getSecondNumber()); } catch(Exception ex) { logger.error("error calculating data", ex); throw ex; } } }
package com.developworks.base; import org.junit.Test; /** * <p>Title: </p> * <p>Description: </p> * <p>Author: ouyp </p> * <p>Date: 2018-05-08 15:30</p> */ public class TryExceptionPuzzles { @Test public void f1() { try{ System.out.println("hello world"); }catch (RuntimeException e) { //}catch (IOException e) {//无法编译成功 System.out.println("catch block!"); } } @Test public void f2() { try{ //System.out.println("hello world"); }catch (Exception e) {//无法编译成功 System.out.println("catch block!"); } } @Test public void f3() { T4 t4 = new T4(); t4.f1(); } interface T1 { void f1() throws ClassNotFoundException; } interface T2 { void f1() throws InterruptedException; } interface T3 extends T1, T2{ } class T4 implements T3 { public void f1() {//一个方法可以抛出的被检查异常集合是它所适用的所有类型声明要抛出的被检查异常集合的交集,而不是合集。因此,静态类型为 Type3 的对象上的 f 方法根本就不能抛出任何被检查异常。 System.out.println("hello world!"); } } }
package com.trump.auction.trade.dao; import com.trump.auction.trade.domain.RobotInfo; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Service; import java.util.List; /** * 机器人 * * @author zhangliyan * @create 2018-01-02 17:48 **/ @Service public interface RobotInfoDao { /** * 添加 * @param robotInfo * @return */ Integer insertRobot(RobotInfo robotInfo); /** * 修改 * @param robotInfo * @return */ int saveUpdateRobot(RobotInfo robotInfo); /** * 删除 * @param ids * @return */ int deleteRobot(String[] ids); /** * 列表 * @return */ List<RobotInfo> findRobotInfo(@Param("start") Integer start,@Param("end") Integer end); }
public class prob1 { int result[] = new int[2]; public int[] twoSum(int[] nums, int target) { outerloop: for(int i =0; i<nums.length; i++) { for(int j = i+1; j<nums.length; j++) { if(nums[i]+ nums[j]== target) { int result[] = {i,j}; break outerloop; } } } return result; } public static void main(String[] args) { prob1 pb = new prob1(); int nums[] = {2,1,6,5}; pb.twoSum( nums, 7); } }
package org.juxtasoftware.model; import java.util.HashSet; import java.util.Set; /** * Data used to generate the histogram * @author loufoster * */ public class VisualizationInfo { private final ComparisonSet set; private final Witness base; private final Set<Long> witnesses = new HashSet<Long>(); public VisualizationInfo(ComparisonSet set, Witness base, Set<Long> witnessFilterList ) { this.base = base; this.witnesses.addAll(witnessFilterList); this.set = set; } public long getKey() { return (long)hashCode(); } public ComparisonSet getSet() { return this.set; } public Witness getBase() { return this.base; } public Set<Long> getWitnessFilter() { return this.witnesses; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((base == null) ? 0 : base.hashCode()); result = prime * result + ((set == null) ? 0 : set.hashCode()); result = prime * result + ((witnesses == null) ? 0 : witnesses.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; VisualizationInfo other = (VisualizationInfo) obj; if (base == null) { if (other.base != null) return false; } else if (!base.equals(other.base)) return false; if (set == null) { if (other.set != null) return false; } else if (!set.equals(other.set)) return false; if (witnesses == null) { if (other.witnesses != null) return false; } else if (!witnesses.equals(other.witnesses)) return false; return true; } @Override public String toString() { return "VisualizationInfo [set=" + set + ", base=" + base + ", witnesses=" + witnesses + "] = KEY: " +getKey(); } }
package org.musicbrainz.model; public abstract interface EntityFactory {}
package com.exam.logic.actions.profile; import com.exam.logic.Action; import com.exam.logic.services.PhotoService; import com.exam.logic.services.PostService; import com.exam.logic.services.ProfileService; import com.exam.logic.services.UserService; import com.exam.models.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import static com.exam.logic.Constants.*; public class ProfileAction implements Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) { UserService userService = (UserService) request.getServletContext().getAttribute(USER_SERVICE); User currentUser = (User) request.getSession().getAttribute(CURRENT_USER); User user = Optional.ofNullable(request.getParameter("id")) .map(Long::parseLong) .flatMap(userService::getById) .map(user1 -> { Relation relation = userService.getRelation(currentUser.getId(), user1.getId()); request.setAttribute(RELATION_TYPE, relation.getType()); return user1; }) .orElse(currentUser); request.setAttribute("user", user); ProfileService profileService = (ProfileService) request.getServletContext().getAttribute(PROFILE_SERVICE); Profile profile = profileService.getById(user.getId()); request.setAttribute("profile", profile); PhotoService photoService = (PhotoService) request.getServletContext().getAttribute(PHOTO_SERVICE); Optional<Photo> avaOptional = photoService.getUserAva(profile.getId()); avaOptional.ifPresent(ava -> request.setAttribute("avatar", ava)); int offset = Optional.ofNullable(request.getParameter(OFFSET)) .map(Integer::parseInt) .orElse(0); request.setAttribute(OFFSET, offset); int limit = Optional.ofNullable(request.getParameter(LIMIT)) .filter(s -> s.length() > 0) .map(Integer::parseInt) .orElse(DEFAULT_LIMIT); request.setAttribute(LIMIT, limit); PostService postService = (PostService) request.getServletContext().getAttribute(POST_SERVICE); List<Post> postList = postService.getPosts(profile.getId(), offset, limit); request.setAttribute(POST_LIST, postList); boolean hasNextPage = postService.hasNextPage(profile.getId(), offset, limit); request.setAttribute(HAS_NEXT_PAGE, hasNextPage); Map<Long, User> userMap = postList.stream() .map(Post::getSender) .map(userService::getById) .map(Optional::get) .collect(Collectors.toMap( User::getId, s -> s, (id1, id2) -> id1)); request.setAttribute(USER_MAP, userMap); Map<Long, String> minAvatars = postList.stream() .map(Post::getSender) .map(photoService::getUserAva) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toMap( Photo::getSender, Photo::getLinkOfMinPhoto, (f1, f2) -> f1)); request.setAttribute(MIN_AVATARS, minAvatars); return "/WEB-INF/jsp/profile/profile.jsp"; } }
package com.vti.frontend; import com.vti.backent.Exercise_1; import com.vti.backent.Exercise_2; import com.vti.backent.Exercise_3; import com.vti.backent.Exercise_4; import com.vti.backent.Exercise_5; public class Program_1 { public static void main(String[] args) { // Exercise_1 ex1 = new Exercise_1(); // ex1.question_1(); // // ex1.question_2(); // // ex1.question_3(); // // ex1.question_4(); // // Exercise_2 ex2 = new Exercise_2(); // ex2.question_1(); // Exercise_3 ex3 = new Exercise_3(); // ex3.question_1(); // // ex3.question_2(); // // ex3.question_3(); Exercise_4 ex4 = new Exercise_4(); // ex4.question_1(); // ex4.question_2(); // ex4.question_3(); // ex4.question_4(); // ex4.question_5(); // ex4.question_8(); // ex4.question_9(); Exercise_5 ex5 = new Exercise_5(); ex5.question_1(); } }
package cern.molr.inspector.remote; import cern.molr.inspector.controller.JdiController; import org.junit.Before; import org.junit.Test; import java.io.*; import java.time.Duration; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class JdiControllerReaderWriterTest { private static final Duration ONE_MILLISECOND = Duration.ofMillis(1); private JdiController mockedController; private JdiControllerWriter writer; @Before public void setup() throws IOException { mockedController = mock(JdiController.class); PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = new PipedOutputStream(inputStream); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); PrintWriter printWriter = new PrintWriter(outputStream); writer = new JdiControllerWriter(printWriter){}; new JdiControllerReader(bufferedReader, mockedController, ONE_MILLISECOND); } @Test public void forwardsStepCommands() throws InterruptedException { writer.stepForward(); Thread.sleep(100); verify(mockedController).stepForward(); } @Test public void forwardsTerminateCommands() throws InterruptedException { writer.terminate(); Thread.sleep(100); verify(mockedController).terminate(); } }
package week06d05; import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public class BottleTest { @Test public void testConstructorNull() throws IllegalArgumentException { Exception exception = assertThrows(IllegalArgumentException.class, () -> new Bottle(null)); assertEquals("Type can't be null", exception.getMessage()); } @Test public void testStaticOf() { assertEquals(BottleType.GLASS_BOTTLE, Bottle.of(BottleType.GLASS_BOTTLE).getType()); assertEquals(BottleType.PET_BOTTLE, Bottle.of(BottleType.PET_BOTTLE).getType()); } @Test public void testFill() throws IllegalStateException { Bottle bottle = Bottle.of(BottleType.PET_BOTTLE); bottle.fill(300); assertEquals(300, bottle.getFilledUntil()); bottle.fill(200); assertEquals(BottleType.PET_BOTTLE.getMaximumAmount(), bottle.getFilledUntil()); Exception exception = assertThrows(IllegalStateException.class, () -> bottle.fill(1)); assertEquals("Bottle overfilled.", exception.getMessage()); } }
package com.test.processor; import com.test.task.Task; import java.util.concurrent.Future; public interface TaskProcessor { Future<String> calculate(Task task); int getThreadPoolCapacity(); void shutdown(); }
package com.example.elite.telephonereport; import android.content.DialogInterface; import android.os.Handler; import android.os.Message; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class AdminSignUpActivity extends AppCompatActivity { private EditText username,password; private Button signup; public final int business_conflict = 1;//用户已存在 public final int success = 2;//成功 //成功后的弹框 private AlertDialog alert = null; private AlertDialog.Builder builder = null; //处理子线程向主线程传递的数据 private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case success://成功,弹框提示 builder = new AlertDialog.Builder(AdminSignUpActivity.this); alert = builder.setMessage("sign up was successful") .setPositiveButton("sure", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AdminSignUpActivity.this.finish(); } }).setCancelable(false).create(); alert.show(); break; case business_conflict://用户已存在 Toast.makeText(AdminSignUpActivity.this,"User already exists",Toast.LENGTH_SHORT).show(); username.setText(""); password.setText(""); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin_sign_up); username = findViewById(R.id.admin_signup_username); password = findViewById(R.id.admin_signup_password); signup = findViewById(R.id.admin_signup); signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!username.getText().toString().equals("")&&!password.getText().toString().equals("")) { //向数据库传递用户名和密码 sendInfo(); } else { //username和password不能为空 Toast.makeText(AdminSignUpActivity.this,"Username and password cannot be empty",Toast.LENGTH_SHORT).show(); username.setText(""); password.setText(""); } } }); } private void sendInfo() { //新开一个线程 new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null;//连接 BufferedReader reader = null; try { URL url = new URL("http://10.242.39.104:8080/businessSignUp");//地址 connection = (HttpURLConnection) url.openConnection();//打开 connection.setConnectTimeout(8000); connection.setReadTimeout(8000); connection.setRequestMethod("POST"); connection.connect(); OutputStream out = connection.getOutputStream();//输出流 String paramsString = "name=" + username.getText().toString() + "&pass=" + password.getText().toString();//传递用户名和密码 out.write(paramsString.getBytes()); out.flush(); out.close();//关闭 InputStream in = connection.getInputStream();//返回流 reader = new BufferedReader(new InputStreamReader(in)); StringBuffer respond = new StringBuffer(); String line; //获取数据 while ((line = reader.readLine()) != null) { respond.append(line); } //转化为JSON格式 JSONObject jsonObject = new JSONObject(respond.toString()); //获取results的值 String result = jsonObject.getString("results"); Message msg = new Message(); if (result.equals("success")) { msg.what = success; handler.sendMessage(msg); } else { msg.what = business_conflict; handler.sendMessage(msg); } }catch (Exception e) { e.printStackTrace(); }finally { if(reader != null) { try { reader.close(); }catch (Exception e) { e.printStackTrace(); } } if(connection != null) { connection.disconnect(); } } } }).start(); } }
package nxpense.service; import nxpense.domain.Attachment; import nxpense.domain.Expense; import nxpense.exception.ServerException; import nxpense.service.api.AttachmentService; import nxpense.service.api.ExpenseService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.IOException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; @Service public class AttachmentServiceImpl implements AttachmentService { private static final Logger LOGGER = LoggerFactory.getLogger(AttachmentServiceImpl.class); @Value("${attachmentDir}") private String attachmentDir; @Autowired private ExpenseService expenseService; @Override public void createAttachment(Integer expenseId, String filename) { Path attachmentPath = Paths.get(attachmentDir, expenseId.toString(), filename); if (Files.notExists(attachmentPath, LinkOption.NOFOLLOW_LINKS)) { LOGGER.info("Requested attachment does not exist on disk -> to be created"); try { Files.createDirectories(Paths.get(attachmentDir, expenseId.toString())); Files.createFile(attachmentPath); Expense expense = expenseService.getExpense(expenseId); List<Attachment> attachments = expense.getAttachments().stream().filter(a -> a.getFilename().equals(filename)).collect(Collectors.toList()); Files.write(attachmentPath, attachments.get(0).getByteContent(), LinkOption.NOFOLLOW_LINKS); } catch (IOException e) { throw new ServerException("An error occurred making the requested attachment available", e); } } } @Override public void deleteAttachment(Integer expenseId, String filename) { Path pathToDelete = Paths.get(attachmentDir, expenseId.toString(), filename); try { Files.delete(pathToDelete); } catch (IOException e) { LOGGER.error("Failed deleting attachment with path= {}", pathToDelete, e); } } }
package net.lantrack.framework.sysbase.entity; import net.lantrack.framework.core.entity.BaseEntity; import org.springframework.context.annotation.Description; /** * 用户职务表 * 2018年1月16日 * @author lin */ public class Duty extends BaseEntity<Duty> { /** * id */ private Integer id; /** * 职务名称 */ private String dutyName; /** * 部门名称 */ private String officeName; /** * 部门id */ private String officeId; /** * 是否可授权 */ private String ifAuth = BaseEntity.NO; private static final long serialVersionUID = 1L; public Duty(Integer id, String dutyName, String officeName, String officeId, String ifAuth, String createBy, String createDate, String updateBy, String updateDate, String remarks, String delFlag) { super(createBy, createDate, updateBy, updateDate, remarks, delFlag); this.id = id; this.dutyName = dutyName; this.officeName = officeName; this.officeId = officeId; this.ifAuth = ifAuth; } public Duty() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Description("职务名称") public String getDutyName() { return dutyName; } public void setDutyName(String dutyName) { this.dutyName = dutyName == null ? null : dutyName.trim(); } @Description("部门名称") public String getOfficeName() { return officeName; } public void setOfficeName(String officeName) { this.officeName = officeName == null ? null : officeName.trim(); } @Description("部门id") public String getOfficeId() { return officeId; } public void setOfficeId(String officeId) { this.officeId = officeId == null ? null : officeId.trim(); } @Description("是否可授权") public String getIfAuth() { return ifAuth; } public void setIfAuth(String ifAuth) { this.ifAuth = ifAuth == null ? null : ifAuth.trim(); } @Override public String toString() { return "Duty [id=" + id + ", dutyName=" + dutyName + ", officeName=" + officeName + ", officeId=" + officeId + ", ifAuth=" + ifAuth + "]"; } }
package Testcase; import static org.junit.Assert.fail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.By; import com.Core.BaseClass; import com.Core.CommFunc; import com.csvreader.CsvReader; import TestScript.ControlsStockTS; import java.nio.charset.Charset; /** * @author Lili.Sun * @date 2015年6月9日 上午10:53:53 * */ public class ControlsStockTest extends BaseClass{ private static final Logger log = LoggerFactory.getLogger(ControlsStockTest.class); @BeforeClass public static void testAddStock() throws Exception { ControlsStockTS.addStock(driver); } @Test public void testInputBox() throws Exception { log.info("***Run case of testInputBox.***"); PrintFlag = true; //输入框测试 try { String filePath = CommFunc.getTestDataFile(); CsvReader reader = new CsvReader(filePath,',',Charset.forName("UTF-8")); log.info(filePath); reader.readHeaders(); while (reader.readRecord()) { ControlsStockTS.controlsStock(driver, reader); } } catch (Exception e) { log.error("InputBox is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } @Test public void testDateControl() throws Exception { log.info("***Run case of testDateControl.***"); PrintFlag = true; //日期控件测试 try { CommFunc.highlightElement(driver,driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[2]/td[4]/span"))); driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[2]/td[4]/span")).click(); driver.findElement(By.xpath("//iframe[@border='0']")); driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@border='0']"))); CommFunc.highlightElement(driver,driver.findElement(By.id("dpTodayInput"))); driver.findElement(By.id("dpTodayInput")).click(); driver.switchTo().defaultContent(); driver.switchTo().frame("ifrf"); } catch (Exception e) { log.error("DateControl is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } @Test public void testMultiSelect() throws Exception { log.info("***Run case of testMultiSelect.***"); PrintFlag = true; //多选下拉框测试 try { CommFunc.highlightElement(driver,driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[3]/td[4]/span/span/a"))); driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[3]/td[4]/span/span/a")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='_easyui_combobox_i5_2']"))); driver.findElement(By.xpath("//div[@id='_easyui_combobox_i5_2']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='_easyui_combobox_i5_6']"))); driver.findElement(By.xpath("//div[@id='_easyui_combobox_i5_6']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[4]/td[2]/span/input"))); driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[4]/td[2]/span/input")).clear(); driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[4]/td[2]/span/input")).sendKeys("15.9"); } catch (Exception e) { log.error("MultiSelect is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } @Test public void testSingleSelect() throws Exception { log.info("***Run case of testSingleSelect.***"); PrintFlag = true; //单选框下拉测试 try { CommFunc.highlightElement(driver,driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[4]/td[4]/span/span/a"))); driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[4]/td[4]/span/span/a")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='_easyui_combobox_i6_1']"))); driver.findElement(By.xpath("//div[@id='_easyui_combobox_i6_1']")).click(); } catch (Exception e) { log.error("SingleSelect is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } @Test public void testMultiSelectTree() throws Exception { log.info("***Run case of testMultiSelectTree.***"); PrintFlag = true; //多选树测试 try { CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='modify_div_AREA']"))); driver.findElement(By.xpath("//div[@id='modify_div_AREA']")).click(); Thread.sleep(1000); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='_easyui_tree_2']/span[@class='tree-checkbox tree-checkbox0']"))); driver.findElement(By.xpath("//div[@id='_easyui_tree_2']/span[@class='tree-checkbox tree-checkbox0']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='_easyui_tree_3']/span[@class='tree-checkbox tree-checkbox0']"))); driver.findElement(By.xpath("//div[@id='_easyui_tree_3']/span[@class='tree-checkbox tree-checkbox0']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@class='panel window'][2]"))); //driver.findElement(By.xpath("//div[@class='panel window'][2]")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='dia_modify_t_AREA']/div/table/tbody/tr[2]/td[2]/input[@id='selectTo']"))); driver.findElement(By.xpath("//div[@id='dia_modify_t_AREA']/div/table/tbody/tr[2]/td[2]/input[@id='selectTo']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@class='panel window'][2]/div[@class='dialog-button']/a/span/span"))); driver.findElement(By.xpath("//div[@class='panel window'][2]/div[@class='dialog-button']/a/span/span")).click(); } catch (Exception e) { log.error("MultiSelectTree is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } @Test public void testSingleSelectTree() throws Exception { log.info("***Run case of testSingleSelectTree.***"); PrintFlag = true; //单选树测试 try { CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='modify_div_DEPARTMENT']"))); driver.findElement(By.xpath("//div[@id='modify_div_DEPARTMENT']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@class='panel window'][2]"))); driver.findElement(By.xpath("//div[@class='panel window'][2]")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li"))); driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li/ul/li"))); driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li/ul/li")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li/ul/li/ul/li"))); driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li/ul/li/ul/li")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div/table/tbody/tr[2]/td[2]/input[@id='selectTo']"))); driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div/table/tbody/tr[2]/td[2]/input[@id='selectTo']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@class='panel window'][2]/div[@class='dialog-button']/a/span/span"))); driver.findElement(By.xpath("//div[@class='panel window'][2]/div[@class='dialog-button']/a/span/span")).click(); } catch (Exception e) { log.error("SingleSelectTree is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } }
package com.gaby.service.stu; import com.gaby.mybatis.auto.stu.entity.Student; import com.gaby.mybatis.base.service.BaseService; import com.gaby.stu.model.student.list.Item; import com.gaby.stu.model.student.query.Response; import java.util.List; import java.util.Map; public interface CustomStudentService extends BaseService<Student> { Response query(Map map); List<Item> list(); }
import java.io.*; import java.net.*; import java.util.*; import java.math.*; import java.text.*; import java.util.concurrent.ThreadLocalRandom; public class ChandyANDModel { public enum msgType { PROBE, DEADLOCK } public enum processType { ACTIVE, WAITING, DEADLOCKED } static Integer myId = 0; static Integer numProcess = 0; static ArrayList<String> ipList = new ArrayList<String>(); static ArrayList<ArrayList<Integer>> adjList = new ArrayList<ArrayList<Integer>>(); static ArrayList<ArrayList<Integer>> wfgList = new ArrayList<ArrayList<Integer>>(); static ArrayList<ArrayList<Integer>> routing = new ArrayList<ArrayList<Integer>>(); static HashSet<Integer> dependants = new HashSet<>(); static HashMap<Integer, Socket> socketMap = new HashMap<Integer, Socket>(); static HashSet<Integer> reqSent = new HashSet<Integer>(); static processType myType = processType.ACTIVE; static Boolean probeFlag = false; static Integer getHash(Integer x, Integer y) { return numProcess * Math.min(x, y) + Math.max(x, y) + 2000; } public static Boolean bfs(Integer curr) { Integer cntVisited = 0; ArrayList<Boolean> visited = new ArrayList<Boolean>(); for(int i = 0; i < numProcess; i++) { visited.add(false); } routing.get(curr).set(curr, -1); visited.set(curr, true); cntVisited++; Queue<Integer> nodes = new LinkedList<Integer>(); nodes.add(-1); nodes.add(curr); while(!nodes.isEmpty()) { Integer par = nodes.poll(); Integer x = nodes.poll(); for(Integer neigh: adjList.get(x)) { if(!visited.get(neigh)) { if(par == -1) { nodes.add(curr); nodes.add(neigh); routing.get(curr).set(neigh, neigh); } else if(par == curr) { nodes.add(x); nodes.add(neigh); routing.get(curr).set(neigh, x); } else { nodes.add(par); nodes.add(neigh); routing.get(curr).set(neigh, par); } visited.set(neigh, true); cntVisited++; } } } return (cntVisited == numProcess); } static String makeMsg(Integer orig, Integer sender, Integer target, Integer flag) { return orig.toString() + " " + sender.toString() + " " + target.toString() + " " + flag.toString(); } static void sendDeadlockMsg(ArrayList<Integer> routing, Integer dest) throws IOException { String outMsg = makeMsg(myId, myId, dest, msgType.DEADLOCK.ordinal()); DataOutputStream dout = new DataOutputStream(socketMap.get(routing.get(dest)).getOutputStream()); dout.writeUTF(outMsg); dout.flush(); } static void handleDeadlock(ArrayList<Integer> routing) { if (myType == processType.DEADLOCKED) { return; } System.out.println("Deadlock detected"); myType = processType.DEADLOCKED; for(Integer x: dependants) { try { sendDeadlockMsg(routing, x); System.out.println((myId + 1) + " sent a DEADLOCK message to " + (x + 1)); } catch(Exception e) { continue; } } } static void dowork(ArrayList<Integer> routing) throws Exception { if(wfgList.get(myId).contains(myId)) { handleDeadlock(routing); } if (probeFlag) { for(Integer x: wfgList.get(myId)) { Integer intermediate = routing.get(x); String probeMsg = makeMsg(myId, myId, x, msgType.PROBE.ordinal()); DataOutputStream dout = new DataOutputStream(socketMap.get(intermediate).getOutputStream()); dout.writeUTF(probeMsg); System.out.println((myId + 1) + " sent a PROBE message to " + (x + 1)); dout.flush(); } } while(true) { for(Integer x: adjList.get(myId)) { String msg; try { DataInputStream dis = new DataInputStream(socketMap.get(x).getInputStream()); msg = (String)dis.readUTF(); } catch(Exception e) { //No message continue; } String[] inMsg = msg.split(" "); Integer orig = Integer.parseInt(inMsg[0]); Integer sender = Integer.parseInt(inMsg[1]); Integer target = Integer.parseInt(inMsg[2]); msgType type = msgType.values()[Integer.parseInt(inMsg[3])]; if (target != myId) { //I'm not the target, just forward String outMsg = makeMsg(orig, sender, target, type.ordinal()); DataOutputStream dout = new DataOutputStream(socketMap.get(routing.get(target)).getOutputStream()); dout.writeUTF(outMsg); dout.flush(); continue; } if (type == msgType.PROBE) { //It's a probe message System.out.println((myId + 1) + " received a PROBE message from " + (sender + 1)); if (orig == myId) { //I am the origin, so there's a deadlock handleDeadlock(routing); } else if (myType == processType.DEADLOCKED) { sendDeadlockMsg(routing, sender); System.out.println((myId + 1) + " sent a DEADLOCK message to " + (sender + 1)); } else if (myType == processType.WAITING) { //I got a probe message, probe all those that I depend upon if not already done if (!reqSent.contains(orig)) { //First one for (Integer wf: wfgList.get(myId)) { Integer intermediate = routing.get(wf); String probeMsg = makeMsg(orig, myId, wf, msgType.PROBE.ordinal()); DataOutputStream dout = new DataOutputStream(socketMap.get(intermediate).getOutputStream()); dout.writeUTF(probeMsg); dout.flush(); System.out.println((myId + 1) + " sent a PROBE message to " + (wf + 1)); } } dependants.add(orig); dependants.add(sender); reqSent.add(orig); } } else { //Flag is 1 now, it's a deadlock message System.out.println((myId + 1) + " received a DEADLOCK message from " + (sender + 1)); handleDeadlock(routing); } } } } static ArrayList<ArrayList<Integer>> getList(Boolean isDirected, BufferedReader inReader) throws IOException { ArrayList<ArrayList<Integer>> adjList = new ArrayList<ArrayList<Integer>>(); while(adjList.size() < numProcess) { adjList.add(new ArrayList<Integer>()); } for (Integer i = 0; i < numProcess; i++) { String tempLine; tempLine = inReader.readLine(); String[] nums = tempLine.split(" "); Integer curr = Integer.parseInt(nums[0]); curr--; for(Integer j = 1; j < nums.length; j++) { Integer x = Integer.parseInt(nums[j]); x--; adjList.get(curr).add(x); if(!isDirected) { adjList.get(x).add(curr); } } } return adjList; } public static void main(String[] args) throws Exception { if(args.length != 2) { System.out.println("Usage: java ChandyANDModel <id> <Probe flag>"); System.exit(-1); } myId = Integer.parseInt(args[0]); myId--; if(Integer.parseInt(args[1]) == 1) { probeFlag = true; } BufferedReader inReader = new BufferedReader(new FileReader("inp-params.txt")); String tempLine = inReader.readLine(); String[] nums = tempLine.split(" "); numProcess = Integer.parseInt(nums[0]); for (Integer i = 0; i < numProcess; i++) { tempLine = inReader.readLine(); nums = tempLine.split(" "); ipList.add(nums[2]); } while(adjList.size() < numProcess) { adjList.add(new ArrayList<Integer>()); wfgList.add(new ArrayList<Integer>()); routing.add(new ArrayList<Integer>()); } adjList = getList(false, inReader); wfgList = getList(true, inReader); for(int i = 0; i < numProcess; i++) { //Making adjacency lists unique HashSet<Integer> temp = new HashSet<>(); temp.addAll(adjList.get(i)); adjList.get(i).clear(); adjList.get(i).addAll(temp); Collections.sort(adjList.get(i)); temp = new HashSet<>(); temp.addAll(wfgList.get(i)); wfgList.get(i).clear(); wfgList.get(i).addAll(temp); for(int j = 0; j < numProcess; j++) { routing.get(i).add(0); } } //Routing needed for(Integer i = 0; i < numProcess; i++) { if(!bfs(i)) { System.out.println("Topology not connected"); System.exit(-1); } } for(Integer neigh: adjList.get(myId)) { //Establising connections if(neigh < myId) { while(true) { try { Socket s = new Socket(ipList.get(neigh), getHash(neigh, myId)); s.setSoTimeout(1000); socketMap.put(neigh, s); break; } catch (ConnectException e) { continue; } } } else { ServerSocket ss = new ServerSocket(getHash(neigh, myId)); Socket s = ss.accept(); s.setSoTimeout(1000); socketMap.put(neigh, s); } } if (wfgList.get(myId).size() > 0) { myType = processType.WAITING; } dowork(routing.get(myId)); } }
package com.eshop.models; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank; import com.eshop.exceptions.InvalidInputException; public abstract class Article { private String label; private String model; private double price; private String image; private int id; public Article(){ } public Article(String label, String model, double price, String image, int id) throws InvalidInputException { setLabel(label); setModel(model); setPrice(price); setImage(image); setId(id); } public int getId() { return id; } public void setId(int id) throws InvalidInputException { if(id>0) this.id = id; else throw new InvalidInputException(); } public double getPrice() { return price; } public void setPrice(double price) throws InvalidInputException { if (price > 0) { this.price = price; } else { throw new InvalidInputException("Invalid price!"); } } public String getLabel() { return label; } public void setLabel(String label) throws InvalidInputException { if (label != null && !label.isEmpty()) { this.label = label; } else { throw new InvalidInputException("Invalid label!"); } } public String getModel() { return model; } public void setModel(String model) throws InvalidInputException { if (model != null && !model.isEmpty()) { this.model = model; } else { throw new InvalidInputException("Invalid label!"); } } public String getImage() { return image; } public void setImage(String image) throws InvalidInputException { if(image != null && !image.isEmpty()) this.image = image; else throw new InvalidInputException("Invalid input!"); } @Override public String toString() { return "Article [label=" + label + ", model=" + model + ", price=" + price + ", image=" + image + "]"; } }
package com.ztstudio.ane.MobileMarket; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.util.Log; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; import com.adobe.fre.FREInvalidObjectException; import com.adobe.fre.FREObject; import com.adobe.fre.FRETypeMismatchException; import com.adobe.fre.FREWrongThreadException; public class SetScreenOffTime implements FREFunction { private String TAG = "SetScreenOffTime"; private FREContext _context; @Override public FREObject call(FREContext context, FREObject[] argv) { // TODO Auto-generated method stub _context = context; int time = 30000; try { time = argv[0].getAsInt(); } catch (IllegalStateException e) { // TODO Auto-generated catch block callBack(e.getMessage()); } catch (FRETypeMismatchException e) { // TODO Auto-generated catch block callBack(e.getMessage()); } catch (FREInvalidObjectException e) { // TODO Auto-generated catch block callBack(e.getMessage()); } catch (FREWrongThreadException e) { // TODO Auto-generated catch block callBack(e.getMessage()); } Settings.System.putInt(context.getActivity().getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, time); return null; } /** * 回调 结果传给AS端 */ public void callBack(String status) { Log.d(TAG, status); _context.dispatchStatusEventAsync(TAG, TAG + ":" + status); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.context.testng; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.lang.Nullable; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; /** * Abstract {@linkplain Transactional transactional} extension of * {@link AbstractTestNGSpringContextTests} which adds convenience functionality * for JDBC access. Expects a {@link DataSource} bean and a * {@link PlatformTransactionManager} bean to be defined in the Spring * {@linkplain ApplicationContext application context}. * * <p>This class exposes a {@link JdbcTemplate} and provides an easy way to * {@linkplain #countRowsInTable count the number of rows in a table} * (potentially {@linkplain #countRowsInTableWhere with a WHERE clause}), * {@linkplain #deleteFromTables delete from tables}, * {@linkplain #dropTables drop tables}, and * {@linkplain #executeSqlScript execute SQL scripts} within a transaction. * * <p>Concrete subclasses must fulfill the same requirements outlined in * {@link AbstractTestNGSpringContextTests}. * * @author Sam Brannen * @author Juergen Hoeller * @since 2.5 * @see AbstractTestNGSpringContextTests * @see org.springframework.test.context.ContextConfiguration * @see org.springframework.test.context.TestExecutionListeners * @see org.springframework.transaction.annotation.Transactional * @see org.springframework.test.annotation.Commit * @see org.springframework.test.annotation.Rollback * @see org.springframework.test.context.transaction.BeforeTransaction * @see org.springframework.test.context.transaction.AfterTransaction * @see org.springframework.test.jdbc.JdbcTestUtils * @see org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests */ @Transactional public abstract class AbstractTransactionalTestNGSpringContextTests extends AbstractTestNGSpringContextTests { /** * The {@code JdbcTemplate} that this base class manages, available to subclasses. * @since 3.2 */ protected final JdbcTemplate jdbcTemplate = new JdbcTemplate(); @Nullable private String sqlScriptEncoding; /** * Set the {@code DataSource}, typically provided via Dependency Injection. * <p>This method also instantiates the {@link #jdbcTemplate} instance variable. */ @Autowired public void setDataSource(DataSource dataSource) { this.jdbcTemplate.setDataSource(dataSource); } /** * Specify the encoding for SQL scripts, if different from the platform encoding. * @see #executeSqlScript */ public void setSqlScriptEncoding(String sqlScriptEncoding) { this.sqlScriptEncoding = sqlScriptEncoding; } /** * Convenience method for counting the rows in the given table. * @param tableName table name to count rows in * @return the number of rows in the table * @see JdbcTestUtils#countRowsInTable */ protected int countRowsInTable(String tableName) { return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName); } /** * Convenience method for counting the rows in the given table, using the * provided {@code WHERE} clause. * <p>See the Javadoc for {@link JdbcTestUtils#countRowsInTableWhere} for details. * @param tableName the name of the table to count rows in * @param whereClause the {@code WHERE} clause to append to the query * @return the number of rows in the table that match the provided * {@code WHERE} clause * @since 3.2 * @see JdbcTestUtils#countRowsInTableWhere */ protected int countRowsInTableWhere(String tableName, String whereClause) { return JdbcTestUtils.countRowsInTableWhere(this.jdbcTemplate, tableName, whereClause); } /** * Convenience method for deleting all rows from the specified tables. * <p>Use with caution outside of a transaction! * @param names the names of the tables from which to delete * @return the total number of rows deleted from all specified tables * @see JdbcTestUtils#deleteFromTables */ protected int deleteFromTables(String... names) { return JdbcTestUtils.deleteFromTables(this.jdbcTemplate, names); } /** * Convenience method for deleting all rows from the given table, using the * provided {@code WHERE} clause. * <p>Use with caution outside of a transaction! * <p>See the Javadoc for {@link JdbcTestUtils#deleteFromTableWhere} for details. * @param tableName the name of the table to delete rows from * @param whereClause the {@code WHERE} clause to append to the query * @param args arguments to bind to the query (leaving it to the {@code * PreparedStatement} to guess the corresponding SQL type); may also contain * {@link org.springframework.jdbc.core.SqlParameterValue SqlParameterValue} * objects which indicate not only the argument value but also the SQL type * and optionally the scale. * @return the number of rows deleted from the table * @since 4.0 * @see JdbcTestUtils#deleteFromTableWhere */ protected int deleteFromTableWhere(String tableName, String whereClause, Object... args) { return JdbcTestUtils.deleteFromTableWhere(this.jdbcTemplate, tableName, whereClause, args); } /** * Convenience method for dropping all the specified tables. * <p>Use with caution outside of a transaction! * @param names the names of the tables to drop * @since 3.2 * @see JdbcTestUtils#dropTables */ protected void dropTables(String... names) { JdbcTestUtils.dropTables(this.jdbcTemplate, names); } /** * Execute the given SQL script. * <p>Use with caution outside of a transaction! * <p>The script will normally be loaded by classpath. * <p><b>Do not use this method to execute DDL if you expect rollback.</b> * @param sqlResourcePath the Spring resource path for the SQL script * @param continueOnError whether to continue without throwing an * exception in the event of an error * @throws DataAccessException if there is an error executing a statement * @see ResourceDatabasePopulator * @see #setSqlScriptEncoding */ protected void executeSqlScript(String sqlResourcePath, boolean continueOnError) throws DataAccessException { DataSource ds = this.jdbcTemplate.getDataSource(); Assert.state(ds != null, "No DataSource set"); Assert.state(this.applicationContext != null, "No ApplicationContext available"); Resource resource = this.applicationContext.getResource(sqlResourcePath); new ResourceDatabasePopulator(continueOnError, false, this.sqlScriptEncoding, resource).execute(ds); } }
package com.ashishkaul.rest.interfaces; import java.util.List; public interface ISlamBook { String AddPersonInfo(String data); String EditPersonInfo(String id, String data); String RemovePersonInfo(String id); String ViewPersonInfo(String id); List<String> ViewPersonsInfo(); }
import java.util.Scanner; import java.util.Locale; public class uri2780 { public static void main(String[] args) { Locale.setDefault(Locale.US); Scanner input = new Scanner(System.in); int distancia; distancia = input.nextInt(); if(distancia <= 800) { System.out.println("1"); } else if(distancia <= 1400) { System.out.println("2"); } else if(distancia > 1400 || distancia <= 2000) { System.out.println("3"); } } }
package com.example.trialattemptone.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.widget.ListView; import android.widget.TextView; import com.example.trialattemptone.CourseDetailsScreen; import com.example.trialattemptone.Creators.Alert; import com.example.trialattemptone.Creators.Assessment; import com.example.trialattemptone.Creators.AssessmentType; import com.example.trialattemptone.Creators.Course; import com.example.trialattemptone.Creators.CourseNote; import com.example.trialattemptone.Creators.CourseStatus; import com.example.trialattemptone.Creators.Mentor; import com.example.trialattemptone.Creators.Term; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; public class DataSource { private Context mContext; private SQLiteDatabase mDatabase; SQLiteOpenHelper mDbHelper; private static final String[] courseStats = {"In Progress", "Completed", "Dropped", "Plan To Take"}; public static final List<String> courseStatusList = Arrays.asList(courseStats); private static final String[] assessType = {"Objective", "Performance"}; public static final List<String> assessmentTypesList = Arrays.asList(assessType); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); // Variables for the conditional methods public static Date curDate; public static int curTerm; public DataSource(Context context) { this.mContext = context; mDbHelper = new DBHelper(mContext); mDatabase = mDbHelper.getWritableDatabase(); } public void open() { mDatabase = mDbHelper.getWritableDatabase(); } public void close() { mDatabase.close(); } // Term methods public Term createTerm(Term term) { ContentValues values = term.toValues(); mDatabase.insert(TermsTable.TABLE_TERMS, null, values); return term; } public void seedDataBase(List<String> courseStatuses, List<String> assessTypes) { long numCourseStatusItems = getStatusCount(); long numAssessmentTypeItems = getAssessmentTypesCount(); if (numCourseStatusItems == 0) { for (int i = 0; i < courseStatuses.size(); i++) { try { CourseStatus courseStatus = new CourseStatus(courseStatuses.get(i)); createCourseStatus(courseStatus); } catch (SQLiteException e) { System.out.println(e.getLocalizedMessage()); } } } if (numAssessmentTypeItems == 0) { for (int i = 0; i < assessTypes.size(); i++) { try { AssessmentType assessmentType = new AssessmentType(assessTypes.get(i)); createAssessmentType(assessmentType); } catch (SQLiteException e) { System.out.println(e.getLocalizedMessage()); } } } } public void deleteTermByID(int termID) { mDatabase.delete(TermsTable.TABLE_TERMS, TermsTable.COLUMN_ID + " = " + termID, null); } public long getTermCount() { return DatabaseUtils.queryNumEntries(mDatabase, TermsTable.TABLE_TERMS); } public List<Term> getAllTerms() { List<Term> terms = new ArrayList<>(); Cursor cursor = mDatabase.query(TermsTable.TABLE_TERMS, TermsTable.ALL_COLUMNS, null, null, null, null, TermsTable.COLUMN_START); while(cursor.moveToNext()) { Term term = new Term(); term.setTermID(cursor.getInt(cursor.getColumnIndex(TermsTable.COLUMN_ID))); term.setTermName(cursor.getString(cursor.getColumnIndex(TermsTable.COLUMN_NAME))); term.setStartDate(cursor.getString(cursor.getColumnIndex(TermsTable.COLUMN_START))); term.setEndDate(cursor.getString(cursor.getColumnIndex(TermsTable.COLUMN_END))); terms.add(term); } cursor.close(); return terms; } public void addTerm(Term term) { ContentValues values = term.toValues(); mDatabase.insert(TermsTable.TABLE_TERMS,null, values); } public int getTermId(String termTitle) { int termID = 0; Cursor cursor = mDatabase.query(TermsTable.TABLE_TERMS, TermsTable.ALL_COLUMNS, TermsTable.COLUMN_NAME + " = '" + termTitle +"'",null,null,null,null); while (cursor.moveToNext()) { termID = cursor.getInt(cursor.getColumnIndex(TermsTable.COLUMN_ID)); } cursor.close(); return termID; } public Term getTermByTermID(int termID) { Term term = new Term(); Cursor cursor = mDatabase.query(TermsTable.TABLE_TERMS, TermsTable.ALL_COLUMNS, TermsTable.COLUMN_ID + " = " + termID, null,null,null,null); while (cursor.moveToNext()) { term.setTermID(cursor.getInt(cursor.getColumnIndex(TermsTable.COLUMN_ID))); term.setTermName(cursor.getString(cursor.getColumnIndex(TermsTable.COLUMN_NAME))); term.setStartDate(cursor.getString(cursor.getColumnIndex(TermsTable.COLUMN_START))); term.setEndDate(cursor.getString(cursor.getColumnIndex(TermsTable.COLUMN_END))); } return term; } // Course Methods public Course createCourse(Course course) { ContentValues values = course.toValues(); mDatabase.insert(CoursesTable.TABLE_COURSES, null,values); return course; } public void updateCourse(Course course, int courseID) { ContentValues values = course.toValues(); mDatabase.update(CoursesTable.TABLE_COURSES, values, CoursesTable.COLUMN_ID + " = '" + courseID + "'", null); } // Delete course, assessments associated with the course, and notes associated with the course public void deleteCourseByID(int courseID) { mDatabase.delete(CoursesTable.TABLE_COURSES, CoursesTable.COLUMN_ID + " = " + courseID, null); mDatabase.delete(AssessmentsTable.TABLE_ASSESSMENTS, AssessmentsTable.COLUMN_COURSE_ID + " = " + courseID, null); mDatabase.delete(NotesTable.TABLE_NOTES, NotesTable.COLUMN_COURSE_ID + " = " + courseID, null); } public long getCourseCount() { return DatabaseUtils.queryNumEntries(mDatabase, CoursesTable.TABLE_COURSES); } public List<Course> getAllCourses() { List<Course> courses = new ArrayList<>(); Cursor cursor = mDatabase.query(CoursesTable.TABLE_COURSES, CoursesTable.ALL_COLUMNS, null,null,null,null,CoursesTable.COLUMN_START); while (cursor.moveToNext()) { Course course = new Course(); course.setCourseId(cursor.getInt(cursor.getColumnIndex(CoursesTable.COLUMN_ID))); course.setCourseTitle(cursor.getString(cursor.getColumnIndex(CoursesTable.COLUMN_NAME))); course.setCourseStart(cursor.getString(cursor.getColumnIndex(CoursesTable.COLUMN_START))); course.setCourseEnd(cursor.getString(cursor.getColumnIndex(CoursesTable.COLUMN_END))); course.setCourseStatusID(cursor.getInt(cursor.getColumnIndex(CoursesTable.COLUMN_COURSE_STATUS))); course.setMentorId(cursor.getInt(cursor.getColumnIndex(CoursesTable.COLUMN_COURSE_MENTOR_ID))); courses.add(course); } cursor.close(); return courses; } public Course getCourseByID(int courseID) { Course course = new Course(); Cursor cursor = mDatabase.query(CoursesTable.TABLE_COURSES, CoursesTable.ALL_COLUMNS, CoursesTable.COLUMN_ID + "= '" + courseID + "';", null, null, null, null); while (cursor.moveToNext()) { course.setCourseId(cursor.getInt(cursor.getColumnIndex(CoursesTable.COLUMN_ID))); course.setCourseTitle(cursor.getString(cursor.getColumnIndex(CoursesTable.COLUMN_NAME))); course.setCourseStart(cursor.getString(cursor.getColumnIndex(CoursesTable.COLUMN_START))); course.setCourseEnd(cursor.getString(cursor.getColumnIndex(CoursesTable.COLUMN_END))); course.setCourseStatusID(cursor.getInt(cursor.getColumnIndex(CoursesTable.COLUMN_COURSE_STATUS))); course.setMentorId(cursor.getInt(cursor.getColumnIndex(CoursesTable.COLUMN_COURSE_MENTOR_ID))); } return course; } public List<Course> getTermsCourses(int termID) { List<Course> courses = new ArrayList<>(); Cursor cursor = mDatabase.query(CoursesTable.TABLE_COURSES, CoursesTable.ALL_COLUMNS, CoursesTable.COLUMN_TERM_ID + " = '" + termID + "';",null,null,null,null); while (cursor.moveToNext()) { Course course = new Course(); course.setCourseId(cursor.getInt(cursor.getColumnIndex(CoursesTable.COLUMN_ID))); course.setCourseTitle(cursor.getString(cursor.getColumnIndex(CoursesTable.COLUMN_NAME))); course.setCourseStart(cursor.getString(cursor.getColumnIndex(CoursesTable.COLUMN_START))); course.setCourseEnd(cursor.getString(cursor.getColumnIndex(CoursesTable.COLUMN_END))); course.setCourseStatusID(cursor.getInt(cursor.getColumnIndex(CoursesTable.COLUMN_COURSE_STATUS))); course.setMentorId(cursor.getInt(cursor.getColumnIndex(CoursesTable.COLUMN_COURSE_MENTOR_ID))); courses.add(course); } cursor.close(); return courses; } public void addCourse(Course course) { ContentValues values = course.toValues(); mDatabase.insert(CoursesTable.TABLE_COURSES,null,values); } // Assessment Methods public Assessment createAssessment(Assessment assessment) { ContentValues values = assessment.toValues(); mDatabase.insert(AssessmentsTable.TABLE_ASSESSMENTS,null,values); return assessment; } public void deleteAssessment(int assessmentID) { mDatabase.delete(AssessmentsTable.TABLE_ASSESSMENTS, AssessmentsTable.COLUMN_ID + " = " + assessmentID, null); } public void updateAssessment(Assessment assessment, int assessmentID) { System.out.println(assessmentID); ContentValues values = assessment.toValues(); mDatabase.update(AssessmentsTable.TABLE_ASSESSMENTS, values, AssessmentsTable.COLUMN_ID + "=" + assessmentID , null); } public long getAssessmentCount() { return DatabaseUtils.queryNumEntries(mDatabase, AssessmentsTable.TABLE_ASSESSMENTS); } public Assessment getAssessmentByAssessmentID(int assessmentID) { Assessment assessment = new Assessment(); Cursor cursor = mDatabase.query(AssessmentsTable.TABLE_ASSESSMENTS, AssessmentsTable.ALL_COLUMNS, AssessmentsTable.COLUMN_ID + " = '" + assessmentID + "';", null,null,null,null); while (cursor.moveToNext()) { assessment.setAssId(cursor.getInt(cursor.getColumnIndex(AssessmentsTable.COLUMN_ID))); assessment.setAssTitle(cursor.getString(cursor.getColumnIndex(AssessmentsTable.COLUMN_NAME))); assessment.setAssEnd(cursor.getString(cursor.getColumnIndex(AssessmentsTable.COLUMN_END))); assessment.setAssCourseID(cursor.getInt(cursor.getColumnIndex(AssessmentsTable.COLUMN_COURSE_ID))); assessment.setAssTypeID(cursor.getInt(cursor.getColumnIndex(AssessmentsTable.COLUMN_TYPE_ID))); } return assessment; } public List<Assessment> getAssessmentsByCourseID(int courseID) { List<Assessment> assessments = new ArrayList<>(); Cursor cursor = mDatabase.query(AssessmentsTable.TABLE_ASSESSMENTS, AssessmentsTable.ALL_COLUMNS, AssessmentsTable.COLUMN_COURSE_ID + " = '" + courseID + "';", null, null , null, null); while (cursor.moveToNext()) { Assessment assessment = new Assessment(); assessment.setAssId(cursor.getInt(cursor.getColumnIndex(AssessmentsTable.COLUMN_ID))); assessment.setAssTitle(cursor.getString(cursor.getColumnIndex(AssessmentsTable.COLUMN_NAME))); assessment.setAssEnd(cursor.getString(cursor.getColumnIndex(AssessmentsTable.COLUMN_END))); assessment.setAssCourseID(cursor.getInt(cursor.getColumnIndex(AssessmentsTable.COLUMN_COURSE_ID))); assessment.setAssTypeID(cursor.getInt(cursor.getColumnIndex(AssessmentsTable.COLUMN_TYPE_ID))); assessments.add(assessment); } cursor.close(); return assessments; } public List<Assessment> getAllAssessments() { List<Assessment> assessments = new ArrayList<>(); Cursor cursor = mDatabase.query(AssessmentsTable.TABLE_ASSESSMENTS, AssessmentsTable.ALL_COLUMNS,null,null,null,null, AssessmentsTable.COLUMN_END); while (cursor.moveToNext()) { Assessment assessment = new Assessment(); assessment.setAssId(cursor.getInt(cursor.getColumnIndex(AssessmentsTable.COLUMN_ID))); assessment.setAssTitle(cursor.getString(cursor.getColumnIndex(AssessmentsTable.COLUMN_NAME))); assessment.setAssEnd(cursor.getString(cursor.getColumnIndex(AssessmentsTable.COLUMN_END))); assessment.setAssTypeID(cursor.getInt(cursor.getColumnIndex(AssessmentsTable.COLUMN_TYPE_ID))); assessments.add(assessment); } cursor.close(); return assessments; } public void addAssessment(Assessment assessment) { ContentValues values = assessment.toValues(); mDatabase.insert(AssessmentsTable.TABLE_ASSESSMENTS,null,values); } // Mentor Methods public Mentor createMentor(Mentor mentor) { ContentValues values = mentor.toValues(); mDatabase.insert(MentorTable.TABLE_MENTORS,null,values); return mentor; } public long getMentorCount() { return DatabaseUtils.queryNumEntries(mDatabase,MentorTable.TABLE_MENTORS); } public Mentor getSelectedCourseMentor(int mentorID) { Mentor mentor = new Mentor(); Cursor cursor = mDatabase.query(MentorTable.TABLE_MENTORS, MentorTable.ALL_COLUMNS, MentorTable.COLUMN_ID + "= '" + mentorID + "';", null,null,null,null); while (cursor.moveToNext()) { mentor.setMentorId(cursor.getInt(cursor.getColumnIndex(MentorTable.COLUMN_ID))); mentor.setFirstName(cursor.getString(cursor.getColumnIndex(MentorTable.COLUMN_FNAME))); mentor.setLastName(cursor.getString(cursor.getColumnIndex(MentorTable.COLUMN_LNAME))); mentor.setMentorPhone(cursor.getString(cursor.getColumnIndex(MentorTable.COLUMN_PHONE))); mentor.setMentorEmail(cursor.getString(cursor.getColumnIndex(MentorTable.COLUMN_EMAIL))); } cursor.close(); return mentor; } public List<Mentor> getAllMentors() { List<Mentor> mentors = new ArrayList<>(); Cursor cursor = mDatabase.query(MentorTable.TABLE_MENTORS, MentorTable.ALL_COLUMNS,null,null,null,null, null); while (cursor.moveToNext()) { Mentor mentor = new Mentor(); mentor.setMentorId(cursor.getInt(cursor.getColumnIndex(MentorTable.COLUMN_ID))); mentor.setFirstName(cursor.getString(cursor.getColumnIndex(MentorTable.COLUMN_FNAME))); mentor.setLastName(cursor.getString(cursor.getColumnIndex(MentorTable.COLUMN_LNAME))); mentor.setMentorPhone(cursor.getString(cursor.getColumnIndex(MentorTable.COLUMN_PHONE))); mentor.setMentorEmail(cursor.getString(cursor.getColumnIndex(MentorTable.COLUMN_EMAIL))); mentors.add(mentor); } cursor.close(); return mentors; } public void addMentor(Mentor mentor) { ContentValues values = mentor.toValues(); mDatabase.insert(MentorTable.TABLE_MENTORS,null,values); } public int getMentorID(String lastName, String firstName) { int mentorID = 0; Cursor cursor = mDatabase.query(MentorTable.TABLE_MENTORS, MentorTable.ALL_COLUMNS, MentorTable.COLUMN_FNAME + " = '" + firstName +"' AND " + MentorTable.COLUMN_LNAME + " = '" + lastName + "';", null , null, null, null); while(cursor.moveToNext()) { mentorID= cursor.getInt(cursor.getColumnIndex(MentorTable.COLUMN_ID)); } cursor.close(); return mentorID; } // Methods for Status public CourseStatus createCourseStatus(CourseStatus status) { ContentValues values = status.toValues(); mDatabase.insert(StatusTable.TABLE_STATUS,null,values); return status; } public long getStatusCount() { return DatabaseUtils.queryNumEntries(mDatabase, StatusTable.TABLE_STATUS); } public List<CourseStatus> getAllCourseStatus() { List<CourseStatus> coursesStatus = new ArrayList<>(); Cursor cursor = mDatabase.query(StatusTable.TABLE_STATUS, StatusTable.ALL_COLUMNS,null,null,null,null,null); while (cursor.moveToNext()) { CourseStatus status = new CourseStatus(); status.setCourseStatusID(cursor.getInt(cursor.getColumnIndex(StatusTable.COLUMN_ID))); status.setCourseStatus(cursor.getString(cursor.getColumnIndex(StatusTable.COLUMN_NAME))); coursesStatus.add(status); } cursor.close(); return coursesStatus; } public void addCourseStatus(CourseStatus cStatus) { ContentValues values = cStatus.toValues(); mDatabase.insert(StatusTable.TABLE_STATUS, null, values); } public String getCourseStatusByStatusID(int statusID) { String statusTitle = null; Cursor cursor = mDatabase.query(StatusTable.TABLE_STATUS, StatusTable.ALL_COLUMNS, StatusTable.COLUMN_ID + " = '" + statusID + "'", null,null,null,null); while(cursor.moveToNext()) { statusTitle = cursor.getString(cursor.getColumnIndex(StatusTable.COLUMN_NAME)); } return statusTitle; } public int getCourseStatusId(String statusTitle) { int statusID = 0; Cursor cursor = mDatabase.query(StatusTable.TABLE_STATUS, StatusTable.ALL_COLUMNS, StatusTable.COLUMN_NAME + " = '" + statusTitle +"'",null,null,null,null); while (cursor.moveToNext()) { statusID = cursor.getInt(cursor.getColumnIndex(StatusTable.COLUMN_ID)); } cursor.close(); return statusID; } // Methods for notes public CourseNote createCourseNote(CourseNote courseNote) { ContentValues values = courseNote.toValues(); mDatabase.insert(NotesTable.TABLE_NOTES, null, values); return courseNote; } public void addCourseNote(CourseNote courseNote) { ContentValues values = courseNote.toValues(); mDatabase.insert(NotesTable.TABLE_NOTES, null,values); } public void deleteCourseNote(int courseNoteId) { mDatabase.delete(NotesTable.TABLE_NOTES, NotesTable.COLUMN_ID + " = " + courseNoteId, null); } public void updateCourseNote(CourseNote courseNote, int noteID) { ContentValues values = courseNote.toValues(); mDatabase.update(NotesTable.TABLE_NOTES, values, NotesTable.COLUMN_ID + "=" + noteID , null); } public CourseNote getNoteByNoteID(int noteID) { CourseNote courseNote = new CourseNote(); Cursor cursor = mDatabase.query(NotesTable.TABLE_NOTES, NotesTable.ALL_COLUMNS, NotesTable.COLUMN_ID + " = '" + noteID + "';",null,null,null,null); while (cursor.moveToNext()) { courseNote.setNoteId(cursor.getInt(cursor.getColumnIndex(NotesTable.COLUMN_ID))); courseNote.setTitle(cursor.getString(cursor.getColumnIndex(NotesTable.COLUMN_TITLE))); courseNote.setNote(cursor.getString(cursor.getColumnIndex(NotesTable.COLUMN_NOTE))); courseNote.setCourseID(cursor.getInt(cursor.getColumnIndex(NotesTable.COLUMN_COURSE_ID))); } cursor.close(); return courseNote; } public List<CourseNote> getAllCourseNotes() { List<CourseNote> allCourseNotes = new ArrayList<>(); Cursor cursor = mDatabase.query(NotesTable.TABLE_NOTES, NotesTable.ALL_COLUMNS, null,null,null,null,null); while(cursor.moveToNext()) { CourseNote courseNote = new CourseNote(); courseNote.setNoteId(cursor.getInt(cursor.getColumnIndex(NotesTable.COLUMN_ID))); courseNote.setTitle(cursor.getString(cursor.getColumnIndex(NotesTable.COLUMN_TITLE))); courseNote.setNote(cursor.getString(cursor.getColumnIndex(NotesTable.COLUMN_NOTE))); courseNote.setCourseID(cursor.getInt(cursor.getColumnIndex(NotesTable.COLUMN_COURSE_ID))); allCourseNotes.add(courseNote); } cursor.close(); return allCourseNotes; } public List<CourseNote> getCourseNoteByCourseID(int courseID) { List<CourseNote> notes = new ArrayList<>(); Cursor cursor = mDatabase.query(NotesTable.TABLE_NOTES, NotesTable.ALL_COLUMNS, NotesTable.COLUMN_COURSE_ID + " = '" + courseID + "';", null,null,null,null); while (cursor.moveToNext()) { CourseNote courseNote = new CourseNote(); courseNote.setNoteId(cursor.getInt(cursor.getColumnIndex(NotesTable.COLUMN_ID))); courseNote.setTitle(cursor.getString(cursor.getColumnIndex(NotesTable.COLUMN_TITLE))); courseNote.setNote(cursor.getString(cursor.getColumnIndex(NotesTable.COLUMN_NOTE))); courseNote.setCourseID(cursor.getInt(cursor.getColumnIndex(NotesTable.COLUMN_COURSE_ID))); notes.add(courseNote); } cursor.close(); return notes; } // Methods for assessmentType public AssessmentType createAssessmentType(AssessmentType assessmentType) { ContentValues values = assessmentType.toValues(); mDatabase.insert(TypesTable.TABLE_TYPES, null,values); return assessmentType; } public void addAssessmentType(AssessmentType assessmentType) { ContentValues values = assessmentType.toValues(); mDatabase.insert(TypesTable.TABLE_TYPES, null,values); } public String getAssessmentTypeByID(int assType) { String assessmentType; AssessmentType assessmentType1 = new AssessmentType(); Cursor cursor = mDatabase.query(TypesTable.TABLE_TYPES, TypesTable.ALL_COLUMNS, TypesTable.COLUMN_ID + " = '" + assType + "';", null,null,null,null); while (cursor.moveToNext()) { assessmentType1.setAssessmentTypeID(cursor.getInt(cursor.getColumnIndex(TypesTable.COLUMN_ID))); assessmentType1.setAssessmentType(cursor.getString(cursor.getColumnIndex(TypesTable.COLUMN_NAME))); } assessmentType = assessmentType1.getAssessmentType(); return assessmentType; } public int getAssessmentTypeID(String assTitle) { int assessID = 0; Cursor cursor = mDatabase.query(TypesTable.TABLE_TYPES, TypesTable.ALL_COLUMNS, TypesTable.COLUMN_NAME + " = '" + assTitle + "';",null,null,null,null); while (cursor.moveToNext()) { assessID = cursor.getInt(cursor.getColumnIndex(TypesTable.COLUMN_ID)); } return assessID; } public List<AssessmentType> getAllAssessmentTypes() { List<AssessmentType> assessmentTypes = new ArrayList<>(); Cursor cursor = mDatabase.query(TypesTable.TABLE_TYPES, TypesTable.ALL_COLUMNS, null,null,null,null,null); while (cursor.moveToNext()) { AssessmentType assessmentType = new AssessmentType(); assessmentType.setAssessmentTypeID(cursor.getInt(cursor.getColumnIndex(TypesTable.COLUMN_ID))); assessmentType.setAssessmentType(cursor.getString(cursor.getColumnIndex(TypesTable.COLUMN_NAME))); assessmentTypes.add(assessmentType); } cursor.close(); return assessmentTypes; } public long getAssessmentTypesCount() { return DatabaseUtils.queryNumEntries(mDatabase, TypesTable.TABLE_TYPES); } // Methods for alerts public void addCourseAlert(Alert alert) { ContentValues values = alert.toValues(); mDatabase.insert(CourseAlertsTable.TABLE_COURSEALERTS, null, values); } public void updateCourseAlert(Alert alert, int alertID) { ContentValues values = alert.toValues(); mDatabase.update(CourseAlertsTable.TABLE_COURSEALERTS, values, CourseAlertsTable.COLUMN_COURSE_ID + "=" + alertID + "", null); } public Alert getCourseAlertByCourseID(int courseID) { Alert alert = new Alert(); Cursor cursor = mDatabase.query(CourseAlertsTable.TABLE_COURSEALERTS, CourseAlertsTable.ALL_COLUMNS, CourseAlertsTable.COLUMN_COURSE_ID + " = '" + courseID + "'", null,null,null,null); while (cursor.moveToNext()) { alert.setTitle(cursor.getString(cursor.getColumnIndex(CourseAlertsTable.COLUMN_NAME))); alert.setDate(cursor.getString(cursor.getColumnIndex(CourseAlertsTable.COLUMN_DATE))); alert.setHour(cursor.getInt(cursor.getColumnIndex(CourseAlertsTable.COLUMN_HOUR))); alert.setActive(cursor.getInt(cursor.getColumnIndex(CourseAlertsTable.COLUMN_ACTIVE))); alert.setCourseID(cursor.getInt(cursor.getColumnIndex(CourseAlertsTable.COLUMN_COURSE_ID))); alert.setTypeId(cursor.getInt(cursor.getColumnIndex(CourseAlertsTable.COLUMN_TYPE_ID))); } cursor.close(); return alert; } public void updateAssessmentAlert(Alert alert, int assId) { ContentValues values = alert.toValues(); mDatabase.update(CourseAlertsTable.TABLE_COURSEALERTS, values, CourseAlertsTable.COLUMN_TYPE_ID + " = " + assId,null); } public Alert getAssessmentAlertByAssID(int assID) { Alert alert = new Alert(); Cursor cursor = mDatabase.query(CourseAlertsTable.TABLE_COURSEALERTS, CourseAlertsTable.ALL_COLUMNS, CourseAlertsTable.COLUMN_TYPE_ID + " = '" + assID + "'", null,null,null,null); while (cursor.moveToNext()) { alert.setTitle(cursor.getString(cursor.getColumnIndex(CourseAlertsTable.COLUMN_NAME))); alert.setDate(cursor.getString(cursor.getColumnIndex(CourseAlertsTable.COLUMN_DATE))); alert.setHour(cursor.getInt(cursor.getColumnIndex(CourseAlertsTable.COLUMN_HOUR))); alert.setActive(cursor.getInt(cursor.getColumnIndex(CourseAlertsTable.COLUMN_ACTIVE))); alert.setCourseID(cursor.getInt(cursor.getColumnIndex(CourseAlertsTable.COLUMN_COURSE_ID))); alert.setTypeId(cursor.getInt(cursor.getColumnIndex(CourseAlertsTable.COLUMN_TYPE_ID))); } cursor.close(); return alert; } // Conditional queries public int getCurrentTermID(String currentDate) { List<Term> allTerms = getAllTerms(); try { curDate = sdf.parse(currentDate); } catch (ParseException ex) { System.out.println(ex.getLocalizedMessage()); } int currentTerm = 0; List<Date> termStart = new ArrayList<>(); List<Date> termEnd = new ArrayList<>(); for (int i = 0; i < allTerms.size(); i++) { try { Date s = sdf.parse(allTerms.get(i).getStartDate()); termStart.add(s); Date f = sdf.parse(allTerms.get(i).getEndDate()); termEnd.add(f); if (curDate.after(s) == true && curDate.before(f) == true) { currentTerm = allTerms.get(i).getTermID(); } } catch (ParseException ex) { System.out.println(ex.getLocalizedMessage()); } } return currentTerm; } }
package com.leador.androidannotationsdemo; import android.support.v7.app.AppCompatActivity; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.androidannotations.annotations.Click; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.ViewById; /** * 首先@EActivity后必须要有一个layout id 来表示这 个Activity所使用的布局,远来的onCreate方法就不用了 */ @EActivity(R.layout.activity_main) public class MainActivity extends AppCompatActivity { /** *@ViewById 就和原来 的findViewById()方法一样,值得注意的是:@ViewById后的id是可以不写的,条件是控件变量名称要与xml中定义的id 必须一致,也就是说 当我在xml文件中定义的TextView的id必须是:android:id="@+id/textView" . 这样我们在@ViewById 后就不用再写括号了,直接写 */ @ViewById(R.id.textView) TextView textView; @ViewById EditText editText; @Click(R.id.btn) void myButton() { Toast.makeText(this,"点击按钮",Toast.LENGTH_SHORT).show(); } }
package com.example.dsucksto.todo.Model; import org.joda.time.DateTimeUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class IntervalUnitTest { @Before public void setUp() { DateTimeUtils.setCurrentMillisSystem(); } @After public void tearDown() { DateTimeUtils.setCurrentMillisSystem(); } @Test public void shouldReturnHourlyWhenIndexedWithInteger() throws Exception { assertThat(Interval.values()[3], is(Interval.HOURLY)); } @Test public void shouldReturnFiveMinutesInMillis() { long fiveMinutesInMillis = 300000L; assertEquals(fiveMinutesInMillis, Interval.EVERY_FIVE_MINUTES.getMillis()); } @Test public void shouldReturnForTenMinutesInMillis() { long tenMinutesInMillis = 600000L; assertEquals(tenMinutesInMillis, Interval.EVERY_TEN_MINUTES.getMillis()); } @Test public void shouldReturnForOneHourInMillis() { long oneHourInMillis = 3600000L; assertEquals(oneHourInMillis, Interval.HOURLY.getMillis()); } @Test public void shouldReturnOneDayInMillis() { long onDayInMillis = 86400000L; assertEquals(onDayInMillis, Interval.DAILY.getMillis()); } @Test public void onJulyFirst2017ShouldReturnThirtyOneDaysInMillis() { long thirtyDaysInMillis = 2592000000L; long timeInMillisOnJulyFirst2017 = 14988852000L; DateTimeUtils.setCurrentMillisFixed(timeInMillisOnJulyFirst2017); assertEquals(thirtyDaysInMillis, Interval.MONTHLY.getMillis()); } @Test public void shouldReturnAStringRepresentation() { assertEquals("EVERY_FIVE_MINUTES", Interval.EVERY_FIVE_MINUTES.name()); } @Test public void shouldGetAnEnumFromAName() { assertEquals(Interval.EVERY_FIVE_MINUTES, Interval.valueOf("EVERY_FIVE_MINUTES")); } }
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS.utils; /** * A routine to produce a nice looking hex dump * * @author Brian Wellington */ public class hexdump { private static final char[] hex = "0123456789ABCDEF".toCharArray(); /** * Dumps a byte array into hex format. * * @param description If not null, a description of the data. * @param b The data to be printed. * @param offset The start of the data in the array. * @param length The length of the data in the array. */ public static String dump(String description, byte[] b, int offset, int length) { StringBuilder sb = new StringBuilder(); sb.append(length).append("b"); if (description != null) { sb.append(" (").append(description).append(")"); } sb.append(':'); int prefixlen = sb.toString().length(); prefixlen = (prefixlen + 8) & ~7; sb.append('\t'); int perline = (80 - prefixlen) / 3; for (int i = 0; i < length; i++) { if (i != 0 && i % perline == 0) { sb.append('\n'); for (int j = 0; j < prefixlen / 8; j++) { sb.append('\t'); } } int value = (int) b[i + offset] & 0xFF; sb.append(hex[value >> 4]); sb.append(hex[value & 0xF]); sb.append(' '); } sb.append('\n'); return sb.toString(); } public static String dump(String s, byte[] b) { return dump(s, b, 0, b.length); } }
package com.example.android_lab5; import android.app.Application; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.google.android.gms.maps.model.LatLng; import java.util.List; public class AppRepository { private final AppDao appDao; private MutableLiveData<List<Cuisine>> cuisines = new MutableLiveData<>(); private MutableLiveData<List<Restaurant>> restaurants = new MutableLiveData<>(); // constructor for AppRepository AppRepository(Application application) { AppDatabase db = AppDatabase.getDatabase(application); // init variables appDao = db.appDao(); } public MutableLiveData<List<Cuisine>> getCuisines() { return cuisines; } public MutableLiveData<List<Restaurant>> getRestaurants() { return restaurants; } public void getAllCuisines(){ new Thread(new Runnable() { @Override public void run() { List<Cuisine> c= appDao.getAll(); if(c.isEmpty()){ appDao.insertAll(new Cuisine( 1,"Caprese Salad with Pesto Sauce")); appDao.insertAll(new Restaurant("Scaddabush Italian Kitchen & Bar Scarborough", 1,"580 Progress Ave, Scarborough, ON M1P 2K2", 43.77765042790276, -79.25401184964606)); appDao.insertAll(new Restaurant("Nova Ristorante", 1,"2272 Lawrence Ave E #2, Scarborough, ON M1P 2P9", 43.749630782386184, -79.27758633061958)); // japanese appDao.insertAll(new Cuisine( 2,"Sushi(壽司)")); appDao.insertAll(new Restaurant("Sushi Legend Scarborough 糰長壽司", 2,"Chartwell Shopping Centre, 175 Commander Blvd unit 2, Scarborough, ON M1S 3M7",43.796731216643224, -79.26965083671064)); appDao.insertAll(new Restaurant("Umami House 鲜味屋", 2,"2038 Sheppard Ave E, North York, ON M2J 5B3", 43.775384916052204, -79.33036027294717)); // korean appDao.insertAll(new Cuisine( 3,"Samgyetang (삼계탕)")); appDao.insertAll(new Restaurant("The Nilgiris Restaurant", 3,"3021 Markham Rd #50, Scarborough, ON M1X 1L8", 43.829290436445575, -79.24872277294583)); appDao.insertAll(new Restaurant("Tutto Pronto Bayview", 3,"1551 Bayview Ave, East York, ON M4G 3B5", 43.70558507626752, -79.37483557294877)); // chinese appDao.insertAll(new Cuisine(4,"Dumplings(饺子)")); appDao.insertAll(new Restaurant("Perfect Chinese Restaurant", 4,"4386 Sheppard Ave E, Unit 1, Toronto, ON M1S 1T8", 43.78771157452607, -79.27055947299833)); appDao.insertAll(new Restaurant("May Yan Seafood Restaurant 陸福海鮮酒家", 4,"4227 Sheppard Ave E Unit B2, Scarborough, ON M1S 5H5", 43.784714174372574, -79.27770214416279)); } cuisines.postValue(appDao.getAll()); } }).start(); } public void getRestaurants(int cuisineId){ new Thread(new Runnable() { @Override public void run() { restaurants.postValue(appDao.getRestaurantsByCuisineId(cuisineId)); } }).start(); } }
package com.alpha.toy.vo; import java.util.Date; public class BoardVo { private int no; private int board_no; private int member_no; private String board_title; private String board_content; private int board_readcount; private Date board_writedate; public BoardVo() { super(); } public BoardVo(int no, int board_no, int member_no, String board_title, String board_content, int board_readcount, Date board_writedate) { super(); this.no = no; this.board_no = board_no; this.member_no = member_no; this.board_title = board_title; this.board_content = board_content; this.board_readcount = board_readcount; this.board_writedate = board_writedate; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public int getBoard_no() { return board_no; } public void setBoard_no(int board_no) { this.board_no = board_no; } public int getMember_no() { return member_no; } public void setMember_no(int member_no) { this.member_no = member_no; } public String getBoard_title() { return board_title; } public void setBoard_title(String board_title) { this.board_title = board_title; } public String getBoard_content() { return board_content; } public void setBoard_content(String board_content) { this.board_content = board_content; } public int getBoard_readcount() { return board_readcount; } public void setBoard_readcount(int board_readcount) { this.board_readcount = board_readcount; } public Date getBoard_writedate() { return board_writedate; } public void setBoard_writedate(Date board_writedate) { this.board_writedate = board_writedate; } }