text
stringlengths
10
2.72M
package com.tencent.mm.plugin.wallet_core.model; import com.tencent.mm.g.a.sg; import com.tencent.mm.platformtools.ab; import com.tencent.mm.protocal.c.ayv; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.x; import java.util.List; class o$5 extends c<sg> { final /* synthetic */ o pqJ; o$5(o oVar) { this.pqJ = oVar; this.sFo = sg.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { sg sgVar = (sg) bVar; if (sgVar.cdb.bJE == 11) { List list = sgVar.cdb.cdc; if (list == null || list.size() <= 0) { x.e("MicroMsg.UpdateMassSendPlaceTopListener", "empty UpdatePackageEvent"); } else { byte[] a = ab.a(((ayv) list.get(0)).rdp); if (!(a == null || a.length == 0)) { String str = new String(a); if (str.equals(o.a(this.pqJ))) { x.i("MicroMsg.UpdateMassSendPlaceTopListener", "the same result : %s" + str); } else { x.i("MicroMsg.UpdateMassSendPlaceTopListener", "UpdatePackageEvent: %s", new Object[]{str}); com.tencent.mm.plugin.wallet_core.d.b.Pi(str); o.a(this.pqJ, str); } } } } return false; } }
package collection.test2; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import collection.vo.Customer; public class CustomerMapTest2 { public static void main(String[] args) { HashMap<String, Customer> map = new HashMap<String, Customer>(); map.put("111", new Customer("KANG", "강호동", 48)); map.put("222", new Customer("LEE", "이수근", 42)); map.put("333", new Customer("SEO", "서장훈", 44)); map.put("444", new Customer("KIM", "김희철", 37)); //1. KEY 값이 222인 사람의 정보를 출력 System.out.println(map.get("222")); //2. id가 LEE인 사람을 찾아서 그 사람의 이름을 출력 Collection<Customer> col = map.values(); Iterator<Customer> it2 = col.iterator(); while(it2.hasNext()) { Customer c = it2.next(); if(c.getId().equals("LEE")) System.out.println(c.getName()); } Set<String> set = map.keySet(); Iterator<String> it = set.iterator(); while(it.hasNext()) { Customer c = map.get(it.next()); if(c.getId().equals("LEE")) System.out.println(c.getName()); } //3. MAP에 저장된 데이터의 모든 KEY값들을 출력 System.out.println(map.keySet()); //4. MAP에 저장된 사람들 나이의 총합과 평균연령을 출력 Iterator<Customer> it3 = col.iterator(); int total = 0; while(it3.hasNext()) { Customer c = it3.next(); total += c.getAge(); } System.out.println(total); System.out.println(total/map.size()); Set<String> keys = map.keySet(); int totalAge = 0; for(String s : keys) { totalAge += map.get(s).getAge(); } System.out.println(totalAge); System.out.println(totalAge/map.size()); } }
package day8; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import day7.ForgetPage; public class FactoryRunner { WebDriver driver; @Test public void cancelButtonTest() { ExtentReports ex= new ExtentReports(); ex.attachReporter(new ExtentHtmlReporter("Orange.html")); ExtentTest tc=ex.createTest("ForgetLinkTest"); driver.get("https://opensource-demo.orangehrmlive.com/index.php/auth/login"); //PageFacc.info("Initializing Login Factory Class")tory Official Way Of Attaching Driver to page classes tc.info("Initializing LoginFactory class"); LoginFactory lf = PageFactory.initElements(driver, LoginFactory.class); tc.info("Click on Forget"); lf.clickForget(); tc.info("Verifying"); try { Assert.assertTrue(driver.getCurrentUrl().contains("requestPasswordResetCode")); tc.pass("Cancel Button Checked & Its Pass"); } catch(AssertionError e) { tc.fail("Cancel Button test gets Failed"+e.getMessage()); Assert.fail(e.getMessage()); } ex.flush(); } @BeforeTest public void beforeMethod() { System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @AfterTest public void afterMethod() throws Exception { Thread.sleep(3000); driver.quit(); } }
/* * 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.abeam.itap.framework.service; import com.abeam.itap.framework.common.exception.ABSystemException; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.PersistenceContext; import javax.transaction.SystemException; import javax.transaction.UserTransaction; /** * * @author smiyazawa@abeam.com */ public abstract class AbstractService implements ServiceInterface{ //@PersistenceContext(unitName="sample") //EntityManager em; @Resource UserTransaction utx; /** * * @param input * @return */ public OutputDTOInterface execute(InputDTOInterface input) { EntityTransaction eTran = null; try { preExecute(input); eTran = getEntityTransaction("sample"); if (eTran != null) { eTran.begin(); } else { utx.begin(); } OutputDTOInterface output = doExecute(input); if (eTran != null) { eTran.commit(); } else { utx.commit(); } return output; } catch (Throwable e) { try { //em.getTransaction().rollback(); if (eTran != null) { eTran.rollback(); } else { utx.rollback(); } System.out.println(e); } catch (SystemException se) { } throw new ABSystemException(); } finally { } } /** * * @param input */ protected void preExecute(InputDTOInterface input) { } /** * * @param input * @return */ protected abstract OutputDTOInterface doExecute(InputDTOInterface input); protected EntityTransaction getEntityTransaction(String unitName) { EntityManagerFactory emf = Persistence.createEntityManagerFactory(unitName); EntityManager em = emf.createEntityManager(); return em.getTransaction(); } }
/* * 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 classes; import java.util.ArrayList; import javax.swing.JOptionPane; /** * * @author Mateus Bernini */ public class Banco { public ArrayList<ContaBancaria> getC() { return c; } public void setC(ArrayList<ContaBancaria> c) { this.c = c; } ArrayList<ContaBancaria> c = new ArrayList<>(); public void inserir(ContaBancaria cb) { c.add(cb); JOptionPane.showMessageDialog(null, "Conta adicionada"); } public void remover(ContaBancaria cb) { c.remove(cb); } public ContaBancaria procurar(int numConta) { for (ContaBancaria conta : c) { if (conta.getNumConta() == numConta) { return conta; } } return null; } }
package com.system.service; import com.github.pagehelper.PageHelper; import com.system.entity.BusinessLogEntity; import com.system.mapper.BusinessLogMapper; import com.system.util.BusinessException; import com.system.util.PagerInfo; import com.system.util.ServiceResult; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import java.util.List; import java.util.Map; @Service("businessLogService") public class BusinessLogService { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(BusinessLogService.class); @Autowired private BusinessLogMapper businessLogMapper; /** * find list * * @Author qinwanli * @Description //TODO * @Date 2019/5/20 13:56 * @Param [params, pagerInfo] **/ public ServiceResult<List<BusinessLogEntity>> findList(Map<String, Object> params, PagerInfo<?> pagerInfo) { Assert.notNull(businessLogMapper, "Property 'businessLogMapper' is required."); ServiceResult<List<BusinessLogEntity>> result = new ServiceResult<>(); try { if (pagerInfo != null) { PageHelper.startPage(pagerInfo.getPageIndex(), pagerInfo.getPageSize()); } result.setResult(this.businessLogMapper.findList(params)); } catch (BusinessException be) { result.setSuccess(false); result.setMessage(be.getMessage()); } catch (Exception e) { result.setSuccess(false); result.setMessage("Unknown error!"); LOGGER.error("[BusinessLogService][findList]:query findList occur exception", e); } return result; } /** * find info * * @Author qinwanli * @Description //TODO * @Date 2019/5/20 13:57 * @Param [params] **/ public ServiceResult<BusinessLogEntity> findInfo(Map<String, Object> params) { Assert.notNull(businessLogMapper, "Property 'businessLogMapper' is required."); ServiceResult<BusinessLogEntity> result = new ServiceResult<>(); try { result.setResult(this.businessLogMapper.findInfo(params)); } catch (BusinessException be) { result.setSuccess(false); result.setMessage(be.getMessage()); } catch (Exception e) { result.setSuccess(false); result.setMessage("Unknown error!"); LOGGER.error("[BusinessLogService][findInfo]:query findList occur exception", e); } return result; } /** * do insert * * @Author qinwanli * @Description //TODO * @Date 2019/5/20 13:57 * @Param [businessLogEntity] **/ public ServiceResult<Integer> doInsert(BusinessLogEntity businessLogEntity) { Assert.notNull(businessLogMapper, "Property 'businessLogMapper' is required."); ServiceResult<Integer> result = new ServiceResult<>(); int id = 0; try { Integer success = this.businessLogMapper.doInsert(businessLogEntity); if (success > 0) { id=businessLogEntity.getBusinessLogId(); } result.setResult(id); } catch (BusinessException be) { result.setSuccess(false); result.setMessage(be.getMessage()); } catch (Exception e) { result.setSuccess(false); result.setMessage("Unknown error!"); LOGGER.error("[BusinessLogService][doInsert]:do Insert occur exception", e); } return result; } /** * do update * * @Author qinwanli * @Description //TODO * @Date 2019/5/20 13:56 * @Param [businessLogEntity] **/ public ServiceResult<Integer> doUpdate(BusinessLogEntity businessLogEntity) { Assert.notNull(businessLogMapper, "Property 'businessLogMapper' is required."); ServiceResult<Integer> result = new ServiceResult<>(); Integer id = 0; try { Integer success = this.businessLogMapper.doUpdate(businessLogEntity); if (success > 0) { id=businessLogEntity.getBusinessLogId(); } result.setResult(id); } catch (BusinessException be) { result.setSuccess(false); result.setMessage(be.getMessage()); } catch (Exception e) { result.setSuccess(false); result.setMessage("Unknown error!"); LOGGER.error("[BusinessLogService][doUpdate]: do update occur exception", e); } return result; } /** * do delete * * @Author qinwanli * @Description //TODO * @Date 2019/5/20 13:41 * @Param [businessId] **/ public ServiceResult<Boolean> doDelete(int businessId) { Assert.notNull(businessLogMapper, "Property 'businessLogMapper' is required."); ServiceResult<Boolean> result = new ServiceResult<>(); boolean flag = false; try { int id = this.businessLogMapper.doDelete(businessId); if (id > 0) { flag = true; } result.setResult(flag); } catch (BusinessException be) { result.setResult(false); result.setMessage(be.getMessage()); } catch (Exception e) { result.setResult(false); result.setMessage("Unknown error!"); LOGGER.error("[BusinessLogService][doDelete]:do delete occur exception", e); } return result; } }
import java.util.ArrayList; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; /** * Created by tanya on 4/13/2016. */ public class SchoolSystem { public static void main(String args[]) { Scanner console = new Scanner( System.in ); int rows = Integer.parseInt( console.nextLine() ); TreeMap<String, TreeMap<String, ArrayList<Integer>>> students = new TreeMap<>(); int count = 0; for (int i = 0; i < rows; i++) { String[] input = console.nextLine().split( "\\s+" ); String name = input[0] + " " + input[1]; String subject = input[2]; int score = Integer.parseInt( input[3] ); TreeMap<String, ArrayList<Integer>> subjects = new TreeMap<>(); if (students.containsKey( name )) { subjects = students.get( name ); if (!subjects.containsKey( subject )) { subjects.put( subject, new ArrayList<>() ); } subjects.get( subject ).add( score ); // ArrayList<Integer>marks=subjects.get( subject ); } else { ArrayList<Integer> marks = new ArrayList<>(); marks.add( score ); subjects.put( subject, marks ); students.put( name, subjects ); } } // for (String fullName : students.keySet()) { for (Map.Entry<String, TreeMap<String, ArrayList<Integer>>> result : students.entrySet()) { String fullName = result.getKey(); TreeMap<String, ArrayList<Integer>> marks = result.getValue(); System.out.print( fullName + ": " ); System.out.print( "[" ); boolean first = true; for (Map.Entry<String, ArrayList<Integer>> point : marks.entrySet()) { String sub = point.getKey(); ArrayList<Integer> res = point.getValue(); if (!first) { System.out.print( ", " ); } first = false; int sum = 0; for (double grade : res) { sum += grade; } double average = (double) sum / res.size(); System.out.printf( "%s - %.2f", sub, average ); } System.out.println( "]" ); } } }
package com.beiyelin.document.repository; import com.beiyelin.document.entity.Document; import org.springframework.data.solr.repository.Query; import org.springframework.data.solr.repository.SolrCrudRepository; import java.util.List; /** * Created by newmann 017-09-17. */ public interface DocumentRepository extends SolrCrudRepository<Document, String> { List<Document> findByItemTypeAndParentPath(String itemType,String parentPath); Document getByPath(String path); List<Document> findByName(String pathname); }
package student.collectionsgenerics; public class UsingCollections { public static void main(String[] args) { // Work with a list of Strings. manageFootballTeams(); // Work with a LinkedList of Doubles. // manageSalaries(); // Work with a TreeMap of Employees. // manageEmployees(); } // Work with a list of Strings. public static void manageFootballTeams() { // TODO: Declare a list to hold football teams (i.e. Strings). // You can create either an ArrayList or a LinkedList. // Miscellaneous helper variables. String team; int index; // Display menu options in a loop. int option = -1; do { try { System.out.println(); System.out.println("---------------------------------------------------------"); System.out.println("Options for managing a list of football teams (Strings)" ); System.out.println("---------------------------------------------------------"); System.out.println("1. Append team"); System.out.println("2. Add team at index"); System.out.println("3. Set team at index"); System.out.println("4. Remove team at index"); System.out.println("5. Remove specified team"); System.out.println("6. List all teams"); System.out.println("7. Quit"); option = Helper.getInt("\nEnter option => "); switch (option) { case 1: team = Helper.getString("Enter team: "); // TODO: Append team to list, and display success/failure message. // Display a success/failure message. break; case 2: team = Helper.getString("Enter team: "); index = Helper.getInt("Enter index: "); // TODO: If index is within range, add team at specified index in list. // Note, you ARE allowed to add an item at one-beyond-the-end of the list (similar effect to appending). // Display a success/failure message. break; case 3: team = Helper.getString("Enter team: "); index = Helper.getInt("Enter index: "); // TODO: If index is within range, set team at specified index in list. // Display a success/failure message. break; case 4: index = Helper.getInt("Enter index: "); // TODO: If index is within range, remove team at specified index in list. // Display a success/failure message. break; case 5: team = Helper.getString("Enter team: "); // TODO: Remove team from list. // Display a success/failure message. break; case 6: // TODO: Display all items in list. break; case 7: // This is a valid option, but there's nothing to do here. break; default: System.out.println("Invalid option selected."); } } catch (Exception ex) { System.out.printf("Exception occurred: %s.\n", ex.getMessage()); } } while (option != 7); } // Work with a LinkedList of Doubles. public static void manageSalaries() { // TODO: Declare a LinkedList to hold salaries (i.e. Doubles). // Miscellaneous helper variables. double salary; // Display menu options in a loop. int option = -1; do { try { System.out.println(); System.out.println("---------------------------------------------------------"); System.out.println("Options for managing a LinkedList of salaries (Doubles) "); System.out.println("---------------------------------------------------------"); System.out.println("1. Push salary"); System.out.println("2. Pop salary"); System.out.println("3. Add first "); System.out.println("4. Add last"); System.out.println("5. Peek first and last"); System.out.println("6. List all salaries"); System.out.println("7. Quit"); option = Helper.getInt("\nEnter option => "); switch (option) { case 1: salary = Helper.getDouble("Enter salary: "); // TODO: Push salary into linked list. // Display a success/failure message. break; case 2: // TODO: Pop salary off linked list. // Display a success/failure message. break; case 3: salary = Helper.getDouble("Enter salary: "); // TODO: Add salary at the start of the linked list. // Display a success/failure message. break; case 4: salary = Helper.getDouble("Enter salary: "); // TODO: Add salary at the end of the linked list. // Display a success/failure message. break; case 5: // TODO: If linked list isn't empty, peek at the first and last entries. // If linked list IS empty, display a suitable message. break; case 6: // TODO: Display all items in linked list. break; case 7: // This is a valid option, but there's nothing to do here. break; default: System.out.println("Invalid option selected."); } } catch (Exception ex) { System.out.printf("Exception occurred: %s.\n", ex.getMessage()); } } while (option != 7); } // Work with a TreeMap of Employees. public static void manageEmployees() { // TODO: Declare a TreeMap to hold Employees (keyed by employee id). // Miscellaneous helper variables. Employee emp; String id; // Display menu options in a loop. int option = -1; do { try { System.out.println(); System.out.println("---------------------------------------------------------"); System.out.println("Options for managing a TreeMap of Employees (keyed by ID)"); System.out.println("---------------------------------------------------------"); System.out.println("1. Put employee"); System.out.println("2. Remove employee for id"); System.out.println("3. Is id present?"); System.out.println("4. Is employee present?"); System.out.println("5. Display first and last entries"); System.out.println("6. Display all employees"); System.out.println("7. Quit"); option = Helper.getInt("\nEnter option => "); switch (option) { case 1: emp = Employee.createEmployee(); // TODO: Put employee into map. // Display a success/failure message. break; case 2: id = Helper.getString("Enter id: "); // TODO: Remove employee with specified id. // Display a success/failure message. break; case 3: id = Helper.getString("Enter id: "); // TODO: Display message indicating whether the map contains the specified id. break; case 4: emp = Employee.createEmployee(); // TODO: Display message indicating whether the map contains an employee with the specified values. break; case 5: // TODO: If map isn't empty, display the key/value for the first entry and for the last entry. // If map IS empty, display a suitable message. break; case 6: // TODO: Display all employee objects (i.e. values) in map. break; case 7: // This is a valid option, but there's nothing to do here. break; default: System.out.println("Invalid option selected."); } } catch (Exception ex) { System.out.printf("Exception occurred: %s.\n", ex.getMessage()); } } while (option != 7); } }
package rest.dao; import java.util.List; import org.springframework.stereotype.Repository; import rest.entity.Employee; @Repository public interface EmployeeDAO { public Employee getEmployeeById(int id) ; public List<Employee> getAllEmployees() ; public void deleteEmployee(int id); public void updateEmployee( Employee item ) ; public void createEmployee(Employee item) ; }
package org.scottrager.appfunding; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class CouponBookArrayAdapter extends ArrayAdapter<String> { private final Context context; private final ArrayList<String> couponBookNames; private final ArrayList<Integer> couponBookCosts; private final ArrayList<String> couponBookValues; private final ArrayList<Integer> couponBookNumbers; public CouponBookArrayAdapter(Context context, ArrayList<String> couponBookNames, ArrayList<Integer> couponBookCosts, ArrayList<String> couponBookValues, ArrayList<Integer> couponBookNumbers) { super(context, R.layout.coupon_row, couponBookNames); this.context = context; this.couponBookNames = couponBookNames; this.couponBookCosts = couponBookCosts; this.couponBookValues = couponBookValues; this.couponBookNumbers = couponBookNumbers; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.coupon_book_row, parent, false); TextView coupBookName = (TextView) rowView.findViewById(R.id.couponBookName); coupBookName.setText(couponBookNames.get(position)); TextView coupBookCost = (TextView) rowView.findViewById(R.id.couponBookCost); coupBookCost.setText("Cost: $"+couponBookCosts.get(position)); TextView coupBookValue = (TextView) rowView.findViewById(R.id.couponBookValue); coupBookValue.setText(couponBookValues.get(position)); return rowView; } }
package com.monsordi.na_at; import android.content.ContentValues; import android.database.Cursor; import com.monsordi.na_at.sqlite.FeedReaderContract.FeedEntry; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created by diego on 09/04/18. */ public class Worker{ private String name; private String email; private String job; private String imageUrl; public Worker(String name, String email, String job, String imageUrl) { this.name = name; this.email = email; this.job = job; this.imageUrl = imageUrl; } public Worker(Cursor cursor){ this.name = cursor.getString(cursor.getColumnIndex(FeedEntry.COLUMN_NAME)); this.email = cursor.getString(cursor.getColumnIndex(FeedEntry.COLUMN_EMAIL)); this.job = cursor.getString(cursor.getColumnIndex(FeedEntry.COLUMN_JOB)); this.imageUrl = cursor.getString(cursor.getColumnIndex(FeedEntry.COLUMN_IMAGE)); } public String getName() { return name; } public String getEmail() { return email; } public String getJob() { return job; } public String getImageUrl() { return imageUrl; } public ContentValues toContentValues(){ ContentValues contentValues = new ContentValues(); contentValues.put(FeedEntry.COLUMN_NAME,name); contentValues.put(FeedEntry.COLUMN_EMAIL,email); contentValues.put(FeedEntry.COLUMN_JOB,job); contentValues.put(FeedEntry.COLUMN_IMAGE,imageUrl); return contentValues; } }
package com.tencent.pb.common.b.a; import com.google.a.a.b; import com.google.a.a.e; public final class a$ap extends e { public int veE; public int veF; public a$ap() { this.veE = 0; this.veF = 0; this.bfP = -1; } public final void a(b bVar) { if (this.veE != 0) { bVar.aE(1, this.veE); } if (this.veF != 0) { bVar.aE(2, this.veF); } super.a(bVar); } protected final int sl() { int sl = super.sl(); if (this.veE != 0) { sl += b.aG(1, this.veE); } if (this.veF != 0) { return sl + b.aG(2, this.veF); } return sl; } }
package walking_web.webb; import java.util.Optional; 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.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import walking_web.models.Order; import walking_web.models.Shoe; import walking_web.services.OrderService; import walking_web.services.ShoeService; import walking_web.services.StaffService; @Controller public class AdminWebController { @Autowired private StaffService staffService; @Autowired private ShoeService shoeService; @Autowired private OrderService orderService; Logger logger = LoggerFactory.getLogger(AdminWebController.class); @GetMapping("/admin/login") public String loginForm(Model model) { model.addAttribute("loginFormBean", new LoginFormBean()); model.addAttribute("message", "Please login:"); return "login-admin"; } @PostMapping("/admin/login") public String loginSubmit(@ModelAttribute LoginFormBean loginFormBean, Model model) { if (staffService.login(loginFormBean.getUsername())) { model.addAttribute("username", loginFormBean.getUsername()); return "admin-main"; } else { return "login-admin"; } } @GetMapping("/admin/main") public String mainForm() { return "admin-main"; } @PostMapping("/admin/main") public String main() { return "admin-main"; } @GetMapping("/admin/orders") public String showOrders(Model model) { model.addAttribute("listAllOrders", orderService.getAllOrders()); return "orders"; } @GetMapping("/admin/order/viewOrder/{id}") public String showOrderDetails(@PathVariable Long id, Model model) { Order order = orderService.getOrder(id).get(); model.addAttribute("orderlines", order.getOrderlines()); model.addAttribute("order", orderService.getOrder(id).get()); return "expedite"; } @PostMapping("/admin/order/viewOrder/shipOrder/{id}") public String shipOrder(@PathVariable Long id) { Order order = orderService.getOrder(id).get(); order.setStatusDelivered(true); orderService.editOrder(order); return "redirect:/admin/orders"; } @PostMapping("/admin/order/viewOrder/deleteOrder/{id}") public String deleteOrder(@PathVariable Long id) { Order order = orderService.getOrder(id).get(); if (order.isStatusDelivered()) { System.out.println("Nope"); return "redirect:/admin/orders"; } else { orderService.removeOrder(order); } return "redirect:/admin/orders"; } @GetMapping("/admin/products") public String showShoes(Model model) { model.addAttribute("listAllShoes", shoeService.listAllShoes()); return "shoes"; } @GetMapping("/admin/products/create") public String createShoeForm(Model model) { Shoe shoe = new Shoe(); model.addAttribute("shoe", shoe); return "new-shoe"; } @PostMapping("/admin/products/create") public String createShoe(@ModelAttribute("shoe") Shoe shoe) { shoeService.addShoe(shoe); return "redirect:/admin/products"; } @GetMapping("/admin/products/edit/{id}") public ModelAndView editShoeForm(@PathVariable Long id) { ModelAndView mav = new ModelAndView("edit-shoe"); Optional<Shoe> shoe = shoeService.findById(id); mav.addObject("shoe", shoe); return mav; } @RequestMapping("/admin/products/delete/{id}") public String removeShoe(@PathVariable Long id) { shoeService.removeShoeById(id); return "redirect:/admin/products"; } }
package com.hit.neuruimall.mapper; import com.hit.neuruimall.model.OrderItemModel; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; @Mapper @Repository public interface OrderItemMapper { public List<Integer> selectAllOrderId(); public List<OrderItemModel> selectById(Integer orderId); public List<Integer> selectAllOrderIdWithUserId(Integer userId); }
package org.maven.ide.eclipse.io; import junit.framework.TestSuite; import org.sonatype.tests.http.runner.junit.Junit3SuiteConfiguration; public class RedirectProjectCatalogTest extends AbstractIOTest { public void testDummy() { } public static TestSuite suite() throws Exception { return Junit3SuiteConfiguration.suite( RedirectProjectCatalogTest.class ); } }
package cn.edu.sdjzu.xg.bysj.dao; //201902104050 姜瑞临 import cn.edu.sdjzu.xg.bysj.domain.Department; import cn.edu.sdjzu.xg.bysj.domain.School; import cn.edu.sdjzu.xg.bysj.service.SchoolService; import util.Condition; import util.JdbcHelper; import util.Pagination; import java.sql.*; import java.util.Collection; import java.util.HashSet; public final class DepartmentDao { private static DepartmentDao departmentDao = new DepartmentDao(); private DepartmentDao() { } public static DepartmentDao getInstance() { return departmentDao; } public Collection<Department> findAll(Connection conn, String condition, Pagination pagination) throws SQLException { //创建集合类对象,用来保存并排序所有获得的department对象 Collection<Department> depts = new HashSet<>(); int totalNum = SchoolDao.getInstance().count(conn); //创建查询的主句 StringBuilder select = new StringBuilder("SELECT * from department "); //将可能的条件附加到主句后 if (condition != null){ String clause = Condition.toWhereClause(condition); select.append(clause); } if (pagination != null){ select.append(pagination.toLimitClause(totalNum)+ " "); } //在连接上创建语句盒子对象 System.out.println(select.toString()); PreparedStatement statement = conn.prepareStatement(select.toString()); //执行SQL语句 ResultSet results = statement.executeQuery(); //遍历resultSet,并将结果写入对象存进集合内 while (results.next()){ int id = results.getInt("id"); String description = results.getString("description"); String no = results.getString("no"); String remarks = results.getString("remarks"); int school_id = results.getInt("managementSchool"); Department department = new Department(id,description,no,remarks, SchoolService.getInstance().find(school_id)); depts.add(department); } //关闭资源 JdbcHelper.close(results,statement,null); //返回获得的集合对象 return depts; } public Department find(Integer id,Connection conn) throws SQLException { Department desiredDepartment = null; //创建SQL语句 String search = "SELECT * from department where id = " + id; //在连接上创建语句盒子对象 Statement statement = conn.createStatement(); //执行SQL语句 ResultSet results = statement.executeQuery(search); results.next(); try(statement;results){ //将获取的对象参数写入预先创建的对象 desiredDepartment = new Department( results.getInt(1), results.getString(2), results.getString(3), results.getString(4), SchoolService.getInstance().find(results.getInt(5)) ); return desiredDepartment; } } public boolean update(Department department,Connection conn) throws SQLException { //使用预编译创建SQL语句 String update = "update department set description = ?,no= ?,remarks= ?,managementSchool= ? where id = " + department.getId(); PreparedStatement statement = conn.prepareStatement(update); //执行SQL语句并返回结果和关闭连接 try (statement) { statement.setString(1, department.getDescription()); statement.setString(2, department.getNo()); statement.setString(3, department.getRemarks()); statement.setInt(4, department.getSchool().getId()); statement.executeUpdate(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } public boolean add(Department department,Connection conn) throws SQLException { //使用预编译创建SQL语句 String create = "insert into department(description,no,remarks,managementSchool) values (?,?,?,?)"; PreparedStatement statement = conn.prepareStatement(create); System.out.println(department); //执行SQL语句并返回结果和关闭连接 try (statement) { statement.setString(1, department.getDescription()); statement.setString(2, department.getNo()); statement.setString(3, department.getRemarks()); statement.setInt(4, department.getSchool().getId()); statement.executeUpdate(); return true; }catch (SQLException e){ return false; } } public boolean delete(Integer id,Connection conn) throws SQLException { //创建删除语句 String delete = "delete from department where id = " + id; //在连接上创建语句盒子对象 Statement statement = conn.createStatement(); //执行SQL语句 int i = statement.executeUpdate(delete); //关闭连接 JdbcHelper.close(statement,conn); return (i>0); } public Integer countAll(School school,Connection conn) throws SQLException{ int id = school.getId(); //创建SQL语句 String search = "SELECT count(id) as cnt_by_school from department where id = " + id; //在连接上创建语句盒子对象 PreparedStatement statement = conn.prepareStatement(search); //执行SQL语句 ResultSet results = statement.executeQuery(); results.next(); //获取学院下专业数量 int count = results.getInt(1); //关闭资源 JdbcHelper.close(results,statement,conn); //返回数据 return count; } public int count(Connection connection) throws SQLException { String sql_count = "SELECT COUNT(id) as cnt FROM department"; PreparedStatement pstmt_count = connection.prepareStatement(sql_count); int counter = 0; ResultSet resultSet_count = pstmt_count.executeQuery(); if (resultSet_count.next()) { counter = resultSet_count.getInt("cnt"); }return counter; } }
import org.antlr.v4.runtime.misc.NotNull; import java.util.HashMap; import java.util.List; import java.util.Map; public class VisitorImplementation extends KornBaseVisitor<Value> { }
/* * Copyright (c) 2008-2016 Haulmont. * * 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.company.cubavisionclinic.entity; import com.haulmont.chile.core.annotations.Composition; import com.haulmont.chile.core.annotations.MetaProperty; import com.haulmont.chile.core.annotations.NamePattern; import com.haulmont.cuba.core.entity.BaseIdentityIdEntity; import com.haulmont.cuba.core.global.DesignSupport; import com.haulmont.cuba.core.global.PersistenceHelper; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; import java.util.Set; @DesignSupport("{'imported':true}") @AttributeOverrides({ @AttributeOverride(name = "id", column = @Column(name = "ProductID")) }) @NamePattern("%s|productName") @Table(name = "Product") @Entity(name = "cubavisionclinic$Product") public class Product extends BaseIdentityIdEntity { private static final long serialVersionUID = 6459017363675748947L; @Column(name = "ProductName", nullable = false, length = 50) protected String productName; @Column(name = "MSRP", nullable = false, precision = 19, scale = 4) protected BigDecimal msrp; @Lob @Column(name = "Description") protected String description; @Column(name = "ProductImage") protected byte[] productImage; @Lob @Column(name = "Category") protected String category; /** * The collection contains all {@link ProductRebate} instances that have reference * to this {@link Product} via the {@link ProductRebate#productID} field */ @Composition @OneToMany(mappedBy = "productID") protected Set<ProductRebate> rebates; public void setRebates(Set<ProductRebate> rebates) { this.rebates = rebates; } public Set<ProductRebate> getRebates() { return rebates; } public void setProductName(String productName) { this.productName = productName; } public String getProductName() { return productName; } public void setMsrp(BigDecimal msrp) { this.msrp = msrp; } public BigDecimal getMsrp() { return msrp; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void setProductImage(byte[] productImage) { this.productImage = productImage; } public byte[] getProductImage() { return productImage; } public void setCategory(String category) { this.category = category; } public String getCategory() { return category; } /** * Calculates the currentPrice value for the {@link Product} instance, considering {@link Product#rebates} * @return {@link BigDecimal} value representing the product price after rebates */ @MetaProperty public BigDecimal getCurrentPrice() { if (msrp == null) return null; if (rebates != null && PersistenceHelper.isLoaded(this, "rebates")) { final Date now = new Date(); BigDecimal totalRebate = rebates.stream() .filter(e -> (e.rebateStart == null || now.after(e.rebateStart)) && (e.rebateEnd == null || now.before(e.rebateEnd)) && e.rebate != null ) .map(ProductRebate::getRebate) .reduce(BigDecimal.ZERO, BigDecimal::add); return msrp.subtract(totalRebate); } return null; } }
/* * Copyright 2006 Ameer Antar. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.antfarmer.ejce.hibernate; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import org.antfarmer.ejce.util.StreamUtil; import org.hibernate.engine.spi.SessionImplementor; /** * Hibernate UserType class which encrypts and decrypts arbitrarily large text values transparently. * This ensures data is stored in it's encrypted form in persistent storage, while not affecting it's * real value in the application. * @author Ameer Antar */ public class EncryptedTextType extends EncryptedClobType { /** * {@inheritDoc} */ @Override public Class<?> returnedClass() { return String.class; } /** * {@inheritDoc} */ @Override protected InputStream lobToStream(final Object value) throws SQLException { return value instanceof String ? new ByteArrayInputStream(((String) value).getBytes(getCharset())) : super.lobToStream(value); } /** * {@inheritDoc} */ @Override protected Object createLob(final InputStream is, final long length, final SessionImplementor session) throws IOException { return new String(StreamUtil.streamToBytes(is), getCharset()); } /** * {@inheritDoc} */ @Override protected Object createLob(final byte[] bytes, final SessionImplementor session) throws IOException { return new String(bytes, getCharset()); } }
import com.sun.jna.*; import com.sun.jna.platform.win32.WinDef; import com.sun.jna.platform.win32.WinNT; import com.sun.jna.ptr.PointerByReference; import java.util.List; import java.util.Arrays; public class SCREEN extends Structure { public int nScreenIndex; public short uVendorID; public short uProductID; public short uVersionNumber; public char[] szDevicePath = new char[WinDef.MAX_PATH]; public WinNT.HANDLE hCalTouchThread; public MONITOR.ByReference pMonitor; public PointerByReference pCWndBeamHandler; public boolean bIrBeams; public SCREEN() { super(); } @Override protected List<?> getFieldOrder() { return Arrays.asList("nScreenIndex", "uVendorID", "uProductID", "uVersionNumber", "szDevicePath", "hCalTouchThread", "pMonitor", "pCWndBeamHandler", "bIrBeams"); } public SCREEN(Pointer peer) { super(peer); } public static class ByReference extends SCREEN implements Structure.ByReference { }; public static class ByValue extends SCREEN implements Structure.ByValue { }; }
package com.av.payment.repository; import com.av.payment.model.SubscriptionRequest; import com.av.payment.model.SubscriptionResponse; import com.av.payment.repository.validator.RequestValidator; import com.av.payment.util.Contants; import com.av.payment.repository.persistor.SubscriptionPersister; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by Aman Verma on 18/03/2018. * <p> * Internal data struture used to save the data */ @Service public class SubscriptionRepository { private final RequestValidator reqValidator; private final SubscriptionPersister reqPersister; private final SubscriptionRepositoryUtil subReqUtil; /** * @param reqValidator * @param reqPersister * @param subReqUtil */ @Autowired public SubscriptionRepository(RequestValidator reqValidator, SubscriptionPersister reqPersister, SubscriptionRepositoryUtil subReqUtil) { this.reqValidator = reqValidator; this.reqPersister = reqPersister; this.subReqUtil = subReqUtil; } /** * Service endpoint /api/createSub * creates subscription, persists and send response with invoice dates details. * * @param subReq * @return */ public SubscriptionResponse fetchSubscriptionInvoiceDetails(SubscriptionRequest subReq) { reqValidator.validateRequest(subReq, Contants.DATE_PATTERN); reqPersister.saveSubscriptionRequest(subReq); List<String> invoiceDates = subReqUtil.computeInvoiceDates(subReq); SubscriptionResponse response = new SubscriptionResponse(subReq.getId(), subReq.getAmount(), subReq.getSubscriptionType(), invoiceDates); return response; } }
package com.mideas.rpg.v2.game.item.shop; import java.sql.SQLException; import java.util.ArrayList; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import com.mideas.rpg.v2.Interface; import com.mideas.rpg.v2.Mideas; import com.mideas.rpg.v2.FontManager; import com.mideas.rpg.v2.game.CharacterStuff; import com.mideas.rpg.v2.game.IconsManager; import com.mideas.rpg.v2.game.Shop; import com.mideas.rpg.v2.game.item.Item; import com.mideas.rpg.v2.game.item.ItemType; import com.mideas.rpg.v2.game.item.container.Container; import com.mideas.rpg.v2.game.item.container.ContainerManager; import com.mideas.rpg.v2.game.item.gem.GemManager; import com.mideas.rpg.v2.game.item.potion.Potion; import com.mideas.rpg.v2.game.item.potion.PotionManager; import com.mideas.rpg.v2.game.item.stuff.Stuff; import com.mideas.rpg.v2.game.item.stuff.StuffManager; import com.mideas.rpg.v2.game.item.weapon.WeaponManager; import com.mideas.rpg.v2.game.unit.ClassType; import com.mideas.rpg.v2.game.unit.Joueur; import com.mideas.rpg.v2.hud.ContainerFrame; import com.mideas.rpg.v2.hud.DragManager; import com.mideas.rpg.v2.hud.LogChat; import com.mideas.rpg.v2.jdo.JDOStatement; import com.mideas.rpg.v2.render.Draw; import com.mideas.rpg.v2.render.Sprites; import com.mideas.rpg.v2.utils.Color; public class ShopManager { private static int slot_hover = -1; private static boolean left_arrow; private static boolean right_arrow; private static boolean hover_button; private static int page; private static int numberPage; private static Color bgColors = new Color(0, 0, 0, .6f); private static Color borderColors = Color.decode("#494D4B"); private static ArrayList<Shop> shopList = new ArrayList<Shop>(); /*public static void loadStuffs() { try { JDOStatement statement = Mideas.getJDO().prepare("SELECT id, class, price FROM shop"); statement.execute(); double i = 0; while(statement.fetch()) { int id = statement.getInt(); short classeTemp = statement.getShort(); ClassType[] classeType = StuffManager.getClasses(classeTemp); int sellPrice = statement.getInt(); shopList.add(new Shop(id, classeType, sellPrice)); i++; } numberPage = (int)Math.ceil(i/10); } catch(SQLException e) { e.printStackTrace(); } }*/ public static Item getItem(int id) { if(StuffManager.exists(id)) { return StuffManager.getStuff(id); } if(PotionManager.exists(id)) { return PotionManager.getPotion(id); } if(ContainerManager.exists(id)) { return ContainerManager.getContainer(id); } if(WeaponManager.exists(id)) { return WeaponManager.getWeapon(id); } if(GemManager.exists(id)) { return GemManager.getGem(id); } return null; } public static void draw() { int xLeft = (int)(-279*Mideas.getDisplayXFactor()); int xRight = (int)(-114*Mideas.getDisplayXFactor()); int y = (int)(-275*Mideas.getDisplayYFactor()); int y_arrow = (int)(267*Mideas.getDisplayXFactor()); int yShift = (int)(52*Mideas.getDisplayXFactor()); Draw.drawQuad(Sprites.shop_frame, Display.getWidth()/2-300*Mideas.getDisplayXFactor(), Display.getHeight()/2-350*Mideas.getDisplayYFactor()); int i = 0; int j = 0; int x = xLeft; int z = 0; while(i < 10) { drawShopItem(i, x, y+j*yShift); shopHover(i, x+z, y+j*yShift, x, y+j*yShift); drawGoldCoin(i, x, y+j*yShift); i++; j++; if(i%5 == 0) { j = 0; } if(i == 5) { x = xRight; z = 165; } } calcCoin(Mideas.joueur1().getGold(), xRight, y+250); if(hover_button) { Draw.drawQuad(Sprites.close_shop_hover, Display.getWidth()/2+27, Display.getHeight()/2-337); } if(page != 0) { Draw.drawQuad(Sprites.left_colored_arrow, Display.getWidth()/2+xLeft+3, Display.getHeight()/2+y+y_arrow); } if(page != numberPage-1) { Draw.drawQuad(Sprites.right_colored_arrow, Display.getWidth()/2+xRight+125*Mideas.getDisplayXFactor(), Display.getHeight()/2+y+y_arrow); } if(right_arrow && page != numberPage-1) { Draw.drawQuad(Sprites.right_arrow_hover, Display.getWidth()/2+xRight+125*Mideas.getDisplayXFactor(), Display.getHeight()/2+y+y_arrow); } if(left_arrow && page != 0) { Draw.drawQuad(Sprites.left_arrow_hover, Display.getWidth()/2+xLeft+3, Display.getHeight()/2+y+y_arrow); } if(page == numberPage-1) { Draw.drawQuad(Sprites.right_uncolored_arrow, Display.getWidth()/2+xRight+125*Mideas.getDisplayXFactor(), Display.getHeight()/2+y+y_arrow); } } public static boolean mouseEvent() { if(isHoverShopFrame()) { slot_hover = -1; } right_arrow = false; left_arrow = false; hover_button = false; int xLeft = -279; int xRight = -114; int y = -275; if(Mideas.mouseX() >= Display.getWidth()/2+xRight+126 && Mideas.mouseX() <= Display.getWidth()/2+xRight+151 && Mideas.mouseY() >= Display.getHeight()/2+y+266 && Mideas.mouseY() <= Display.getHeight()/2+y+292) { right_arrow = true; } else if(Mideas.mouseX() >= Display.getWidth()/2+xRight-161 && Mideas.mouseX() <= Display.getWidth()/2+xRight-136 && Mideas.mouseY() >= Display.getHeight()/2+y+266 && Mideas.mouseY() <= Display.getHeight()/2+y+292) { left_arrow = true; } if(Mideas.mouseX() >= Display.getWidth()/2+27 && Mideas.mouseX() <= Display.getWidth()/2+46 && Mideas.mouseY() >= Display.getHeight()/2-337 && Mideas.mouseY() <= Display.getHeight()/2-319) { hover_button = true; } if(Mouse.getEventButtonState()) { if(Mideas.mouseX() >= Display.getWidth()/2+27 && Mideas.mouseX() <= Display.getWidth()/2+46 && Mideas.mouseY() >= Display.getHeight()/2-337 && Mideas.mouseY() <= Display.getHeight()/2-319) { Interface.closeShopFrame(); return true; } else if(right_arrow && page < numberPage-1) { page++; return true; } else if(left_arrow && page > 0) { page--; return true; } } isSlotHover(xLeft, y, 0, 41, 0); isSlotHover(xLeft, y, 52, 93, 1); isSlotHover(xLeft, y, 104, 145, 2); isSlotHover(xLeft, y, 156, 197, 3); isSlotHover(xLeft, y, 208, 249, 4); isSlotHover(xRight, y, 0, 41, 5); isSlotHover(xRight, y, 52, 93, 6); isSlotHover(xRight, y, 104, 145, 7); isSlotHover(xRight, y, 156, 197, 8); isSlotHover(xRight, y, 208, 249, 9); if(!Mouse.getEventButtonState()) { if(Mouse.getEventButton() == 1) { int i = 0; if(DragManager.isHoverBagFrame()) { while(i < Mideas.joueur1().bag().getBag().length) { if(sellItem(i)) { break; } i++; } } } else if(Mouse.getEventButton() == 0) { if(isHoverShopFrame()) { int i = 0; while(i < 10 && i+10*page < shopList.size()) { if(buyItems(i, shopList.get(i+10*page))) { return true; } i++; } } } } return false; } public static boolean buyItems(int i, Shop item) { if(slot_hover == i && item != null) { if(Mideas.joueur1().getGold() >= item.getSellPrice()) { checkItem(item); } else { LogChat.setStatusText3("Vous n'avez pas assez d'argent"); } return true; } return false; } private static boolean sellItem(int i) { Item item = Mideas.joueur1().bag().getBag(i); boolean hover = ContainerFrame.getContainerFrameSlotHover(i); boolean click_hover = DragManager.getClickBag(i); if(item != null && hover && click_hover && Interface.getShopFrameStatus()) { if(item.isStackable()) { LogChat.setStatusText3("Vous avez vendu "+item.getAmount()+" "+item.getStuffName()+" pour "+item.getSellPrice()*item.getAmount()); Mideas.joueur1().setGold(Mideas.joueur1().getGold()+item.getSellPrice()*item.getAmount()); Mideas.joueur1().bag().setBag(i, null); } else { Mideas.joueur1().setGold(Mideas.joueur1().getGold()+item.getSellPrice()); LogChat.setStatusText3("Vous avez vendu "+item.getStuffName()+" pour "+item.getSellPrice()); } //CharacterStuff.setBagItems(); DragManager.mouseEvent(); return true; } return false; } private static boolean checkItem(Shop item) { int i = 0; if(StuffManager.exists(item.getId()) || WeaponManager.exists(item.getId())) { while(i < Mideas.joueur1().bag().getBag().length) { if(Mideas.joueur1().bag().getBag(i) == null) { Mideas.joueur1().bag().setBag(i, StuffManager.getClone(item.getId())); LogChat.setStatusText3("Vous avez bien achet� "+StuffManager.getStuff(item.getId()).getStuffName()); Mideas.joueur1().setGold(Mideas.joueur1().getGold()-item.getSellPrice()); //CharacterStuff.setBagItems(); return true; } i++; } } else if(PotionManager.exists(item.getId())) { if(checkBagItem(item)) { while(i < Mideas.joueur1().bag().getBag().length) { if(Mideas.joueur1().bag().getBag(i) != null && Mideas.joueur1().bag().getBag(i).getId() == item.getId()) { Mideas.joueur1().bag().getBag(i).setAmount(Mideas.joueur1().bag().getBag(i).getAmount()+1); LogChat.setStatusText3("Vous avez bien achet� "+PotionManager.getPotion(item.getId()).getStuffName()); Mideas.joueur1().setGold(Mideas.joueur1().getGold()-item.getSellPrice()); //CharacterStuff.setBagItems(); return true; } i++; } } else { while(i < Mideas.joueur1().bag().getBag().length) { if(Mideas.joueur1().bag().getBag(i) == null) { Potion temp = PotionManager.getClone(item.getId()); Mideas.joueur1().bag().setBag(i, temp); temp.setAmount(1); LogChat.setStatusText3("Vous avez bien achet� "+PotionManager.getPotion(item.getId()).getStuffName()); Mideas.joueur1().setGold(Mideas.joueur1().getGold()-item.getSellPrice()); //CharacterStuff.setBagItems(); return true; } i++; } } } else if(GemManager.exists(item.getId())) { while(i < Mideas.joueur1().bag().getBag().length) { if(Mideas.joueur1().bag().getBag(i) == null) { Mideas.joueur1().bag().setBag(i, GemManager.getClone(item.getId())); LogChat.setStatusText3("Vous avez bien achet� "+GemManager.getGem(item.getId()).getStuffName()); Mideas.joueur1().setGold(Mideas.joueur1().getGold()-item.getSellPrice()); //CharacterStuff.setBagItems(); return true; } i++; } } LogChat.setStatusText3("Votre inventaire est pleins"); return false; } private static boolean checkBagItem(Shop item) { int i = 0; while(i < Mideas.joueur1().bag().getBag().length) { if(Mideas.joueur1().bag().getBag(i) != null && Mideas.joueur1().bag().getBag(i).getId() == item.getId()) { return true; } i++; } return false; } private static void drawShopItem(int i, int x, int y) { if(i+10*page < shopList.size()) { Draw.drawQuad(IconsManager.getSprite37(getItem(shopList.get(i+10*page).getId()).getSpriteId()), Display.getWidth()/2+x+3, Display.getHeight()/2+y+3); Draw.drawQuad(Sprites.shop_border, Display.getWidth()/2+x-1, Display.getHeight()/2+y); } } private static void shopHover(int i, int x_item, int y_item, int x_hover, int y_hover) { if(slot_hover == i) { if(i+10*page < shopList.size()) { int shift = 40; Item item = getItem(shopList.get(i+10*page).getId()); if(item.getItemType() == ItemType.STUFF) { if(i < 5) { drawLeftStuff(i, x_item, y_item); } else { drawRightStuff(i, x_item, y_item); } } else if(item.getItemType() == ItemType.POTION) { shift = 25; Draw.drawColorQuad(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item, 285, 40+FontManager.get("FRIZQT", 15).getLineHeight()*2, bgColors); Draw.drawColorQuadBorder(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item, 287, 40+FontManager.get("FRIZQT", 15).getLineHeight()*2, borderColors); x_item+= 10; FontManager.get("FRIZQT", 20).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item, item.getStuffName(), item.getNameColor(), Color.BLACK, 1, 1, 1); if(((Potion)item).getPotionHeal() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, "Restores "+((Potion)item).getPotionHeal()+" Hp", Color.GREEN, Color.BLACK, 1, 1, 1); shift+= 20; } if(((Potion)item).getPotionMana() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, "Restores "+((Potion)item).getPotionMana()+" Mana", Color.GREEN, Color.BLACK, 1, 1, 1); shift+= 20; } if(Mideas.joueur1().getLevel() >= ((Potion)item).getLevel()) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, "Level "+((Potion)item).getLevel()+" requiRED", Color.WHITE, Color.BLACK, 1, 1, 1); } else { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, "Level "+((Potion)item).getLevel()+" requiRED", Color.RED, Color.BLACK, 1, 1, 1); } } else if(item.isContainer()) { Draw.drawColorQuad(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item, 285, 40+FontManager.get("FRIZQT", 15).getLineHeight(), bgColors); Draw.drawColorQuadBorder(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item, 287, 40+FontManager.get("FRIZQT", 15).getLineHeight(), borderColors); FontManager.get("FRIZQT", 20).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item, item.getStuffName(), item.getNameColor(), Color.BLACK, 1, 1, 1); FontManager.get("FRIZQT", 20).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+20, "Container "+((Container)item).getSize()+" slots", Color.WHITE, Color.BLACK, 1, 1, 1); } } Draw.drawQuad(Sprites.shop_hover, Display.getWidth()/2+x_hover, Display.getHeight()/2+y_hover); } } private static void drawLeftStuff(int i, int x_item, int y_item) { Color temp = null; Item item = getItem(shopList.get(i+10*page).getId()); int xShift = 280; int shift = 75; String classe = ""; if(((Stuff)item).getClassType().length < 10) { classe = "Classes: "; int k = 0; while(k < ((Stuff)item).getClassType().length) { if(k == ((Stuff)item).getClassType().length-1) { classe+= ((Stuff)item).convClassTypeToString(k); } else { classe+= ((Stuff)item).convClassTypeToString(k)+", "; } k++; } } if(FontManager.get("FRIZQT", 20).getWidth(item.getStuffName()) > 285 || FontManager.get("FRIZQT", 15).getWidth(classe) > 285) { xShift = Math.max(FontManager.get("FRIZQT", 20).getWidth(item.getStuffName()), FontManager.get("FRIZQT", 15).getWidth(classe))+15; } Draw.drawColorQuad(Display.getWidth()/2+x_item-15, Display.getHeight()/2+30+y_item, -5-xShift, 75+FontManager.get("FRIZQT", 15).getLineHeight()*ContainerFrame.getNumberStats((Stuff)item), bgColors); Draw.drawColorQuadBorder(Display.getWidth()/2+x_item-14, Display.getHeight()/2+30+y_item, -7-xShift, 75+FontManager.get("FRIZQT", 15).getLineHeight()*ContainerFrame.getNumberStats((Stuff)item), borderColors); FontManager.get("FRIZQT", 20).drawStringShadow(Display.getWidth()/2+x_item-10-xShift, Display.getHeight()/2+y_item+33, item.getStuffName(), item.getNameColor(), Color.BLACK, 1, 1, 1); FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item-10-xShift, Display.getHeight()/2+y_item+55, ((Stuff)item).convStuffTypeToString(), Color.WHITE, Color.BLACK, 1, 1, 1); if(Mideas.joueur1().canWear((Stuff)item)) { temp = Color.WHITE; } else { temp = Color.RED; } FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item-20-FontManager.get("FRIZQT", 16).getWidth(((Stuff)item).convWearToString()), Display.getHeight()/2+y_item+55, ((Stuff)item).convWearToString(), temp, Color.BLACK, 1, 1, 1); if(((Stuff)item).getArmor() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item-10-xShift, Display.getHeight()/2+y_item+shift, "Armor : "+((Stuff)item).getArmor(), Color.WHITE, Color.BLACK, 1, 1, 1); shift+= 20; } if(((Stuff)item).getStrength() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item-10-xShift, Display.getHeight()/2+y_item+shift, "+ "+((Stuff)item).getStrength()+" Strengh", Color.WHITE, Color.BLACK, 1, 1, 1); shift+= 20; } if(((Stuff)item).getMana() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item-10-xShift, Display.getHeight()/2+y_item+shift, "+ "+((Stuff)item).getMana()+" Mana", Color.WHITE, Color.BLACK, 1, 1, 1); shift+= 20; } if(((Stuff)item).getStamina() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item-10-xShift, Display.getHeight()/2+y_item+shift, "+ "+((Stuff)item).getStamina()+" Stamina", Color.WHITE, Color.BLACK, 1, 1, 1); shift+= 20; } if(((Stuff)item).getCritical() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item-10-xShift, Display.getHeight()/2+y_item+shift, "+ "+((Stuff)item).getCritical()+" Critical", Color.WHITE, Color.BLACK, 1, 1, 1); shift+= 20; } if(((Stuff)item).canEquipTo(Joueur.convStringToClassType(Mideas.joueur1().getClasseString()))) { temp = Color.WHITE; } else { temp = Color.RED; } if(classe.length() != 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item-10-xShift, Display.getHeight()/2+y_item+shift, classe, temp, Color.BLACK, 1, 1, 1); shift+= 20; } if(Mideas.joueur1().getLevel() >= ((Stuff)item).getLevel()) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item-10-xShift, Display.getHeight()/2+y_item+shift, "Level "+((Stuff)item).getLevel()+" requiRED", Color.WHITE, Color.BLACK, 1, 1, 1); } else { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item-10-xShift, Display.getHeight()/2+y_item+shift, "Level "+((Stuff)item).getLevel()+" requiRED", Color.RED, Color.BLACK, 1, 1, 1); } } private static void drawRightStuff(int i, int x_item, int y_item) { Color temp = null; Item item = getItem(shopList.get(i+10*page).getId()); int xShift = 280; int shift = 75; String classe = ""; if(((Stuff)item).getClassType().length < 10) { classe = "Classes: "; int k = 0; while(k < ((Stuff)item).getClassType().length) { if(k == ((Stuff)item).getClassType().length-1) { classe+= ((Stuff)item).convClassTypeToString(k); } else { classe+= ((Stuff)item).convClassTypeToString(k)+", "; } k++; } } if(FontManager.get("FRIZQT", 20).getWidth(item.getStuffName()) > 285 || FontManager.get("FRIZQT", 15).getWidth(classe) > 285) { xShift = Math.max(FontManager.get("FRIZQT", 20).getWidth(item.getStuffName()), FontManager.get("FRIZQT", 15).getWidth(classe))+15; } Draw.drawColorQuad(Display.getWidth()/2+x_item, Display.getHeight()/2+30+y_item, xShift, 75+FontManager.get("FRIZQT", 15).getLineHeight()*ContainerFrame.getNumberStats((Stuff)item), bgColors); Draw.drawColorQuadBorder(Display.getWidth()/2+x_item, Display.getHeight()/2+30+y_item, xShift, 75+FontManager.get("FRIZQT", 15).getLineHeight()*ContainerFrame.getNumberStats((Stuff)item), borderColors); x_item+= 10; FontManager.get("FRIZQT", 20).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+33, item.getStuffName(), item.getNameColor(), Color.BLACK, 1, 1, 1); FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+55, ((Stuff)item).convStuffTypeToString(), Color.WHITE, Color.BLACK, 1, 1, 1); if(Mideas.joueur1().canWear((Stuff)item)) { temp = Color.WHITE; } else { temp = Color.RED; } FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item+xShift-FontManager.get("FRIZQT", 15).getWidth(((Stuff)item).convWearToString())-15, Display.getHeight()/2+y_item+55, ((Stuff)item).convWearToString(), temp, Color.BLACK, 1, 1, 1); if(((Stuff)item).getArmor() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, "Armor : "+((Stuff)item).getArmor(), Color.WHITE, Color.BLACK, 1, 1, 1); shift+= 20; } if(((Stuff)item).getStrength() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, "+ "+((Stuff)item).getStrength()+" Strengh", Color.WHITE, Color.BLACK, 1, 1, 1); shift+= 20; } if(((Stuff)item).getMana() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, "+ "+((Stuff)item).getMana()+" Mana", Color.WHITE, Color.BLACK, 1, 1, 1); shift+= 20; } if(((Stuff)item).getStamina() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, "+ "+((Stuff)item).getStamina()+" Stamina", Color.WHITE, Color.BLACK, 1, 1, 1); shift+= 20; } if(((Stuff)item).getCritical() > 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, "+ "+((Stuff)item).getCritical()+" Critical", Color.WHITE, Color.BLACK, 1, 1, 1); shift+= 20; } if(((Stuff)item).canEquipTo(Joueur.convStringToClassType(Mideas.joueur1().getClasseString()))) { temp = Color.WHITE; } else { temp = Color.RED; } if(classe.length() != 0) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, classe, temp, Color.BLACK, 1, 1, 1); shift+= 20; } if(Mideas.joueur1().getLevel() >= ((Stuff)item).getLevel()) { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, "Level "+((Stuff)item).getLevel()+" requiRED", Color.WHITE, Color.BLACK, 1, 1, 1); } else { FontManager.get("FRIZQT", 15).drawStringShadow(Display.getWidth()/2+x_item, Display.getHeight()/2+y_item+shift, "Level "+((Stuff)item).getLevel()+" requiRED", Color.RED, Color.BLACK, 1, 1, 1); } } public static void isSlotHover(int x, int y, int i, int j, int k) { if(Mideas.mouseX() >= Display.getWidth()/2+x && Mideas.mouseX() <= Display.getWidth()/2+x+42 && Mideas.mouseY() >= Display.getHeight()/2+y+i && Mideas.mouseY() <= Display.getHeight()/2+y+j) { slot_hover = k; } } private static void drawGoldCoin(int i, int x, int y) { if(i+10*page < shopList.size()) { calcCoin(shopList.get(i+10*page).getSellPrice(), x+49, y+35); } } public static boolean calcCoin(long cost, int x, int y) { if(Mideas.calcGoldCoinCost(cost) > 0 && Mideas.calcSilverCoinCost(cost) > 0 && cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100 > 0) { FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x, Display.getHeight()/2+y, String.valueOf(Mideas.calcGoldCoinCost(cost)), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.gold_coin, Display.getWidth()/2+x+1+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost))), Display.getHeight()/2+y); FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x+20+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost))), Display.getHeight()/2+y, String.valueOf(Mideas.calcSilverCoinCost(cost)), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.silver_coin, Display.getWidth()/2+x+21+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost))+String.valueOf(Mideas.calcSilverCoinCost(cost))), Display.getHeight()/2+y); FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x+48+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost)+Mideas.calcSilverCoinCost(cost))), Display.getHeight()/2+y, String.valueOf(cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.copper_coin, Display.getWidth()/2+x+38+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost))+String.valueOf(Mideas.calcSilverCoinCost(cost))+String.valueOf(cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100)), Display.getHeight()/2+y); return true; } if(Mideas.calcGoldCoinCost(cost) > 0 && Mideas.calcSilverCoinCost(cost) > 0 && cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100 <= 0) { FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x, Display.getHeight()/2+y, String.valueOf(Mideas.calcGoldCoinCost(cost)), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.gold_coin, Display.getWidth()/2+x+1+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost))), Display.getHeight()/2+y); FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x+20+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost))), Display.getHeight()/2+y, String.valueOf(Mideas.calcSilverCoinCost(cost)), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.silver_coin, Display.getWidth()/2+x+21+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost))+String.valueOf(Mideas.calcSilverCoinCost(cost))), Display.getHeight()/2+y); return true; } if(Mideas.calcGoldCoinCost(cost) > 0 && Mideas.calcSilverCoinCost(cost) <= 0 && cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100 > 0) { FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x, Display.getHeight()/2+y, String.valueOf(Mideas.calcGoldCoinCost(cost)), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.gold_coin, Display.getWidth()/2+x+1+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost))), Display.getHeight()/2+y); FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x+20+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost))), Display.getHeight()/2+y, String.valueOf(cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.copper_coin, Display.getWidth()/2+x+21+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost))+String.valueOf(cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100)), Display.getHeight()/2+y); return true; } if(Mideas.calcGoldCoinCost(cost) <= 0 && Mideas.calcSilverCoinCost(cost) > 0 && cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100 > 0) { FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x, Display.getHeight()/2+y, String.valueOf(Mideas.calcSilverCoinCost(cost)), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.silver_coin, Display.getWidth()/2+x+1+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcSilverCoinCost(cost))), Display.getHeight()/2+y); FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x+20+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcSilverCoinCost(cost))), Display.getHeight()/2+y, String.valueOf(cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.copper_coin, Display.getWidth()/2+x+21+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcSilverCoinCost(cost))+String.valueOf(cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100)), Display.getHeight()/2+y); return true; } if(Mideas.calcGoldCoinCost(cost) > 0 && Mideas.calcSilverCoinCost(cost) <= 0 && cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100 <= 0) { FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x, Display.getHeight()/2+y, String.valueOf(Mideas.calcGoldCoinCost(cost)), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.gold_coin, Display.getWidth()/2+x+1+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcGoldCoinCost(cost))), Display.getHeight()/2+y); return true; } if(Mideas.calcGoldCoinCost(cost) <= 0 && Mideas.calcSilverCoinCost(cost) > 0 && cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100 <= 0) { FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x, Display.getHeight()/2+y, String.valueOf(Mideas.calcSilverCoinCost(cost)), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.silver_coin, Display.getWidth()/2+x+1+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(Mideas.calcSilverCoinCost(cost))), Display.getHeight()/2+y); return true; } if(Mideas.calcGoldCoinCost(cost) <= 0 && Mideas.calcSilverCoinCost(cost) <= 0 && cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100 > 0) { FontManager.get("FRIZQT", 11).drawStringShadow(Display.getWidth()/2+x, Display.getHeight()/2+y, String.valueOf(cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100), Color.WHITE, Color.BLACK, 1, 1, 1); Draw.drawQuad(Sprites.copper_coin, Display.getWidth()/2+x+1+FontManager.get("FRIZQT", 11).getWidth(String.valueOf(cost-Mideas.calcGoldCoinCost(cost)*10000-Mideas.calcSilverCoinCost(cost)*100)), Display.getHeight()/2+y); return true; } return true; } public static boolean isHoverShopFrame() { if(Mideas.mouseX() >= Display.getWidth()/2-300 && Mideas.mouseX() <= Display.getWidth()/2-300+Sprites.shop_frame.getImageWidth() && Mideas.mouseY() >= Display.getHeight()/2-350 && Mideas.mouseY() <= Display.getHeight()/2-350+Sprites.shop_frame.getImageHeight()) { return true; } return false; } public static ArrayList<Shop> getShopList() { return shopList; } }
package demo.rabbit.controller; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.Cache; import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller public class DemoController { @Value("${tomcat.server.name}") private String serverName; @Autowired private EhCacheCacheManager cacheManager; @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { model.addAttribute("batchSize", 1000); return "tools/load"; } @RequestMapping(value = "/load", method = RequestMethod.GET) public String load(Locale locale, Model model) { return "redirect:/"; } @RequestMapping(value="/load", method=RequestMethod.POST) public String loadPost(Model model, @RequestParam(required = false, value = "batchSize") String batchSize) { String message = "Success"; int elements = 0; try { elements = Integer.valueOf(batchSize); } catch (NumberFormatException e) { message = "Invalid batch size"; } for (int i = 0; i < elements; i++) { Cache cache = cacheManager.getCache("demo"); cache.put(i, "Johnny Football"); } model.addAttribute("message", message); model.addAttribute("batchSize", batchSize); return "tools/load"; } @RequestMapping(value="/update", method=RequestMethod.GET) public String update(Model model, HttpServletRequest request, HttpServletResponse response) { model.addAttribute("batchSize", 1000); return "tools/update"; } @RequestMapping(value= "/update", method = RequestMethod.POST) public String updatePost(Model model, @RequestParam(required = false, value = "batchSize") String batchSize) { String message = "Success"; int elements = 0; try { elements = Integer.valueOf(batchSize); } catch (NumberFormatException e) { message = "Invalid batch size"; } for (int i = 0; i < elements; i++) { Cache cache = cacheManager.getCache("demo"); cache.put(i, "Tony Romo"); } model.addAttribute("message", message); model.addAttribute("batchSize", batchSize); return "tools/update"; } @RequestMapping(value="/evict", method=RequestMethod.GET) public String evict(Model model, HttpServletRequest request, HttpServletResponse response) { model.addAttribute("batchSize", 1000); return "tools/evict"; } @RequestMapping(value= "/evict", method = RequestMethod.POST) public String evictPost(Model model, @RequestParam(required = false, value = "batchSize") String batchSize) { String message = "Success"; int elements = 0; try { elements = Integer.valueOf(batchSize); } catch (NumberFormatException e) { message = "Invalid batch size"; } for (int i = 0; i < elements; i++) { Cache cache = cacheManager.getCache("demo"); cache.evict(i); } model.addAttribute("message", message); model.addAttribute("batchSize", batchSize); return "tools/evict"; } @RequestMapping(value= "/evictAll", method = RequestMethod.GET) public String evictAll(Model model, HttpServletRequest request, HttpServletResponse response) { return "tools/evict"; } @RequestMapping(value= "/evictAll", method = RequestMethod.POST) public String evictAllPost(Model model) { Cache cache = cacheManager.getCache("demo"); cache.clear(); model.addAttribute("message", "Success"); return "tools/evict"; } @ModelAttribute("currentServerName") public String getCurrentServerName() { return serverName; } }
package com.dis.bankaccount4.business.service; import java.util.Calendar; import com.dis.bankaccount4.data.dao.BankAcountDAO; import com.dis.bankaccount4.data.dao.TransactionDAO; import com.dis.bankaccount4.data.entity.BankAccountDTO; import com.dis.bankaccount4.data.entity.TransactionDTO; public class BankAccount { public static BankAcountDAO bankAccountDAO; public static TransactionDAO transactionDAO; public static Calendar calendar; public static BankAccountDTO openAccount(String accountNumber) { BankAccountDTO bankAccountDTO = new BankAccountDTO(accountNumber); long timestamp = calendar.getTimeInMillis(); bankAccountDTO.setTimestamp(timestamp); bankAccountDAO.save(bankAccountDTO); return bankAccountDTO; } public static BankAccountDTO getAccount(String accountNumber) { return bankAccountDAO.getAccount(accountNumber); } public static void deposit(String accountNumber, double amount, String description) { BankAccountDTO bankAccountDTO = bankAccountDAO .getAccount(accountNumber); bankAccountDTO.setBalance(bankAccountDTO.getBalance() + amount); bankAccountDAO.save(bankAccountDTO); long timestamp = calendar.getTimeInMillis(); TransactionDTO transactionDTO = new TransactionDTO(accountNumber, timestamp, amount, description); transactionDAO.createTransaction(transactionDTO); } public static void withdraw(String accountNumber, double amount, String description) { BankAccountDTO bankAccountDTO = bankAccountDAO .getAccount(accountNumber); bankAccountDTO.setBalance(bankAccountDTO.getBalance() - amount); bankAccountDAO.save(bankAccountDTO); } public static void getTransactionOccurred(String accountNumber) { transactionDAO.getTransactionOccurred(accountNumber); } public static void getTransactionsInPeriodOfTime(String accountNumber, long startTime, long stopTime) { transactionDAO.getTransactionsInPeriodOfTime(accountNumber, startTime, stopTime); } public static void getTheLastNTransactions(String accountNumber, int n) { transactionDAO.getTheLastNTransactions(accountNumber, n); } }
/* * Copyright 2008 University of California at Berkeley * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.rebioma.server.util; import java.security.Security; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; import java.util.Set; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.log4j.Logger; import org.rebioma.client.Email; import org.rebioma.client.EmailException; import org.rebioma.client.bean.Occurrence; import org.rebioma.client.bean.User; /** * This class is a utility for sending email from one user to another user * * @author Tri * */ public class EmailUtil { private static class PasswordAuthenticator extends Authenticator { private final String username; private final String password; public PasswordAuthenticator(String username, String password) { super(); this.username = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } } private static final Logger logger = Logger.getLogger(EmailUtil.class); public static final String ADMIN_EMAIL = "Aaron D. Steele"; private static Properties mailProperties = null; static { ResourceBundle rb = ResourceBundle.getBundle("SendMail"); if (rb != null) { mailProperties = new Properties(); Enumeration<String> keys = rb.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); mailProperties.put(key, rb.getObject(key)); } } else { logger.error("unable to open properties file " + "SendMail.properties" + " for send mail. Make sure it existed.", null); } } public static void adminSendEmailTo2(String recipientAddress, String subject, String body) throws EmailException { if (mailProperties == null) { EmailException e = new EmailException("open properties file can't" + "SendMail.properties" + " for send mail. Make sure it existed."); logger.error(e.getMessage(), e); throw e; } if (true) { String senderAddress = "\"" + mailProperties.getProperty("mail.displayname", "Admin") + "\" <" + mailProperties.getProperty("mail.from", "admin@gmail.com") + ">"; String username = mailProperties.getProperty("mail.from", "fail"); String password = mailProperties.getProperty("mail.password", "fail"); try { sendMail2(subject, body, senderAddress, recipientAddress, username, password); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage(), e); throw new EmailException(senderAddress + " unable to send email to " + recipientAddress); } return; } } public static void adminSendEmailTo(String recipientAddress, String subject, String body) throws EmailException { if (mailProperties == null) { EmailException e = new EmailException("open properties file can't" + "SendMail.properties" + " for send mail. Make sure it existed."); logger.error(e.getMessage(), e); throw e; } if (true) { String senderAddress = "\"" + mailProperties.getProperty("mail.displayname", "Admin") + "\" <" + mailProperties.getProperty("mail.from", "admin@gmail.com") + ">"; String username = mailProperties.getProperty("mail.from", "fail"); String password = mailProperties.getProperty("mail.password", "fail"); try { sendMail(subject, body, senderAddress, recipientAddress, username, password); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage(), e); throw new EmailException(senderAddress + " unable to send email to " + recipientAddress); } return; } // String senderAddress = "\"" // + mailProperties.getProperty("mail.displayname", "Admin") + "\" <" // + mailProperties.getProperty("mail.from", "admin@gmail.com") + ">"; // try { // Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); // // Session session = Session.getDefaultInstance(mailProperties, // new PasswordAuthenticator(mailProperties.getProperty("mail.from", // "fail"), mailProperties.getProperty("mail.password", "fail"))); // // MimeMessage message = new MimeMessage(session); // // message.setSender(new InternetAddress(sender)); // // message.setSubject(subject); // // message.setContent(body, "text/plain"); // // Message msg = new MimeMessage(session); // // InternetAddress sender = new InternetAddress(senderAddress); // InternetAddress recipient = new InternetAddress(recipientAddress); // msg.setFrom(sender); // // msg.setFrom(); // msg.setRecipient(Message.RecipientType.TO, recipient); // msg.setSubject(subject); // msg.setContent(body, "text/plain"); // msg.setSentDate(new Date()); // // Charset s; // // msg.setText(body); // // final Transport transport = session.getTransport("smtp"); // // transport.connect(); // // transport.connect(mailProperties.getProperty("mail.smtp.host", // // "smtp.gmail.com"), Integer.parseInt(mailProperties.getProperty( // // "mail.smtp.port", "25")), mailProperties.getProperty("mail.from", // // "fail"), mailProperties.getProperty("mail.password", "fail")); // // transport.sendMessage(msg, new InternetAddress[] { recipient }); // // transport.close(); // Transport.send(msg); // } catch (MessagingException e) { // logger.error(e.getMessage(), e); // e.printStackTrace(); // throw new EmailException(senderAddress + " unable to send email to " // + recipientAddress); // } } /** * quick test * * @param agrs */ public static void main(String agrs[]) { try { adminSendEmailTo("wilfried@rebioma.net", "test", "test"); System.out.println("mail envoyé"); } catch (EmailException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void notifyUserAssignmentNewOrChanged(User user, Set<Occurrence> occurrences) throws EmailException { // if (!RecordReviewUtil.isDevMode()) { // logger.info("not in development mode"); // return; // } if (!occurrences.isEmpty()) { String subject = "[REBIOMA PORTAL] New record assignment notification"; StringBuilder bodyBuilder = new StringBuilder("Dear " + user.getFirstName() + " " + user.getLastName() + ",\n\n"); bodyBuilder .append("You are receiving this email as a member of the REBIOMA Taxonomic Review Board. New or changed occurrence records have been assigned to you for review. \n"); //for (Occurrence occurrence : occurrences) { // bodyBuilder.append(occurrence.getId() + ", "); //} bodyBuilder.delete(bodyBuilder.length() - 2, bodyBuilder.length()); bodyBuilder.append("\n\n"); bodyBuilder .append("To find your occurrences to review, sign into the REBIOMA data portal (data.rebioma.net) with your email and password and select \"My Occurrences to Review\", or use \"Advanced Search\" to search for specific records."); bodyBuilder.append("\n\n"); bodyBuilder.append(Email.REBIOMA_TEAM); String userEmail = user.getEmail(); userEmail = RecordReviewUtil.getSentEmail(userEmail); adminSendEmailTo(userEmail, subject, bodyBuilder.toString()); logger.info("successfully send nofication email to " + userEmail); } else { logger.info("no email was sent to " + user.getEmail() + " because no assignment match"); } } public static void notifyUserNewAssignment(User user, Integer assignmentCount, Map<String, Set<String>> userToTaxoAssignMap) throws EmailException { // if (!RecordReviewUtil.isDevMode()) { // logger.info("not in development mode"); // return; // } String subject = "[REBIOMA PORTAL] New reviewer assignment notification"; StringBuilder bodyBuilder = new StringBuilder("Dear " + user.getFirstName() + " " + user.getLastName() + ",\n\n"); bodyBuilder .append("You are receiving this email as a member of the REBIOMA Taxonomic Review Board. The following taxonomic fields and values have been assigned to you: \n"); for (String field : userToTaxoAssignMap.keySet()) { bodyBuilder.append("taxonomic field: " + field + " with associated value(s) " + userToTaxoAssignMap.get(field) + "\n"); } bodyBuilder.append("\n"); if (assignmentCount > 0) { bodyBuilder .append("There are " + assignmentCount + " records awaiting your review based on the above taxonomic assignment.\n\n"); bodyBuilder .append("To find your occurrences to review, sign into the REBIOMA data portal (data.rebioma.net) with your email and password and select \"My Occurrences to Review\", or use \"Advanced Search\" to search for specific records by taxonomy."); } else { bodyBuilder .append("no existing occurrence yet match with your assignment.\n"); } bodyBuilder.append("\n\n"); bodyBuilder.append(Email.REBIOMA_TEAM); String userEmail = user.getEmail(); userEmail = RecordReviewUtil.getSentEmail(userEmail); adminSendEmailTo(userEmail, subject, bodyBuilder.toString()); logger.info("successfully sent notification email to " + userEmail); } public static void notifyUserReviewedChangeToNeg(User owner, Set<Integer> occurrenceIds) throws EmailException { String subject = "[REBIOMA PORTAL] Record(s) Questionably Reviewed notification"; StringBuilder bodyBuilder = new StringBuilder("Dear " + owner.getFirstName() + " " + owner.getLastName() + ",\n\n"); bodyBuilder.append("There are " + occurrenceIds.size() + " records that have been questionably reviewed.\n\n"); bodyBuilder .append("To find your reviewed records, sign into the REBIOMA data portal (data.rebioma.net) with your email and password and select \"My Positively Reviews\" or \"My Negatively Reviews\", or use \"Advanced Search\" to search for specific records by REBIOMA id."); bodyBuilder.append("\n\n"); bodyBuilder.append(Email.REBIOMA_TEAM); String userEmail = owner.getEmail(); userEmail = RecordReviewUtil.getSentEmail(userEmail); adminSendEmailTo(userEmail, subject, bodyBuilder.toString()); logger.info("successfully sent nofication email to " + userEmail); } public static void notifyUserForRevalidation(User owner, Set<Integer> occurrenceIds, String subjects, String body) throws EmailException { String subject = "[REBIOMA PORTAL] Record(s) Questionably for Revalidation :"+subjects; StringBuilder bodyBuilder = new StringBuilder("Dear " + owner.getFirstName() + " " + owner.getLastName() + ",\n\n"); //bodyBuilder.append("There are " + occurrenceIds.size()+" "+ body); bodyBuilder.append(body); bodyBuilder.append("\n These are the ID of all records affected: "+buildOclist(occurrenceIds)); // bodyBuilder // .append(" \n To find your records, sign into the REBIOMA data portal (data.rebioma.net) with your email and password and select \"My Positively Reviews\" or \"My Negatively Reviews\", or use \"Advanced Search\" to search for specific records by REBIOMA id."); bodyBuilder.append(" \n\n To find your records, sign into the REBIOMA data portal (data.rebioma.net) with your email and password and select use \"Advanced Search\" to search for specific records by REBIOMA id."); bodyBuilder.append(" Then, once you found out affected records, please check comments left by the TRB members and update your records. To update some informations in your records, you can download it then re-upload it. Or you can modify it directly on the data portal."); bodyBuilder.append("\n\n"); bodyBuilder.append(Email.REBIOMA_TEAM); String userEmail = owner.getEmail(); userEmail = RecordReviewUtil.getSentEmail(userEmail); adminSendEmailTo(userEmail, subject, bodyBuilder.toString()); logger.info("successfully sent nofication email to " + userEmail); } private static String buildOclist(Set<Integer> occurrenceIds){ String list=""; for(int id:occurrenceIds){ list+=""+id+" ,"; } return list; } /** * This method sends an email from sender address to recipient address with a * given subject and body content. It throws and SendEmailException if there * is an error occurs during mail sending process. If the sender address is * null, it uses ADMIN_EMAIL instead. This method doesn't check for * non-existing email address since the user can only log in to the Rebioma * Portal using a password that is sent in an welcome email. * * @param senderAddress the sender email address. * @param recipientAddress the recipient email address. * @param subject subject of a sending email. * @param body content of a sending email. * @throws EmailException if there is an error occurs during mail sending * process. */ public static void sendEmailTo(String senderAddress, String recipientAddress, String subject, String body) throws EmailException { // try { // if (senderAddress == null) { // senderAddress = ADMIN_EMAIL; // } // Properties props = new Properties(); // props.put("mail.smtp.host", "smtp.gmail.com"); // // props.put("mail.smtp.user", "tri282"); // props.put("mail.smtp.port", 25); // // props.put("mail.from", "tri282@gmail.com"); // props.put("mail.smtp.auth", "true"); // props.put("mail.smtp.starttls.enable", "true"); // // Session session = Session.getInstance(props, new // PasswordAuthenticator()); // // Message msg = new SMTPMessage(session); // // InternetAddress sender = new InternetAddress(senderAddress); // InternetAddress recipient = new InternetAddress(recipientAddress); // msg.setFrom(sender); // msg.setRecipient(Message.RecipientType.TO, recipient); // msg.setSubject(subject); // msg.setSentDate(new Date()); // msg.setFlag(Flag.RECENT, true); // // Charset s; // msg.setText(body); // Transport.send(msg); // // } catch (MessagingException e) { // logger.error(e.getMessage(), e); // e.printStackTrace(); // throw new EmailException(senderAddress + " unable to send email to " // + recipientAddress); // } } public static synchronized void sendMail(String subject, String body, String sender, String recipients, final String username, final String password) throws Exception { //Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", "smtp.gmail.com"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.smtp.socketFactory.port", "465"); props .put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.quitwait", "false"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); MimeMessage message = new MimeMessage(session); message.setSender(new InternetAddress(sender)); message.setSubject(subject); message.setContent(body, "text/plain"); //verify devmode recipients = RecordReviewUtil.getSentEmail(recipients); if (recipients.indexOf(',') > 0) { message.setRecipients(Message.RecipientType.TO, InternetAddress .parse(recipients)); } else { message.setRecipient(Message.RecipientType.TO, new InternetAddress( recipients)); } Transport.send(message); } public static synchronized void sendMail2(String subject, String body, String sender, String recipients, final String username, final String password) throws Exception { //Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", "smtp.gmail.com"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.smtp.socketFactory.port", "465"); props .put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.quitwait", "false"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); MimeMessage message = new MimeMessage(session); message.setSender(new InternetAddress(sender)); message.setSubject(subject); message.setContent(body, "text/html"); //verify devmode recipients = RecordReviewUtil.getSentEmail(recipients); if (recipients.indexOf(',') > 0) { message.setRecipients(Message.RecipientType.TO, InternetAddress .parse(recipients)); } else { message.setRecipient(Message.RecipientType.TO, new InternetAddress( recipients)); } Transport.send(message); } }
package com.facebook.react.modules.systeminfo; import android.app.UiModeManager; import android.os.Build; import android.provider.Settings; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.module.annotations.ReactModule; import java.util.HashMap; import java.util.Map; @ReactModule(name = "PlatformConstants") public class AndroidInfoModule extends ReactContextBaseJavaModule { public AndroidInfoModule(ReactApplicationContext paramReactApplicationContext) { super(paramReactApplicationContext); } private String uiMode() { int i = ((UiModeManager)getReactApplicationContext().getSystemService("uimode")).getCurrentModeType(); return (i != 1) ? ((i != 2) ? ((i != 3) ? ((i != 4) ? ((i != 6) ? "unknown" : "watch") : "tv") : "car") : "desk") : "normal"; } public Map<String, Object> getConstants() { HashMap<Object, Object> hashMap = new HashMap<Object, Object>(); hashMap.put("Version", Integer.valueOf(Build.VERSION.SDK_INT)); hashMap.put("Release", Build.VERSION.RELEASE); hashMap.put("Serial", Build.SERIAL); hashMap.put("Fingerprint", Build.FINGERPRINT); hashMap.put("Model", Build.MODEL); hashMap.put("ServerHost", AndroidInfoHelpers.getServerHost()); hashMap.put("isTesting", Boolean.valueOf("true".equals(System.getProperty("IS_TESTING")))); hashMap.put("reactNativeVersion", ReactNativeVersion.VERSION); hashMap.put("uiMode", uiMode()); hashMap.put("androidID", Settings.Secure.getString(getReactApplicationContext().getContentResolver(), "android_id")); return (Map)hashMap; } public String getName() { return "PlatformConstants"; } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\modules\systeminfo\AndroidInfoModule.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.database.endingCredit.domain.user.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor @AllArgsConstructor public class UserIdDTO { private String customerId; /** * @return String return the customerId */ public String getCustomerId() { return customerId; } /** * @param customerId the customerId to set */ public void setCustomerId(String customerId) { this.customerId = customerId; } }
package cn.canlnac.onlinecourse.domain.interactor; import java.util.Map; import javax.inject.Inject; import cn.canlnac.onlinecourse.domain.executor.PostExecutionThread; import cn.canlnac.onlinecourse.domain.executor.ThreadExecutor; import cn.canlnac.onlinecourse.domain.repository.ChatRepository; import rx.Observable; /** * 回复评论使用用例. */ public class ReplyCommentInChatUseCase extends UseCase { private final int chatId; private final int commentId; private final Map<String,Object> reply; private final ChatRepository chatRepository; @Inject public ReplyCommentInChatUseCase( int chatId, int commentId, Map<String,Object> reply, ChatRepository chatRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread ) { super(threadExecutor, postExecutionThread); this.chatId = chatId; this.commentId = commentId; this.reply = reply; this.chatRepository = chatRepository; } @Override protected Observable buildUseCaseObservable() { return this.chatRepository.replyCommentInChat(chatId,commentId,reply); } }
package lib.game.path; import math.geom.Point3f; public interface ParametricPath { public Point3f par(float t); }
/** * */ package com.cnk.travelogix.mdmbackoffice.workflow; import de.hybris.platform.catalog.enums.ArticleApprovalStatus; import de.hybris.platform.core.model.ItemModel; import de.hybris.platform.workflow.model.WorkflowActionModel; import de.hybris.platform.workflow.model.WorkflowDecisionModel; import org.apache.log4j.Logger; import com.cnk.travelogix.ccintegrationfacade.consumer.CCIntegrationConsumer; import com.cnk.travelogix.ccintegrationfacade.dto.CCIntegrationDto; import com.cnk.travelogix.ccintegrationfacade.exception.CCIntegrationException; import com.cnk.travelogix.masterdata.core.enums.ApprovalWorkFlowStatus; import com.cnk.travelogix.product.transport.masters.core.model.AirRouteModel; import com.cnk.travelogix.product.transport.masters.core.model.RouteConnectionModel; /** * To Publish Work flow Action * */ public class WorkflowPublishApprovedActionJob extends AbstractWorkflowSubmitActionJob { /** The Constant LOGGER. */ private static final Logger LOGGER = Logger.getLogger(WorkflowPublishApprovedActionJob.class); /* * (non-Javadoc) * * @see de.hybris.platform.workflow.jobs.AutomatedWorkflowTemplateJob#perform(de.hybris.platform.workflow.model. * WorkflowActionModel) */ @Override public WorkflowDecisionModel perform(final WorkflowActionModel action) { final ItemModel itemModel = getSubmitRequest(action); try { CCIntegrationConsumer.consumeFacade(new CCIntegrationDto(itemModel)); setworkFlowStatus(itemModel, ApprovalWorkFlowStatus.PUBLISH); if (itemModel instanceof AirRouteModel) { final AirRouteModel airRouteModel = (AirRouteModel) itemModel; validateSectorStatus(airRouteModel); } getModelService().save(itemModel); LOGGER.debug("Workflow for " + itemModel.getItemtype() + " is Approved. Item Published."); } catch (final CCIntegrationException e) { setworkFlowStatus(itemModel, ApprovalWorkFlowStatus.DRAFT); LOGGER.error("WorkflowPublishActionJob : perform : ERROR : " + e); } for (final WorkflowDecisionModel decision : action.getDecisions()) { return decision; } return null; } private static void validateSectorStatus(final AirRouteModel airRouteModel) { final RouteConnectionModel routeConnection = airRouteModel.getSectors(); if (routeConnection != null) { final Boolean status = routeConnection.getActive(); if (status != null && !status.booleanValue()) { airRouteModel.setApprovalStatus(ArticleApprovalStatus.UNAPPROVED); } else { airRouteModel.setApprovalStatus(ArticleApprovalStatus.APPROVED); } } } }
/* * Copyright (C) 2018 Ilya Lebedev * * 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 io.github.ilya_lebedev.worldmeal.data; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.Observer; import android.support.annotation.Nullable; import java.util.Date; import java.util.List; import io.github.ilya_lebedev.worldmeal.AppExecutors; import io.github.ilya_lebedev.worldmeal.data.database.AreaEntry; import io.github.ilya_lebedev.worldmeal.data.database.AreaMealEntry; import io.github.ilya_lebedev.worldmeal.data.database.CategoryEntry; import io.github.ilya_lebedev.worldmeal.data.database.CategoryMealEntry; import io.github.ilya_lebedev.worldmeal.data.database.IngredientEntry; import io.github.ilya_lebedev.worldmeal.data.database.IngredientMealEntry; import io.github.ilya_lebedev.worldmeal.data.database.MealEntry; import io.github.ilya_lebedev.worldmeal.data.database.MealOfDayEntry; import io.github.ilya_lebedev.worldmeal.data.database.WorldMealDao; import io.github.ilya_lebedev.worldmeal.data.network.WorldMealNetworkDataSource; import io.github.ilya_lebedev.worldmeal.utilities.WorldMealDateUtils; /** * WorldMealRepository */ public class WorldMealRepository { // For singleton instantiation private static final Object LOCK = new Object(); private static WorldMealRepository sInstance; private final WorldMealDao mWorldMealDao; private final WorldMealNetworkDataSource mNetworkDataSource; private final AppExecutors mAppExecutors; private boolean mInitialized = false; private WorldMealRepository(WorldMealDao worldMealDao, WorldMealNetworkDataSource networkDataSource, AppExecutors appExecutors) { mWorldMealDao = worldMealDao; mNetworkDataSource = networkDataSource; mAppExecutors = appExecutors; initializeNetworkDataObservers(); } private void initializeNetworkDataObservers() { LiveData<AreaEntry[]> networkAreaListData = mNetworkDataSource.getCurrentAreaList(); networkAreaListData.observeForever(new Observer<AreaEntry[]>() { @Override public void onChanged(@Nullable final AreaEntry[] areaEntries) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { mWorldMealDao.bulkInsert(areaEntries); } }); } }); LiveData<CategoryEntry[]> networkCategoryListData = mNetworkDataSource.getCurrentCategoryList(); networkCategoryListData.observeForever(new Observer<CategoryEntry[]>() { @Override public void onChanged(@Nullable final CategoryEntry[] categoryEntries) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { mWorldMealDao.bulkInsert(categoryEntries); } }); } }); LiveData<IngredientEntry[]> networkIngredientListData = mNetworkDataSource .getCurrentIngredientList(); networkIngredientListData.observeForever(new Observer<IngredientEntry[]>() { @Override public void onChanged(@Nullable final IngredientEntry[] ingredientEntries) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { mWorldMealDao.bulkInsert(ingredientEntries); } }); } }); LiveData<AreaMealEntry[]> networkAreaMealData = mNetworkDataSource.getCurrentAreaMealList(); networkAreaMealData.observeForever(new Observer<AreaMealEntry[]>() { @Override public void onChanged(@Nullable final AreaMealEntry[] areaMealEntries) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { mWorldMealDao.bulkInsert(areaMealEntries); } }); } }); LiveData<CategoryMealEntry[]> networkCategoryMealData = mNetworkDataSource.getCurrentCategoryMealList(); networkCategoryMealData.observeForever(new Observer<CategoryMealEntry[]>() { @Override public void onChanged(@Nullable final CategoryMealEntry[] categoryMealEntries) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { mWorldMealDao.bulkInsert(categoryMealEntries); } }); } }); LiveData<IngredientMealEntry[]> networkIngredientMealData = mNetworkDataSource.getCurrentIngredientMealList(); networkIngredientMealData.observeForever(new Observer<IngredientMealEntry[]>() { @Override public void onChanged(@Nullable final IngredientMealEntry[] ingredientMealEntries) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { mWorldMealDao.bulkInsert(ingredientMealEntries); } }); } }); LiveData<MealEntry> networkMealData = mNetworkDataSource.getCurrentMeal(); networkMealData.observeForever(new Observer<MealEntry>() { @Override public void onChanged(@Nullable final MealEntry mealEntry) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { mWorldMealDao.insert(mealEntry); } }); } }); LiveData<MealOfDayEntry> networkMealOfDayData = mNetworkDataSource.getCurrentMealOfDay(); networkMealOfDayData.observeForever(new Observer<MealOfDayEntry>() { @Override public void onChanged(@Nullable final MealOfDayEntry mealOfDayEntry) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { deleteOldMealOfDay(); mWorldMealDao.insert(mealOfDayEntry); } }); } }); } private synchronized void initializeMealOfDayData() { if (mInitialized) return; mInitialized = true; mNetworkDataSource.scheduleRecurringFetchMealOfDaySync(); mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { if (isMealOfDayFetchNeeded()) { startFetchMealOfDay(); } } }); } public static WorldMealRepository getInstance(WorldMealDao worldMealDao, WorldMealNetworkDataSource networkDataSource, AppExecutors appExecutors) { if (sInstance == null) { synchronized (LOCK) { sInstance = new WorldMealRepository(worldMealDao, networkDataSource, appExecutors); } sInstance.initializeMealOfDayData(); } return sInstance; } public LiveData<List<AreaEntry>> getAreaList() { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { if (isAreaListFetchNeeded()) { startFetchAreaList(); } } }); return mWorldMealDao.getAreaList(); } public LiveData<List<CategoryEntry>> getCategoryList() { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { if (isCategoryListFetchNeeded()) { startFetchCategoryList(); } } }); return mWorldMealDao.getCategoryList(); } public LiveData<List<IngredientEntry>> getIngredientList() { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { if (isIngredientListFetchNeeded()) { startFetchIngredientList(); } } }); return mWorldMealDao.getIngredientList(); } public LiveData<List<AreaMealEntry>> getAreaMealList(final String areaName) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { if (isAreaMealListFetchNeeded(areaName)) { startFetchAreaMealList(areaName); } } }); return mWorldMealDao.getAreaMeal(areaName); } public LiveData<List<CategoryMealEntry>> getCategoryMealList(final String categoryName) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { if (isCategoryMealListFetchNeeded(categoryName)) { startFetchCategoryMealList(categoryName); } } }); return mWorldMealDao.getCategoryMeal(categoryName); } public LiveData<List<IngredientMealEntry>> getIngredientMealList(final String ingredientName) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { if (isIngredientMealListFetchNeeded(ingredientName)) { startFetchIngredientMealList(ingredientName); } } }); return mWorldMealDao.getIngredientMeal(ingredientName); } public LiveData<MealEntry> getMeal(final long mealId) { mAppExecutors.diskIO().execute(new Runnable() { @Override public void run() { if (isMealFetchNeeded(mealId)) { startFetchMeal(mealId); } } }); return mWorldMealDao.getMeal(mealId); } public MealOfDayEntry getMealOfDay() { return mWorldMealDao.getMealOfDay(); } private boolean isAreaListFetchNeeded() { int areaCount = mWorldMealDao.countAllArea(); return (areaCount == 0); } private boolean isCategoryListFetchNeeded() { int categoryCount = mWorldMealDao.countAllCategory(); return (categoryCount ==0); } private boolean isIngredientListFetchNeeded() { int ingredientCount = mWorldMealDao.countAllIngredient(); return (ingredientCount == 0); } private boolean isAreaMealListFetchNeeded(String areaName) { int areaMealCount = mWorldMealDao.countAllAreaMeal(areaName); return (areaMealCount == 0); } private boolean isCategoryMealListFetchNeeded(String categoryName) { int categoryMealCount = mWorldMealDao.countAllCategoryMeal(categoryName); return (categoryMealCount == 0); } private boolean isIngredientMealListFetchNeeded(String ingredientName) { int ingredientMealCount = mWorldMealDao.countAllIngredientMeal(ingredientName); return (ingredientMealCount == 0); } private boolean isMealFetchNeeded(long mealId) { int mealCount = mWorldMealDao.countMeal(mealId); return (mealCount == 0); } private boolean isMealOfDayFetchNeeded() { int mealOfDayCount = mWorldMealDao.countAllMealOfDay(); return (mealOfDayCount == 0); } private void deleteOldMealOfDay() { Date today = WorldMealDateUtils.getNormalizedUtcDateForToday(); mWorldMealDao.deleteOldMealOfDay(today); } private void startFetchAreaList() { mNetworkDataSource.startFetchAreaList(); } private void startFetchCategoryList() { mNetworkDataSource.startFetchCategoryList(); } private void startFetchIngredientList() { mNetworkDataSource.startFetchIngredientList(); } private void startFetchAreaMealList(String areaName) { mNetworkDataSource.startFetchAreaMealList(areaName); } private void startFetchCategoryMealList(String categoryName) { mNetworkDataSource.startFetchCategoryMealList(categoryName); } private void startFetchIngredientMealList(String ingredientName) { mNetworkDataSource.startFetchIngredientMealList(ingredientName); } private void startFetchMeal(long mealId) { mNetworkDataSource.startFetchMeal(mealId); } private void startFetchMealOfDay() { mNetworkDataSource.startFetchMealOfDay(); } }
public class limitOrderMatch { }
package com.rock.andrew.fit.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.rock.andrew.fit.R; import com.rock.andrew.fit.activities.SignupActivity; import com.rock.andrew.fit.dialogs.SecuritySentDialog; import com.rock.andrew.fit.models.CommonFragemtModels; import com.rock.andrew.fit.models.SignUserModel; import com.rock.andrew.fit.dialogs.SecuritySentDialog; public class Signup_Step_verify_step1 extends Fragment implements View.OnClickListener{ TextView txt_header_view, txt_email_address; Button button_resend_message, button_change_email; Button button_skip; EditText txt_signup_code; public Signup_Step_verify_step1() { // Required empty public constructor } public static Signup_Step_verify_step1 newInstance() { Signup_Step_verify_step1 fragment = new Signup_Step_verify_step1(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootview = inflater.inflate(R.layout.fragment_signup_verify__step1,container,false); txt_header_view = (TextView)rootview.findViewById(R.id.lbl_signup_hi); txt_email_address = (TextView)rootview.findViewById(R.id.txt_signup_emailaddress); txt_header_view.setText("Hi, " + SignUserModel.UserName); txt_email_address.setText("(" + SignUserModel.UserEmail+")"); button_resend_message = (Button)rootview.findViewById(R.id.button_signup_resendmessage); button_change_email = (Button)rootview.findViewById(R.id.button_signup_chanagemail); button_skip = (Button)rootview.findViewById(R.id.button_signup_skip); txt_signup_code = (EditText)rootview.findViewById(R.id.txt_signup_code); button_skip.setOnClickListener(this); button_resend_message.setOnClickListener(this); button_change_email.setOnClickListener(this); return rootview; } private void showDialog(){ final SecuritySentDialog m_dialog = new SecuritySentDialog(getContext()); View.OnClickListener m_listener = new View.OnClickListener(){ @Override public void onClick(View view) { m_dialog.dismiss(); onRemoveDialog(); } }; m_dialog.setButtonClickListener(m_listener); m_dialog.show(); } private void onRemoveDialog() { gotoOtherFragment(CommonFragemtModels.SIGNUP_FRAGMENT_VERIFY2); } @Override public void onClick(View view) { int view_id = view.getId(); if(view_id == R.id.button_signup_resendmessage ){ showDialog(); } else if(view_id == R.id.button_signup_chanagemail){ gotoOtherFragment(CommonFragemtModels.SIGNUP_FRAGMENT_EMAIL_CHANGE); } else if(view_id == R.id.button_signup_skip){ gotoOtherFragment(CommonFragemtModels.SIGNUP_FRAGMENT_UPLOAD_PICTURE); } } private void gotoOtherFragment(int position){ ((SignupActivity)getActivity()).FragmentSetupBasedOnStep(position); } }
package com.tiandi.logistics.controller; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.metadata.IPage; import com.tiandi.logistics.aop.log.annotation.ControllerLogAnnotation; import com.tiandi.logistics.aop.log.enumeration.OpTypeEnum; import com.tiandi.logistics.aop.log.enumeration.SysTypeEnum; import com.tiandi.logistics.constant.SystemConstant; import com.tiandi.logistics.entity.pojo.Order; import com.tiandi.logistics.entity.pojo.OrderGoods; import com.tiandi.logistics.entity.result.ResultMap; import com.tiandi.logistics.service.OrderService; import io.swagger.annotations.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 订单管理控制层接口 * * @author ZhanTianYi * @version 1.0 * @since 2020/12/1 19:43 */ @RestController @RequestMapping("/order") @Api(tags = "订单管理") public class OrderController { @Autowired private ResultMap resultMap; @Autowired private OrderService orderService; @PostMapping("/getAllOrder") @ControllerLogAnnotation(remark = "订单获取",sysType = SysTypeEnum.ADMIN,opType = OpTypeEnum.SELECT) @ApiOperation(value = "订单获取",notes = "通过页码、页数、收寄地、配送地、收件人姓名,订单状态任一条件查询") @ApiImplicitParams({ @ApiImplicitParam(name = "receiverAddress", value = "收寄地", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "idDistribution", value = "配送地", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "receiverName", value = "收件人姓名", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "stateOrder", value = "订单状态", required = true, paramType = "query", dataType = "Integer"), }) @ApiResponses({ @ApiResponse(code = 40000, message = "订单查询成功!"), @ApiResponse(code = 50011, message = "订单查询失败,请重试!") }) public ResultMap getAllOrder(@RequestParam(value = "page", required = true) int page, @RequestParam(value = "limit", required = true) int limit, @RequestParam(value = "receiverAddress",required = false) String receiverAddress, @RequestParam(value = "senderAddress",required = false) String senderAddress, @RequestParam(value = "receiverName",required = false) String receiverName, @RequestParam(value = "stateOrder",required = false) Integer stateOrder){ final IPage allOrder = orderService.getAllOrder(page, limit, receiverAddress, senderAddress, receiverName, stateOrder); resultMap.addElement("data",allOrder.getRecords()); resultMap.addElement("total",allOrder.getTotal()); resultMap.success().message("查询成功"); return resultMap; } @PostMapping("/updateOrder") @ControllerLogAnnotation(remark = "订单更新",sysType = SysTypeEnum.ADMIN,opType = OpTypeEnum.UPDATE) @ApiOperation(value = "订单更新", notes = "根据订单ID更新订单信息") @ApiImplicitParams({ @ApiImplicitParam(name = "order", value = "订单对象", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "heavy", value = "物品重量", required = false, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "volume", value = "物品体积", required = false, paramType = "query", dataType = "String") }) @ApiResponses({ @ApiResponse(code = 40000, message = "订单更新成功!"), @ApiResponse(code = 50011, message = "订单更新失败,请重试!") }) public ResultMap updateOrder(@RequestParam(value = "order") String orderStr, @RequestParam(value = "heavy", required = false) Double heavy){ //判空,防止抛出异常 if (orderStr == null || "".equals(orderStr)) { return resultMap.fail().code(40010).message("服务器内部错误"); } Order order = JSON.parseObject(orderStr, Order.class); int update = orderService.updateOrder(order,heavy); if (update == 1){ resultMap.success().message("更新成功"); } else { resultMap.fail().message("更新失败"); } return resultMap; } @GetMapping("/deleteOrder/{idOrder}") @ControllerLogAnnotation(remark = "订单删除",sysType = SysTypeEnum.ADMIN,opType = OpTypeEnum.DELETE) @ApiOperation(value = "删除订单", notes = "根据订单ID删除订单") @ApiImplicitParam(name = "id_order",value = "订单ID",required = true,paramType = "query",dataType = "String") @ApiResponses({ @ApiResponse(code = 40000, message = "订单删除成功!"), @ApiResponse(code = 50011, message = "订单删除失败,请重试!") }) public ResultMap deleteOrder(@PathVariable String idOrder){ if (idOrder == null || "".equals(idOrder)){ return resultMap.fail().code(40010).message("服务器内部错误"); } int delete = orderService.deleteOrder(idOrder); if (delete == 1){ resultMap.success().message("删除成功"); } else { resultMap.fail().message("删除失败"); } return resultMap; } // @PostMapping("/confirmOrder") // @ApiResponses({ // @ApiResponse(code = 40000, message = "订单确认成功!"), // @ApiResponse(code = 50011, message = "订单确认失败,请重试!") // }) // public ResultMap confirmOrder(){ // List<Order> stateOrder = orderService.getStateOrder(); // return resultMap.addElement("data",stateOrder).success(); // } @PostMapping("/getOrderGoodsById") @ApiResponses({ @ApiResponse(code = 40000, message = "订单获取成功!"), @ApiResponse(code = 50011, message = "订单获取失败,请重试!") }) public ResultMap getOrderById(String idOrder){ OrderGoods ordergoods = orderService.getOrderById(idOrder); return resultMap.addElement("data",ordergoods).success(); } }
package prefeitura.siab.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import prefeitura.siab.persistencia.AcsDao; import prefeitura.siab.tabela.Acs; @Component public class AcsController { private @Autowired AcsDao dao; @Transactional public void salvarAcs(Acs agente) throws BusinessException { Acs auxiliar = dao.searchAcs(agente); if(auxiliar != null){ if(auxiliar.getMatricula().equals(agente.getMatricula()) && auxiliar.getMicroarea().equals(agente.getMicroarea())){ throw new BusinessException("Esse ACS já foi Cadastrado!"); }else if(auxiliar.getMatricula().equals(agente.getMatricula())){ throw new BusinessException("Essa matricula já pertence a algum ACS cadastrado!"); }else if(auxiliar.getMicroarea().equals(agente.getMicroarea())){ throw new BusinessException("Essa Microarea já pertence a algum ACS cadastrado!"); } throw new BusinessException("Impossível salvar esse ACS"); } dao.insert(agente); } public List<Acs> searchListAcs(AcsSearchOptions options){ return dao.searchListAcs(options); } }
package fang.dailytask; import com.fang.dailytask.DuplicateRemoval; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; /** * Author: fangxueshun * Description: 快速去重验证 * Date: 2017/3/2 * Time: 23:08 */ public class TestDuplicateRemoval { @Test //int类型验证 TODO 待完善 public final void testIntType(){ DuplicateRemoval duplicateRemoval = new DuplicateRemoval(); int[] nums= {234,123,234,45,6,6,444,444,444}; int[] targetNums = {234,123,45,6,444}; assertEquals(Arrays.asList(targetNums),duplicateRemoval.removalDup(Arrays.asList(nums))); } @Test //String类型验证 TODO 待完善 public final void testStringType(){ DuplicateRemoval duplicateRemoval = new DuplicateRemoval(); List<String> sourece= new ArrayList<>(); sourece.add("122"); sourece.add("122"); sourece.add("123"); List<String> target = new ArrayList<>(); target.add("122"); target.add("123"); assertEquals(target,duplicateRemoval.removalDup(sourece)); } }
package com.vilio.plms.service.bms.impl; import com.sun.org.apache.xpath.internal.operations.Bool; import com.vilio.plms.dao.*; import com.vilio.plms.exception.ErrorException; import com.vilio.plms.glob.BmsGlobDict; import com.vilio.plms.glob.Fields; import com.vilio.plms.glob.GlobDict; import com.vilio.plms.glob.ReturnCode; import com.vilio.plms.pojo.*; import com.vilio.plms.service.base.CommonService; import com.vilio.plms.service.base.RemoteFmsService; import com.vilio.plms.service.bms.BmsRepaymentScheduleService; import com.vilio.plms.service.bms.BmsSynchronizationService; import com.vilio.plms.service.quartz.PayRepaymentScheduleDetailService; import com.vilio.plms.util.DateUtil; import com.vilio.plms.util.JsonUtil; import com.vilio.plms.util.PlmsUtil; import net.sf.json.JSONObject; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import javax.json.Json; import javax.persistence.criteria.CriteriaBuilder; import java.math.BigDecimal; import java.util.*; /** * Created by martin on 2017/8/24. */ @Service public class BmsSynchronizationServiceImpl implements BmsSynchronizationService { private static final Logger logger = Logger.getLogger(BmsSynchronizationServiceImpl.class); @Resource PayRepaymentScheduleDetailService payRepaymentScheduleDetailService; @Resource ContractDao contractDao; @Resource HouseDao houseDao; @Resource PlmsPropertyInvestigationDao plmsPropertyInvestigationDao; @Resource PlmsInvestDetailDao plmsInvestDetailDao; @Resource PlmsHouseholdRegistrationDao plmsHouseholdRegistrationDao; @Resource PlmsHouseApprovalDao plmsHouseApprovalDao; @Resource ApplyInterestingDao applyInterestingDao; @Resource FundSideDao fundSideDao; @Resource PlmsGuaranteeCorporationDao plmsGuaranteeCorporationDao; @Resource PlmsInsuranceCompanyDao plmsInsuranceCompanyDao; @Resource PlmsCustomerFeeInfoDao plmsCustomerFeeInfoDao; @Resource PlmsSignNotarialDao plmsSignNotarialDao; @Resource PlmsMortgageDao plmsMortgageDao; @Resource PlmsInvestQueryDao plmsInvestQueryDao; @Resource PlmsPigeonholeInfoDao plmsPigeonholeInfoDao; @Resource PlmsCompanyDao plmsCompanyDao; @Resource RemoteFmsService remoteFmsService; @Resource BmsSynchronousDao synchronousDao; @Resource AccountInfoDao accountInfoDao; @Resource ApplyInfoDao applyInfoDao; @Resource CustomerDao customerDao; @Resource UserInfoDao userInfoDao; @Resource ProductDao productDao; @Resource SpareHouseInfoDao spareHouseInfoDao; @Resource CreditInfoDao creditInfoDao; @Resource JudicialInfoDao judicialInfoDao; @Resource LoanCaseUseDao loanCaseUseDao; @Resource LoanAttachDao loanAttachDao; @Resource ApprovalDao loanRiskInfoDao; @Resource CommonService commonService; @Resource BaseTableDao baseTableDao; @Resource PlmsFundSideProductDao plmsFundSideProductDao; @Resource BmsRepaymentScheduleService bmsRepaymentScheduleService; @Resource BmsSynchronizateDao bmsSynchronizateDao; @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public void synchronizeApplyInfo(Map map) throws Exception { logger.info(map); String jsonString = JsonUtil.objectToJson(map); System.out.println(jsonString); Map jsonMap = new HashMap(); // JSONObject json = JSONObject.fromObject(jsonString); jsonMap.put("synchronizeInfo", jsonString); jsonMap.put("status", GlobDict.bms_synchronize_status_init.getKey()); bmsSynchronizateDao.insert(jsonMap); return; } @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) public void synchronize(Map map) throws Exception { //核心系统进价编码 String BMSLoanCode = (String) map.get("bmsLoanCode"); logger.info("本次解析的bmsLoanCode是:"+BMSLoanCode+" 。"); if (BMSLoanCode != null && !"".equals(BMSLoanCode)) { ApplyInfo plmApplyInfo = applyInfoDao.qryApplyInfoByBmsCode(BMSLoanCode); if (plmApplyInfo!=null){ logger.info("无需同步进件数据。"); } if (plmApplyInfo == null) { //进件信息 Map applyInfo = (Map) map.get("applyInfo"); //渠道信息 Map distributeInfo = (Map) map.get("distrbuteInfo"); //渠道产品信息 Map distributeProductInfo = (Map) map.get("distributeProductInfo"); //抵押物信息 List loanPawnList = (List<Map>) map.get("loanPawnList"); //运营登记信息 Map operationsInfo = (Map) map.get("operationsInfo"); //借款人信息 List loanPeopleList = (List<Map>) applyInfo.get("customerInfo"); //备用房信息 List loanSepraroomList = (List<Map>) applyInfo.get("spareHouseInfo"); //征信信息 List loanCreditInfoList = (List<Map>) applyInfo.get("creditInvestigationInfo"); //司法信息 List loanJsuticeInfoList = (List<Map>) applyInfo.get("judicialInfo"); //案件评估信息 Map loanCaseUse = (Map) map.get("loanCaseUse"); //附件材料信息 List loanAttachList = (List<Map>) applyInfo.get("materialInfo"); //风控审批信息 Map riskControlInfo = (Map) map.get("riskControlInfo"); //风险控制信息 Map loanRiskInfo = (Map) map.get("loanRiskInfo"); //审批通知单信息 Map approvalNoticeInfo = (Map) riskControlInfo.get("approvalNoticeInfo"); //业务员信息 String bmsAgentCode = (String)map.get("agentId"); Map agent = (HashMap)baseTableDao.qryAgent(bmsAgentCode); String agentCode = (String)agent.get("code"); String bmsDistributeCode = (String) map.get("distributorCode"); Map distribute = (HashMap)baseTableDao.qryDistribute(bmsDistributeCode); String distributeCode = (String)distribute.get("code"); //同步银行账户信息 Map operationsRegisterInfo = (Map) operationsInfo.get("operationsRegisterInfo"); Map lendingRegistration = (Map)operationsRegisterInfo.get("lendingRegistration"); String bmsAccountName = (String) lendingRegistration.get("accountName"); String bmsAccountNo = (String) lendingRegistration.get("accountNumber"); String bmsAccountBank = (String) lendingRegistration.get("openingBank"); Map plmsAccountInfo = new HashMap(); String accountCode = commonService.getUUID(); plmsAccountInfo.put("code", accountCode); plmsAccountInfo.put("name", bmsAccountName); plmsAccountInfo.put("accountNo", bmsAccountNo); plmsAccountInfo.put("bank", bmsAccountBank); plmsAccountInfo.put("status", GlobDict.valid.getKey()); accountInfoDao.insert(plmsAccountInfo); //同步申请信息 String applyDate = (String) map.get("applyTime"); Object applyAmount = map.get("loanAmount"); String applyAmountString = null; if (applyAmount != null) { applyAmountString = String.valueOf(applyAmount); } BigDecimal applyAmountDecimal = new BigDecimal(applyAmountString); String applyPeriod = (String) map.get("loanPeriodName"); String paidMethod = (String) map.get("creditTypeCode"); if (paidMethod != null && GlobDict.bms_paid_method_permits_loan.getDesc().equals(paidMethod)) { paidMethod = GlobDict.bms_paid_method_permits_loan.getKey(); } else if (paidMethod != null && GlobDict.bms_paid_method_collection_receipt_loan.getDesc().equals(paidMethod)) { paidMethod = GlobDict.bms_paid_method_collection_receipt_loan.getKey(); } BigDecimal intentionMoneyDecimal = null; if (null != approvalNoticeInfo.get("intentionMoney")){ String intentionMoney = String.valueOf(approvalNoticeInfo.get("intentionMoney")); intentionMoneyDecimal = new BigDecimal(intentionMoney); } String mobilephoneValidateNo = (String) map.get("mobilephoneValidateNo"); String remark = (String) map.get("remark"); String applyAccountCode = accountCode; String applyAgentCode = agentCode; String bmsCode = (String) map.get("bmsLoanCode"); Map plmsApplyInfo = new HashMap(); String applyCode = commonService.getUUID(); plmsApplyInfo.put("code", applyCode); plmsApplyInfo.put("applyDate", applyDate); //applyAmountDecimal = applyAmountDecimal.multiply(new BigDecimal(10000)); plmsApplyInfo.put("applyAmount", applyAmountDecimal); plmsApplyInfo.put("applyPeriod", applyPeriod); plmsApplyInfo.put("lendingMethods", paidMethod); plmsApplyInfo.put("intentionMoney", intentionMoneyDecimal); plmsApplyInfo.put("identifyingCode", mobilephoneValidateNo); plmsApplyInfo.put("remark", remark); plmsApplyInfo.put("accountCode", applyAccountCode); plmsApplyInfo.put("agentCode", applyAgentCode); plmsApplyInfo.put("distributeCode", distributeCode); plmsApplyInfo.put("bmsCode", bmsCode); plmsApplyInfo.put("status", GlobDict.valid.getKey()); applyInfoDao.insert(plmsApplyInfo); //同步借款人信息 if (loanPeopleList != null && loanPeopleList.size() > 0) { for (int i = 0; i < loanPeopleList.size(); i++) { Map loanPeople = (Map) loanPeopleList.get(i); String name = (String) loanPeople.get("name"); String usedName = (String) loanPeople.get("usedName"); String certificateType = (String) loanPeople.get("certificateType"); String plmsIdType = ""; if (certificateType != null && GlobDict.id_type_id_card.getDesc().equals(certificateType)) { plmsIdType = GlobDict.id_type_id_card.getKey(); } if (certificateType != null && GlobDict.id_type_temp_id_card.getDesc().equals(certificateType)) { plmsIdType = GlobDict.id_type_temp_id_card.getKey(); } if (certificateType != null && GlobDict.id_type_birth_card.getDesc().equals(certificateType)) { plmsIdType = GlobDict.id_type_birth_card.getKey(); } String certificateNumber = (String) loanPeople.get("certificateNumber"); String certificateValidityStart = (String) loanPeople.get("certificateValidityStart"); if (null != certificateValidityStart && "null".equals(certificateValidityStart)){ certificateValidityStart = null; } String certificateValidityEnd = (String) loanPeople.get("certificateValidityEnd"); if (null != certificateValidityEnd && "null".equals(certificateValidityEnd)){ certificateValidityEnd = null; } Integer age = (Integer) loanPeople.get("age"); String cellphone = (String) loanPeople.get("cellphone"); String workUnit = (String) loanPeople.get("workUnit"); String annualIncome = null; if (loanPeople.get("annualIncome")!= null) { annualIncome = loanPeople.get("annualIncome").toString(); } String post = (String) loanPeople.get("post"); String familyAddress = (String) loanPeople.get("familyAddress"); String maritalStatusCode = (String) loanPeople.get("maritalStatusCode"); String maritalStatusString = ""; String marriageHistory = (String) loanPeople.get("marriageHistory"); Boolean mainLoanner = (Boolean) loanPeople.get("mainLoanner"); String mainLoannerString = ""; if (mainLoanner != null && !mainLoanner) { mainLoannerString = GlobDict.bms_main_loanner_false.getKey(); } else if (mainLoanner != null && mainLoanner) { mainLoannerString = GlobDict.bms_main_loanner_true.getKey(); } String customerApplyCode = applyCode; Map plmsCustomerInfo = new HashMap(); String customerInfoCode = commonService.getUUID(); plmsCustomerInfo.put("code", customerInfoCode); plmsCustomerInfo.put("name", name); plmsCustomerInfo.put("oldName", usedName); plmsCustomerInfo.put("idType", plmsIdType); plmsCustomerInfo.put("idNo", certificateNumber); plmsCustomerInfo.put("startTime", certificateValidityStart); plmsCustomerInfo.put("endTime", certificateValidityEnd); plmsCustomerInfo.put("age", age); plmsCustomerInfo.put("mobile", cellphone); plmsCustomerInfo.put("organization", workUnit); BigDecimal annualIncomeDecimal = null; if (annualIncome != null) { annualIncomeDecimal = new BigDecimal(annualIncome); } //annualIncomeDecimal = annualIncomeDecimal.multiply(new BigDecimal(10000)); plmsCustomerInfo.put("annualIncome", annualIncomeDecimal); plmsCustomerInfo.put("titile", post); plmsCustomerInfo.put("address", familyAddress); plmsCustomerInfo.put("marriage", maritalStatusCode); plmsCustomerInfo.put("marriageHistory", marriageHistory); plmsCustomerInfo.put("isMain", mainLoanner); plmsCustomerInfo.put("accountCode", mainLoanner); plmsCustomerInfo.put("status", GlobDict.valid.getKey()); plmsCustomerInfo.put("applyCode", customerApplyCode); customerDao.insert(plmsCustomerInfo); //更新用户信息表 if (GlobDict.bms_main_loanner_true.getKey().equals(mainLoannerString)) { Map customerMap = new HashMap(); customerMap.put("name", name); customerMap.put("idType", plmsIdType); customerMap.put("idNo", certificateNumber); Map userInfo = (HashMap) userInfoDao.queryUserInfoMapByNameAndIdNo(customerMap); if (userInfo == null) { userInfo = new HashMap(); String code = commonService.getUUID(); userInfo.put("code", code); userInfo.put("name", name); userInfo.put("idType", plmsIdType); userInfo.put("idNo", certificateNumber); userInfo.put("status", GlobDict.valid.getKey()); //userInfo.put("umId",umId); userInfoDao.insert(userInfo); //更新申请信息的用户编码 plmsApplyInfo.put("userCode", code); applyInfoDao.update(plmsApplyInfo); }else { String code = (String)userInfo.get("code"); plmsApplyInfo.put("userCode", code); applyInfoDao.update(plmsApplyInfo); } } } } //同步产品信息 String productName = (String) distributeProductInfo.get("productName"); String circle = (String) distributeProductInfo.get("circle"); String interestCycle = (String) distributeProductInfo.get("interestCycle"); if (interestCycle != null && GlobDict.bms_interest_circle_day.getDesc().equals(interestCycle)) { interestCycle = GlobDict.bms_interest_circle_day.getKey(); } else if (interestCycle != null && GlobDict.bms_interest_circle_month.getDesc().equals(interestCycle)) { interestCycle = GlobDict.bms_interest_circle_month.getKey(); } else if (interestCycle != null && GlobDict.bms_interest_circle_year.getDesc().equals(interestCycle)) { interestCycle = GlobDict.bms_interest_circle_year.getKey(); } String yearPeriod = (String) distributeProductInfo.get("yearPeriod"); String repaymentMethod = GlobDict.first_interest.getKey(); String loanMinimumUnit = (String) distributeProductInfo.get("loanMinimumUnit"); BigDecimal loanMinimumUnitDecimal = null; if (loanMinimumUnit != null) { loanMinimumUnitDecimal = new BigDecimal(loanMinimumUnit); } String loanMinimumAmount = (String) distributeProductInfo.get("loanMinimumAmount"); BigDecimal loanMinimumAmountDecimal = null; if (loanMinimumAmount != null) { loanMinimumAmountDecimal = new BigDecimal(loanMinimumAmount); } String repaymentMinUnit = (String) distributeProductInfo.get("repaymentMinUnit"); BigDecimal repaymentMinUnitDecimal = null; if (repaymentMinUnit != null) { repaymentMinUnitDecimal = new BigDecimal(repaymentMinUnit); } String repaymentMinimumAmount = (String) distributeProductInfo.get("repaymentMinimumAmount"); BigDecimal repaymentMinimumAmountDecimal = null; if (repaymentMinimumAmount != null) { repaymentMinimumAmountDecimal = new BigDecimal(repaymentMinimumAmount); } String borrowClosedPeriod = (String) distributeProductInfo.get("borrowClosedPeriod"); String repaymentClosedPeriod = (String) distributeProductInfo.get("repaymentClosedPeriod"); String isPenalty = (String) distributeProductInfo.get("isPenalty"); String penaltyPeriod = (String) distributeProductInfo.get("penaltyPeriod"); String isFirstMax = (String) distributeProductInfo.get("isFirstMax"); String interestCollectionDate = (String) distributeProductInfo.get("interestCollectionDate"); Map interestCollectionMethodMap = (Map) distributeProductInfo.get("interestCollectionMethod"); String interestCollectionMethod = (String)interestCollectionMethodMap.get("method"); if (null !=interestCollectionMethod && GlobDict.bms_interest_collection_method_pre.getDesc().equals(interestCollectionMethod)){ interestCollectionMethod = GlobDict.bms_interest_collection_method_pre.getKey(); } else if (null !=interestCollectionMethod && GlobDict.bms_interest_collection_method_back.getDesc().equals(interestCollectionMethod)){ interestCollectionMethod = GlobDict.bms_interest_collection_method_back.getKey(); } else if (null !=interestCollectionMethod && GlobDict.bms_interest_collection_method_fix.getDesc().equals(interestCollectionMethod)){ interestCollectionMethod = GlobDict.bms_interest_collection_method_fix.getKey(); } System.out.println("interestCollectionMethod:"+interestCollectionMethod); Integer mortgageInterestPeriod = (Integer)interestCollectionMethodMap.get("term"); Integer graceDays = (Integer) interestCollectionMethodMap.get("moratorium"); String principalDate = (String) distributeProductInfo.get("principalDate"); String principalRepaymentMethod = (String) distributeProductInfo.get("principalRepaymentMethod"); if (principalRepaymentMethod != null && GlobDict.bms_repayment_method_rate.getDesc().equals(principalRepaymentMethod)) { principalRepaymentMethod = GlobDict.bms_repayment_method_rate.getKey(); } else if (principalRepaymentMethod != null && GlobDict.bms_repayment_method_amount.getDesc().equals(principalRepaymentMethod)) { principalRepaymentMethod = GlobDict.bms_repayment_method_amount.getKey(); } String partRepayment = null; if (distributeProductInfo.get("partRepayment") != null) { partRepayment = String.valueOf(distributeProductInfo.get("partRepayment")); } String isPeriodSelect = (String) distributeProductInfo.get("isPeriodSelect"); String overdueFormula = (String) distributeProductInfo.get("overdueFormula"); String overdueMethod = null; if (overdueFormula != null) { overdueMethod = (String) overdueFormula.substring(0, 2); } String serviceFeeMethod = null; String spreadsFormula = (String) distributeProductInfo.get("spreadsFormula"); if (spreadsFormula != null) { serviceFeeMethod = (String) spreadsFormula.substring(0, 2); } String isSpreadOneTime = (String) distributeProductInfo.get("spreadsMethod"); if (isSpreadOneTime != null && GlobDict.bms_is_spread_one_time_once.getDesc().equals(isSpreadOneTime)){ isSpreadOneTime = GlobDict.bms_is_spread_one_time_once.getKey(); } else if (isSpreadOneTime != null && GlobDict.bms_is_spread_one_time_period.getDesc().equals(isSpreadOneTime)){ isSpreadOneTime = GlobDict.bms_is_spread_one_time_period.getKey(); } Integer maxLoanNum = (Integer) distributeProductInfo.get("maxLoanNum"); String paidDaysComputationalRule = GlobDict.product_paid_days_computational_rule_both.getKey(); //bms2.0版本添加,暂时先取利3。 Integer paidDateGraceDays = 3; Map plmsProductInfo = new HashMap(); String productCode = commonService.getUUID(); plmsProductInfo.put("code", productCode); plmsProductInfo.put("productName", productName); plmsProductInfo.put("circle", circle); plmsProductInfo.put("interestCycle", interestCycle); plmsProductInfo.put("yearPeriod", yearPeriod); plmsProductInfo.put("repaymentMethods", repaymentMethod); plmsProductInfo.put("loanMinimumUnit", loanMinimumUnitDecimal); plmsProductInfo.put("loanMinimumAmount", loanMinimumAmountDecimal); plmsProductInfo.put("repaymentMinimumUnit", repaymentMinUnitDecimal); plmsProductInfo.put("repaymentMinimumAmount", repaymentMinimumAmountDecimal); plmsProductInfo.put("borrowClosedPeriod", borrowClosedPeriod); plmsProductInfo.put("repaymentClosedPeriod", repaymentClosedPeriod); plmsProductInfo.put("isPenalty", isPenalty); plmsProductInfo.put("penaltyPeriod", penaltyPeriod); plmsProductInfo.put("isFirstMax", isFirstMax); plmsProductInfo.put("partRepayment",partRepayment); plmsProductInfo.put("interestRepaymentDay", interestCollectionDate); plmsProductInfo.put("mortgageInterestPeriod", mortgageInterestPeriod); plmsProductInfo.put("interestCollectionMethod", interestCollectionMethod); plmsProductInfo.put("graceDays", graceDays); plmsProductInfo.put("paidDateGraceDays", paidDateGraceDays); plmsProductInfo.put("principalRepaymentPeriod", principalDate); plmsProductInfo.put("principalRepaymentMethod", principalRepaymentMethod); plmsProductInfo.put("isPeriodSelect", isPeriodSelect); plmsProductInfo.put("overdueMethod", overdueMethod); plmsProductInfo.put("serviceFeeMethod", serviceFeeMethod); plmsProductInfo.put("isSpreadOneTime", isSpreadOneTime); plmsProductInfo.put("maxLoanNum", maxLoanNum); plmsProductInfo.put("status", GlobDict.valid.getKey()); plmsProductInfo.put("applyCode", applyCode); plmsProductInfo.put("paidDaysComputationalRule", paidDaysComputationalRule); productDao.insert(plmsProductInfo); //同步备用房信息 if (loanSepraroomList != null && loanSepraroomList.size() > 0) { for (int i = 0; i < loanSepraroomList.size(); i++) { Map loanSepraroom = (Map) loanSepraroomList.get(i); String propertyOwner = (String) loanSepraroom.get("propertyOwner"); String propertyAddress = (String) loanSepraroom.get("propertyAddress"); Map plmsSpareInfo = new HashMap(); String spareInfoCode = commonService.getUUID(); plmsSpareInfo.put("code",spareInfoCode); plmsSpareInfo.put("propertyPerson", propertyOwner); plmsSpareInfo.put("propertyAddress", propertyAddress); plmsSpareInfo.put("applyCode", applyCode); plmsSpareInfo.put("status", GlobDict.valid.getKey()); spareHouseInfoDao.insert(plmsSpareInfo); } } //同步征信信息 if (loanCreditInfoList != null && loanCreditInfoList.size() > 0) { for (int s = 0; s < loanCreditInfoList.size(); s++) { Map loanCreditInfo = (Map) loanCreditInfoList.get(s); String name = (String) loanCreditInfo.get("name"); String creditReportDate = (String) loanCreditInfo.get("creditReportDate"); String creditRemark = (String) loanCreditInfo.get("remark"); Map plmsCreditInfo = new HashMap(); String creditInfoCode = commonService.getUUID(); plmsCreditInfo.put("code", creditInfoCode); plmsCreditInfo.put("name", name); plmsCreditInfo.put("reportTime", creditReportDate); plmsCreditInfo.put("remark", creditRemark); plmsCreditInfo.put("status", GlobDict.valid.getKey()); plmsCreditInfo.put("applyCode", applyCode); creditInfoDao.insert(plmsCreditInfo); //同步未结清贷款信息 Integer outstandLoanCount = (Integer) loanCreditInfo.get("outstandLoanCount"); String outstandLoanSum = null; if (loanCreditInfo.get("outstandLoanSum") != null) { outstandLoanSum = String.valueOf(loanCreditInfo.get("outstandLoanSum")); } String outstandLoanBalance = null; if (loanCreditInfo.get("outstandLoanBalance") != null) { outstandLoanBalance = String.valueOf(loanCreditInfo.get("outstandLoanBalance")); } String outstandLoanMonthAvgRepay = null; if (loanCreditInfo.get("outstandLoanMonthAvgRepay")!=null) { outstandLoanMonthAvgRepay = String.valueOf(loanCreditInfo.get("outstandLoanMonthAvgRepay")); } Map plmsLoanUnSettle = new HashMap(); String loanUnSettleCode = commonService.getUUID(); plmsLoanUnSettle.put("code", loanUnSettleCode); plmsLoanUnSettle.put("loanTimes", outstandLoanCount); BigDecimal outstandLoanSumDecimal = null; if (outstandLoanSum != null) { outstandLoanSumDecimal = new BigDecimal(outstandLoanSum); } //outstandLoanSumDecimal = outstandLoanSumDecimal.multiply(new BigDecimal(10000)); plmsLoanUnSettle.put("contractAmount", outstandLoanSumDecimal); BigDecimal balanceDecimal = null; if (outstandLoanBalance != null) { balanceDecimal = new BigDecimal(outstandLoanBalance); } //balanceDecimal = balanceDecimal.multiply(new BigDecimal(10000)); plmsLoanUnSettle.put("balance", balanceDecimal); BigDecimal outstandLoanMonthAvgRepayDecimal = null; if (outstandLoanMonthAvgRepay != null){ outstandLoanMonthAvgRepayDecimal = new BigDecimal(outstandLoanMonthAvgRepay); } //outstandLoanMonthAvgRepayDecimal = outstandLoanMonthAvgRepayDecimal.multiply(new BigDecimal(10000)); plmsLoanUnSettle.put("sixMonthRepayment", outstandLoanMonthAvgRepayDecimal); plmsLoanUnSettle.put("creditCode", creditInfoCode); plmsLoanUnSettle.put("status", GlobDict.valid.getKey()); creditInfoDao.insertLoanUnSettle(plmsLoanUnSettle); //同步未销户贷记卡信息 //账户数 Integer usableCreditCardCount = (Integer) loanCreditInfo.get("usableCreditCardCount"); //授信总额 String usableCardSum = null; if (loanCreditInfo.get("usableCardSum") != null) { usableCardSum = String.valueOf(loanCreditInfo.get("usableCardSum")); } //最近6个月平均使用额度 String usableCardMonthQuotaUsed = null; if (loanCreditInfo.get("usableCardMonthQuotaUsed") != null) { usableCardMonthQuotaUsed = String.valueOf(loanCreditInfo.get("usableCardMonthQuotaUsed")); } //已用额度 String usableCardQuotaUsed = null; if (loanCreditInfo.get("usableCardQuotaUsed") != null) { usableCardQuotaUsed = String.valueOf(loanCreditInfo.get("usableCardQuotaUsed")); } Map plmsUnclosingCard = new HashMap(); String unclosingCardCode = commonService.getUUID(); plmsUnclosingCard.put("code", unclosingCardCode); plmsUnclosingCard.put("accountNumber", usableCreditCardCount); BigDecimal usableCardSumDecimal = null; if (usableCardSum != null){ usableCardSumDecimal = new BigDecimal(usableCardSum); } //usableCardSumDecimal = usableCardSumDecimal.multiply(new BigDecimal(10000)); plmsUnclosingCard.put("totalCredit", usableCardSumDecimal); BigDecimal usableCardQuotaUsedDecimal = null; if (usableCardQuotaUsed != null){ usableCardQuotaUsedDecimal = new BigDecimal(usableCardQuotaUsed); } //usableCardQuotaUsedDecimal = usableCardQuotaUsedDecimal.multiply(new BigDecimal(10000)); plmsUnclosingCard.put("contractAmount", usableCardQuotaUsedDecimal); BigDecimal usableCardMonthQuotaUsedDecimal = null; if (usableCardMonthQuotaUsed != null){ usableCardMonthQuotaUsedDecimal = new BigDecimal(usableCardMonthQuotaUsed); } //usableCardMonthQuotaUsedDecimal = usableCardMonthQuotaUsedDecimal.multiply(new BigDecimal(10000)); plmsUnclosingCard.put("sixMonthLoanAmount", usableCardMonthQuotaUsedDecimal); plmsUnclosingCard.put("creditCode", creditInfoCode); plmsUnclosingCard.put("status", GlobDict.valid.getKey()); creditInfoDao.insertUnclosingCard(plmsUnclosingCard); //同步查询记录表 //近三个月查询次数 Integer findThreemonthCount = (Integer) loanCreditInfo.get("findThreemonthCount"); //贷后管理次数 Integer loanAfterCount = (Integer) loanCreditInfo.get("loanAfterCount"); //担保资格审查次数 Integer guaranteeSeniorityCount = (Integer) loanCreditInfo.get("guaranteeSeniorityCount"); Map plmsQueryRecord = new HashMap(); String queryRecordCode = commonService.getUUID(); plmsQueryRecord.put("code", queryRecordCode); plmsQueryRecord.put("queryNum", findThreemonthCount); plmsQueryRecord.put("manageNum", loanAfterCount); plmsQueryRecord.put("checkNum", guaranteeSeniorityCount); plmsQueryRecord.put("status", GlobDict.valid.getKey()); plmsQueryRecord.put("creditCode", creditInfoCode); creditInfoDao.insertQueryRecord(plmsQueryRecord); //针对逾期信息同步已贷款信息表 List loanInfoList = (List<Map>) loanCreditInfo.get("loanInfoList"); if (loanInfoList != null && loanInfoList.size() > 0) { for (int c = 0; c < loanInfoList.size(); c++) { Map loanInfo = (Map) loanInfoList.get(c); //针对逾期信息同步已贷款信息表 Map currentOverdueLoan = (Map) loanInfo.get("currentOverdueLoan"); if (currentOverdueLoan != null) { //贷款序号 String serialNo = (String) currentOverdueLoan.get("serialNo"); //逾期金额 String overdueAmount = null; if (currentOverdueLoan.get("overdueAmount") != null) { overdueAmount = String.valueOf(currentOverdueLoan.get("overdueAmount")); } Map plmsLoanInfo = new HashMap(); String loanInfoCode = commonService.getUUID(); plmsLoanInfo.put("code", loanInfoCode); plmsLoanInfo.put("loanNo", serialNo); BigDecimal overdueAmountDecimal = null; if (overdueAmount != null){ overdueAmountDecimal = new BigDecimal(overdueAmount); } //overdueAmountDecimal = overdueAmountDecimal.multiply(new BigDecimal(10000)); plmsLoanInfo.put("overdueAmount", overdueAmountDecimal); plmsLoanInfo.put("creditCode", creditInfoCode); plmsLoanInfo.put("type","01"); plmsLoanInfo.put("status", GlobDict.valid.getKey()); creditInfoDao.insertLoanInfo(plmsLoanInfo); } //针对非正常贷款信息同步已贷款信息表 Map aberrantLoan = (Map) loanInfo.get("aberrantLoan"); if (aberrantLoan != null) { //贷款序号 String serialNo = (String) aberrantLoan.get("serialNo"); //贷款状态 String status = (String) aberrantLoan.get("status"); Map plmsLoanInfo = new HashMap(); String aberrantLoanCode = commonService.getUUID(); plmsLoanInfo.put("code", aberrantLoanCode); plmsLoanInfo.put("loanNo", serialNo); plmsLoanInfo.put("loanStatus", status); plmsLoanInfo.put("creditCode", creditInfoCode); plmsLoanInfo.put("type","02"); plmsLoanInfo.put("status", GlobDict.valid.getKey()); creditInfoDao.insertLoanInfo(plmsLoanInfo); } //针对近12个月累计最高逾期次数信息同步已贷款信息表 Map topOverdueCountLoan = (Map) loanInfo.get("topOverdueCountLoan"); if (topOverdueCountLoan!= null) { //贷款序号 String serialNo = (String) topOverdueCountLoan.get("serialNo"); //逾期次数 String overdueCount = (String) topOverdueCountLoan.get("overdueCount"); Map plmsLoanInfo = new HashMap(); String aberrantLoanCode = commonService.getUUID(); plmsLoanInfo.put("code", aberrantLoanCode); plmsLoanInfo.put("loanNo", serialNo); plmsLoanInfo.put("overdueNum", overdueCount); plmsLoanInfo.put("creditCode", creditInfoCode); plmsLoanInfo.put("type","03"); plmsLoanInfo.put("status", GlobDict.valid.getKey()); creditInfoDao.insertLoanInfo(plmsLoanInfo); } //针对近12个月最高连续逾期期数信息同步已贷款信息表 Map topContinuousOverdueLoan = (Map) loanInfo.get("topContinuousOverdueLoan"); if (topContinuousOverdueLoan!= null) { //贷款序号 String serialNo = (String) topContinuousOverdueLoan.get("serialNo"); //期数 String continuityOverduePeriods = (String) topContinuousOverdueLoan.get("continuityOverduePeriods"); Map plmsLoanInfo = new HashMap(); String topContinuousOverdueLoanCode = commonService.getUUID(); plmsLoanInfo.put("code", topContinuousOverdueLoanCode); plmsLoanInfo.put("loanNo", serialNo); plmsLoanInfo.put("period", continuityOverduePeriods); plmsLoanInfo.put("creditCode", creditInfoCode); plmsLoanInfo.put("type","04"); plmsLoanInfo.put("status", GlobDict.valid.getKey()); creditInfoDao.insertLoanInfo(plmsLoanInfo); } } } List creditCardInfos = (List<Map>) loanCreditInfo.get("creditCardInfos"); if (creditCardInfos != null && creditCardInfos.size() > 0) { for (int i = 0; i < creditCardInfos.size(); i++) { Map creditCardInfo = (Map) creditCardInfos.get(i); String type = (String)creditCardInfo.get("type"); if (null != type && "非正常类贷记卡".equals(type)){ //贷记卡序号 String serialNo = (String) creditCardInfo.get("serialNumber"); //贷款状态 String loanStatus = (String) creditCardInfo.get("content"); Map plmsCreaditCard = new HashMap(); String cardAbnormalCode = commonService.getUUID(); plmsCreaditCard.put("code", cardAbnormalCode); plmsCreaditCard.put("cardNo", serialNo); plmsCreaditCard.put("cardStatus", loanStatus); plmsCreaditCard.put("type","02"); plmsCreaditCard.put("creditCode", creditInfoCode); plmsCreaditCard.put("status", GlobDict.valid.getKey()); creditInfoDao.insertCreaditCard(plmsCreaditCard); } //针对贷记卡信息列表下的当前逾期信息同步已贷款信息表 Map cardCurrentOverdue = (Map) creditCardInfo.get("cardCurrentOverdue"); if (cardCurrentOverdue != null){ //贷款序号 String serialNo = (String) cardCurrentOverdue.get("serialNo"); //逾期状态 String overdueAmount = null; if (cardCurrentOverdue.get("overdueAmount") != null) { overdueAmount = String.valueOf(cardCurrentOverdue.get("overdueAmount")); } Map plmsCreaditCard = new HashMap(); String creaditCardCode = commonService.getUUID(); plmsCreaditCard.put("code", creaditCardCode); plmsCreaditCard.put("cardNo", serialNo); BigDecimal overdueAmountDecimal = null; if (overdueAmount != null){ overdueAmountDecimal = new BigDecimal(overdueAmount); } //overdueAmountDecimal = overdueAmountDecimal.multiply(new BigDecimal(10000)); plmsCreaditCard.put("overdueAmount", overdueAmount); plmsCreaditCard.put("type","01"); plmsCreaditCard.put("creditCode", creditInfoCode); plmsCreaditCard.put("status", GlobDict.valid.getKey()); creditInfoDao.insertCreaditCard(plmsCreaditCard); } //针对贷记卡信息列表下的非正常类贷记卡信息同步已贷款信息表 // Map cardAbnormal = (HashMap) creditCardInfo.get("cardAbnormal"); // if (cardAbnormal != null) { // //贷记卡序号 // String serialNo = (String) cardAbnormal.get("serialNo"); // //贷款状态 // String loanStatus = (String) cardAbnormal.get("loanStatus"); // // Map plmsCreaditCard = new HashMap(); // String cardAbnormalCode = commonService.getUUID(); // plmsCreaditCard.put("code", cardAbnormalCode); // plmsCreaditCard.put("cardNo", serialNo); // plmsCreaditCard.put("cardStatus", loanStatus); // plmsCreaditCard.put("type","02"); // plmsCreaditCard.put("creditCode", creditInfoCode); // plmsCreaditCard.put("status", GlobDict.valid.getKey()); // // creditInfoDao.insertCreaditCard(plmsCreaditCard); // } //针对贷记卡信息列表下的近12个月累计最高逾期次数 Map cardTotalOverdueCount = (Map) creditCardInfo.get("cardTotalOverdueCount"); if (cardTotalOverdueCount != null) { //贷记卡序号 String serialNo = (String) cardTotalOverdueCount.get("serialNo"); //贷款状态 String overdueCount = (String) cardTotalOverdueCount.get("overdueCount"); Map plmsCreaditCard = new HashMap(); String cardTotalOverdueCode = commonService.getUUID(); plmsCreaditCard.put("code", cardTotalOverdueCode); plmsCreaditCard.put("cardNo", serialNo); plmsCreaditCard.put("overdueNum", overdueCount); plmsCreaditCard.put("type","03"); plmsCreaditCard.put("creditCode", creditInfoCode); plmsCreaditCard.put("status", GlobDict.valid.getKey()); creditInfoDao.insertCreaditCard(plmsCreaditCard); } //针对贷记卡信息列表下的近12个月最高连续逾期期数 Map cardContinuityOverdueCount = (Map) creditCardInfo.get("cardContinuityOverdueCount"); if (cardContinuityOverdueCount != null ) { //贷记卡序号 String serialNo = (String) cardContinuityOverdueCount.get("serialNo"); //贷款状态 String continuityOverduePeriods = (String) cardContinuityOverdueCount.get("continuityOverduePeriods"); Map plmsCreaditCard = new HashMap(); String cardContinuityOverdueCountCode = commonService.getUUID(); plmsCreaditCard.put("code", cardContinuityOverdueCountCode); plmsCreaditCard.put("cardNo", serialNo); plmsCreaditCard.put("period", continuityOverduePeriods); plmsCreaditCard.put("type","04"); plmsCreaditCard.put("creditCode", creditInfoCode); plmsCreaditCard.put("status", GlobDict.valid.getKey()); creditInfoDao.insertCreaditCard(plmsCreaditCard); } } } //同步担保信息表 List loanGuaranteeInfos = (List<Map>) loanCreditInfo.get("loanGuaranteeInfos"); if (loanGuaranteeInfos != null && loanGuaranteeInfos.size() > 0) { for (int i = 0; i < loanGuaranteeInfos.size(); i++) { Map loanGuaranteeInfo = (Map) loanGuaranteeInfos.get(i); String guaranteeStatus = (String) loanGuaranteeInfo.get("guaranteeStatus"); String guaranteeAmount = null; if (loanGuaranteeInfo.get("guaranteeAmount") != null) { guaranteeAmount = String.valueOf(loanGuaranteeInfo.get("guaranteeAmount")); } String guaranteeBalance = null; if (loanGuaranteeInfo.get("guaranteeBalance") != null) { guaranteeBalance = String.valueOf(loanGuaranteeInfo.get("guaranteeBalance")); } Map plmsLoanGuaranteeInfo = new HashMap(); String loanGuaranteeInfoCode = commonService.getUUID(); plmsLoanGuaranteeInfo.put("code", loanGuaranteeInfoCode); plmsLoanGuaranteeInfo.put("guaranteeStatus", guaranteeStatus); BigDecimal guaranteeAmountDecimal = null; if (guaranteeAmount != null){ guaranteeAmountDecimal = new BigDecimal(guaranteeAmount); } plmsLoanGuaranteeInfo.put("guaranteeAmount", guaranteeAmountDecimal); BigDecimal guaranteeBalanceDecimal = null; if (guaranteeBalance != null){ guaranteeBalanceDecimal = new BigDecimal(guaranteeBalance); } plmsLoanGuaranteeInfo.put("guaranteeBalance", guaranteeBalanceDecimal); plmsLoanGuaranteeInfo.put("creditCode", creditInfoCode); plmsLoanGuaranteeInfo.put("status", GlobDict.valid.getKey()); creditInfoDao.insertLoanGuaranteeInfo(plmsLoanGuaranteeInfo); } } } //同步司法信息 if (loanJsuticeInfoList != null && loanJsuticeInfoList.size() > 0) { for (int i = 0; i < loanJsuticeInfoList.size(); i++) { Map loanJsuticeInfo = (Map) loanJsuticeInfoList.get(i); String name = (String) loanJsuticeInfo.get("name"); String justiceInfo = (String) loanJsuticeInfo.get("justiceInfoCode"); String caseNo = (String) loanJsuticeInfo.get("caseNo"); String subjectExecution = (String) loanJsuticeInfo.get("subjectExecution"); String flagLawsuit = (String) loanJsuticeInfo.get("flagLawsuit"); String flagLawsuitCode = null; if (flagLawsuit != null && GlobDict.bms_is_closed_false.getDesc().equals(flagLawsuit)) { flagLawsuitCode = GlobDict.bms_is_closed_false.getKey(); } if (flagLawsuit != null && GlobDict.bms_is_closed_true.getDesc().equals(flagLawsuit)) { flagLawsuitCode = GlobDict.bms_is_closed_true.getKey(); } String infoNote = (String) loanJsuticeInfo.get("infoNote"); Map plmsLoanJsuticeInfo = new HashMap(); String loanJsuticeInfoCode = commonService.getUUID(); plmsLoanJsuticeInfo.put("code", loanJsuticeInfoCode); plmsLoanJsuticeInfo.put("name", name); plmsLoanJsuticeInfo.put("hasLitigationInfo", justiceInfo); plmsLoanJsuticeInfo.put("litigationNo", caseNo); plmsLoanJsuticeInfo.put("execution", subjectExecution); plmsLoanJsuticeInfo.put("isClosed", flagLawsuitCode); plmsLoanJsuticeInfo.put("details", infoNote); plmsLoanJsuticeInfo.put("applyCode", applyCode); plmsLoanJsuticeInfo.put("status", GlobDict.valid.getKey()); judicialInfoDao.insert(plmsLoanJsuticeInfo); } } //同步案件评估信息 if (loanCaseUse != null) { String familyAssets = (String) loanCaseUse.get("familyAssets"); String familyDebt = (String) loanCaseUse.get("familyDebt"); String familyIncome = (String) loanCaseUse.get("familyIncome"); String mortgaged = (String) loanCaseUse.get("mortgaged"); String loanUse = (String) loanCaseUse.get("loanUse"); String refundSource = (String) loanCaseUse.get("refundSource"); Map plmsLoanCaseUse = new HashMap(); String loanCaseUseCode = commonService.getUUID(); plmsLoanCaseUse.put("code", loanCaseUseCode); plmsLoanCaseUse.put("majorAsset", familyAssets); plmsLoanCaseUse.put("majorLiabilities", familyDebt); plmsLoanCaseUse.put("incomeSources", familyIncome); plmsLoanCaseUse.put("collateralInvestigation", mortgaged); plmsLoanCaseUse.put("loanUsage", loanUse); plmsLoanCaseUse.put("repaymentSource", refundSource); plmsLoanCaseUse.put("applyCode", applyCode); plmsLoanCaseUse.put("status", GlobDict.valid.getKey()); loanCaseUseDao.insert(plmsLoanCaseUse); } //同步附件信息 if (loanAttachList != null && loanAttachList.size() > 0) { for (int i = 0; i < loanAttachList.size(); i++) { Map loanAttach = (Map) loanAttachList.get(i); List fileList = new ArrayList(); Map fileMap = new HashMap(); fileMap.put("serialNo",(String) loanAttach.get("fileId")); fileList.add(fileMap); Map result = new HashMap(); map.put("serialNoList",fileList); try { result = remoteFmsService.getUrlList(map); } catch (Exception e) { e.printStackTrace(); } Map body = (Map)result.get(Fields.PARAM_MESSAGE_BODY); List fileMaps = (List)body.get("fileMaps"); String fileSuffix = null; String uploadTime = null; String fileCode = null; if (fileMaps!=null && fileMaps.size()>0) { fileMap = (Map) fileMaps.get(0); fileCode = (String) fileMap.get("serialNo"); fileSuffix = (String) fileMap.get("fileSuffix"); uploadTime = (String) fileMap.get("uploadTime"); } String fileType = (String) loanAttach.get("fileType"); if (fileType != null && fileType.length() == 1){ fileType = "0"+fileType; } String fileId = (String) loanAttach.get("fileId"); String fileName = (String) loanAttach.get("fileName"); Boolean isDelete = (Boolean) loanAttach.get("isDeleteFlag"); String status = (String)GlobDict.valid.getKey(); if (isDelete){ status = GlobDict.un_valid.getKey(); } Map plmsFileMap = new HashMap(); String code = commonService.getUUID(); plmsFileMap.put("code", code); plmsFileMap.put("fileId", fileId); plmsFileMap.put("fileCode",fileCode); plmsFileMap.put("fileName", fileName); plmsFileMap.put("fileSuffix", fileSuffix); plmsFileMap.put("fileType", fileType); plmsFileMap.put("isDelete",isDelete); plmsFileMap.put("status",status); plmsFileMap.put("applyCode",applyCode); plmsFileMap.put("uploadTime",DateUtil.parseDateTimeForPattern(uploadTime, DateUtil.DATE_TIME_PATTERN3)); applyInfoDao.insertMaterial(plmsFileMap); } } //同步审批信息表记录 if (loanRiskInfo != null) { String firstOpinion = (String) loanRiskInfo.get("firstOpinion"); String secondOpinion = (String) loanRiskInfo.get("secondOpinion"); String thirdOpinion = (String) loanRiskInfo.get("thirdOpinion"); String proprietaryOption = (String) loanRiskInfo.get("proprietaryOption"); String insuranceOption = (String) loanRiskInfo.get("insuranceOption"); String guaranteeCorporationOption = (String) loanRiskInfo.get("guaranteeCorporationOption"); String guaranteeTerms = (String) loanRiskInfo.get("guaranteeTerms"); String lendingTerms = (String) loanRiskInfo.get("lendingTerms"); String totalApprovalAmount = null; if (loanRiskInfo.get("totalApprovalAmount") != null) { totalApprovalAmount = String.valueOf(loanRiskInfo.get("totalApprovalAmount")); } BigDecimal totalApprovalAmountDecimal = null; if (totalApprovalAmount != null){ totalApprovalAmountDecimal = new BigDecimal(totalApprovalAmount); } String guaranteeAmount = null; if (loanRiskInfo.get("guaranteeAmount") != null) { guaranteeAmount = String.valueOf(loanRiskInfo.get("guaranteeAmount")); } BigDecimal guaranteeAmountDecimal = null; if (guaranteeAmount != null){ guaranteeAmountDecimal = new BigDecimal(guaranteeAmount); } Integer approvalPeriod = null; if (loanPawnList != null && loanPawnList.size() >0) { Map loanPawn = (Map)loanPawnList.get(0); approvalPeriod = (Integer) loanPawn.get("approvalPeriod"); } String approvalDate = (String) loanRiskInfo.get("approvalDate"); Map plmsLoanRiskInfo = new HashMap(); String loanRiskInfoCode = commonService.getUUID(); plmsLoanRiskInfo.put("code", loanRiskInfoCode); plmsLoanRiskInfo.put("firstApprovalSuggestion", firstOpinion); plmsLoanRiskInfo.put("secondApprovalSuggesion", secondOpinion); plmsLoanRiskInfo.put("finalApprovalSuggesion", thirdOpinion); plmsLoanRiskInfo.put("fundSideSuggesion", proprietaryOption); plmsLoanRiskInfo.put("insuranceSuggesion", insuranceOption); plmsLoanRiskInfo.put("guaranteeSuggesion", guaranteeCorporationOption); plmsLoanRiskInfo.put("guaranteeCondition", guaranteeTerms); plmsLoanRiskInfo.put("lendingTerms", lendingTerms); plmsLoanRiskInfo.put("approvalQuota", totalApprovalAmountDecimal); plmsLoanRiskInfo.put("guaranteeLimit", guaranteeAmountDecimal); plmsLoanRiskInfo.put("approvalPeriod", approvalPeriod); plmsLoanRiskInfo.put("approvalTime", approvalDate); plmsLoanRiskInfo.put("status", GlobDict.valid.getKey()); plmsLoanRiskInfo.put("applyCode", applyCode); loanRiskInfoDao.insert(plmsLoanRiskInfo); } } } //同步合同信息 synchronizeContract(map); //还款计划相关 bmsRepaymentScheduleService.calculateRepaymentScheduleDependencyInfo(map); } } /** * 同步核心合同信息 * @param data */ void synchronizeContract(Map data) throws ErrorException { //核心系统code String bmsCode = (String) data.get("bmsLoanCode"); //运营信息 Map operationsInfo = (Map) data.get("operationsInfo"); //合同信息记录 List<Map> contractInfoList = (List<Map>) operationsInfo.get("contractInfo"); String contractCode = null; //实收实付信息 Map receiveAndPaidInfo = (Map) operationsInfo.get("receiveAndPaidInfo"); //运营登记信息 Map operationsRegisterInfo = (Map) operationsInfo.get("operationsRegisterInfo"); Map lendingRegistration = (Map) operationsRegisterInfo.get("lendingRegistration"); //运营材料信息 List<Map> operationsMaterialInfoList = (List<Map>) operationsInfo.get("operationsMaterialInfo"); //风控审批信息 Map riskControlInfo = (Map) data.get("riskControlInfo"); //审批通知单 Map approvalNoticeInfo = (Map) riskControlInfo.get("approvalNoticeInfo"); //进件信息 Map applyInfo = (Map) data.get("applyInfo"); //抵押物信息列表(进件所有抵押物) List<Map> collateralInfoList = (List<Map>) data.get("loanPawnList"); Map collateralInfoMap = new HashedMap(); if (collateralInfoList != null && collateralInfoList.size() > 0) { for (Map collateralInfo : collateralInfoList) { collateralInfoMap.put(collateralInfo.get("id"), collateralInfo); } } //渠道信息 Map distrbuteInfo = (Map) data.get("distrbuteInfo"); //渠道产品信息 Map distributeProductInfo = (Map) data.get("distributeProductInfo"); //资方信息 Map fundSideInfo = (Map) data.get("fundSideInfo"); //收息方式 Map interestCollectionMethod = (Map) distributeProductInfo.get("interestCollectionMethod"); //资方产品信息 Map fundSideProductInfo = (Map) data.get("fundSideProductInfo"); //担保公司信息 Map guaranteeInfo = (Map) data.get("guaranteeInfo"); //保险公司 Map insuranceInfo = (Map) data.get("insuranceInfo"); //合同抵押物列表 List<Map> collateralList = null; //创建借款合同信息记录 if (contractInfoList != null && contractInfoList.size() > 0) { for (Map contractInfo : contractInfoList) { boolean isLoanContract = (boolean) contractInfo.get("isLoanContract"); if (!isLoanContract) { continue; } collateralList = (List<Map>) contractInfo.get("collateralList"); contractCode = commonService.getUUID(); //保存合同 Contract contract = new Contract(); contract.setCode(contractCode); String contractNo = (String) contractInfo.get("contractNo"); logger.info("本次同步的合同编号是:" + contractNo); if (StringUtils.isBlank(contractNo)) { logger.info("合同编号存在异常!"); throw new ErrorException(ReturnCode.SYSTEM_EXCEPTION, "合同编号异常"); } contract.setContractNo(contractNo); //获取进件编号 ApplyInfo applyInfoBean = applyInfoDao.qryApplyInfoByBmsCode(bmsCode); if (null == applyInfoBean) { logger.info("获取进件bmsCode=" + bmsCode + "出现异常!"); throw new ErrorException(ReturnCode.SYSTEM_EXCEPTION, "对应进件信息异常"); } contract.setApplyCode(applyInfoBean.getCode()); String strCreditStartDate = (String) lendingRegistration.get("creditTime"); contract.setCreditStartDate(strCreditStartDate); Map collateralInfo = (Map) collateralInfoMap.get(collateralList.get(0).get("id")); Integer approvalPeriod = null; if (collateralInfo != null) { approvalPeriod = (Integer) collateralInfo.get("approvalPeriod"); if (approvalPeriod != null) { contract.setCreditPeriod(approvalPeriod.toString()); } } if (approvalPeriod != null && strCreditStartDate!= null) { Date creditEndDate = PlmsUtil.getDueDate(DateUtil.parseDateTimeForPattern(strCreditStartDate, DateUtil.DATE_PATTERN2), approvalPeriod); String strCreditEndDate = DateUtil.formatDateTime(creditEndDate, DateUtil.DATE_PATTERN2); contract.setCreditEndDate(strCreditEndDate); } String today = DateUtil.getCurrentDateTime2(); contract.setCreateDate(today); contract.setModifyDate(today); contract.setStatus(GlobDict.contract_status_valid.getKey()); contractDao.saveContractInfo(contract); break; } //抵押类型(同一个合同抵押类型相同) String mortgageTypeCode = null; //保存抵押物信息 if (collateralList != null && collateralList.size() > 0) { for (int i = 0; i < collateralList.size(); i++) { Map collateralInfo = (Map) collateralInfoMap.get(collateralList.get(i).get("id")); if (collateralInfo != null) { mortgageTypeCode = (String) collateralInfo.get("mortgageType"); collateralInfo.put("contractCode", contractCode); createHouseInfo(collateralInfo); } } } AccountInfo accountInfo = new AccountInfo(); //为资方还款账户创建银行账户表记录 String fundSideAccountCode = commonService.getUUID(); accountInfo.setCode(fundSideAccountCode); accountInfo.setName((String) fundSideInfo.get("receiveAccountName")); accountInfo.setBank((String) fundSideInfo.get("receiveBank")); accountInfo.setAccountNo((String) fundSideInfo.get("receiveAccountNo")); accountInfo.setStatus(GlobDict.account_info_status_valid.getKey()); accountInfo.setCreateDate(DateUtil.getCurrentDateTime2()); accountInfo.setModifyDate(DateUtil.getCurrentDateTime2()); accountInfoDao.saveAccountInfo(accountInfo); //为宏获还款账户创建银行账户表记录 String honghuoAccountCode = commonService.getUUID(); accountInfo.setCode(honghuoAccountCode); accountInfo.setName((String) distrbuteInfo.get("interestAccountName")); accountInfo.setBank((String) distrbuteInfo.get("interestAccountBank")); accountInfo.setAccountNo((String) distrbuteInfo.get("interestAccountNo")); accountInfo.setStatus(GlobDict.account_info_status_valid.getKey()); accountInfo.setCreateDate(DateUtil.getCurrentDateTime2()); accountInfo.setModifyDate(DateUtil.getCurrentDateTime2()); accountInfoDao.saveAccountInfo(accountInfo); //为宏获保证金账户创建银行账户表记录 String honghuoDepositAccountCode = commonService.getUUID(); accountInfo.setCode(honghuoDepositAccountCode); accountInfo.setName((String) distrbuteInfo.get("interestAccountName")); accountInfo.setBank((String) distrbuteInfo.get("interestAccountBank")); accountInfo.setAccountNo((String) distrbuteInfo.get("interestAccountNo")); accountInfo.setStatus(GlobDict.account_info_status_valid.getKey()); accountInfo.setCreateDate(DateUtil.getCurrentDateTime2()); accountInfo.setModifyDate(DateUtil.getCurrentDateTime2()); accountInfoDao.saveAccountInfo(accountInfo); //创建进件利息信息表记录 ApplyInteresting applyInteresting = new ApplyInteresting(); String applyInterestingCode = commonService.getUUID(); applyInteresting.setCode(applyInterestingCode); Map collateralInfo = (Map) collateralInfoMap.get(collateralList.get(0).get("id")); if (collateralInfo != null) { applyInteresting.setAnnualizedInterest(null == collateralInfo.get("interestRate") ? "0" : collateralInfo.get("interestRate").toString()); } //本金逾期年化利率 applyInteresting.setPrincipalOverInterest((String) distributeProductInfo.get("principalOverInterest")); //利息逾期年化利率 applyInteresting.setInterestOverInterest((String) distributeProductInfo.get("interestOverInterest")); applyInteresting.setServiceFeeInterestRate((String) distributeProductInfo.get("serviceFeeOverInterest")); applyInteresting.setDefaultInterestRate((String) distributeProductInfo.get("plentyRate")); applyInteresting.setContractCode(contractCode); //资方机构代码 String organizationCode = (String) fundSideInfo.get("organizationCode"); //资方产品名称 String productName = (String) fundSideProductInfo.get("productName"); Map fundSideReq = new HashedMap(); fundSideReq.put("bmsCode", organizationCode); fundSideReq.put("productName", productName); List<Map> fundSideProductList = plmsFundSideProductDao.queryFundSideProductByParms(fundSideReq); Map fundSideProduct = fundSideProductList.get(0); applyInteresting.setIsPrincipalInstead(null == fundSideProduct.get("isPrincipalInstead") ? null : fundSideProduct.get("isPrincipalInstead").toString()); applyInteresting.setIsInterestInstead(null == fundSideProduct.get("isInterestInstead") ? null : fundSideProduct.get("isInterestInstead").toString()); applyInteresting.setIsFullRepurchase((String) distrbuteInfo.get("isFullRepurchase")); applyInteresting.setFundSideCode(fundSideAccountCode); applyInteresting.setHonghuoCode(honghuoAccountCode); applyInteresting.setHonghuoBailAccountCode(honghuoDepositAccountCode); applyInteresting.setStatus(GlobDict.apply_interesting_status_valid.getKey()); applyInteresting.setCreateDate(DateUtil.getCurrentDateTime2()); applyInteresting.setModifyDate(DateUtil.getCurrentDateTime2()); applyInterestingDao.saveApplyInteresting(applyInteresting); //创建资方信息表记录 String companyCode = null; PlmsCompany company = new PlmsCompany(); company.setBmsCode(organizationCode); company.setCompanyType(GlobDict.company_type_fundside.getKey()); company = plmsCompanyDao.getCompanyByBmsCode(company); if (null == company) { //创建公司信息 company = new PlmsCompany(); companyCode = commonService.getUUID(); company.setCode(companyCode); company.setBmsCode(organizationCode); company.setCompanyName((String) fundSideInfo.get("organizationName")); company.setAbbrName((String) fundSideInfo.get("organizationAbbr")); company.setCompanyType(GlobDict.company_type_fundside.getKey()); company.setStatus(GlobDict.company_status_valid.getKey()); company.setCreateDate(new Date()); company.setModifyDate(new Date()); plmsCompanyDao.saveCompanyInfo(company); } else { companyCode = company.getCode(); } FundSide fundSide = new FundSide(); String fundSideCode = commonService.getUUID(); fundSide.setCode(fundSideCode); fundSide.setCompanyCode(companyCode); fundSide.setLenders((String) fundSideProductInfo.get("lenders")); fundSide.setYearPeriod((String) fundSideProductInfo.get("yearPeriod")); fundSide.setDefaultInterestRate((String) fundSideProductInfo.get("penaltyRate")); fundSide.setPenaltyPeriod((String) fundSideProductInfo.get("penaltyPeriod")); fundSide.setOverInterest((String) fundSideProductInfo.get("overdueAnnualizedInterest")); //利率 List<Map> interestRate = (List<Map>) fundSideProductInfo.get("interestRate"); if (interestRate != null && interestRate.size() > 0) { for (Map rate : interestRate) { String type = (String) rate.get("type"); //todo String mortgageType = ""; if (mortgageTypeCode!=null && mortgageTypeCode.equals("01")) { mortgageType = "一抵"; } else if (mortgageTypeCode!=null && mortgageTypeCode.equals("02")) { mortgageType = "二抵"; } else if (mortgageTypeCode!=null && mortgageTypeCode.equals("03")) { mortgageType = "一抵转单"; } else if (mortgageTypeCode!=null && mortgageTypeCode.equals("04")) { mortgageType = "二抵转单"; } //todo if (!mortgageType.equals(type)) { continue; } fundSide.setActualInterest(null == rate.get("actRate") ? "0" : rate.get("actRate").toString()); fundSide.setContractInterest(null == rate.get("rate") ? "0" : rate.get("rate").toString()); } } //收息方式 String method = (String) interestCollectionMethod.get("method"); if (BmsGlobDict.fund_side_receive_interest_method_pre.getDesc().equals(method)) { fundSide.setReceiveInterestMethod(GlobDict.fund_side_receive_interest_method_pre.getKey()); } else if (BmsGlobDict.fund_side_receive_interest_method_back.getDesc().equals(method)) { fundSide.setReceiveInterestMethod(GlobDict.fund_side_receive_interest_method_back.getKey()); } else if (BmsGlobDict.fund_side_receive_interest_method_fix.getDesc().equals(method)) { fundSide.setReceiveInterestMethod(GlobDict.fund_side_receive_interest_method_fix.getKey()); } fundSide.setReceiveInterestDate(null == interestCollectionMethod.get("interestDate") ? "0" : interestCollectionMethod.get("interestDate").toString()); fundSide.setMortgageInterestPeriod(null == interestCollectionMethod.get("term") ? "0" : interestCollectionMethod.get("term").toString()); fundSide.setInterestGraceDate(null == interestCollectionMethod.get("moratorium") ? "0" : interestCollectionMethod.get("moratorium").toString()); fundSide.setServiceChargeRate(null == receiveAndPaidInfo.get("proprietaryProductServiceFeeRatio") ? "0" : receiveAndPaidInfo.get("proprietaryProductServiceFeeRatio").toString()); fundSide.setServiceChargeAmount(null == receiveAndPaidInfo.get("proprietaryProductServiceFeeRatioAmount") ? "0" : receiveAndPaidInfo.get("proprietaryProductServiceFeeRatioAmount").toString()); fundSide.setServiceChargePaidAmount(null == receiveAndPaidInfo.get("proprietaryProductServiceFeeRatioReviceAmount") ? "0" : receiveAndPaidInfo.get("proprietaryProductServiceFeeRatioReviceAmount").toString()); fundSide.setServiceChargePaidTime(null == receiveAndPaidInfo.get("proprietaryProductServiceFeeRatioDate") ? null : receiveAndPaidInfo.get("proprietaryProductServiceFeeRatioDate").toString()); fundSide.setBailRate(null == receiveAndPaidInfo.get("proprietaryProductMarginRatio") ? "0" : receiveAndPaidInfo.get("proprietaryProductMarginRatio").toString()); fundSide.setBailAmount(null == receiveAndPaidInfo.get("proprietaryProductMarginAmount") ? "0" : receiveAndPaidInfo.get("proprietaryProductMarginAmount").toString()); fundSide.setBailPayedAmount(null == receiveAndPaidInfo.get("proprietaryProductMarginRevice") ? "0" : receiveAndPaidInfo.get("proprietaryProductMarginRevice").toString()); fundSide.setBailPayedTime((String) receiveAndPaidInfo.get("proprietaryProductMarginDate")); fundSide.setReceiptFeeRate(null == receiveAndPaidInfo.get("proprietaryProductReceiptRatio") ? "0" : receiveAndPaidInfo.get("proprietaryProductReceiptRatio").toString()); fundSide.setReceiptFeeAmount(null == receiveAndPaidInfo.get("proprietaryProductReceiptRatioAmount") ? "0" : receiveAndPaidInfo.get("proprietaryProductReceiptRatioAmount").toString()); fundSide.setReceiptFeePaidAmount(null == receiveAndPaidInfo.get("proprietaryProductReceiptRatioReviceAmount") ? "0" : receiveAndPaidInfo.get("proprietaryProductReceiptRatioReviceAmount").toString()); fundSide.setReceiptFeePaidTime((String) receiveAndPaidInfo.get("proprietaryProductReceiptRatioDate")); fundSide.setContractCode(contractCode); fundSide.setStatus(GlobDict.fund_side_status_valid.getKey()); fundSide.setCreateDate(DateUtil.getCurrentDateTime2()); fundSide.setModifyDate(DateUtil.getCurrentDateTime2()); fundSideDao.saveFundSideInfo(fundSide); //创建担保公司 createGuaranteeCorporation(receiveAndPaidInfo, guaranteeInfo, contractCode); //创建保险公司 createInsuranceCompany(receiveAndPaidInfo, insuranceInfo, contractCode); //创建客户费用信息 createCustomerFeeInfo(receiveAndPaidInfo, contractCode); //创建签约公正信息 createSignNotarial(operationsRegisterInfo, contractCode); //创建抵押登记信息 createMortgage(operationsRegisterInfo, contractCode); //创建产调查询表记录 createInvestQuery(operationsRegisterInfo, contractCode); //创建归档材料信息 if (operationsMaterialInfoList != null && operationsMaterialInfoList.size() > 0) { for (Map operationsMaterialInfo : operationsMaterialInfoList) { createPigeonholeInfo(operationsMaterialInfo, contractCode); } } } } /** * 抵押物信息保存 * @param collateralInfo 抵押物信息 */ private void createHouseInfo(Map collateralInfo){ String mortgageTypeCode = (String) collateralInfo.get("mortgageType"); House house = new House(); String code = commonService.getUUID(); house.setCode(code); house.setCertificateNumberFirst((String) collateralInfo.get("certificateNumberFirst")); house.setCertificateNumberSecond((String) collateralInfo.get("certificateNumberSecond")); //登记日期 String strRegisterDate = (String) collateralInfo.get("purchasingDate"); house.setRegisterDate(strRegisterDate); //评估价 house.setInquiryInformation(collateralInfo.get("valuation") == null ? "0" :collateralInfo.get("valuation").toString()); house.setPropertyOwner((String) collateralInfo.get("propertyOwner")); house.setCityNo((String) collateralInfo.get("cityName")); house.setPropertyArea((String) collateralInfo.get("propertyArea")); house.setCertificateAddress((String) collateralInfo.get("propertyAddress")); //土地性质 String landProperty = (String) collateralInfo.get("landProperty"); String landPropertyCode = null; if(BmsGlobDict.house_land_property_national.getDesc().equals(landProperty)){ landPropertyCode = GlobDict.house_land_property_national.getKey(); }else if(BmsGlobDict.house_land_property_collective.getDesc().equals(landProperty)){ landPropertyCode = GlobDict.house_land_property_collective.getKey(); } house.setLandProperty(landPropertyCode); //土地使用权取得方式 String acquisitionForm = (String) collateralInfo.get("landMakeWay"); String acquisitionFormCode = null; if(BmsGlobDict.house_acquisition_form_sell.getDesc().equals(acquisitionForm)){ acquisitionFormCode = GlobDict.house_acquisition_form_sell.getKey(); }else if(BmsGlobDict.house_acquisition_form_allotted.getDesc().equals(acquisitionForm)){ acquisitionFormCode = GlobDict.house_acquisition_form_allotted.getKey(); }else if(BmsGlobDict.house_acquisition_form_transfer.getDesc().equals(acquisitionForm)){ acquisitionFormCode = GlobDict.house_acquisition_form_transfer.getKey(); } house.setAcquisitionForm(acquisitionFormCode); //房屋类型 String type = (String) collateralInfo.get("propertyType"); String typeCode = null; if(BmsGlobDict.house_type_apartment.getDesc().equals(type)){ typeCode = GlobDict.house_type_apartment.getKey(); }else if(BmsGlobDict.house_type_villa.getDesc().equals(type)){ typeCode = GlobDict.house_type_villa.getKey(); } house.setType(typeCode); house.setOwnerSource((String) collateralInfo.get("homeOwnership")); //建筑面积 String coveredArea = (String) collateralInfo.get("coveredArea"); house.setCoveredArea(coveredArea); house.setGarageAddress((String) collateralInfo.get("garageAddress")); //车库面积 String garageArea = (String) collateralInfo.get("garageArea"); house.setGarageArea(garageArea); if (null != collateralInfo.get("totalFloors")) { house.setTotalFloor(((Integer) collateralInfo.get("totalFloors")).toString()); } house.setBuildYear((String) collateralInfo.get("completionDate")); //共有类型 String publicType = (String) collateralInfo.get("publicType"); String shareTypeCode = null; if(BmsGlobDict.house_share_type_common.getDesc().equals(publicType)){ shareTypeCode = GlobDict.house_share_type_common.getKey(); }else if(BmsGlobDict.house_share_type_several.getDesc().equals(publicType)){ shareTypeCode = GlobDict.house_share_type_several.getKey(); } house.setShareType(shareTypeCode); house.setMinorsUnits((String) collateralInfo.get("propertyMinors")); house.setLandUsage((String) collateralInfo.get("landUse")); //房屋使用情况 String houseUse = (String) collateralInfo.get("housingUsage"); if(BmsGlobDict.house_usage_detail_self.getDesc().equals(houseUse)){ houseUse = GlobDict.house_usage_detail_self.getKey(); }else if(BmsGlobDict.house_usage_detail_record_rent.getDesc().equals(houseUse)){ houseUse = GlobDict.house_usage_detail_record_rent.getKey(); }else if(BmsGlobDict.house_usage_detail_unrecord_rent.getDesc().equals(houseUse)){ houseUse = GlobDict.house_usage_detail_unrecord_rent.getKey(); }else if(BmsGlobDict.house_usage_detail_vacancy.getDesc().equals(houseUse)){ houseUse = GlobDict.house_usage_detail_vacancy.getKey(); } house.setUsageDetail(houseUse); //是否唯一住房 Boolean isUnique = (Boolean) collateralInfo.get("onlyHouse"); if(isUnique != null &&isUnique){ house.setIsUnique(GlobDict.house_is_unique_yes.getKey()); }else if (isUnique != null && !isUnique){ house.setIsUnique(GlobDict.house_is_unique_no.getKey()); } house.setRegisteredResidenceStructure((String) collateralInfo.get("housingStructure")); house.setRemark((String) collateralInfo.get("pragmaticRemark")); //抵押类型 if(BmsGlobDict.house_mortgage_type_first.getKey().equals(mortgageTypeCode)){ mortgageTypeCode = GlobDict.house_mortgage_type_first.getKey(); }else if(BmsGlobDict.house_mortgage_type_second.getKey().equals(mortgageTypeCode)){ mortgageTypeCode = GlobDict.house_mortgage_type_second.getKey(); }else if(BmsGlobDict.house_mortgage_type_first_transfer.getKey().equals(mortgageTypeCode)){ mortgageTypeCode = GlobDict.house_mortgage_type_first_transfer.getKey(); }else if(BmsGlobDict.house_mortgage_type_second_transfer.getKey().equals(mortgageTypeCode)){ mortgageTypeCode = GlobDict.house_mortgage_type_second_transfer.getKey(); } house.setMortgageType(mortgageTypeCode); //一抵余额类型 String firstBalanceTypeCode = (String) collateralInfo.get("balanceType"); if(BmsGlobDict.first_balance_type_left.getDesc().equals(firstBalanceTypeCode)){ house.setFirstBalanceType(GlobDict.house_first_balance_type_left.getKey()); }else if(BmsGlobDict.first_balance_type_top.getDesc().equals(firstBalanceTypeCode)){ house.setFirstBalanceType(GlobDict.house_first_balance_type_max.getKey()); } //一抵余额金额 house.setFirstBalanceAmount(collateralInfo.get("mortgageFirstBalance") == null ? "0" : collateralInfo.get("mortgageFirstBalance").toString()); //一抵金额 house.setFirstMortgageAmount(collateralInfo.get("mortgageFirstAmount") == null ? "0" : collateralInfo.get("mortgageFirstAmount").toString()); //二抵金额 house.setSecondMortgageAmount(collateralInfo.get("mortgageSecondAmount") == null ? "0" : collateralInfo.get("mortgageSecondAmount").toString()); house.setMortgageRate(collateralInfo.get("mortgageRate") == null ? "0" : collateralInfo.get("mortgageRate").toString()); house.setContractCode((String) collateralInfo.get("contractCode")); String today = DateUtil.getCurrentDateTime2(); house.setCreateDate(today); house.setModifyDate(today); house.setStatus(GlobDict.house_status_valid.getKey()); houseDao.saveHouseInfo(house); //保存产调信息 List<Map> dispatchingInformationList = (List<Map>)collateralInfo.get("propertyAdjustmentInfoList"); if (dispatchingInformationList != null && dispatchingInformationList.size()>0) { createPropertyInvestigation(dispatchingInformationList, code); } //保存户口信息 List<Map> accountInformationList = (List<Map>)collateralInfo.get("householdInfoList"); if (accountInformationList != null && accountInformationList.size()>0) { for (Map accountInformation : accountInformationList) { accountInformation.put("houseCode", code); createHouseholdRegistration(accountInformation); } } //创建抵押物审批信息记录 collateralInfo.put("code", code); createHouseholdHouseApproval(collateralInfo); } /** * 产调信息保存 * @param dispatchingInformationList 产调信息列表 * @param houseCode 抵押物 code */ private void createPropertyInvestigation(List<Map> dispatchingInformationList, String houseCode){ Map dispatchingInformation = dispatchingInformationList.get(0); PlmsPropertyInvestigation propertyInvestigation = new PlmsPropertyInvestigation(); String code = commonService.getUUID(); propertyInvestigation.setCode(code); propertyInvestigation.setHouseCode(houseCode); propertyInvestigation.setInCaseInformation((String) dispatchingInformation.get("inCaseInfo")); String strInvestigationTime = (String) dispatchingInformation.get("propertyTransferDate"); propertyInvestigation.setInvestigationTime(DateUtil.parseDateTimeForPattern(strInvestigationTime, DateUtil.DATE_PATTERN2)); propertyInvestigation.setStatus(GlobDict.property_investigation_status_valid.getKey()); propertyInvestigation.setCreateDate(new Date()); propertyInvestigation.setModifyDate(new Date()); plmsPropertyInvestigationDao.savePlmsPropertyInvestigationInfo(propertyInvestigation); //保存产调明细 if (dispatchingInformationList!= null && dispatchingInformationList.size() >0) { for (Map record : dispatchingInformationList) { record.put("investigationCode", code); createInvestDetail(record); } } } /** * 产调明细保存 * @param record 产调明细 */ private void createInvestDetail(Map record){ PlmsInvestDetail investDetail = new PlmsInvestDetail(); String code = commonService.getUUID(); investDetail.setCode(code); investDetail.setMortgageRank((String) record.get("mortgageWeight")); //债权类型 String mortgageType = (String) record.get("mortgageType"); if(BmsGlobDict.creditor_rights_type.getDesc().equals(mortgageType)){ investDetail.setCreditorRightsType((String)BmsGlobDict.creditor_rights_type.getKey()); }else{ investDetail.setCreditorRightsType((String)BmsGlobDict.creditor_rights_max.getKey()); } investDetail.setCreditorRightsPerson((String) record.get("mortgagePeople")); //债权性质 //债券性质:银行借贷、民间借贷, String creditorProperty = (String) record.get("mortgageProperty"); if(BmsGlobDict.creditor_property_bank.getDesc().equals(creditorProperty)){ investDetail.setCreditorProperty(GlobDict.invest_detail_creditor_property_bank.getKey()); }else if(BmsGlobDict.creditor_property_private.getDesc().equals(creditorProperty)){ investDetail.setCreditorProperty(GlobDict.invest_detail_creditor_property_private.getKey()); } //债权金额 String strCreditorAmount = (null == record.get("mortgagePrice") ? "0" : record.get("mortgagePrice").toString()); investDetail.setCreditorAmount(new BigDecimal(strCreditorAmount)); investDetail.setInvestigationCode((String) record.get("investigationCode")); investDetail.setCreateDate(new Date()); investDetail.setModifyDate(new Date()); investDetail.setStatus(GlobDict.invest_detail_status_valid.getKey()); plmsInvestDetailDao.saveInvestDetail(investDetail); } /** * 户口信息保存 * @param accountInformation */ private void createHouseholdRegistration(Map accountInformation){ PlmsHouseholdRegistration householdRegistration = new PlmsHouseholdRegistration(); String code = commonService.getUUID(); householdRegistration.setCode(code); householdRegistration.setName((String) accountInformation.get("name")); householdRegistration.setIdNo((String) accountInformation.get("idCardNum")); householdRegistration.setHouseCode((String) accountInformation.get("houseCode")); householdRegistration.setCreateDate(new Date()); householdRegistration.setModifyDate(new Date()); householdRegistration.setStatus(GlobDict.household_registration_status_valid.getKey()); plmsHouseholdRegistrationDao.saveHouseholdRegistration(householdRegistration); } /** * 保存抵押物审批信息 * @param collateralInfo 抵押物信息 */ private void createHouseholdHouseApproval(Map collateralInfo){ PlmsHouseApproval houseApproval = new PlmsHouseApproval(); String code = commonService.getUUID(); houseApproval.setCode(code); //批复金额 String strApproveAmount = null == collateralInfo.get("approvalAmount") ? "0" : collateralInfo.get("approvalAmount").toString(); houseApproval.setApproveAmount(new BigDecimal(strApproveAmount)); //批复期限 String approvePeroid = (null == collateralInfo.get("approvalPeriod") ? "0" : collateralInfo.get("approvalPeriod").toString() ); houseApproval.setApprovePeroid(Integer.parseInt(approvePeroid)); //合同抵押物价值 String strHouseValue = (null == collateralInfo.get("contractPawnPrice") ? "0" : collateralInfo.get("contractPawnPrice").toString()); houseApproval.setHouseValue(new BigDecimal(strHouseValue)); houseApproval.setHouseCode((String) collateralInfo.get("code")); houseApproval.setStatus(GlobDict.house_approval_status_valid.getKey()); //担保额度 String strGuaranteeLimit = (null == collateralInfo.get("pawnGuaranteeAmount") ? "0" : collateralInfo.get("pawnGuaranteeAmount").toString()); houseApproval.setGuaranteeLimit(new BigDecimal(strGuaranteeLimit)); //抵押权债权总额 String strMortgageTotalAmount = (null == collateralInfo.get("pawnMortgageAmount") ? "0" : collateralInfo.get("pawnMortgageAmount").toString()); houseApproval.setMortgageTotalAmount(new BigDecimal(strMortgageTotalAmount)); houseApproval.setCreateDate(new Date()); houseApproval.setModifyDate(new Date()); plmsHouseApprovalDao.savePlmsHouseApproval(houseApproval); } /** * 保存担保公司信息 * @param receiveAndPaidInfo 实收实付信息 * @param guaranteeInfo 担保公司信息 * @param contractCode 合同编号 */ private void createGuaranteeCorporation(Map receiveAndPaidInfo , Map guaranteeInfo, String contractCode){ PlmsGuaranteeCorporation guaranteeCorporation = new PlmsGuaranteeCorporation(); String code = commonService.getUUID(); guaranteeCorporation.setCode(code); String companyCode = null; PlmsCompany company = new PlmsCompany(); company.setBmsCode((String) guaranteeInfo.get("organizationCode")); company.setCompanyType(GlobDict.company_type_guarantee.getKey()); company = plmsCompanyDao.getCompanyByBmsCode(company); if(null == company){ //创建公司信息 company = new PlmsCompany(); companyCode = commonService.getUUID(); company.setCode(companyCode); company.setBmsCode((String) guaranteeInfo.get("organizationCode")); company.setCompanyName((String) guaranteeInfo.get("organizationName")); company.setAbbrName((String) guaranteeInfo.get("organizationAbbr")); company.setCompanyType(GlobDict.company_type_guarantee.getKey()); company.setStatus(GlobDict.company_status_valid.getKey()); company.setCreateDate(new Date()); company.setModifyDate(new Date()); plmsCompanyDao.saveCompanyInfo(company); }else{ companyCode = company.getCode(); } guaranteeCorporation.setCompanyCode(companyCode); //担保费率 String strGuaranteeRate = (null == receiveAndPaidInfo.get("guaranteeCorporationProductGuaranteeRate") ? "0" : receiveAndPaidInfo.get("guaranteeCorporationProductGuaranteeRate").toString() ); guaranteeCorporation.setGuaranteeRate(new BigDecimal(strGuaranteeRate)); //担保费金额 String strGuaranteeAmount = (null == receiveAndPaidInfo.get("guaranteeCorporationProductGuaranteeRateAmount") ? "0" : receiveAndPaidInfo.get("guaranteeCorporationProductGuaranteeRateAmount").toString()); guaranteeCorporation.setGuaranteeAmount(new BigDecimal(strGuaranteeAmount)); //担保费实付金额 String strGuaranteePayedAmount = (null == receiveAndPaidInfo.get("guaranteeCorporationProductGuaranteeRateReviceAmount") ? "0" : receiveAndPaidInfo.get("guaranteeCorporationProductGuaranteeRateReviceAmount").toString()); guaranteeCorporation.setGuaranteePayedAmount(new BigDecimal(strGuaranteePayedAmount)); //担保费实付时间 String strGuaranteePayedTime = (String) receiveAndPaidInfo.get("guaranteeCorporationProductGuaranteeRateDate"); guaranteeCorporation.setGuaranteePayedTime(DateUtil.parseDateTimeForPattern(strGuaranteePayedTime, DateUtil.DATE_TIME_PATTERN3)); //保证金比例 String strBailRate = (null == receiveAndPaidInfo.get("guaranteeCorporationProductMarginRatio") ? "0" : receiveAndPaidInfo.get("guaranteeCorporationProductMarginRatio").toString()); guaranteeCorporation.setBailRate(new BigDecimal(strBailRate)); //保证金金额 String strBailAmount = (null == receiveAndPaidInfo.get("guaranteeCorporationProductMarginRatioAmount") ? "0" : receiveAndPaidInfo.get("guaranteeCorporationProductMarginRatioAmount").toString()); guaranteeCorporation.setBailAmount(new BigDecimal(strBailAmount)); //保证金实付金额 String strBailPayedAmount = (null == receiveAndPaidInfo.get("guaranteeCorporationProductMarginReviceAmount") ? "0" : receiveAndPaidInfo.get("guaranteeCorporationProductMarginReviceAmount").toString()); guaranteeCorporation.setBailPayedAmount(new BigDecimal(strBailPayedAmount)); //保证金实付时间 String strBailPayedTime = (String) receiveAndPaidInfo.get("guaranteeCorporationProductMarginDate"); guaranteeCorporation.setBailPayedTime(DateUtil.parseDateTimeForPattern(strBailPayedTime, DateUtil.DATE_TIME_PATTERN3)); guaranteeCorporation.setContractCode(contractCode); guaranteeCorporation.setStatus(GlobDict.guarantee_corporation_status_valid.getKey()); guaranteeCorporation.setCreateDate(new Date()); guaranteeCorporation.setModifyDate(new Date()); plmsGuaranteeCorporationDao.saveGuaranteeCorporation(guaranteeCorporation); } /** * 保存保险公司信息 * @param receiveAndPaidInfo 实收实付信息 * @param insuranceInfo 保险公司信息 * @param contractCode 合同编号 */ private void createInsuranceCompany(Map receiveAndPaidInfo , Map insuranceInfo, String contractCode){ PlmsInsuranceCompany insuranceCompany= new PlmsInsuranceCompany(); String code = commonService.getUUID(); insuranceCompany.setCode(code); String companyCode = null; PlmsCompany company = new PlmsCompany(); company.setBmsCode((String) insuranceInfo.get("organizationCode")); company.setCompanyType(GlobDict.company_type_insurance.getKey()); company = plmsCompanyDao.getCompanyByBmsCode(company); if(null == company){ //创建公司信息 company = new PlmsCompany(); companyCode = commonService.getUUID(); company.setCode(companyCode); company.setBmsCode((String) insuranceInfo.get("organizationCode")); company.setCompanyName((String) insuranceInfo.get("organizationName")); company.setAbbrName((String) insuranceInfo.get("organizationAbbr")); company.setCompanyType(GlobDict.company_type_insurance.getKey()); company.setStatus(GlobDict.company_status_valid.getKey()); company.setCreateDate(new Date()); company.setModifyDate(new Date()); plmsCompanyDao.saveCompanyInfo(company); }else{ companyCode = company.getCode(); } insuranceCompany.setCompanyCode(companyCode); //保证金比例 String strBailRate = (null == receiveAndPaidInfo.get("insuranceProductMarginRatio") ? "0" : receiveAndPaidInfo.get("insuranceProductMarginRatio").toString()); insuranceCompany.setBailRate(new BigDecimal(strBailRate)); //保证金应付金额 String strBailAmount = (null == receiveAndPaidInfo.get("insuranceProductMarginAmount") ? "0" : receiveAndPaidInfo.get("insuranceProductMarginAmount").toString()); insuranceCompany.setBailAmount(new BigDecimal(strBailAmount)); //保证金实付金额 String strBailPayedPaidAmount = (null == receiveAndPaidInfo.get("insuranceProductMarginReviceAmount") ? "0" : receiveAndPaidInfo.get("insuranceProductMarginReviceAmount").toString()); insuranceCompany.setBailPayedPaidAmount(new BigDecimal(strBailPayedPaidAmount)); //保证金实付完成时间 String strBailPayedTime = (String) receiveAndPaidInfo.get("insuranceProductMarginReviceDate"); insuranceCompany.setBailPayedTime(DateUtil.parseDateTimeForPattern(strBailPayedTime, DateUtil.DATE_TIME_PATTERN3)); insuranceCompany.setBailPayedMethod((String) receiveAndPaidInfo.get("insuranceProductMarginType")); //履约保证保险费率 String strPerformanceBondRate = (null == receiveAndPaidInfo.get("insuranceProductInsurance1Ratio") ? "0" : receiveAndPaidInfo.get("insuranceProductInsurance1Ratio").toString()); insuranceCompany.setPerformanceBondRate(new BigDecimal(strPerformanceBondRate)); //履约保证保险费应付金额 String strPerformanceBondAmount = (null == receiveAndPaidInfo.get("insuranceProductInsurance1Amount") ? "0" : receiveAndPaidInfo.get("insuranceProductInsurance1Amount").toString()); insuranceCompany.setPerformanceBondAmount(new BigDecimal(strPerformanceBondAmount)); //履约保证保险费实付金额 String strPerformanceBondPaidAmount = (null == receiveAndPaidInfo.get("insuranceProductInsurance1ReviceAmount") ? "0" : receiveAndPaidInfo.get("insuranceProductInsurance1ReviceAmount").toString()); insuranceCompany.setPerformanceBondPaidAmount(new BigDecimal(strPerformanceBondPaidAmount)); //履约保证保险费实付时间 String strPerformanceBondPayedTime = (String) receiveAndPaidInfo.get("insuranceProductInsurance1Date"); insuranceCompany.setPerformanceBondPayedTime(DateUtil.parseDateTimeForPattern(strPerformanceBondPayedTime, DateUtil.DATE_TIME_PATTERN3)); insuranceCompany.setPerformanceBondPayedMethod((String) receiveAndPaidInfo.get("insuranceProductInsurance1Type")); insuranceCompany.setSecondInsuranceName((String) receiveAndPaidInfo.get("insurance2")); //险种2费率 String strSecondInsuranceFeeRate = (null == receiveAndPaidInfo.get("insuranceProductInsurance2Ratio") ? "0" : receiveAndPaidInfo.get("insuranceProductInsurance2Ratio").toString()); insuranceCompany.setSecondInsuranceFeeRate(new BigDecimal(strSecondInsuranceFeeRate)); //险种2费用应付金额 String strSecondInsuranceFeeAmount = (null == receiveAndPaidInfo.get("insuranceProductInsurance2Amount") ? "0" : receiveAndPaidInfo.get("insuranceProductInsurance2Amount").toString()); insuranceCompany.setSecondInsuranceFeeAmount(new BigDecimal(strSecondInsuranceFeeAmount)); //险种2费用实付金额 String strSecondInsurancePaidAmount = (null == receiveAndPaidInfo.get("insuranceProductInsurance2ReviceAmount") ? "0" : receiveAndPaidInfo.get("insuranceProductInsurance2ReviceAmount").toString()); insuranceCompany.setSecondInsurancePaidAmount(new BigDecimal(strSecondInsurancePaidAmount) ); //险种2费用实付时间 String strSecondInsurancePayedTime = (String) receiveAndPaidInfo.get("insuranceProductInsurance2Date"); insuranceCompany.setSecondInsurancePayedTime(DateUtil.parseDateTimeForPattern(strSecondInsurancePayedTime, DateUtil.DATE_TIME_PATTERN3)); insuranceCompany.setSecondInsurancePayedMethod((String) receiveAndPaidInfo.get("insuranceProductInsurance2Type")); insuranceCompany.setContractCode(contractCode); insuranceCompany.setStatus(GlobDict.insurance_company_status_valid.getKey()); insuranceCompany.setCreateDate(new Date()); insuranceCompany.setModifyDate(new Date()); plmsInsuranceCompanyDao.saveInsuranceCompanyInfo(insuranceCompany); } /** * 保存客户费用信息 * @param receiveAndPaidInfo 实收实付信息 * @param contractCode 合同编号 */ private void createCustomerFeeInfo(Map receiveAndPaidInfo, String contractCode){ PlmsCustomerFeeInfo customerFeeInfo = new PlmsCustomerFeeInfo(); String code = commonService.getUUID(); customerFeeInfo.setCode(code); //手续费比例 String strServiceChargeRate = (null == receiveAndPaidInfo.get("serviceRatio") ? "0" : receiveAndPaidInfo.get("serviceRatio").toString()); customerFeeInfo.setServiceChargeRate(new BigDecimal(strServiceChargeRate)); //手续费应收金额 String strServiceChargeAmount = (null == receiveAndPaidInfo.get("serviceAmount") ? "0" : receiveAndPaidInfo.get("serviceAmount").toString()); customerFeeInfo.setServiceChargeAmount(new BigDecimal(strServiceChargeAmount)); //手续费实收金额 String strServiceChargeReceiveAmount = (null == receiveAndPaidInfo.get("serviceReviceAmout") ? "0" : receiveAndPaidInfo.get("serviceReviceAmout").toString()); customerFeeInfo.setServiceChargeReceiveAmount(new BigDecimal(strServiceChargeReceiveAmount)); //手续费实收完成时间 String strServiceChargeReceiveTime = (String) receiveAndPaidInfo.get("serviceReviceDate"); customerFeeInfo.setServiceChargeReceiveTime(DateUtil.parseDateTimeForPattern(strServiceChargeReceiveTime, DateUtil.DATE_TIME_PATTERN3)); //担保费率 String strGuaranteeFeeRate = (null == receiveAndPaidInfo.get("guaranteeFeeRatio") ? "0" : receiveAndPaidInfo.get("guaranteeFeeRatio").toString()); customerFeeInfo.setGuaranteeFeeRate(new BigDecimal(strGuaranteeFeeRate)); //担保费应收金额 String strGuaranteeFeeAmount = (null == receiveAndPaidInfo.get("guaranteeFee") ? "0" : receiveAndPaidInfo.get("guaranteeFee").toString()); customerFeeInfo.setGuaranteeFeeAmount(new BigDecimal(strGuaranteeFeeAmount)); //担保费实收金额 String strGuaranteeFeeReceiveAmount = (null == receiveAndPaidInfo.get("guaranteeFeeRevice") ? "0" : receiveAndPaidInfo.get("guaranteeFeeRevice").toString()); customerFeeInfo.setGuaranteeFeeReceiveAmount(new BigDecimal(strGuaranteeFeeReceiveAmount)); //担保费实收时间 String strGuaranteeFeeReceiveTime = (String) receiveAndPaidInfo.get("guaranteeFeeDate"); customerFeeInfo.setGuaranteeFeeReceiveTime(DateUtil.parseDateTimeForPattern(strGuaranteeFeeReceiveTime, DateUtil.DATE_TIME_PATTERN3)); //保证金比例 String strBailRate = (String) receiveAndPaidInfo.get("marginRatio"); customerFeeInfo.setBailRate(new BigDecimal(strBailRate)); //保证金应收金额 String strBailAmount = (String) receiveAndPaidInfo.get("marginFee"); customerFeeInfo.setBailAmount(new BigDecimal(strBailAmount)); //保证金实收金额 String strBailReceiveAmount = (null == receiveAndPaidInfo.get("marginFeeReviceAmout") ? "0" : receiveAndPaidInfo.get("marginFeeReviceAmout").toString()); customerFeeInfo.setBailReceiveAmount(new BigDecimal(strBailReceiveAmount)); //保证金实收时间 String strBailReceiveTime = (String) receiveAndPaidInfo.get("guaranteeFeeDate"); customerFeeInfo.setBailReceiveTime(DateUtil.parseDateTimeForPattern(strBailReceiveTime, DateUtil.DATE_TIME_PATTERN3)); //履约保证保险费率 String strPerformanceBondRate = (String) receiveAndPaidInfo.get("fontPropertyInsuranceRate"); customerFeeInfo.setPerformanceBondRate(new BigDecimal(strPerformanceBondRate)); //履约保证保险费应收金额 String strPerformanceBondAmount = (String) receiveAndPaidInfo.get("fontPropertyInsuranceFee"); customerFeeInfo.setPerformanceBondAmount(new BigDecimal(strPerformanceBondAmount)); //履约保证保险费实收金额 String strPerformanceBondReceiveAmount = (null == receiveAndPaidInfo.get("fontPropertyInsuranceReciveAmount") ? "0" : receiveAndPaidInfo.get("fontPropertyInsuranceReciveAmount").toString()); customerFeeInfo.setPerformanceBondReceiveAmount(new BigDecimal(strPerformanceBondReceiveAmount)); //履约保证金实收时间 String strPerformanceBondReceiveTime = (String) receiveAndPaidInfo.get("fontPropertyInsuranceDate"); customerFeeInfo.setPerformanceBondReceiveTime(DateUtil.parseDateTimeForPattern(strPerformanceBondReceiveTime, DateUtil.DATE_TIME_PATTERN3)); customerFeeInfo.setContractCode(contractCode); customerFeeInfo.setStatus(GlobDict.customer_fee_info_status_valid.getKey()); customerFeeInfo.setCreateDate(new Date()); customerFeeInfo.setModifyDate(new Date()); plmsCustomerFeeInfoDao.saveCustomerFeeInfo(customerFeeInfo); } /** * 保存签约公正信息 * @param operationsRegisterInfo 运营登记信息 * @param contractCode 合同code */ private void createSignNotarial(Map operationsRegisterInfo, String contractCode){ //签约信息 Map signing = (Map) operationsRegisterInfo.get("signing"); PlmsSignNotarial signNotarial = new PlmsSignNotarial (); String code = commonService.getUUID(); signNotarial.setCode(code); signNotarial.setSignResult((String) signing.get("signingResult")); signNotarial.setRemark((String) signing.get("signingRemark")); signNotarial.setSignPlace((String) signing.get("signingPlace")); //签约公证时间 String strBailReceiveTime = (String) signing.get("signingApproveTime"); signNotarial.setSignTime(DateUtil.parseDateTimeForPattern(strBailReceiveTime, DateUtil.DATE_TIME_PATTERN3)); signNotarial.setContractCode(contractCode); signNotarial.setStatus(GlobDict.sign_notarial_status_valid.getKey()); signNotarial.setCreateDate(new Date()); signNotarial.setModifyDate(new Date()); plmsSignNotarialDao.saveSignNotarialInfo(signNotarial); } /** * 保存抵押登记信息 * @param operationsRegisterInfo 运营登记信息 * @param contractCode 合同code */ private void createMortgage(Map operationsRegisterInfo, String contractCode){ //抵押登记信息 Map notarization = (Map) operationsRegisterInfo.get("notarization"); PlmsMortgage mortgage = new PlmsMortgage(); String code = commonService.getUUID(); mortgage.setCode(code); mortgage.setRegistrationResult((String) notarization.get("notarizationResult")); mortgage.setRemark((String) notarization.get("notarizationRemark")); mortgage.setRegistrationPlace((String) notarization.get("notarizationPlace")); //抵押登记时间 String strRegistrationTime = (String) notarization.get("notarizationApproveTime"); mortgage.setRegistrationTime(DateUtil.parseDateTimeForPattern(strRegistrationTime, DateUtil.DATE_TIME_PATTERN3)); mortgage.setContractCode(contractCode); mortgage.setStatus(GlobDict.mortgage_status_valid.getKey()); mortgage.setCreateDate(new Date()); mortgage.setModifyDate(new Date()); plmsMortgageDao.saveMortgageInfo(mortgage); } /** * 保存产调查询 * @param operationsRegisterInfo 运营登记信息 * @param contractCode 合同code */ private void createInvestQuery(Map operationsRegisterInfo, String contractCode){ List propertyInquireList = (List<Map>)operationsRegisterInfo.get("propertyInquireList"); if (propertyInquireList != null) { for (int i = 0; i < propertyInquireList.size();i++) { Map propertyInquire = (Map) propertyInquireList.get(i); PlmsInvestQuery investQuery = new PlmsInvestQuery(); String code = commonService.getUUID(); investQuery.setCode(code); investQuery.setInvestQueryResult((String) propertyInquire.get("propertyInquireRemark")); investQuery.setRemark((String) propertyInquire.get("propertyInquireRemark")); String strInvestQueryTime = (String) propertyInquire.get("selectTime"); investQuery.setInvestQueryTime(DateUtil.parseDateTimeForPattern(strInvestQueryTime, DateUtil.DATE_TIME_PATTERN3)); investQuery.setContractCode(contractCode); investQuery.setStatus(GlobDict.invest_query_status_valid.getKey()); investQuery.setCreateTime(new Date()); investQuery.setModifyTime(new Date()); plmsInvestQueryDao.saveInvestQuery(investQuery); } } } private void createPigeonholeInfo(Map operationsMaterialInfo, String contractCode){ PlmsPigeonholeInfo pigeonholeInfo = new PlmsPigeonholeInfo(); String code = commonService.getUUID(); pigeonholeInfo.setCode(code); pigeonholeInfo.setFileCode((String) operationsMaterialInfo.get("fileId")); pigeonholeInfo.setFileName((String) operationsMaterialInfo.get("fileName")); //归档文件类别 String type = (String) operationsMaterialInfo.get("fileType"); if(BmsGlobDict.pigeonhole_info_type_notarization.getKey().equals(type)){ pigeonholeInfo.setType(GlobDict.pigeonhole_info_type_notarization.getKey()); }else if(BmsGlobDict.pigeonhole_info_type_guarantee.getKey().equals(type)){ pigeonholeInfo.setType(GlobDict.pigeonhole_info_type_guarantee.getKey()); }else if(BmsGlobDict.pigeonhole_info_type_insurance.getKey().equals(type)) { pigeonholeInfo.setType(GlobDict.pigeonhole_info_type_insurance.getKey()); }else if(BmsGlobDict.pigeonhole_info_type_mortgage.getKey().equals(type)) { pigeonholeInfo.setType(GlobDict.pigeonhole_info_type_mortgage.getKey()); }else if(BmsGlobDict.pigeonhole_info_type_invest_query.getKey().equals(type)) { pigeonholeInfo.setType(GlobDict.pigeonhole_info_type_invest_query.getKey()); }else if(BmsGlobDict.pigeonhole_info_type_loan_voucher.getKey().equals(type)) { pigeonholeInfo.setType(GlobDict.pigeonhole_info_type_loan_voucher.getKey()); }else{ pigeonholeInfo.setType(type); } //去文件系统获取上载时间 List fileList = new ArrayList(); Map fileMap = new HashMap(); fileMap.put("serialNo",(String) operationsMaterialInfo.get("fileId")); fileList.add(fileMap); Map map = new HashMap(); map.put("serialNoList",fileList); Map result = null; try { result = remoteFmsService.getUrlList(map); } catch (Exception e) { e.printStackTrace(); } //获取返回结果 Map body = (Map)result.get(Fields.PARAM_MESSAGE_BODY); List fileMaps = (List)body.get("fileMaps"); if (fileMaps!=null && fileMaps.size()>0) { fileMap = (Map) fileMaps.get(0); String uploadTime = (String) fileMap.get("uploadTime"); String fileSuffix = (String) fileMap.get("fileSuffix"); pigeonholeInfo.setUploadTime(DateUtil.parseDateTimeForPattern(uploadTime, DateUtil.DATE_TIME_PATTERN3)); pigeonholeInfo.setContractCode(contractCode); pigeonholeInfo.setFileSuffix(fileSuffix); pigeonholeInfo.setStatus(GlobDict.pigeonhole_info_status_valid.getKey()); pigeonholeInfo.setCreateDate(new Date()); pigeonholeInfo.setModifyDate(new Date()); plmsPigeonholeInfoDao.savePigeonholeInfo(pigeonholeInfo); } } }
package SoftwareAS.Controller; import java.util.HashMap; import java.util.Map; import Exceptions.ActivityAlreadyExistsException; import Exceptions.ActivityNotFoundException; import Exceptions.AdminNotFoundException; import Exceptions.DeveloperNotFoundException; import Exceptions.NotAuthorizedException; import Exceptions.OperationNotAllowedException; import Exceptions.OutOfBoundsException; import Exceptions.OverlappingSessionsException; import Exceptions.ProjectAlreadyExistsException; import Exceptions.ProjectNotFoundException; class DoNothingCommand implements Command { @Override public void execute() {} } // This class was taken from: https://coderwall.com/p/wgtifw/java-tip-3-how-to-implement-dynamic-switch // And is purely used as a helper class to switches public class Switcher { private Map<Integer, Command> caseCommands; private Command defaultCommand; private Command getCaseCommandByCaseId(Integer caseId) { if (caseCommands.containsKey(caseId)) { return caseCommands.get(caseId); } else { return defaultCommand; } } public Switcher() { caseCommands = new HashMap<Integer, Command>(); setDefaultCaseCommand(new DoNothingCommand()); } public void addCaseCommand(Integer caseId, Command caseCommand) { caseCommands.put(caseId, caseCommand); } public void setDefaultCaseCommand(Command defaultCommand) { if (defaultCommand != null) { this.defaultCommand = defaultCommand; } } public void on(Integer caseId) throws AdminNotFoundException, DeveloperNotFoundException, OperationNotAllowedException, OverlappingSessionsException, ActivityNotFoundException, ProjectNotFoundException, ProjectAlreadyExistsException, NumberFormatException, NotAuthorizedException, ActivityAlreadyExistsException, OutOfBoundsException { Command command = getCaseCommandByCaseId(caseId); command.execute(); } }
/*! * Copyright 2002 - 2017 Webdetails, a Pentaho company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package pt.webdetails.cdf.dd.model.inst.validation; import org.apache.commons.lang.StringUtils; public final class ComponentDuplicatePropertyBindingError extends ComponentError { private final String _propertyAlias; public ComponentDuplicatePropertyBindingError( String propertyAlias, String componentId, String componentTypeLabel ) throws IllegalArgumentException { super( componentId, componentTypeLabel ); if ( StringUtils.isEmpty( propertyAlias ) ) { throw new IllegalArgumentException( "propertyAlias" ); } this._propertyAlias = propertyAlias; } public String getPropertyAlias() { return this._propertyAlias; } @Override public String toString() { return "Component of id '" + this._componentId + "' and type '" + this._componentTypeLabel + "' has a duplicate property binding for name/alias '" + this._propertyAlias + "'."; } }
package com.example.ian.youtubeapp; import android.support.constraint.ConstraintLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; import static android.R.id.button1; import static com.google.android.gms.internal.zzt.TAG; public class YoutubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener { static final String GOOGLE_API_KEY = "AIzaSyADaTfDjea6S5Rb72vaU7RX9719SxR8XYs"; static final String YOUTUBE_VIDEO_ID = "mbs2ak1BXAY"; static final String YOUTUBE_PLAYLIST = "PL3xl1Whm1aOFufXNfAL603llu75BTu3m6"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_youtube); ConstraintLayout constraintLayout = (ConstraintLayout) getLayoutInflater().inflate(R.layout.activity_youtube, null); setContentView(constraintLayout); // Button button = new Button(this); // button.setLayoutParams(new ConstraintLayout.LayoutParams(300, 80)); // button.setText("Button Added"); // constraintLayout.addView(button); YouTubePlayerView player = new YouTubePlayerView(this); player.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT , ViewGroup.LayoutParams.MATCH_PARENT)); constraintLayout.addView(player); player.initialize(GOOGLE_API_KEY, this); } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) { Log.d(TAG, "onInitializationSuccess: provider" + provider.getClass().toString()); Toast.makeText(this, "Initialized Youtube Player successfully", Toast.LENGTH_SHORT).show(); youTubePlayer.setPlaybackEventListener(mPlaybackEventListener); youTubePlayer.setPlayerStateChangeListener(mPlayerStateChangeListener); // if(!wasRestored){ youTubePlayer.cueVideo(YOUTUBE_VIDEO_ID); // } } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { final int REQUEST_CODE = 1; if (youTubeInitializationResult.isUserRecoverableError()) { youTubeInitializationResult.getErrorDialog(this, REQUEST_CODE).show(); } else { String errorMessage = String.format("There was an error initializing the Youtube " + "Player(%1$s)", youTubeInitializationResult.toString()); Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show(); } } private YouTubePlayer.PlaybackEventListener mPlaybackEventListener = new YouTubePlayer.PlaybackEventListener() { @Override public void onPlaying() { Toast.makeText(YoutubeActivity.this, "Good, video is playing okay", Toast.LENGTH_SHORT).show(); } @Override public void onPaused() { Toast.makeText(YoutubeActivity.this, "Video has paused", Toast.LENGTH_SHORT).show(); } @Override public void onStopped() { } @Override public void onBuffering(boolean b) { } @Override public void onSeekTo(int i) { } }; private YouTubePlayer.PlayerStateChangeListener mPlayerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() { @Override public void onLoading() { } @Override public void onLoaded(String s) { } @Override public void onAdStarted() { Toast.makeText(YoutubeActivity.this, "Click Ad now.", Toast.LENGTH_SHORT).show(); } @Override public void onVideoStarted() { Toast.makeText(YoutubeActivity.this, "Video has started", Toast.LENGTH_SHORT).show(); } @Override public void onVideoEnded() { Toast.makeText(YoutubeActivity.this, "Video has ended", Toast.LENGTH_SHORT).show(); } @Override public void onError(YouTubePlayer.ErrorReason errorReason) { } }; }
package org.nyer.sns.netease; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.log4j.Logger; import org.nyer.sns.core.AbstractOAuth2Weibo; import org.nyer.sns.core.WeiboResponse; import org.nyer.sns.core.WeiboUser; import org.nyer.sns.http.PrepareHttpClient; import org.nyer.sns.oauth.OAuthDeveloperAccount; import org.nyer.sns.oauth.OAuthProvider; import org.nyer.sns.token.OAuthTokenPair; import org.nyer.sns.util.page.Page; /** * 基于OAuth2的网易微博客户端 * @author leiting * */ public class NeteaseWeibo extends AbstractOAuth2Weibo { private static Logger log = Logger.getLogger(LOG_NAME); public static final String URL_PUBLISH = "https://api.t.163.com/statuses/update.json"; public static final String URL_USER = "https://api.t.163.com/account/verify_credentials.json"; public static final String URL_FOLLOWERS = "https://api.t.163.com/statuses/followers.json"; public static final String URL_FRIENDS = "https://api.t.163.com/statuses/friends.json"; public static final String URL_UPLOAD_IMG = "https://api.t.163.com/statuses/upload.json"; public static final int MESSAGE_MAX_LENGTH = 163; public NeteaseWeibo(OAuthDeveloperAccount developerAccount, PrepareHttpClient httpClient) { super(developerAccount, httpClient, OAuthProvider.NETEASE2_WEIBO); this.protocal = new NeteaseWeiboProtocal(getEndPoint()); } @Override public WeiboResponse publish(OAuthTokenPair accessTokenPair, String title, String message, String url, String clientIP) { Map<String, String> additionalParams = new HashMap<String, String>(); String abbreviatedMsg = StringUtils.abbreviate(message, MESSAGE_MAX_LENGTH); additionalParams.put("status", abbreviatedMsg); return protocal.post(URL_PUBLISH, additionalParams, accessTokenPair); } /** * 发表一个带图微博 * * @param imgName 后缀名必须与图片类型一致 */ @Override public WeiboResponse publishWithImage(OAuthTokenPair accessTokenPair, String title, String message,byte[] imgBytes, String imgName, String url, String clientIP) { WeiboResponse resp = uploadImg(accessTokenPair, imgBytes, imgName); if (resp.isStatusOK()) { JSONObject obj = JSONObject.fromObject(resp.getHttpResponseText()); String imageUrl = obj.getString("upload_image_url"); message = StringUtils.abbreviate(message, MESSAGE_MAX_LENGTH - imageUrl.length()); message += imageUrl; resp = publish(accessTokenPair, title, message, imageUrl, clientIP); } return resp; } /** * 上传图片 * @param tokenPair * @return */ private WeiboResponse uploadImg(OAuthTokenPair tokenPair, byte[] imgBytes, String imgName) { MultipartEntity requestEntity = new MultipartEntity(); requestEntity.addPart("pic", new ByteArrayBody(imgBytes, imgName)); return this.protocal.post(URL_UPLOAD_IMG, requestEntity, tokenPair); } @Override public WeiboUser fetchUser(OAuthTokenPair accessTokenPair) { WeiboResponse resp = protocal.get(URL_USER, accessTokenPair); if (resp.isStatusOK()) { try { WeiboUser user = new WeiboUser(accessTokenPair); JSONObject obj = JSONObject.fromObject(resp.getHttpResponseText()); user.setNickName(obj.getString("name")); user.setImgUrl(obj.getString("profile_image_url")); String userId = obj.getString("screen_name"); user.setUid(userId); user.setProfileUrl("http://t.163.com/" + userId); return user; } catch (Exception e) { resp.setLocalError(e); } } log.error("error to fetch netease weibo user, resp: " + resp); return null; } @Override public Page<WeiboUser> getPageFollower(OAuthTokenPair accessTokenPair, int page, int pageSize) { return getPagedWeiboUser(URL_FOLLOWERS, accessTokenPair, page, pageSize); } @Override public Page<WeiboUser> getPageFriend(OAuthTokenPair accessTokenPair, int page, int pageSize) { return getPagedWeiboUser(URL_FRIENDS, accessTokenPair, page, pageSize); } private Page<WeiboUser> getPagedWeiboUser( String url, OAuthTokenPair accessTokenPair, int page, int pageSize) { Map<String, String> additionalParams = new HashMap<String, String>(); additionalParams.put("screen_name", accessTokenPair.getUid() + ""); int offset = (page - 1) * pageSize; additionalParams.put("cursor", offset + ""); WeiboResponse resp = protocal.get(url, additionalParams, accessTokenPair); if (resp.isStatusOK()) { JSONObject obj = JSONObject.fromObject(resp.getHttpResponseText()); JSONArray friends = obj.getJSONArray("users"); Page<WeiboUser> userPage = new Page<WeiboUser>(page, pageSize); userPage.setPrevCursor(Integer.parseInt(obj.getString("previous_cursor"))); userPage.setNextCursor(Integer.parseInt(obj.getString("next_cursor"))); List<WeiboUser> users = new ArrayList<WeiboUser>(friends.size()); userPage.setContent(users); for (int i = 0;i < friends.size();i ++) { JSONObject follower = (JSONObject) friends.get(i); WeiboUser u = new WeiboUser(null); u.setNickName(follower.getString("name")); String userId = follower.getString("screen_name"); u.setUid(userId); u.setProfileUrl("http://t.163.com/" + userId); u.setImgUrl(follower.getString("profile_image_url")); users.add(u); } return userPage; } log.error("error to get netease weibo user list, resp: " + resp); return null; } }
package com.shangcai.common.wx; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; 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.context.annotation.PropertySource; import org.springframework.stereotype.Component; import com.irille.core.controller.JsonWriter; import com.irille.core.web.exception.ReturnCode; import com.irille.core.web.exception.WebMessageException; import com.shangcai.common.FileDownload; import com.shangcai.common.OssUtil; import com.shangcai.common.http.HttpUtil; import com.shangcai.entity.common.Member; import com.shangcai.view.wx.AccessTokenView; import com.shangcai.view.wx.SessionView; import com.shangcai.view.wx.WxView; import irille.util.MD5Util; import lombok.Getter; @Component @PropertySource("classpath:wxconfig.properties") @Getter public class WXAPI { private static final Logger logger = LoggerFactory.getLogger(WXAPI.class); @Value("${wx.appid}") private String appid; @Value("${wx.secret}") private String secret; private static final String sns_jscode2session_url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code"; // GET 请求 /** * 获取小程序码,适用于需要的码数量极多的业务场景。通过该接口生成的小程序码,永久有效,数量暂无限制 */ private static final String wxa_getwxacodeunlimit_url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN"; // POST 请求 /** * 获取小程序 access_token */ private static final String cgi_bin_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; // GET 请求 @Autowired private HttpUtil httpUtil; public SessionView code2session(String code) { return requestByGet(sns_jscode2session_url.replace("APPID", appid).replace("SECRET", secret).replace("JSCODE", code), SessionView.class); } /** * 获取小程序码,适用于需要的码数量极多的业务场景 * * @param access_token 接口调用凭证 * @param scene 最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用 urlencode 处理,请使用其他编码方式) * @param page 必须是已经发布的小程序存在的页面(否则报错),例如 pages/index/index, 根路径前不要填加 /,不能携带参数(参数请放在scene字段里),如果不填写这个字段,默认跳主页面 * @param width 二维码的宽度,默认为 430px,最小 280px,最大 1280px * @param auto_color 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false * @param line_color auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示,默认全 0 * @param is_hyaline 是否需要透明底色,为 true 时,生成透明底色的小程序码,默认 false */ public String getWXACodeUnlimit(String accessToken, String scene, String page) { try { Map<String, Object> params = new HashMap<>(); params.put("scene", scene); params.put("page", page); String s_params = JsonWriter.oMapper.writeValueAsString(params); StringEntity entity = new StringEntity(s_params); String url = wxa_getwxacodeunlimit_url.replace("ACCESS_TOKEN", accessToken); CloseableHttpClient httpClient = null; BufferedReader reader = null; DataInputStream dataInputStream = null; FileOutputStream fileOutputStream = null; try { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entity); logger.info("发起httpPost请求:{}", url); CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost); logger.info("response.content-type:{}", response.getFirstHeader("content-type")); if(response.getFirstHeader("content-type").getValue().indexOf("json") == -1) { //成功 File temp = File.createTempFile(FileDownload.default_prefix, "jpg"); fileOutputStream = new FileOutputStream(temp); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; InputStream input = response.getEntity().getContent(); dataInputStream = new DataInputStream(input); while ((length = dataInputStream.read(buffer)) > 0) { output.write(buffer, 0, length); } fileOutputStream.write(output.toByteArray()); return OssUtil.upload(Member.class, MD5Util.getMD5(temp)+".jpg", temp); } else { //失败 InputStream input = response.getEntity().getContent(); reader = new BufferedReader(new InputStreamReader(input, Charset.forName("utf-8"))); StringBuilder sb = new StringBuilder(); String buffer = null; while ((buffer = reader.readLine()) != null) { sb.append(buffer); } logger.info("回传内容:{}", sb.toString()); try { WxView view = JsonWriter.oMapper.readValue(sb.toString(), WxView.class); throw new WebMessageException(ReturnCode.third_unknow, view.getErrMsg()); } catch (IOException e) { logger.error("微信api io异常", e); throw new WebMessageException(ReturnCode.third_unknow, "微信服务异常"); } } } finally { if (httpClient != null) httpClient.close(); if (reader != null) reader.close(); if (fileOutputStream != null) fileOutputStream.close(); if (dataInputStream != null) dataInputStream.close(); } } catch (IOException e) { logger.error("微信api io异常", e); throw new WebMessageException(ReturnCode.third_unknow, "微信服务异常"); } } public String getAccessToken() { AccessTokenView view = requestByGet(cgi_bin_token_url.replace("APPID", appid).replace("APPSECRET", secret), AccessTokenView.class); return view.getAccess_token(); } private <T extends WxView> T requestByGet(String url, Class<T> viewClass) { try { String result = httpUtil.doGet(url); T view = JsonWriter.oMapper.readValue(result, viewClass); if (view.getErrcode() == null || view.getErrcode() == 0) { return view; } else throw new WebMessageException(ReturnCode.third_unknow, view.getErrMsg()); } catch (IOException e) { logger.error("微信api io异常", e); throw new WebMessageException(ReturnCode.third_unknow, "微信服务异常"); } } }
package com.example.mobilebooks; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import com.parse.FindCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class CustomAdapter extends BaseAdapter { String[] message, bookAuthor, price, bookImage; Context context; // URL[] bookImage; public int temp; public URL url; public Bitmap myBitmap; public static int count = 1; public VendorsDetails vendorDetails; Handler h = new Handler(); Thread imageSet; int myposition; CustomAdapter(String[] message, String[] bookAuthor, String[] price, String[] bookImage, Context context) { this.context = context; this.bookAuthor = bookAuthor; this.message = message; this.price = price; this.bookImage = bookImage; vendorDetails = new VendorsDetails(); // count = 0; } @Override public int getCount() { // TODO Auto-generated method stub // if (bookAuthor.length < bookImage.length // && bookAuthor.length < message.length) { // // return bookAuthor.length; // // }else if (message.length < bookImage.length // && message.length < message.length) { return message.length; // }else{ // return bookImage.length; // } } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View v; Handler handler = new Handler(); v = convertView; LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); myposition = position; System.out.println(" book author" +bookAuthor.length+" book Image" +bookImage.length+" message" +message.length); // if (v == null) { v = inflater.inflate(R.layout.listview, null); handler.book_name = (TextView) v.findViewById(R.id.book_name); handler.book_author = (TextView) v.findViewById(R.id.book_author); handler.book_image = (ImageView) v.findViewById(R.id.book_image); handler.price = (TextView) v.findViewById(R.id.price); handler.used_availabel = (TextView) v.findViewById(R.id.used_availabel); // if (price[position].equalsIgnoreCase("") || price[position] == // null) { v.setTag(handler); // } try { // handler.used_availabel.setVisibility(View.VISIBLE); handler.book_author.setText(bookAuthor[position]); Log.e("Heell", bookAuthor[position]); if (position == 11) { position = position - 1; } handler.book_name.setText(message[position]); Log.e("Heell", message[position]); Thread t = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub HttpURLConnection connection; try { url = new URL(bookImage[myposition]); // count++; connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); myBitmap = BitmapFactory.decodeStream(input); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (NullPointerException n) { } } }); t.start(); try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.book_image.setImageBitmap(myBitmap); // synchronized (Thread.currentThread()) { // try { // Thread.currentThread().wait(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // handler.book_image.setImageBitmap(myBitmap); // HttpURLConnection connection; // try { // // System.out.println(imageURL); // url = new URL(bookImage[count]); // count++; // connection = (HttpURLConnection) url // .openConnection(); // connection.setDoInput(true); // connection.connect(); // InputStream input = connection.getInputStream(); // // myBitmap = BitmapFactory.decodeStream(input); // // } catch (IOException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } // // // // // handler.book_image.setImageBitmap(myBitmap); // Log.d("checking price[posiotn in custom adaper", price[position]); handler.price.setText(price[position]); } catch (NullPointerException n) { handler.price.setText(" $$"); } // // if (count == 1) { // System.out.println("he is heeeeee"); // // count++; // // if(vendorDetails.getUsedAvailabelDetails(context)) // // { // // handler.used_availabel.setVisibility(View.VISIBLE); // // } // // System.out.println("Heee is bak"); // // Parse.initialize(context, // // "hhvNehUIwK1iY8Bmtt4FnFoHxWwo0dNgwSnqi7iz", // // "B9R0dIdKHeRHyPI0YbShuX9Kapd60yURT7H1c26Z"); // ParseQuery<ParseObject> queryVendors = ParseQuery // .getQuery("BetaObject"); // queryVendors.whereEqualTo(Preferences.SELL_CHECK, "1"); // System.out.println("He is finding"); // // queryVendors.findInBackground(new FindCallback<ParseObject>() { // // @Override // public void done(List<ParseObject> arg0, ParseException arg1) { // // TODO Auto-generated method stub // if (arg0.size() > 0) { // temp = 0; // } else { // temp = 1; // } // System.out.println("He found" + temp); // // } // }); // // } // } // else { // handler = (Handler) v.getTag(); // } return v; } public class Handler { TextView book_name, book_author, price, used_availabel; ImageView book_image; } }
package au.gov.ga.geodesy.igssitelog.support.marshalling.moxy; /** * When marshalling composite null objects, generate empty XML sub-elements (in combination with {@link NullPolicySessionEventListener}. */ public abstract class MandatoryCompositeAdapter<T> extends OptionalCompositeAdapter<T> { @Override public T marshal(T object) throws Exception { return object == null ? getDomainClass().newInstance() : object; } protected abstract Class<T> getDomainClass(); }
package com.zhouyi.business.core.service; import com.zhouyi.business.core.common.ReturnCode; import com.zhouyi.business.core.dao.LedenCollectIrisMapper; import com.zhouyi.business.core.model.LedenCollectIris; import com.zhouyi.business.core.model.Response; import com.zhouyi.business.core.model.provincecomprehensive.pojo.StandardIris; import com.zhouyi.business.core.utils.ResponseUtil; import com.zhouyi.business.core.vo.LedenCollectIrisVo; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import sun.misc.BASE64Encoder; import java.text.SimpleDateFormat; import java.util.*; @Slf4j @Service public class LedenCollectIrisServiceImpl extends BaseServiceImpl<LedenCollectIris, LedenCollectIrisVo> implements LedenCollectIrisService{ @Autowired private LedenCollectIrisMapper ledenCollectIrisMapper; @Override @Transactional public Response<Object> saveMapToRepository(List list,String userUnitCode,String ryjcxxcjbh,String userCode) { if (list == null){ return ResponseUtil.returnError(ReturnCode.ERROR_14); } //删除原有虹膜信息 if(list!=null&&list.size()>0) { String cjrybh = ((LedenCollectIris) list.get(0)).getRyjcxxcjbh(); if (cjrybh != null){ ledenCollectIrisMapper.deleteDataByPersonCode(cjrybh); }else { ledenCollectIrisMapper.deleteDataByPersonCode(ryjcxxcjbh); } } for (Object object : list){ LedenCollectIris ledenCollectIris = (LedenCollectIris)object; ledenCollectIris.setPkId(UUID.randomUUID().toString().replace("-","")); ledenCollectIris.setRyjcxxcjbh(ryjcxxcjbh); ledenCollectIris.setCreateDatetime(new Date()); ledenCollectIris.setCreateUserId(userCode); this.resoveSaveData(ledenCollectIris); } return ResponseUtil.getResponseInfo(true); } /** * 根据人员编号查询虹膜信息 * */ @Override public Response<List<LedenCollectIris>> selectIrisByPersonCode(String id) { List<LedenCollectIris> list = ledenCollectIrisMapper.selectDataByPersonCode(id); list.stream().forEach((s)->{ s.setHmzp(new String(s.getHmsj())); s.setHmsj(null); }); //加密图面信息 // if (list != null && list.size() > 0){ //// list.stream().forEach(s ->{ //// if ("0".equals(s.getQzcjbz())){ ////// BASE64Encoder base64Encoder = new BASE64Encoder(); //// if ("0".equals(s.getHmywdm())){ //// String encode = new String(s.getHmsj()); //// StringBuilder stringBuilder = new StringBuilder(); //// stringBuilder.append("data:image/png;base64,"); //// stringBuilder.append(encode); //// s.setHmzp(stringBuilder.toString()); //// s.setHmsj(null); //// finge} //// else if ("1".equals(s.getHmywdm())){ //// String encode = new String(s.getHmsj()); //// StringBuilder stringBuilder = new StringBuilder(); //// stringBuilder.append("data:image/png;base64,"); //// stringBuilder.append(encode); //// s.setHmzp(stringBuilder.toString()); //// s.setHmsj(null); //// } //// else { //// String encode = new String(s.getHmsj()); //// StringBuilder stringBuilder = new StringBuilder(); //// stringBuilder.append("data:image/png;base64,"); //// stringBuilder.append(encode); //// s.setHmzp(stringBuilder.toString()); //// s.setHmsj(null); //// } //// } // }); // return ResponseUtil.getResponseInfo(ReturnCode.SUCCESS,list); // } return ResponseUtil.getResponseInfo(ReturnCode.SUCCESS,list); } @Override public List<StandardIris> listIrisByPersonCode(String personCode) { log.info("封装虹膜事personCode为:"+personCode); return (List)ledenCollectIrisMapper.listDataByConditions(new HashMap<String,Object>(1){{put("personCode",personCode);}}); } //获取主键 /*private String getPrimaryKey(String userUnitCode,Long serialNumber){ StringBuffer stringBuffer = new StringBuffer(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd"); String dateString = dateFormat.format(new Date()); stringBuffer.append("HM").append(userUnitCode).append(dateString).append(String.format("%06d", serialNumber)); return stringBuffer.toString(); }*/ }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package TFD.DomainModel; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * * @author Rosy */ @Entity public class Recurso implements Entidade, Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long idRecurso; private Double valorUnitario; private String Nome; private int codigoSai; public Long getIdRecurso() { return idRecurso; } public void setIdRecurso(Long idRecurso) { this.idRecurso = idRecurso; } public Double getValorUnitario() { return valorUnitario; } public void setValorUnitario(Double valorUnitario) { this.valorUnitario = valorUnitario; } public String getNome() { return Nome; } public void setNome(String Nome) { this.Nome = Nome; } public int getCodigoSai() { return codigoSai; } public void setCodigoSai(int codigoSai) { this.codigoSai = codigoSai; } @Override public Long getId() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package ru.bm.eetp.controler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import ru.bm.eetp.config.Constants; import ru.bm.eetp.dto.ProcessResult; import ru.bm.eetp.dto.RequestResult; import ru.bm.eetp.exception.GWFaultError; import ru.bm.eetp.exception.SimpleError; import ru.bm.eetp.logging.Logger; import ru.bm.eetp.service.IncomingPackageProcessor; @RestController public class IncomingController { @Autowired private IncomingPackageProcessor incomingPackageProcessor; @Autowired private InternalServiceCaller internalServiceCaller; @Autowired private Logger logger; @PostMapping(value="/incoming", produces="text/xml" ) @ResponseStatus(code = HttpStatus.OK) public String endpointIn(@RequestBody String content) { ProcessResult processResult = incomingPackageProcessor.processing(content); RequestResult requestResult = internalServiceCaller.callInternalService(processResult, content); if (requestResult.getresultCode() != HttpStatus.OK) { processResult = ProcessResult.SERVICE_UNAVAILABLE_ERROR; } switch(processResult) { case OK :{ logger.logIncoming(content); if (Constants.DEBUG) { return processResult.getErrorMessage() + "\n\n<ResultBody>: \n" + requestResult.getresultBody(); } else{ return processResult.getErrorMessage();} } case SERVICE_UNAVAILABLE_ERROR :{ logger.logError(processResult.getErrorMessage(), content); throw new SimpleError(new RequestResult(processResult.getHttpCode(),processResult.getErrorMessage())); } default: logger.logError(processResult.getErrorMessage(), content); throw new GWFaultError(processResult); } } /*@PostMapping(value="/error_500", produces="text/xml") public IncomingResponse endpoint500(@RequestBody String content) { if(1 != 2) { throw new GWFaultError(ProcessResult.SIGNATURE_VALIDATION_ERROR); } return new IncomingResponse(); } @PostMapping(value="/error_503", produces="text/xml") public IncomingResponse endpoint503(@RequestBody String content) { if(1 != 2) { throw new SimpleError(ProcessResult.SERVICE_UNAVAILABLE_ERROR); } return new IncomingResponse(); } @PostMapping(value="/config", produces="text/xml") public IncomingResponse endpointconfig(@RequestBody String content) { return new IncomingResponse(); }*/ }
package com.liuhy.setterinject; /** * Created by liuhy on 2017/2/18. */ public class Address { private String addr; private Integer door; public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public Integer getDoor() { return door; } public void setDoor(Integer door) { this.door = door; } }
package com.company.store_item_abstract_challenge; public class VitaliLinkedList implements NodeList { //vizivajem ListItem interface. private ListItem root = null; public VitaliLinkedList(ListItem root) { //soedenjajem this.root s interface. this.root = root; } @Override public ListItem getRoot() { return this.root; } @Override public boolean addItem(ListItem newItem) { if(this.root == null){ //if root is empty, add a new element there. this.root = newItem; return true; } //if root is not empty. ListItem currentItem = this.root; //here we take an element of this.root. //while currentItem is NOT null cycle while(currentItem != null){ //check if element is not null int comparison = (currentItem.compareTo(newItem)); //compare element and check if string is different. if(comparison <0){ //newItem is greater, move right if possible. if(currentItem.next() != null) { // nextLink is NOT empty, we return a reference of this object // to currentItem. and this becomes to point to go next currentItem = currentItem.next(); } else { //if nextLink is EMPTY //we put setNext to currentItem object a reference of new Item. currentItem.setNext(newItem); //here we set to newItem a reference of currentItem. newItem.setPrevious(currentItem); return true; } } else if(comparison > 0){ //newItem is less if(currentItem.previous() != null){ currentItem.previous().setNext(newItem); newItem.setPrevious(currentItem.previous()); newItem.setNext(currentItem); currentItem.setPrevious(newItem); } else { // the node with a previous is the root newItem.setNext(this.root); this.root.setPrevious(newItem); this.root = newItem; } return true; } else { //equal System.out.println(newItem.getValue() + " is already present."); return false; } } return false; } @Override public boolean removeItem(ListItem item) { if(item != null){ System.out.println("This list is empty"); } ListItem currentItem = this.root; while (currentItem != null){ int comparison = currentItem.compareTo(item); if(comparison == 0) { if (currentItem == this.root) { this.root = currentItem.next(); } else { currentItem.previous().setNext(currentItem.next()); if (currentItem.next() != null) { currentItem.next().setPrevious(currentItem.previous()); } } return true; } else if(comparison < 0) { currentItem = currentItem.next(); } else { return false; } } return false; } @Override public void traverse(ListItem root) { if(root == null){ System.out.println("This list is empty"); } else { while(root != null){ System.out.println(root.getValue()); root = root.next(); } } } }
package com.everis.eCine.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Service; import com.everis.eCine.model.Nationalite; import com.everis.eCine.repository.NationaliteRepository; @Service public class NationaliteService extends AbstractService<Nationalite, Long> { @Autowired private NationaliteRepository nationaliteRepository; @Override protected JpaRepository<Nationalite, Long> getRepository() { return nationaliteRepository; } }
package com.muryang.sureforprice.vo; public class BaseUrl { private long siteId ; private String siteName ; private String categoryId ; private String categoryName ; private long categoryDepth ; private long id ; private String baseURL ; private long authenticationType ; public long getSiteId() { return siteId; } public void setSiteId(long siteId) { this.siteId = siteId; } public String getSiteName() { return siteName; } public void setSiteName(String siteName) { this.siteName = siteName; } public String getCategoryId() { return categoryId; } public void setCategoryId(String categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public long getCategoryDepth() { return categoryDepth; } public void setCategoryDepth(long categoryDepth) { this.categoryDepth = categoryDepth; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getBaseURL() { return baseURL; } public void setBaseURL(String baseURL) { this.baseURL = baseURL; } public long getAuthenticationType() { return authenticationType; } public void setAuthenticationType(long authenticationType) { this.authenticationType = authenticationType; } }
package pl.sdacademy.designpatterns.structural.composite; import java.util.concurrent.CopyOnWriteArrayList; public class Main { public static void main (String[] args) { CocaColaCan coke = new CocaColaCan (); Snickers snickers = new Snickers (); CompositeProduct compositeProduct = new CompositeProduct (coke, snickers); System.out.println (compositeProduct.getPrice ()); CompositeProduct compositeProduct2 = new CompositeProduct (compositeProduct, coke); System.out.println (compositeProduct2.getPrice ()); } }
package cn.lawwing.jisporttactics.utils; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 线程操作类 */ public class ThreadUtils { private static final String TAG = "ThreadUtils"; private static ExecutorService executorService; private ThreadUtils() { executorService = new ThreadPoolExecutor(2, 5, 30L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } private static class ThreadUtilHolder { private static final ThreadUtils INSTANCE = new ThreadUtils(); } public static ThreadUtils getInstance() { return ThreadUtilHolder.INSTANCE; } public void execute(Runnable runnable) { if (executorService != null && runnable != null) { executorService.execute(runnable); } } }
package cn.hrmzone.table; import cn.hrmzone.util.FileNameParser; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * 将获取的数据,存放再excel指定的单元格中。 */ public class ExcelUtil { String fileName; Workbook workbook; Sheet sheet; public ExcelUtil(String fileName) { this.fileName = fileName; workbook=new XSSFWorkbook(); } public void newSheet(String sheetName) { System.out.println("sheet name:"+FileNameParser.getName(fileName)); sheet=workbook.createSheet(FileNameParser.getName(fileName)); } public void writeCell(int row,int col,String s) { //注意:单元格是先创建行,然后在行中获得cell,所以需要先获取这一行,让后填入输入,如果每次新建行,只会保留最后一个单元格数据。 Row row1=sheet.getRow(row); if(row1==null) { row1= sheet.createRow(row); } Cell cell=row1.createCell(col); cell.setCellValue(s); } public void writeExcel() { FileOutputStream fos= null; try { System.out.println(FileNameParser.getPath(fileName)+ File.separator+FileNameParser.getName(fileName)+".xlsx"); fos = new FileOutputStream(FileNameParser.getPath(fileName)+ File.separator+FileNameParser.getName(fileName)+".xlsx"); workbook.write(fos); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.example.demo.service; import com.example.demo.domain.Page; import com.example.demo.domain.User; import com.github.pagehelper.PageInfo; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import java.util.Map; public interface UserService { PageInfo<User> findUserList(HttpServletRequest request, @RequestParam Map<String, String> param); PageInfo<User> findUserList(HttpServletRequest request, @RequestBody Page page); }
package com.chuxin.family.parse; import com.chuxin.family.parse.been.CxKidsInfoData; import com.chuxin.family.parse.been.data.KidFeedChildrenData; import com.chuxin.family.utils.CxLog; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; /** * 孩子资料网络数据解析 对应接口/Child/update * @author shichao * */ public class CxKidsInfoParser { public CxKidsInfoData parserForKidInfo(Object obj, Context ctx, boolean isNative){ if(null == obj){ return null; } JSONObject kidInfoObj = null; try { kidInfoObj = (JSONObject)obj; } catch (Exception e) { try { kidInfoObj = new JSONObject((String)obj); } catch (JSONException e1) { CxLog.w("", ""+e.toString()); } } if(null == kidInfoObj){ return null; } int rc = -1; try { rc = kidInfoObj.getInt("rc"); } catch (JSONException e) { CxLog.w("", ""+e.toString()); } if(-1 == rc){ return null; } CxKidsInfoData kidInfoData = new CxKidsInfoData(); kidInfoData.setRc(rc); try { kidInfoData.setMsg(kidInfoObj.getString("msg")); } catch (JSONException e) { CxLog.w("", ""+e.toString()); } try { kidInfoData.setTs(kidInfoObj.getInt("ts")); } catch (JSONException e) { CxLog.w("", ""+e.toString()); } if(0 != rc){ return kidInfoData; } JSONObject dataObj = null; try { dataObj = kidInfoObj.getJSONObject("data"); } catch (JSONException e) { CxLog.w("", ""+e.toString()); } if( null == dataObj){ return kidInfoData; } KidFeedChildrenData data = new KidFeedChildrenData(); try { if(!dataObj.isNull("id")){ data.setId(dataObj.getString("id")); } } catch (JSONException e1) { CxLog.w("", ""+e1.toString()); } try { if (!dataObj.isNull("avata")){ data.setAvata(dataObj.getString("avata")); } } catch (JSONException e) { CxLog.w("", ""+e.toString()); } try { if (!dataObj.isNull("name")){ data.setName(dataObj.getString("name")); } } catch (JSONException e) { CxLog.w("", ""+e.toString()); } try { if (!dataObj.isNull("nickname")){ data.setNickname(dataObj.getString("nickname")); } } catch (JSONException e) { CxLog.w("", ""+e.toString()); } try { if(!dataObj.isNull("gender")){ data.setGender(dataObj.getInt("gender")); } else { data.setGender(-1); } } catch (JSONException e) { CxLog.w("", ""+e.toString()); } try { if (!dataObj.isNull("note")){ data.setNote(dataObj.getString("note")); } } catch (JSONException e) { CxLog.w("", ""+e.toString()); } try { if(!dataObj.isNull("birth")){ data.setBirth(dataObj.getString("birth")); } } catch (JSONException e) { CxLog.w("", ""+e.toString()); } //data部分 //JSONObject dataObject = null; try { if(!dataObj.isNull("data")){ data.setData(dataObj.getString("data")); } } catch (JSONException e) { CxLog.w("", ""+e.toString()); } kidInfoData.setKidInfo(data); return kidInfoData; } }
/* * 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 models; import java.util.*; import javax.persistence.*; import play.db.jpa.*; import play.data.validation.*; /** * * @author jesus */ @Entity @Table(name="permiso.usuario") public class Usuario extends Model{ @Required String usuario; String password; String nombre; @ManyToMany List<Rol> roles; public Usuario(String usuario, String password, String nombre, List<Rol> roles) { this.usuario = usuario; this.password = password; this.nombre = nombre; this.roles = roles; } }
package controllers; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.Id; import org.apache.commons.codec.binary.Base64; import com.cricmania.models.Base; import com.cricmania.comman.BowlingType; import com.cricmania.models.Address; import com.cricmania.models.City; import com.cricmania.models.Country; import com.cricmania.models.Ground; import com.cricmania.models.Login; import com.cricmania.models.Login.LoginType; import com.cricmania.models.MetaDataDocument; import com.cricmania.models.Player; import com.cricmania.models.Team; import com.cricmania.models.Tournament; import com.cricmania.models.Tournament.TournamentStatus; import com.cricmania.models.TournamentTeam; import com.cricmania.models.Umpire; import com.cricmania.comman.PlayerType; import com.cricmania.models.State; import com.cricmania.utils.Mapper; import com.cricmania.utils.TeamValidator; import com.cricmania.vms.PlayerVM; import com.cricmania.vms.SelectItem; import com.cricmania.vms.TeamVM; import com.cricmania.vms.TournamentVM; import com.cricmania.vms.UmpireVM; import com.fasterxml.jackson.databind.JsonNode; import com.mongodb.Mongo; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSInputFile; import play.api.libs.Codecs; import play.data.DynamicForm; import play.db.ebean.Transactional; import play.libs.Crypto; import play.libs.Json; import play.modules.mongodb.jackson.MongoDB; import play.mvc.*; import play.mvc.Http.MultipartFormData; import play.mvc.Http.MultipartFormData.FilePart; import views.html.*; import views.html.defaultpages.error; public class Application extends Controller { public static Result index() { return ok(index.render()); } public static Result cpanel() { return ok(cpanel.render()); } public static Result saveBase() { //Base base = new Base(); //base.setId("1"); //base.save(); return ok(Json.toJson("")); } public static Result getBowlingTypes() { return ok(Json.toJson(BowlingType.getAllItems())); } public static Result getPlayerTypes() { return ok(Json.toJson(PlayerType.getAllItems())); } public static Result getCountries() { List<Country> countries = Country.getAllCountries(); List<SelectItem> items = new ArrayList<SelectItem>(countries.size()); for(Country country : countries) { SelectItem item = new SelectItem(); item.setName(country.getName()); item.setValue(country.getId().toString()); items.add(item); } return ok(Json.toJson(items)); } public static Result saveCountry() { String str = "ahemad"; String encoded = Crypto.encryptAES(str); String original = Crypto.decryptAES(encoded); System.out.println(encoded); System.out.println(original); return ok(Json.toJson("")); } public static Result getStatesByCountry(String countryId) { List<State> states = State.getAllStatesByCountryId(countryId); List<SelectItem> items = new ArrayList<SelectItem>(states.size()); for(State state : states) { SelectItem item = new SelectItem(); item.setName(state.getName()); item.setValue(state.getId().toString()); items.add(item); } return ok(Json.toJson(items)); } public static Result getCitiesByState(String stateId) { List<City> cities = City.getAllCitiesByStateId(stateId); List<SelectItem> items = new ArrayList<SelectItem>(cities.size()); for(City city : cities) { SelectItem item = new SelectItem(); item.setName(city.getName()); item.setValue(city.getId().toString()); items.add(item); } return ok(Json.toJson(items)); } public static Result savePlayer() { JsonNode object = request().body().asJson(); PlayerVM playerVM1 = request().body().as(PlayerVM.class); PlayerVM playerVM = Mapper.mapJsonNodeToPlayerVM(object); Player player = Mapper.mapPlayerVMToPlayer(playerVM); player.save(); Login login = new Login(); login.setEmail(player.getEmail()); login.setId(player.getId()); login.setLoginType(LoginType.PLAYER); login.setPassword(Crypto.encryptAES(object.get("password") != null ? object.get("password").asText() : "1234")); login.save(); return ok(Json.toJson(player.getId())); } public static Result saveUmpire() { JsonNode object = request().body().asJson(); if(object.get("email") != null && !object.get("email").asText().isEmpty()) { Login login = Login.getLoginByUsername(object.get("email").asText()); if(login != null) { return ok(Json.toJson("Error : Email already exist.")); } } UmpireVM umpireVM = Mapper.mapJsonNodeToUmpireVM(object); Umpire umpire = Mapper.mapUmpireVMToUmpire(umpireVM); umpire.save(); Login login = new Login(); login.setEmail(umpireVM.getEmail()); login.setLoginType(LoginType.UMPIRE); login.setId(umpire.getId()); login.setPassword(object.get("password") != null ? object.get("password").asText() : "1234"); login.save(); return ok(Json.toJson(umpire.getId())); } public static Result findPlayer() { JsonNode object = request().body().asJson(); String email = object.get("email").asText(); Player p = Player.getPlayerByEmail(email); if(p != null) { PlayerVM playerVM = new PlayerVM(); playerVM.setId(p.getId()); playerVM.setEmail(p.getEmail()); playerVM.setFirstName(p.getFirstName()); playerVM.setLastName(p.getLastName()); return ok(Json.toJson(playerVM)); } return ok(Json.toJson("not found")); } public static Result findUmpire() { JsonNode object = request().body().asJson(); String email = object.get("email").asText(); Umpire u = Umpire.getUmpireByEmail(email); if(u != null) { UmpireVM umpireVM = new UmpireVM(); umpireVM.setId(u.getId()); umpireVM.setEmail(u.getEmail()); umpireVM.setFirstName(u.getFirstName()); umpireVM.setLastName(u.getLastName()); return ok(Json.toJson(umpireVM)); } return ok(Json.toJson("not found")); } public static Result loginEntity() { JsonNode object = request().body().asJson(); String username = object.get("username").asText(); String password = object.get("password").asText(); System.out.println(username); System.out.println(password); Login login = Login.getLoginByUsername(username); Map result = new HashMap(); System.out.println(login); if(login != null) { if(login.getPassword().equals(Crypto.encryptAES(password))) { String str = Crypto.encryptAES(username+"-"+request().remoteAddress()); session().put("uuid", str); if(login.getLoginType() == LoginType.TOURNAMENT) { result.put("url", "/tournament"); } else if(login.getLoginType() == LoginType.PLAYER){ result.put("url", "/player"); } else if(login.getLoginType() == LoginType.UMPIRE){ result.put("url", "/umpire"); } result.put("status", "ok"); } else { result.put("status", "error"); } } else { result.put("status", "error"); } return ok(Json.toJson(result)); } public static Result tournament() { String uuid = null; if(session().get("uuid") == null) { return redirect("/cpanel"); } uuid = session().get("uuid"); try { String original = Crypto.decryptAES(uuid); String arr[] = original.split("-"); if(arr.length == 2 && arr[1].equals(request().remoteAddress())) { Login login = Login.getLoginByUsername(arr[0]); return ok(tournament.render(login.getId())); } } catch(Exception e) { } return redirect("/cpanel"); } public static Result saveTournament() { JsonNode node = request().body().asJson(); TournamentVM tournamentVM = Mapper.mapJsonToTournamentVM(node); Tournament tournament = Mapper.mapTournamentVMToTournament(tournamentVM); tournament.save(); Login login = new Login(); login.setEmail(tournament.getId().toLowerCase()+"@cricmania.com"); login.setId(tournament.getId()); login.setLoginType(LoginType.TOURNAMENT); login.setPassword(Crypto.encryptAES(node.get("password") != null ? node.get("password").asText() : "1234")); login.save(); return ok(Json.toJson(tournament.getId())); } public static Result logout() { session().remove("uuid"); return redirect("/cpanel"); } public static Result saveTeam() { JsonNode node = request().body().asJson(); List<String> errors = TeamValidator.validateTeamFromJsonNode(node); Map map = new HashMap(); if(errors.size() > 0) { map.put("status","error"); map.put("errors", errors); return ok(Json.toJson(map)); } Team team = Mapper.mapJsonNodeToTeam(node); team.save(); Login login = new Login(); login.setEmail(team.getEmail()!= null ?team.getEmail() : team.getId().toLowerCase()+"@cricmania.com"); login.setId(team.getId()); login.setPassword(node.get("password") != null ? node.get("password").asText() : "1234"); login.setLoginType(LoginType.TEAM); login.save(); map.put("status","ok"); map.put("id", login.getId()); return ok(Json.toJson(map)); } public static Result uploadTeamLogo() { try { MultipartFormData form = request().body().asMultipartFormData(); Map<String ,String[]> map = form.asFormUrlEncoded(); if(map.get("id") == null || map.get("id").length == 0) { return ok(Json.toJson("error")); } else { String id = map.get("id")[0]; Team team = Team.findById(id); if(team != null) { FilePart file = request().body().asMultipartFormData().getFile("file"); GridFS fs = new GridFS(Login.coll.getDB(),"photo"); GridFSInputFile fsInputFile = fs.createFile(file.getFile()); fsInputFile.setFilename(file.getFilename()); fsInputFile.setContentType(file.getContentType()); fsInputFile.save(); team.setLogoName(file.getFilename()); team.update(); } else { return ok(Json.toJson("error")); } } } catch (IOException e) { return ok(Json.toJson("error")); } return ok(Json.toJson("success")); } public static Result getGroundsByCity(String cityId) { List<Ground> grounds = Ground.getGroundsByCity(cityId); List<SelectItem> items = new ArrayList<SelectItem>(grounds.size()); for(Ground ground : grounds) { SelectItem item = new SelectItem(); item.setName(ground.getName()); item.setValue(ground.getId().toString()); items.add(item); } return ok(Json.toJson(items)); } public static Result saveGround() { JsonNode node = request().body().asJson(); Ground ground = new Ground(); String uuid = session().get("uuid"); if(uuid != null) { try { ground.setAddedBy(Crypto.decryptAES(uuid).split("-")[0]); } catch(Exception e) { ground.setAddedBy(request().remoteAddress()); } } else { ground.setAddedBy(request().remoteAddress()); } ground.setName(node.get("name").asText()); Address address = new Address(); address.setCity(node.get("city").asText()); address.setCountry(node.get("country").asText()); address.setState(node.get("country").asText()); address.setZipcode(node.get("zipcode").asText()); ground.setAddress(address); ground.save(); return ok(Json.toJson(ground.getId())); } public static Result loggedInTournament() { String uuid = session().get("uuid"); if(uuid != null) { String[] arr = Crypto.decryptAES(uuid).split("-"); if(arr.length == 2) { Tournament tournament = Tournament.getTournamentByUsername(arr[0]); TournamentVM tournamentVM = Mapper.mapTournamentToTournamentVM(tournament); Map<String,String> countryMap = new HashMap<String,String>(); Map<String,String> stateMap = new HashMap<String,String>(); Map<String,String> cityMap = new HashMap<String,String>(); if(tournamentVM != null) { tournamentVM.setTeamVMs(new ArrayList<TeamVM>()); if(tournament.getTeams() != null) { for(TournamentTeam tournamentTeam : tournament.getTeams()) { Team team = Team.findById(tournamentTeam.getTeamId()); TeamVM teamVM = new TeamVM(); teamVM.setId(team.getId()); teamVM.setContactPerson(team.getContactNumber()); teamVM.setContactPerson(team.getContactPerson()); teamVM.setEmail(team.getEmail()); teamVM.setName(team.getName()); teamVM.setSponsoredBy(team.getSponsoredBy()); if(team != null) { if(team.getAddress()!=null) { Address address = team.getAddress(); if(address.getCity()!=null) { if(cityMap.get(address.getCity()) == null) { City city = City.findById(address.getCity()); if(city != null) { cityMap.put(city.getId(), city.getName()); teamVM.setCity(city.getName()); } } else { teamVM.setCity(cityMap.get(address.getCity())); } } if(address.getState()!=null) { if(stateMap.get(address.getState()) == null) { State state = State.findById(address.getState()); if(state != null) { stateMap.put(state.getId(), state.getName()); teamVM.setState(state.getName()); } } else { teamVM.setState(stateMap.get(address.getState())); } } if(address.getCountry()!=null) { if(countryMap.get(address.getCountry()) == null) { Country country = Country.findById(address.getCountry()); if(country != null) { countryMap.put(country.getId(), country.getName()); teamVM.setCountry(country.getName()); } } else { teamVM.setCountry(countryMap.get(address.getCountry())); } } } } tournamentVM.getTeamVMs().add(teamVM); } } return ok(Json.toJson(tournamentVM)); } } } return ok(Json.toJson("/cpanel")); } public static Result addTeamToTournament() { JsonNode node = request().body().asJson(); String teamId = node.get("teamId") != null ? node.get("teamId").asText() : null; Team teamEntity = null; if(teamId == null) { return ok(Json.toJson("team id is empty")); } else { teamEntity = Team.findById(teamId); if(teamEntity == null) { return ok(Json.toJson("invalid team id")); } } String uuid = session().get("uuid"); if(uuid != null) { try { String[] arr = Crypto.decryptAES(uuid).split("-"); if(arr.length == 2) { Tournament tournament = Tournament.getTournamentByUsername(arr[0]); if(tournament != null) { if(tournament.getTeams() == null) { List<TournamentTeam> teams = new ArrayList<TournamentTeam>(); TournamentTeam tournamentTeam = new TournamentTeam(); tournamentTeam.setTeamId(teamId); teams.add(tournamentTeam); tournament.setTeams(teams); } else { for(TournamentTeam team : tournament.getTeams()) { if(team.getTeamId().equals(teamId)) { return ok(Json.toJson("team already present")); } } TournamentTeam tournamentTeam = new TournamentTeam(); tournamentTeam.setTeamId(teamId); tournament.getTeams().add(tournamentTeam); } tournament.update(); TeamVM teamVM = new TeamVM(); teamVM.setId(teamEntity.getId()); teamVM.setContactPerson(teamEntity.getContactNumber()); teamVM.setContactPerson(teamEntity.getContactPerson()); teamVM.setEmail(teamEntity.getEmail()); teamVM.setName(teamEntity.getName()); teamVM.setSponsoredBy(teamEntity.getSponsoredBy()); if(teamEntity.getAddress()!=null) { Address address = teamEntity.getAddress(); if(address.getCity()!=null) { City city = City.findById(address.getCity()); if(city != null) { teamVM.setCity(city.getName()); } } if(address.getState()!=null) { State state = State.findById(address.getState()); if(state != null) { teamVM.setState(state.getName()); } } if(address.getCountry()!=null) { Country country = Country.findById(address.getCountry()); if(country != null) { teamVM.setCountry(country.getName()); } } } return ok(Json.toJson(teamVM)); } } } catch(Exception e) { } } return ok(Json.toJson("not authenticated")); } public static Result searchTeam() { List<Team> teams = Team.getTeamByQuery(request().getQueryString("q")); List<SelectItem> results = new ArrayList<SelectItem>(teams.size()); for(Team team : teams) { SelectItem item = new SelectItem(); item.setName(team.getName()+" ["+team.getId()+"]"); item.setValue(team.getId()); results.add(item); } return ok(Json.toJson(results)); } public static Result removeTeamFromTournam() { JsonNode node = request().body().asJson(); String teamId = node.get("teamId") != null ? node.get("teamId").asText() : null; String uuid = session().get("uuid"); if(uuid == null) { return ok(Json.toJson("not authenticated")); } if(teamId != null) { try { String[] arr = Crypto.decryptAES(uuid).split("-"); if(arr.length == 2) { Tournament tournament = Tournament.getTournamentByUsername(arr[0]); if(tournament != null) { if(tournament.getTeams() == null) { return ok(Json.toJson("teams not found")); } else { if(tournament.getTeams().remove(teamId)) { tournament.update(); return ok(Json.toJson("ok")); } } } } } catch(Exception e) { } } return ok(Json.toJson("no change")); } public static Result playerSearch() { List<Player> players = Player.getPlayerByQuery(request().getQueryString("q")); List<SelectItem> results = new ArrayList<SelectItem>(players.size()); for(Player player : players) { SelectItem item = new SelectItem(); item.setName(player.getFirstName() +" "+player.getLastName() +" ["+player.getId()+"]"); item.setValue(player.getId()); results.add(item); } return ok(Json.toJson(results)); } }
/* * Created on 17 oct. 2004 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package jsesh.mdcDisplayer.mdcView; import jsesh.mdc.model.ModelElement; import jsesh.mdcDisplayer.preferences.DrawingSpecification; /** * @author Serge Rosmorduc * * This file is free software under the Gnu Lesser Public License. */ public interface ViewBuilder { public MDCView buildView(ModelElement elt, DrawingSpecification drawingSpecifications); /** * Recompute the layout of a view. * If a view has been modified since it was built, * this methods recomputes its layout. * @param v */ public void reLayout(MDCView v, DrawingSpecification drawingSpecifications ); /** * Build a partial view of an element. * <p> The view will correspond to all sub elements of model between indexes start and end. * <p> mode will typically be a TopItemList which we want to render partially. * @param model * @param start * @param end * @return the view built for this element part. */ public MDCView buildView(ModelElement model, int start, int end, DrawingSpecification drawingSpecifications); }
package com.cnk.travelogix.custom.ziffm.vendor.createchange; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="EtStatus" type="{urn:sap-com:document:sap:soap:functions:mc-style}ZifttStatusDoc"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "etStatus" }) @XmlRootElement(name = "ZVendorCreateChangeServiceResponse") public class ZVendorCreateChangeServiceResponse { @XmlElement(name = "EtStatus", required = true) protected ZifttStatusDoc etStatus; /** * Gets the value of the etStatus property. * * @return * possible object is * {@link ZifttStatusDoc } * */ public ZifttStatusDoc getEtStatus() { return etStatus; } /** * Sets the value of the etStatus property. * * @param value * allowed object is * {@link ZifttStatusDoc } * */ public void setEtStatus(ZifttStatusDoc value) { this.etStatus = value; } }
package com.tencent.mm.plugin.honey_pay.ui; import android.content.Intent; import android.os.Bundle; import com.tencent.mm.plugin.honey_pay.a.l; import com.tencent.mm.plugin.honey_pay.a.m; import com.tencent.mm.protocal.c.bdk; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.a; import com.tencent.mm.wallet_core.c.h; @a(3) public class HoneyPayProxyUI extends HoneyPayBaseUI { private String kkc; private boolean klL; static /* synthetic */ void b(HoneyPayProxyUI honeyPayProxyUI, bdk bdk) { x.i(honeyPayProxyUI.TAG, "go to card detail"); Intent intent = new Intent(honeyPayProxyUI, HoneyPayCardDetailUI.class); intent.putExtra("key_card_no", honeyPayProxyUI.kkc); intent.putExtra("key_scene", 1); try { intent.putExtra("key_qry_response", bdk.toByteArray()); } catch (Throwable e) { x.printErrStackTrace(honeyPayProxyUI.TAG, e, "", new Object[0]); } honeyPayProxyUI.startActivity(intent); } public void onCreate(Bundle bundle) { super.onCreate(bundle); jr(2876); jr(2613); this.klL = getIntent().getBooleanExtra("key_is_payer", false); this.kkc = getIntent().getStringExtra("key_card_no"); x.i(this.TAG, "is payer: %s", new Object[]{Boolean.valueOf(this.klL)}); if (this.klL) { x.i(this.TAG, "do qry payer detail"); l lVar = new l(this.kkc); lVar.m(this); a(lVar, true, false); return; } m mVar = new m(this.kkc); mVar.m(this); a(mVar, true, false); } protected final void aWd() { } public void onDestroy() { super.onDestroy(); js(2876); js(2613); } public final boolean d(int i, int i2, String str, com.tencent.mm.ab.l lVar) { if (lVar instanceof l) { l lVar2 = (l) lVar; lVar2.a(new 3(this, lVar2)).b(new 2(this)).c(new h.a() { public final void g(int i, int i2, String str, com.tencent.mm.ab.l lVar) { } }); } else if (lVar instanceof m) { final m mVar = (m) lVar; mVar.a(new h.a() { public final void g(int i, int i2, String str, com.tencent.mm.ab.l lVar) { x.i(HoneyPayProxyUI.this.TAG, "state: %s", new Object[]{Integer.valueOf(mVar.kjN.rIz.state)}); if (mVar.kjN.rIz.state == 1) { HoneyPayProxyUI.a(HoneyPayProxyUI.this, mVar.kjN); } else { HoneyPayProxyUI.b(HoneyPayProxyUI.this, mVar.kjN); } HoneyPayProxyUI.this.finish(); } }).b(new 5(this)).c(new 4(this)); } return true; } protected final int getLayoutId() { return -1; } protected final boolean aWj() { return true; } }
package pisi.unitedmeows.minecraft; public class Settings { /* define setting(s) */ public static boolean ENCHANTMENT_HELPER_MEMORY_LEAK_FIX = false; public static boolean CHUNK_UPDATE_VANILLAFIX = false; public static boolean NO_FPS_LIMIT_IN_GUIS = true; public static boolean INTEGRATEDSERVER_SHUTDOWN_FIX = true; public static boolean NETHER_PORTAL_GUI_FIX = true; public static boolean ITEM_COMBINE_FIX = true; public static boolean ENUM_FACING_FIX = true; /* could be buggy */ public static boolean FASTER_BLOCKPOS = true; public static boolean OLD_ANIMATIONS = true; /* its basically a shit swing animation + old blockhit swing */ }
package com.mx.profuturo.bolsa.model.vo.common; public class BasicCatalogVO { protected int id; protected String descripcion; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } }
/* * 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 pt.mleiria.mlalgo.distance; /** * @author Manuel Leiria <manuel.leiria at gmail.com> */ public class EuclideanDistance implements DistanceMetric<Double[], Double[], Double> { //private static final Logger LOG = Logger.getLogger(EuclideanDistance.class.getName()); @Override public Double calculate(Double[] x, Double[] y) { double res = 0.0; for (int i = 0; i < x.length; i++) { res += Math.pow(x[i] - y[i], 2); } return Math.sqrt(res); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package unalcol.types.real.array; /** * @author jgomez */ public class DoubleArrayDotProduct { public double apply(double[] x, double[] y) { int n = (x.length < y.length) ? x.length : y.length; double prod = 0.0; for (int i = 0; i < n; i++) { prod += x[i] * y[i]; } return prod; } public double sqr_norm(double[] x) { return apply(x, x); } public double norm(double[] x) { return Math.sqrt(sqr_norm(x)); } }
public class TestTorcia{ public static void main(String[] args){ // Dichiara due oggetti di tipo Torcia Torcia t1; Torcia t2; // Inizializza gli oggetti: richiama il costruttore che inizializza lo stato (torcia accesa) t1 = new Torcia(); t2 = new Torcia(); // Verifica dello stato iniziale degli oggetti System.out.println("t1: " + t1.getAccesa() + "; t2: " + t2.getAccesa() + "."); /** * Possiamo manipolare lo stato di un oggetto tramite un suo metodo. * La modifica di t1 non ha conseguenze sullo stato di t2. */ t1.spegni(); System.out.println("t1: " + t1.getAccesa() + "; t2: " + t2.getAccesa() + "."); // Possiamo accendere nuovamente la torcia. t1.accendi(); System.out.println("t1: " + t1.getAccesa() + "; t2: " + t2.getAccesa() + "."); } }
package FirstDay; import org.junit.Test; import static org.junit.Assert.*; public class SmallestTest { int a=7; int b=13; int c=12; Smallest s=new Smallest(); @Test public void testSmallest() { assertEquals(a,s.small(a,b,c)); } }
package com.amit.indiehooddemo.adapter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.amit.indiehooddemo.DetailActivity; import com.amit.indiehooddemo.MainActivity; import com.amit.indiehooddemo.R; import com.amit.indiehooddemo.models.Item; import org.json.JSONObject; import java.util.ArrayList; public class ListAdapter extends BaseAdapter { private final Context mContext; private final ArrayList<String> items; private final JSONObject schemaJson; private final JSONObject dataJson; //1 public ListAdapter(Context context, ArrayList<String> items, JSONObject schemaJson, JSONObject dataJson) { this.mContext = context; this.items = items; this.schemaJson = schemaJson; this.dataJson = dataJson; } // 2 @Override public int getCount() { return items.size(); } // 3 @Override public long getItemId(int position) { return 0; } // 4 @Override public Object getItem(int position) { return null; } // 5 @Override public View getView(int position, View convertView, ViewGroup parent) { final String item = items.get(position); if (convertView == null) { final LayoutInflater layoutInflater = LayoutInflater.from(mContext); convertView = layoutInflater.inflate(R.layout.list_item, null); } final TextView text1 = convertView.findViewById(R.id.type_name); text1.setText(item); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, DetailActivity.class); intent.putExtra("datajson", dataJson.toString()); intent.putExtra("schemajson", schemaJson.toString()); intent.putExtra("name", item); mContext.startActivity(intent); } }); return convertView; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.apache.clerezza.test.utils; import org.apache.clerezza.Triple; import java.util.Iterator; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Wrapps an iterator<Triple> reading all elements to a cache on construction * and returning them from that cache. * @author reto */ class LockingIteratorForTesting implements Iterator<Triple> { private Iterator<Triple> base; private Lock readLock; private Lock writeLock; private ReentrantReadWriteLock lock; public LockingIteratorForTesting(Iterator<Triple> iterator, ReentrantReadWriteLock lock) { base = iterator; readLock = lock.readLock(); writeLock = lock.writeLock(); this.lock = lock; } @Override public boolean hasNext() { LockChecker.checkIfReadLocked(lock); readLock.lock(); try { return base.hasNext(); } finally { readLock.unlock(); } } @Override public Triple next() { LockChecker.checkIfReadLocked(lock); readLock.lock(); try { return base.next(); } finally { readLock.unlock(); } } @Override public void remove() { LockChecker.checkIfWriteLocked(lock); writeLock.lock(); try { base.remove(); } finally { writeLock.unlock(); } } }
package com.example.lastminute.Trips; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.widget.PopupMenu; import androidx.recyclerview.widget.RecyclerView; import com.example.lastminute.R; import com.firebase.ui.firestore.FirestoreRecyclerAdapter; import com.firebase.ui.firestore.FirestoreRecyclerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; public class TripsEntryRecyclerAdapter extends FirestoreRecyclerAdapter<TripEntryDetails, TripsEntryRecyclerAdapter.TripEntryViewHolder> { private TripListener tripListener; /** * Create a new RecyclerView adapter that listens to a Firestore Query. See {@link * FirestoreRecyclerOptions} for configuration options. * * @param options */ public TripsEntryRecyclerAdapter(@NonNull FirestoreRecyclerOptions<TripEntryDetails> options , TripListener tripListener) { super(options); this.tripListener = tripListener; } @Override protected void onBindViewHolder(@NonNull TripEntryViewHolder holder, int position, @NonNull TripEntryDetails model) { holder.tripName.setText(model.getTripName()); holder.tripPlace.setText(model.getTripPlace()); holder.startDate.setText(model.getStartDate()); holder.endDate.setText(model.getEndDate()); } @NonNull @Override public TripEntryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.trips_view, parent, false); return new TripEntryViewHolder(view); } public void deleteItem(int position) { final DocumentReference documentReference = getSnapshots().getSnapshot(position).getReference(); documentReference.delete(); FirebaseFirestore.getInstance().collection("Trips") .document(documentReference.getId()) .collection("Activities") .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot documentSnapshot : task.getResult()) { documentReference.collection("Activities") .document(documentSnapshot.getId()).delete(); } } } }); notifyDataSetChanged(); } class TripEntryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, PopupMenu.OnMenuItemClickListener { private TextView tripName, tripPlace, startDate, endDate; private ImageButton moreButton; public TripEntryViewHolder(@NonNull View itemView) { super(itemView); setUpUIView(itemView); EditTripEntry(itemView); goToActivities(itemView); openPopup(itemView); } private void setUpUIView(View itemView) { tripName = (TextView) itemView.findViewById(R.id.tripName); tripPlace = (TextView) itemView.findViewById(R.id.tripPlace); startDate = (TextView) itemView.findViewById(R.id.startDate); endDate = (TextView) itemView.findViewById(R.id.endDate); moreButton = (ImageButton) itemView.findViewById(R.id.moreTripButton); } private void EditTripEntry(View itemView) { itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { DocumentSnapshot snapshot = getSnapshots().getSnapshot(getAdapterPosition()); tripListener.handleEditTrip(snapshot, v); return true; } }); } private void goToActivities(View itemView) { itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DocumentSnapshot snapshot = getSnapshots().getSnapshot(getAdapterPosition()); tripListener.handleActivities(snapshot, v); } }); } private void openPopup(View itemView) { moreButton.setOnClickListener(this); } @Override public void onClick(View v) { showPopup(v); } private void showPopup(View v) { PopupMenu popupMenu = new PopupMenu(itemView.getContext(), v); popupMenu.inflate(R.menu.trips_more_menu); popupMenu.setOnMenuItemClickListener(this); popupMenu.show(); } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.popup_edit: DocumentSnapshot snapshotEdit = getSnapshots().getSnapshot(getAdapterPosition()); tripListener.handleEditTrip(snapshotEdit, itemView); return true; case R.id.popup_delete: deleteItem(getAdapterPosition()); return true; case R.id.popup_share: DocumentSnapshot snapshotShare = getSnapshots().getSnapshot(getAdapterPosition()); tripListener.handleShareTrip(snapshotShare, itemView); return true; default: return false; } } } public interface TripListener { void handleEditTrip(DocumentSnapshot snapshot, View v); void handleActivities(DocumentSnapshot snapshot, View v); void handleShareTrip(DocumentSnapshot snapshot, View v); } }
package leecode.Array; import com.sun.org.apache.xpath.internal.operations.Bool; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class 组合总和II_40 { /* 不能包含两个相同的解 但是一个解里面却可以包含重复的数字 */ public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> res=new ArrayList<>(); List<Integer> list = new ArrayList<>(); boolean[]used=new boolean[candidates.length]; //排序去重复 Arrays.sort(candidates); dfs(res,list,candidates,0,target,used); return res; } //使用boolean数组 public void dfs(List<List<Integer>> res,List<Integer> list,int[] candidates,int begin,int target,boolean[]used){ if(target<0){ return; } if(target==0){ res.add(new ArrayList<>(list)); return; } for (int i = begin; i <candidates.length ; i++) { //这样去重 一定要先排序数组!! /* 解释!used[i-1] 在情况1 begin=1 处理右边2时候 左边2已经撤销 状态布尔值为false 在情况2 begin=2 处理下面的2时候 上面的2还没有被撤销 布尔值为true */ if(i>0&&candidates[i]==candidates[i-1]&&!used[i-1]){ continue; } list.add(candidates[i]); used[i]=true; //每个数只能选择一次时,下次搜索的起点就是i+1,对比 lee39 dfs(res,list,candidates,i+1,target-candidates[i],used); list.remove(list.size()-1); used[i]=false; } } //不使用boolean数组 public void dfs2(List<List<Integer>> res,List<Integer> list,int[] candidates,int begin,int target){ if(target<0){ return; } if(target==0){ res.add(new ArrayList<>(list)); return; } for (int i = begin; i <candidates.length ; i++) { //这样去重 一定要先排序数组!! /* 情况1: 1 / \ begin=1 2(i=1) 2(i=2) 这种情况不会发生 但是却允许了不同层级之间的重复即: / \ begin=2 5(i=2) 5 情况2: 1 / 2 这种情况确是允许的 / 2 candidates[i]==candidates[i-1] 这个会把情况1和2都排掉 如何保留情况2,i>begin即可(i>begin排除的是情况1) 例2的两个2是处在不同层级上的,在一个for循环中,所有被遍历到的数都是属于一个层级的 对于重复的2,第一个2:i=begin,其他2:i>begin 所以 i>begin就可以只保留第一个 如果if cur > 0 and candidates[cur-1] == candidates[cur] ,就会排除掉情况2,会导致全局只有一个相同数字可用, 肯定不对,所以改成cur > begin,这样递归进入下一层时和上一层的重复结果没有任何关系了。 同一层中的两个相同的值,i-1搜索的范围会更大,后面的搜索结果都是前面的真子集,所以只保留第一个就包含了全部可能的结果 肯定会在下一层再一次搜索到i所组成组合,就重复了。 for循环的最开始,cur=start,不会越界 */ if(i>begin&&candidates[i]==candidates[i-1]){//i>begin排除的是情况1 continue; } list.add(candidates[i]); //每个数只能选择一次时,下次搜索的起点就是i+1,对比 lee39 dfs2(res,list,candidates,i+1,target-candidates[i]); list.remove(list.size()-1); } } }
package fiscal; public enum FiscalTipoServicoEnum { ENVIO_DE_IMAGEM_PMV(1L); FiscalTipoServicoEnum(Long value) { this.value = value; } private Long value; public void setValue(Long value) { this.value = value; } public Long getValue() { return value; } public boolean compareTo(FiscalTipoServico tipoServico) { return tipoServico.getId().equals(this.getValue()) ? true : false; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author 500062053 */ public class SingleThread { public static void main(String[] args) { SingleThread obj=new SingleThread(); obj.printNumber(); for(int j=1;j<=100;j++) { System.out.println("j"+j+"\t"); } } void printNumber() { for(int i=1;i<100;i++) { System.out.println("i"+i+"\t"); } } }
/* * ********************************************************* * Copyright (c) 2019 @alxgcrz All rights reserved. * This code is licensed under the MIT license. * Images, graphics, audio and the rest of the assets be * outside this license and are copyrighted. * ********************************************************* */ package com.codessus.ecnaris.ambar.fragments; import android.app.Fragment; import android.app.FragmentTransaction; import android.media.AudioManager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.ImageButton; import com.codessus.ecnaris.ambar.R; import com.codessus.ecnaris.ambar.helpers.AmbarManager; public class MapFragment extends Fragment { // --- CONSTRUCTOR --- // public MapFragment() { // Required empty public constructor } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { View rootView = inflater.inflate( R.layout.fragment_map, container, false ); ImageButton cancelImageButton = rootView.findViewById( R.id.include_navigation_cancel ); cancelImageButton.setVisibility( View.VISIBLE ); cancelImageButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick( View view ) { AmbarManager.instance().clickButtonSound( AudioManager.FX_KEY_CLICK, 1f ); returnToReaderScreen(); } } ); WebView webView = rootView.findViewById( R.id.webView ); webView.getSettings().setBuiltInZoomControls( true ); webView.getSettings().setUseWideViewPort( true ); webView.loadUrl( "file:///android_asset/mapa.jpg" ); return rootView; } private void returnToReaderScreen() { FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace( R.id.container, new LecturaFragment() ); transaction.commit(); } }
public class TaxiService { protected MySet<taxi> taxies; protected graph city; public TaxiService() { taxies = new MySet<taxi>(); city = new graph(); } public graph getGraph(){ return city; } public MySet<taxi> getTaxiSet(){ return taxies; } public void performAction(String actionMessage)throws Exception { try{String[] action = actionMessage.split("\\s+"); System.out.println("action to be performed :"+actionMessage); if(action[0].equals("edge")){ this.getGraph().addEdge(action[1], action[2], Integer.valueOf(action[3])); } else if(action[0].equals("taxi")){ this.addTaxi(action[1],action[2]); } else if(action[0].equals("customer")){ this.customerRequest(action[1], action[2], Integer.valueOf(action[3])); } else if(action[0].equals("printTaxiPosition")){ this.printTaxies(Integer.valueOf(action[1])); }} catch(Exception e){ System.out.println("Invalid Input"); } } public void customerRequest(String a, String b, int n)throws Exception{ MySet<taxi> available = new MySet<taxi>(); int i=0; for(;i<this.getTaxiSet().getSize();i++){ if(this.getTaxiSet().getm(i).getStatus()==0||n>this.getTaxiSet().getm(i).getStatus()) available.addElement(this.getTaxiSet().getm(i)); } int j=0; int c=999999999; for(i=0;i<available.getSize();i++){ if(this.getGraph().getShortestPathLength(a,available.getm(i).getSource())<c) j=i; c=Math.min(c,this.getGraph().getShortestPathLength(a,available.getm(i).getSource())); } System.out.println("Available Taxis:"); for(i=0;i<available.getSize();i++){ System.out.println("Path of taxi "+available.getm(i).getname()+" :"+" "); this.getGraph().getShortPath(available.getm(i).getSource(),a); System.out.print(". time taken is "+this.getGraph().getShortestPathLength(available.getm(i).getSource(), a)+" units");System.out.println(); } System.out.println("**choose taxi"+" "+available.getm(j).getname()+"to serve customer request**"); System.out.println("Path of customer"); this.getGraph().getShortPath(a, b); System.out.print(" "+"time taken is"+this.getGraph().getShortestPathLength(a,b)+" units"); available.getm(j).setStatus(n+this.getGraph().getShortestPathLength(a, available.getm(j).getSource())+this.getGraph().getShortestPathLength(a,b)); available.getm(j).setSource(b); System.out.println(); System.out.println(); } public void addTaxi(String name, String vertex)throws Exception{ boolean flag=false; taxi abc = new taxi(vertex,name); Node <vertexNode> head1 = this.getGraph().getvertexList().gethead(); while(head1!=null){ if(head1.getElement().getName().equals(vertex)) flag=true; head1=head1.getNext(); } if(flag) this.getTaxiSet().addElement(abc); else throw new Exception(name+" vertex doesn't exists"); } public void printTaxies(int n){ MySet<taxi> available = new MySet<taxi>(); int i=0; for(;i<this.getTaxiSet().getSize();i++){ if(this.getTaxiSet().getm(i).getStatus()==0||n>this.getTaxiSet().getm(i).getStatus()) available.addElement(this.getTaxiSet().getm(i)); } for(i=0;i<available.getSize();i++){ System.out.println(available.getm(i).getname()+"; "+available.getm(i).getSource()); } System.out.println(); } }
package com.jim.multipos.utils.rxevents.main_order_events; public class NotPermissionUsbEvent { }
package solution; import java.util.Arrays; /** * User: jieyu * Date: 10/21/16. */ public class HouseRobberII213 { public int rob(int[] nums) { if (nums.length == 0) return 0; if (nums.length == 1) return nums[0]; if (nums.length == 2) return Math.max(nums[0],nums[1]); int[] sum1 = new int[nums.length - 1]; int[] sum2 = new int[nums.length]; sum1[0] = nums[0]; sum1[1] = nums[1]; sum2[1] = nums[1]; sum2[2] = nums[2]; for (int i = 2; i < nums.length - 1; i++) { int max1 = -1; int max2 = -1; for (int j = i - 2; j >= 0; j--) { max1 = Math.max(max1, sum1[j]); max2 = Math.max(max2, sum2[j + 1]); } sum1[i] = max1 + nums[i]; sum2[i + 1] = max2 + nums[i + 1]; } Arrays.sort(sum1); Arrays.sort(sum2); return Math.max(sum1[sum1.length - 1], sum2[sum2.length - 1]); } }
package acs.data; public enum MuscaleGroup { hands , legs , upper_abdomen , lower_abdomen ,upper_chest , lower_chest }
package bootcamp.test.filereaders.propertiesreader; import java.io.FileWriter; import java.io.IOException; import java.util.Properties; public class PropertyWriter { public void write() { Properties prop = new Properties(); prop.put("name", "test"); prop.put("email", "test@gmail.com"); try { prop.store(new FileWriter("src/test/resources/test/write.properties"), "Created new file"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { PropertyWriter pr = new PropertyWriter(); pr.write(); } }
package com.zhangtao.fleamarket.Activity; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.Html; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ImageSpan; import android.util.Log; import android.widget.TextView; import com.zhangtao.fleamarket.R; import com.zhangtao.fleamarket.fragemnt.PartTimeJobFragment; import java.io.FileNotFoundException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by zhangtao on 16/2/10. */ public class InformationShow extends Activity { private TextView informationShow; String imgpath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_informationshow); informationShow = (TextView) findViewById(R.id.information_show); Intent intent = getIntent(); String str = intent.getStringExtra(PartTimeJobFragment.PartTimeJob_Information); // Pattern pattern = Pattern.compile("<img src=.*>"); // Matcher matcher = pattern.matcher(str); // SpannableString ss = null; // Log.d("-------",str); // while (matcher.find()) { // Log.d("-------","2"); // imgpath = (((matcher.group().replace("<img src=", ""))).replace("/>", "")).trim(); // // // //Bitmap bitmap = null; // try { // ss = new SpannableString(imgpath); // Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(imgpath)); // Bitmap // ImageSpan span = new ImageSpan(this, bitmap); // ss.setSpan(span, 0, imgpath.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // // Log.d("-------","3"); // } catch (IOException e) { // e.printStackTrace(); // } // //Bitmap bm = BitmapFactory.decodeFile(matcher.group()); // // // // } // informationShow.setText(ss); informationShow.append(Html.fromHtml(str, imageGetter, null)); } private Html.ImageGetter imageGetter = new Html.ImageGetter() { @Override public Drawable getDrawable(String source) { Drawable d = null; try { d = Drawable.createFromStream(getApplicationContext().getContentResolver() .openInputStream(Uri.parse(source)), null); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); Log.d("widthAndheight",d.getIntrinsicWidth()+"----"+d.getIntrinsicHeight()+""); return d; } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } }; }
package task5; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import org.junit.runners.model.TestTimedOutException; import java.util.Random; import java.util.concurrent.TimeoutException; import static org.junit.Assert.*; public class BubbleSortTest { @Rule public Timeout globalTimeout = Timeout.seconds(4000); @Test public void TestBubbleSort() { int size = 100000; int[] best = new int[size]; for (int i = 0; i < size; i++) best[i] = i; BubbleSort.bubbleSort(best); } @Test public void TestBubbleSort2() { int size = 10000; int[] worst = new int[size]; for (int i = size - 1, j = 0; i >= 0; i--, j++) worst[i] = j; BubbleSort.bubbleSort(worst); } @Test public void TestBubbleSort3() { int size = 10000; Random random = new Random(); int[] average = new int[size]; for (int i = 0; i < size; i++) average[i] = random.nextInt(size); BubbleSort.bubbleSort(average); } }
package com; import java.io.*; import java.util.*; import javax.servlet.GenericServlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class InitSnoop */ @WebServlet("/Ass12") public class Ass12 extends GenericServlet { private static final long serialVersionUID = 1L; /** * @see GenericServlet#GenericServlet() */ public Ass12() { super(); // TODO Auto-generated constructor stub } /** * @see Servlet#service(ServletRequest request, ServletResponse response) */ public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("===== ENV VARIABLES ====="); /*Lagrar variablerna i en Map och skriver sedan ut dessa*/ Map map = System.getenv(); Set keys = map.keySet(); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = (String) map.get(key); out.println(key + " = " + value); } } }
package com.example.afshindeveloper.afshindeveloperandroid; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.util.EventLogTags; import android.util.Log; import com.example.afshindeveloper.afshindeveloperandroid.datamodel.Post; import java.util.List; /** * Created by afshindeveloper on 16/09/2017. */ public class AddPostsTask extends AsyncTask<Void,Integer,String> { private static final String TAG = "AddPostsTask"; private Context context; private List<Post> posts; private MyAppDatabaseOpenHelper myAppDatabaseOpenHelper; private ProgressDialog progressDialog; public AddPostsTask(Context context, List<Post>posts,MyAppDatabaseOpenHelper openHelper){ this.context = context; this.posts = posts; this.myAppDatabaseOpenHelper=openHelper; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog=new ProgressDialog(context); progressDialog.setTitle("در حال ذخیره سازی"); progressDialog.setMessage("در حال ذخیره ساز‍ی پست ها لطفا منتظر بمانید... "); progressDialog.setIndeterminate(false); progressDialog.setProgressStyle(progressDialog.STYLE_HORIZONTAL); progressDialog.show(); } @Override protected String doInBackground(Void... paramses) { for (int i=0;i<posts.size(); i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } ContentValues cv=new ContentValues(); Post post=posts.get(i); cv.put(MyAppDatabaseOpenHelper.COL_ID,post.getId()); cv.put(MyAppDatabaseOpenHelper.COL_TITLE,post.getTitle()); cv.put(MyAppDatabaseOpenHelper.COL_CONTENT,post.getContent()); cv.put(MyAppDatabaseOpenHelper.COL_POST_IMAGE_URL,post.getPostimage()); cv.put(MyAppDatabaseOpenHelper.COL_IS_VISITED,post.getIsvisited()); cv.put(MyAppDatabaseOpenHelper.COL_DATE,post.getDate()); SQLiteDatabase sqLiteDatabase=myAppDatabaseOpenHelper.getWritableDatabase(); long isInserted=sqLiteDatabase.insert(MyAppDatabaseOpenHelper.POST_TABLE_NAME,null,cv); publishProgress((i*100)/posts.size()); Log.i(TAG, "addpost: "+isInserted); } return ""; } @Override protected void onPostExecute(String aVoid) { super.onPostExecute(aVoid); progressDialog.hide(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); progressDialog.setProgress(values[0]); } }
package bootcamp.test.jsexecutor; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import bootcamp.selenium.basic.LaunchBrowser; public class Click { public static void main(String[] args) { WebDriver driver = LaunchBrowser.launch("https://demoqa.com/buttons"); WebElement button = driver.findElement(By.xpath("//button[text()='Click Me']")); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", button); } }
/* * 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 vasylts.blackjack.user; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Before; import vasylts.blackjack.user.wallet.FakeWallet; /** * * @author VasylcTS */ public class FakeUserManagerTest { public FakeUserManagerTest() { } FakeUserManager um; @Before public void setUp() { um = new FakeUserManager(); IUser userCarl = new FakeUser(1l, "a", "1", new FakeWallet()); IUser userJack = new FakeUser(2l, "b", "2", new FakeWallet()); IUser userLena = new FakeUser(3l, "c", "3", new FakeWallet()); um.addUser(userCarl); um.addUser(userJack); um.addUser(userLena); } @Test public void testSameUser() { int oldSize = um.getUserCount(); FakeWallet wal = new FakeWallet(); IUser userTaras1 = new FakeUser(999l, "Taras", "999", wal); IUser userTaras2 = new FakeUser(999l, "Taras", "999", wal); Long firstTarasAdded = um.addUser(userTaras1); assertTrue(firstTarasAdded != null); Long secondTarasAdded = um.addUser(userTaras2); assertFalse(secondTarasAdded != null); IUser userTaras3 = new FakeUser(124125412l, "Taras", "4234", new FakeWallet()); Long thirdTarasAdded = um.addUser(userTaras3); assertFalse(thirdTarasAdded != null); assertEquals(oldSize + 1, um.getUserCount()); } @Test public void testDeleteUser() { IUser userTaras = new FakeUser(999l, "Taras", "999", new FakeWallet()); um.addUser(userTaras); int oldSize = um.getUserCount(); boolean wrongUserDeleted = um.deleteUser("taras", "999"); assertFalse(wrongUserDeleted); assertEquals(oldSize, um.getUserCount()); boolean userDeleted = um.deleteUser("Taras", "999"); assertTrue(userDeleted); assertEquals(oldSize - 1, um.getUserCount()); } }
package com.ojas.rpo.security.entity; import org.codehaus.jackson.map.annotate.JsonView; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.ojas.rpo.security.JsonViews; import javax.persistence.*; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Set; @Table(name="user") @javax.persistence.Entity public class User implements Entity, UserDetails { @Id @GeneratedValue private Long id; @Column(unique = true, nullable = false) private String name; @Column(length = 80, nullable = false) private String password; @Column private String firstName; @Column private String lastName; @Column private Long contactNumber; @Column private String email; @Column private String role; @Column private String question; @Column private String answer; @Column private String status; @Column private Date date; private String dob1; private String doj1; @ManyToOne private User reportingId; public String getDob1() { return dob1; } public void setDob1(String dob1) { this.dob1 = dob1; } public String getDoj1() { return doj1; } public void setDoj1(String doj1) { this.doj1 = doj1; } @Column private Integer extension; @Column private String designation; @Column private Date dob; @Column private Date doj; @Column private String newPassword; @Column private Long salary; @Column private Long variablepay; @Column private Long ctc; @Column private Long mintarget; @Column private Long maxtarget; @Column private String targetduration; public String getNewPassword() { return newPassword; } public void setNewPassword(String newPassword) { this.newPassword = newPassword; } public Integer getExtension() { return extension; } public void setExtension(Integer extension) { this.extension = extension; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } public Date getDoj() { return doj; } public void setDoj(Date doj) { this.doj = doj; } @ElementCollection(fetch = FetchType.EAGER) private Set<Role> roles = new HashSet<Role>(); public User() { this.date = new Date(); } public User(String name, String passwordHash) { this.name = name; this.password = passwordHash; } @JsonView(JsonViews.User.class) public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } @JsonView(JsonViews.Admin.class) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @JsonView(JsonViews.User.class) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @JsonView(JsonViews.User.class) public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @JsonView(JsonViews.User.class) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Long getContactNumber() { return contactNumber; } public void setContactNumber(Long contactNumber) { this.contactNumber = contactNumber; } public Long getSalary() { return salary; } public void setSalary(Long salary) { this.salary = salary; } public Long getVariablepay() { return variablepay; } public void setVariablepay(Long variablepay) { this.variablepay = variablepay; } public Long getCtc() { return ctc; } public void setCtc(Long ctc) { this.ctc = ctc; } public Long getMintarget() { return mintarget; } public void setMintarget(Long mintarget) { this.mintarget = mintarget; } public Long getMaxtarget() { return maxtarget; } public void setMaxtarget(Long maxtarget) { this.maxtarget = maxtarget; } public String getTargetduration() { return targetduration; } public void setTargetduration(String targetduration) { this.targetduration = targetduration; } @JsonView(JsonViews.User.class) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @JsonView(JsonViews.User.class) public String getRole() { return role; } public void setRole(String role) { this.role = role; } @JsonView(JsonViews.User.class) public String getStatus() { return status; } @JsonView(JsonViews.User.class) public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } @JsonView(JsonViews.User.class) public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public void setStatus(String status) { this.status = status; } public Set<Role> getRoles() { return this.roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } public void addRole(Role role) { this.roles.add(role); } @Override public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return this.getRoles(); } @Override public String getUsername() { return this.name; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } public User( String name, String password, String firstName, String lastName, Long contactNumber, String email, String role, String question, String answer, String status, int extension, String designation, Date dob, Date doj, String newPassword,Long salary, Long variablepay,Long ctc,Long mintarget, Long maxtarget,String targetduration,User reportingId) { super(); this.name = name; this.password = password; this.firstName = firstName; this.lastName = lastName; this.contactNumber = contactNumber; this.email = email; this.role = role; this.question = question; this.answer = answer; this.status = "Active"; this.extension=extension; this.designation=designation; this.dob=dob; this.doj=doj; this.newPassword=newPassword; this.salary=salary; this.variablepay=variablepay; this.ctc=ctc; this.mintarget=mintarget; this.maxtarget=maxtarget; this.targetduration=targetduration; this.reportingId=reportingId; } public User getReportingId() { return reportingId; } public void setReportingId(User reportingId) { this.reportingId = reportingId; } }
package TestJava; public class arthimeticexception { public static void main(String[] args) { int a=10; int b=0; int result=0; try { result=a/b; } catch(ArithmeticException A) { System.out.println("exception is solved"); } System.out.println("result "+result); } }
package com.example.behavioral.strategy; /** * Copyright (C), 2020 * FileName: Strategy * * @author: xieyufeng * @date: 2020/12/8 13:40 * @description: */ public interface Strategy { int doOperation(int num1, int num2); }
package fr.polytech.al.tfc; import fr.polytech.al.tfc.account.model.Account; import fr.polytech.al.tfc.account.model.AccountType; import fr.polytech.al.tfc.account.model.BankAccount; import fr.polytech.al.tfc.account.repository.AccountRepository; import fr.polytech.al.tfc.profile.business.ProfileBusiness; import fr.polytech.al.tfc.profile.model.Profile; import fr.polytech.al.tfc.profile.repository.ProfileRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TfcAccountApplication implements CommandLineRunner { @Autowired private AccountRepository accountRepository; @Autowired private ProfileRepository profileRepository; @Autowired private ProfileBusiness profileBusiness; public static void main(String[] args) { SpringApplication.run(TfcAccountApplication.class, args); } @Override public void run(String... args) { /* if (profileRepository.findAll().isEmpty() && accountRepository.findAll().isEmpty()) { createAccount("mathieu@email", 300); createAccount("florian@email", 500); createAccount("theos@email", 1000); createAccount("gregoire@email", 10000); } if (!profileRepository.existsById("bank") && !accountRepository.existsById("bank")) { Profile bank = new Profile("bank"); Account bankAccount = new BankAccount(); accountRepository.save(bankAccount); bank.addAccount(bankAccount.getAccountId()); profileRepository.save(bank); } */ } private void createAccount(String email, int amount) { profileBusiness.saveProfileWithAccount(new Profile(email), new Account(amount, AccountType.CHECK)); } }
package com.mfm_app.services; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mfm_app.entities.Exercise; import com.mfm_app.repo.ExerciseRepository; @Service public class ExerciseService { @Autowired ExerciseRepository er; public String[] get_all_exercises() { List<Exercise> exercises = new ArrayList<>(); try { exercises = er.findAll(); } catch (Exception e) { e.printStackTrace(); } String[] ex_arr = new String[exercises.size()]; int i =0; for(Exercise exercise: exercises ) { ex_arr[i] = exercise.getName(); i++; } return ex_arr; } public boolean add_exercise(Exercise exercise) { Boolean return_value = false; try { er.save(exercise); return_value = true; }catch(Exception e) { e.printStackTrace(); } return return_value; } }
package com.diozero.sbc; /* * #%L * Organisation: diozero * Project: diozero - Core * Filename: BoardInfo.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import com.diozero.internal.spi.MmapGpioInterface; /** * Information about the connected SBC. Note that the connected board instance * might be a remote device, e.g. connected via serial, Bluetooth or TCP/IP. The * BoardInfo instance for the connected device must be obtained by calling * {@link com.diozero.internal.spi.NativeDeviceFactoryInterface#getBoardInfo() * getBoardInfo()} the on the * {@link com.diozero.internal.spi.NativeDeviceFactoryInterface * NativeDeviceFactoryInterface} instance returned from * {@link DeviceFactoryHelper#getNativeDeviceFactory()}. */ @SuppressWarnings("static-method") public abstract class BoardInfo extends BoardPinInfo { public static final String UNKNOWN = "unknown"; public static final float UNKNOWN_ADC_VREF = -1; private String make; private String model; private int memoryKb; private String osId; private String osVersion; public BoardInfo(String make, String model, int memoryKb, String osId, String osVersion) { this.make = make; this.model = model; this.memoryKb = memoryKb; this.osId = osId; this.osVersion = osVersion; } /** * Pin initialisation is done separately to the constructor since all known * BoardInfo instances get instantiated on startup by the Java ServiceLoader. */ public abstract void populateBoardPinInfo(); /** * The make of the connected board, e.g. "Raspberry Pi" * * @return the make of the connected board */ public String getMake() { return make; } /** * The model of the connected board, e.g. "3B+" * * @return the model of the connected board */ public String getModel() { return model; } /** * Get the memory (in KB) of the connected board * * @return memory in KB */ public int getMemoryKb() { return memoryKb; } public String getOperatingSystemId() { return osId; } public String getOperatingSystemVersion() { return osVersion; } /** * Get the name of this board - usual a concatenation of make and model * * @return the name of this board */ public String getName() { return make + " " + model; } public String getLongName() { return getName(); } /** * Compare make and model * * @param make2 the make to compare * @param model2 the model to compare * @return true if the make and model are the same */ public boolean compareMakeAndModel(String make2, String model2) { return this.make.equals(make2) && this.model.equals(model2); } /** * Instantiate the memory mapped GPIO interface for this board. Not that the * caller needs to call {@link MmapGpioInterface#initialise initialise} prior to * use. * * @return the MMAP GPIO interface implementation for this board, null if there * isn't one */ public MmapGpioInterface createMmapGpio() { return null; } @Override public String toString() { return "BoardInfo [make=" + make + ", model=" + model + ", memory=" + memoryKb + "]"; } }
package com.niesens.soccersubhelper.engine; public enum AgeGroup { U6(32, 3), U8(40, 4); private final int gameLengthMinutes; private final int gameNumOfPlayers; AgeGroup(int gameLengthMinutes, int gameNumOfPlayers) { this.gameLengthMinutes = gameLengthMinutes; this.gameNumOfPlayers = gameNumOfPlayers; } public int getGameLengthMinutes() { return gameLengthMinutes; } public int getGameNumOfPlayers() { return gameNumOfPlayers; } }
package com.sinata.rwxchina.component_aboutme.contract; import com.sinata.rwxchina.basiclib.utils.rxUtils.BaseContract; import java.io.File; import java.util.List; import java.util.Map; /** * @author:zy * @detetime:2017/11/27 * @describe:类描述 * @modifyRecord:修改记录 */ public interface UpdatePersonalInfoContract { interface View extends BaseContract.BaseView{ void showView (String s); } interface Presenter<T> extends BaseContract.BasePresenter<T>{ void updateInfo(Map<String,String> params, List<File> files); } }
package commandline.language; import commandline.exception.ArgumentNullException; import commandline.language.parser.GenericCommandParser; import commandline.language.syntax.CommandSyntaxValidator; import org.jetbrains.annotations.NotNull; /** * User: gno, Date: 09.07.13 - 14:22 */ public class CommandLineLanguage { @NotNull private final CommandSyntaxValidator syntaxValidator; @NotNull private final GenericCommandParser genericCommandParser; public CommandLineLanguage(@NotNull CommandSyntaxValidator syntaxValidator, @NotNull GenericCommandParser genericCommandParser) { super(); if (syntaxValidator == null) { throw new ArgumentNullException(); } if (genericCommandParser == null) { throw new ArgumentNullException(); } this.syntaxValidator = syntaxValidator; this.genericCommandParser = genericCommandParser; } @NotNull public CommandSyntaxValidator getSyntaxValidator() { return this.syntaxValidator; } @NotNull public GenericCommandParser getGenericCommandParser() { return this.genericCommandParser; } }
/** * 234. Palindrome Linked List * Easy */ public class Solution { public boolean isPalindrome(ListNode head) { ListNode fhead = new ListNode(-1); ListNode slow = head, fast = head, t; boolean isOdd = false; while (slow != null && fast != null) { t = slow; slow = slow.next; fast = fast.next; if (fast != null) { fast = fast.next; } else { isOdd = true; } t.next = fhead.next; fhead.next = t; } ListNode p = fhead.next, q = slow; if (isOdd) { p = p.next; } while (p != null && q != null) { if (p.val != q.val) { break; } p = p.next; q = q.next; } return p == null && q == null; } public static void main(String[] args) { int[][] nums = { { 1, 2, 2, 1 }, { 1 }, { 1, 2 } }; Solution s = new Solution(); for (int i = 0; i < nums.length; i++) { ListNode head = new ListNode(nums[i][0]), p = head; for (int j = 1; j < nums[i].length; j++) { p.next = new ListNode(nums[i][j]); p = p.next; } System.out.println(s.isPalindrome(head)); } } } // Definition for singly-linked list. class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } }
package edu.buffalo.cse.sql.util; import java.util.ArrayList; import edu.buffalo.cse.sql.Schema; import edu.buffalo.cse.sql.data.Datum; import edu.buffalo.cse.sql.data.Datum.CastError; public class TableView { public void show(ArrayList<Datum[]> data, ArrayList<Schema.Var> var) throws CastError{ ArrayList<Integer> field=new ArrayList<Integer>(); for(int i=0;i<var.size();i++){ int max=0; if(data.get(0)[i].getType()==Schema.Type.STRING){ for(int d=0;d<data.size();d++){ if(data.get(d)[i].toString().length()>max){ if(var.get(i).name.length()>max){ max=var.get(i).name.length(); } else{ max=data.get(d)[i].toString().length(); } } } field.add(max+4); continue; } if(data.get(data.size()-1)[i].toString().length()>=var.get(i).name.toString().length()){ field.add(data.get(data.size()-1)[i].toString().length()+4); } else{ field.add(var.get(i).name.toString().length()); } } for(int i=0;i<var.size();i++){ int n; for(n=0;n<(field.get(i)-var.get(i).name.length())/2;n++){ System.out.print(" "); } System.out.print(var.get(i).name); for(int j=0;j<field.get(i)-var.get(i).name.length()-n;j++){ System.out.print(" "); } System.out.print("|"); } System.out.println(); for(int i=0;i<=var.size();i++){ System.out.print("--------------------"); } System.out.println(); for(int i=0;i<data.size();i++){ for(int j=0;j<var.size();j++){ int n; for(n=0;n<(field.get(j)-data.get(i)[j].toString().length())/2;n++){ System.out.print(" "); } System.out.print(data.get(i)[j].toString()); for(int k=0;k<(field.get(j)-data.get(i)[j].toString().length())-n;k++){ System.out.print(" "); } System.out.print("|"); } System.out.println(); } } public void show(ArrayList<Datum[]> data, ArrayList<Schema.Var> var,int num) throws CastError{ ArrayList<Integer> field=new ArrayList<Integer>(); for(int i=0;i<var.size();i++){ int max=0; if(data.get(0)[i].getType()==Schema.Type.STRING){ for(int d=0;d<num;d++){ if(data.get(d)[i].toString().length()>max){ if(var.get(i).name.length()>max){ max=var.get(i).name.length(); } else{ max=data.get(d)[i].toString().length(); } } } field.add(max+4); continue; } if(data.get(data.size()-1)[i].toString().length()>=var.get(i).name.toString().length()){ field.add(data.get(data.size()-1)[i].toString().length()+4); } else{ field.add(var.get(i).name.toString().length()); } } for(int i=0;i<var.size();i++){ int n; for(n=0;n<(field.get(i)-var.get(i).name.length())/2;n++){ System.out.print(" "); } System.out.print(var.get(i).name); for(int j=0;j<field.get(i)-var.get(i).name.length()-n;j++){ System.out.print(" "); } System.out.print("|"); } System.out.println(); for(int i=0;i<=var.size();i++){ System.out.print("--------------------"); } System.out.println(); for(int i=0;i<num;i++){ for(int j=0;j<var.size();j++){ int n; for(n=0;n<(field.get(j)-data.get(i)[j].toString().length())/2;n++){ System.out.print(" "); } System.out.print(data.get(i)[j].toString()); for(int k=0;k<(field.get(j)-data.get(i)[j].toString().length())-n;k++){ System.out.print(" "); } System.out.print("|"); } System.out.println(); } } }
package calcu; import javax.swing.JOptionPane; public class Ventana1 extends javax.swing.JFrame { Calculadora calcu= new Calculadora(); CalculadoraT Calcu1= new CalculadoraT(); Conversor calcu2=new Conversor(); public Ventana1() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTextField1 = new javax.swing.JTextField(); B1 = new javax.swing.JButton(); B2 = new javax.swing.JButton(); B5 = new javax.swing.JButton(); B4 = new javax.swing.JButton(); B7 = new javax.swing.JButton(); Igual = new javax.swing.JButton(); B9 = new javax.swing.JButton(); B6 = new javax.swing.JButton(); B3 = new javax.swing.JButton(); B0 = new javax.swing.JButton(); jButton12 = new javax.swing.JButton(); jButton13 = new javax.swing.JButton(); B8 = new javax.swing.JButton(); Suma = new javax.swing.JButton(); resta = new javax.swing.JButton(); multiplicacion = new javax.swing.JButton(); division = new javax.swing.JButton(); c = new javax.swing.JButton(); seno = new javax.swing.JButton(); cos = new javax.swing.JButton(); tan = new javax.swing.JButton(); cotan = new javax.swing.JButton(); sec = new javax.swing.JButton(); csc = new javax.swing.JButton(); raiz = new javax.swing.JButton(); log = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); valor = new javax.swing.JTextField(); jComboBox1 = new javax.swing.JComboBox<>(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); ok = new javax.swing.JButton(); Borrar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextField1.setForeground(new java.awt.Color(51, 0, 204)); jTextField1.setCaretColor(new java.awt.Color(51, 255, 51)); jTextField1.setDisabledTextColor(new java.awt.Color(0, 102, 102)); B1.setBackground(new java.awt.Color(204, 255, 255)); B1.setForeground(new java.awt.Color(102, 0, 102)); B1.setText("1"); B1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B1ActionPerformed(evt); } }); B2.setBackground(new java.awt.Color(204, 255, 255)); B2.setForeground(new java.awt.Color(51, 0, 102)); B2.setText("2"); B2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B2ActionPerformed(evt); } }); B5.setBackground(new java.awt.Color(204, 255, 255)); B5.setForeground(new java.awt.Color(51, 0, 102)); B5.setText("5"); B5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B5ActionPerformed(evt); } }); B4.setBackground(new java.awt.Color(204, 255, 255)); B4.setForeground(new java.awt.Color(51, 0, 102)); B4.setText("4"); B4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B4ActionPerformed(evt); } }); B7.setBackground(new java.awt.Color(204, 255, 255)); B7.setForeground(new java.awt.Color(51, 0, 102)); B7.setText("7"); B7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B7ActionPerformed(evt); } }); Igual.setBackground(new java.awt.Color(255, 204, 255)); Igual.setForeground(new java.awt.Color(204, 0, 204)); Igual.setText("="); Igual.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { IgualActionPerformed(evt); } }); B9.setBackground(new java.awt.Color(204, 255, 255)); B9.setForeground(new java.awt.Color(51, 0, 102)); B9.setText("9"); B9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B9ActionPerformed(evt); } }); B6.setBackground(new java.awt.Color(204, 255, 255)); B6.setForeground(new java.awt.Color(51, 0, 102)); B6.setText("6"); B6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B6ActionPerformed(evt); } }); B3.setBackground(new java.awt.Color(204, 255, 255)); B3.setForeground(new java.awt.Color(51, 0, 102)); B3.setText("3"); B3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B3ActionPerformed(evt); } }); B0.setBackground(new java.awt.Color(204, 255, 255)); B0.setForeground(new java.awt.Color(51, 0, 102)); B0.setText("0"); B0.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B0ActionPerformed(evt); } }); jButton12.setText("1"); jButton13.setText("1"); B8.setBackground(new java.awt.Color(204, 255, 255)); B8.setForeground(new java.awt.Color(51, 0, 102)); B8.setText("8"); B8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B8ActionPerformed(evt); } }); Suma.setBackground(new java.awt.Color(255, 204, 255)); Suma.setForeground(new java.awt.Color(204, 0, 204)); Suma.setText("+"); Suma.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SumaActionPerformed(evt); } }); resta.setBackground(new java.awt.Color(255, 204, 255)); resta.setForeground(new java.awt.Color(204, 0, 204)); resta.setText("-"); resta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { restaActionPerformed(evt); } }); multiplicacion.setBackground(new java.awt.Color(255, 204, 255)); multiplicacion.setForeground(new java.awt.Color(204, 0, 204)); multiplicacion.setText("x"); multiplicacion.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { multiplicacionActionPerformed(evt); } }); division.setBackground(new java.awt.Color(255, 204, 255)); division.setForeground(new java.awt.Color(204, 0, 204)); division.setText("/"); division.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { divisionActionPerformed(evt); } }); c.setBackground(new java.awt.Color(255, 204, 255)); c.setForeground(new java.awt.Color(204, 0, 204)); c.setText("c"); c.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cActionPerformed(evt); } }); seno.setText("seno"); seno.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { senoActionPerformed(evt); } }); cos.setText("cos"); cos.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cosActionPerformed(evt); } }); tan.setText("tan"); tan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tanActionPerformed(evt); } }); cotan.setText("cotan"); cotan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cotanActionPerformed(evt); } }); sec.setText("sec"); sec.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { secActionPerformed(evt); } }); csc.setText("csc"); csc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cscActionPerformed(evt); } }); raiz.setText("raiz"); raiz.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { raizActionPerformed(evt); } }); log.setText("log natural"); log.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { logActionPerformed(evt); } }); jLabel1.setText("Medidas"); jLabel2.setText("opciones"); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Unidades a convertir", "Milimetros", "Centimetros", "Pulgadas", "Pies", "Metros", "Yardas", "Kilometros", "Millas" })); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); ok.setText("ok"); Borrar.setText("Borrar"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(ok) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Borrar))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ok) .addComponent(Borrar)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(B1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(B2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(B3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addComponent(Suma, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(resta, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(csc) .addComponent(sec) .addComponent(cotan) .addComponent(tan) .addGroup(layout.createSequentialGroup() .addComponent(cos) .addGap(18, 18, 18) .addComponent(raiz, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(seno) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(log, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(86, 86, 86)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(B4, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B7, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(B5, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B8, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(B6, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B9, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(division, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(multiplicacion, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(10, 10, 10) .addComponent(Igual, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(150, 150, 150) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(114, 114, 114) .addComponent(valor, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(126, 126, 126)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(B0, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton13, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(140, 140, 140) .addComponent(c, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(91, 91, 91)))) .addGroup(layout.createSequentialGroup() .addGap(267, 267, 267) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(B1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Suma, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(resta, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(B4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(B7, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(B5, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(B8, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(B6, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(B9, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(division, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(multiplicacion, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(Igual, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton13, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B0, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(c, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cos) .addComponent(raiz)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(seno) .addComponent(log)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tan) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cotan) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(sec) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(csc))) .addGap(39, 39, 39) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(valor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(39, 39, 39)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void UnidadesdeMedida(){ double resl1; String unidades; //si esta vafcio/ equals igual if(valor.getText().equals("")){ JOptionPane.showMessageDialog(null, "ingrese valor a convertir"); //el focus valor.requestFocus(); }else{ valor.setText(calcu2.getValor()); //metodo pa extraer del combo box unidades=jComboBox1.getSelectedItem().toString(); //condicion que evalua si las unidades es igual a la funcion seleccionada en comobox y si la variable unidades es igual //a unidades a convertir if("Unidades a convertir".equals(unidades)){ JOptionPane.showMessageDialog(null, "selecciona una de las unidades a convertir"); }else{ //con switch se pueden seleccionar en el comobox de acuerdo a la unidad de medida seleccionada switch(unidades){ case "Milimetros": calcu2.calculoM1(unidades); //calcu2.milimetros(jTextArea1.getText()); } } } } private void B1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B1ActionPerformed calcu.agregarNum(1); jTextField1.setText(calcu.getDigito()); }//GEN-LAST:event_B1ActionPerformed private void B2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B2ActionPerformed calcu.agregarNum(2); jTextField1.setText(calcu.getDigito()); }//GEN-LAST:event_B2ActionPerformed private void B5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B5ActionPerformed calcu.agregarNum(5); jTextField1.setText(calcu.getDigito()); }//GEN-LAST:event_B5ActionPerformed private void B4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B4ActionPerformed calcu.agregarNum(4); jTextField1.setText(calcu.getDigito()); }//GEN-LAST:event_B4ActionPerformed private void B7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B7ActionPerformed calcu.agregarNum(7); jTextField1.setText(calcu.getDigito()); }//GEN-LAST:event_B7ActionPerformed private void IgualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IgualActionPerformed jTextField1.setText(""+calcu.calculo(jTextField1.getText()));//de esta manera se muestra el resultado en pantalla //jTextField1.setText(""+Calcu1.calculo(jTextField1.getText()));//de esta manera se muestra el resultado en pantalla }//GEN-LAST:event_IgualActionPerformed private void B9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B9ActionPerformed calcu.agregarNum(9); jTextField1.setText(calcu.getDigito()); }//GEN-LAST:event_B9ActionPerformed private void B6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B6ActionPerformed calcu.agregarNum(6); jTextField1.setText(calcu.getDigito()); }//GEN-LAST:event_B6ActionPerformed private void B3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B3ActionPerformed calcu.agregarNum(3); jTextField1.setText(calcu.getDigito()); }//GEN-LAST:event_B3ActionPerformed private void B0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B0ActionPerformed calcu.agregarNum(0); jTextField1.setText(calcu.getDigito()); }//GEN-LAST:event_B0ActionPerformed private void B8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B8ActionPerformed calcu.agregarNum(8); jTextField1.setText(calcu.getDigito()); }//GEN-LAST:event_B8ActionPerformed private void SumaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SumaActionPerformed calcu.suma(jTextField1.getText()); jTextField1.setText("");//limpia el contenido que este en la caja de texto }//GEN-LAST:event_SumaActionPerformed private void restaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restaActionPerformed calcu.resta(jTextField1.getText()); jTextField1.setText("");//limpia el contenido que este en la caja de texto }//GEN-LAST:event_restaActionPerformed private void multiplicacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_multiplicacionActionPerformed calcu.multiplicacion(jTextField1.getText()); jTextField1.setText("");//limpia el contenido que este en la caja de texto }//GEN-LAST:event_multiplicacionActionPerformed private void divisionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_divisionActionPerformed calcu.division(jTextField1.getText()); jTextField1.setText("");//limpia el contenido que este en la caja de texto }//GEN-LAST:event_divisionActionPerformed private void cActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cActionPerformed //borrar calcu.Borrar(jTextField1.getText()); jTextField1.setText(""); }//GEN-LAST:event_cActionPerformed private void senoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_senoActionPerformed Calcu1.seno(jTextField1.getText()); jTextField1.setText("");//limpia el contenido que este en la caja de texto }//GEN-LAST:event_senoActionPerformed private void cosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cosActionPerformed Calcu1.cos(jTextField1.getText()); jTextField1.setText("");//limpia el contenido que este en la caja de texto }//GEN-LAST:event_cosActionPerformed private void tanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tanActionPerformed Calcu1.tan(jTextField1.getText()); jTextField1.setText("");//limpia el contenido que este en la caja de texto }//GEN-LAST:event_tanActionPerformed private void cotanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cotanActionPerformed Calcu1.cotan(jTextField1.getText()); jTextField1.setText("");//limpia el contenido que este en la caja de texto }//GEN-LAST:event_cotanActionPerformed private void secActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_secActionPerformed Calcu1.sec(jTextField1.getText()); jTextField1.setText("");//limpia el contenido que este en la caja de texto }//GEN-LAST:event_secActionPerformed private void cscActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cscActionPerformed Calcu1.csc(jTextField1.getText()); jTextField1.setText("");//limpia el contenido que este en la caja de texto }//GEN-LAST:event_cscActionPerformed private void raizActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_raizActionPerformed jTextField1.setText("raiz de :"); Calcu1.raiz(jTextField1.getText()); jTextField1.setText(""); }//GEN-LAST:event_raizActionPerformed private void logActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logActionPerformed jTextField1.setText("log natural:"); Calcu1.log(jTextField1.getText()); jTextField1.setText(""); // TODO add your handling code here: }//GEN-LAST:event_logActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Ventana1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Ventana1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Ventana1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Ventana1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Ventana1().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton B0; private javax.swing.JButton B1; private javax.swing.JButton B2; private javax.swing.JButton B3; private javax.swing.JButton B4; private javax.swing.JButton B5; private javax.swing.JButton B6; private javax.swing.JButton B7; private javax.swing.JButton B8; private javax.swing.JButton B9; private javax.swing.JButton Borrar; private javax.swing.JButton Igual; private javax.swing.JButton Suma; private javax.swing.JButton c; private javax.swing.JButton cos; private javax.swing.JButton cotan; private javax.swing.JButton csc; private javax.swing.JButton division; private javax.swing.JButton jButton12; private javax.swing.JButton jButton13; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextField jTextField1; private javax.swing.JButton log; private javax.swing.JButton multiplicacion; private javax.swing.JButton ok; private javax.swing.JButton raiz; private javax.swing.JButton resta; private javax.swing.JButton sec; private javax.swing.JButton seno; private javax.swing.JButton tan; private javax.swing.JTextField valor; // End of variables declaration//GEN-END:variables }
package net.minecraft.network; public final class ThreadQuickExitException extends RuntimeException { public static final ThreadQuickExitException INSTANCE = new ThreadQuickExitException(); private ThreadQuickExitException() { setStackTrace(new StackTraceElement[0]); } public synchronized Throwable fillInStackTrace() { setStackTrace(new StackTraceElement[0]); return this; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\ThreadQuickExitException.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package inter; public class CuttingRod { public static void main(String[] args) { //int[] price = new int[]{2,5,7,8}; int[] price = new int[] { 1, 5, 8, 9, 10, 17, 17, 20 }; int length = 8; int dp[][] = new int[price.length][length + 1]; for (int i = 0; i < price.length; i++) { for (int j = 1; j < length+1; j++) { if (i == 0) { dp[i][j] = j * price[i]; } else { if(j>=i+1) dp[i][j] = Math.max(dp[i - 1][j], price[i] + dp[i][j - i-1]); else{ dp[i][j]=dp[i-1][j]; } } } } System.out.println(dp[price.length - 1][length]); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[0].length; j++) { System.out.print(dp[i][j] + " "); } System.out.println(); } } }