text
stringlengths
10
2.72M
package com.tch.test.august; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class JsoupTest { public static void main(String[] args) throws Exception { Map<String, String> data = new HashMap<>(); data.put("nname", ""); data.put("agentcode", ""); data.put("sex", "0"); data.put("age1", "18"); data.put("age2", "65"); data.put("education", "0"); data.put("atplace", "上海市"); data.put("type", "0"); //data.put("corp", ""); //data.put("corpzj", ""); //data.put("Submit", "下一页"); Document doc = Jsoup .connect("http://www.life-sky.net/sou/index.asp?page=1") .header("Content-Type", "application/x-www-form-urlencoded") .postDataCharset("gb2312") .data(data) .timeout(10000) .post(); Elements elements = doc.select("td.f"); Element element = elements.get(0); Elements fonts = element.select("font[size=\"-1\"]"); for(Element font : fonts){ String content = font.text(); String[] contenArr = content.split(" "); Pattern pattern = Pattern.compile("MP:\\d{11,12}"); Matcher matcher = pattern.matcher(contenArr[5]); System.out.print("姓名:" + contenArr[0]); if(matcher.find()){ System.out.println(", 手机号:" + matcher.group()); } } } }
package com.company; public class Main { public static void main(String[] args) { Dog doggy = new Dog("Krommis", "Male", true); GermanShepherd doggy2 = new GermanShepherd("German Shepherd", "Female", true, true, true); doggy2.eating(); doggy2.bark(); System.out.println("***************"); doggy.move(); doggy.bark(); doggy.eating(); } }
/** * MIT License * <p> * Copyright (c) 2017-2018 nuls.io * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.nuls.crosschain; import io.nuls.base.basic.AddressTool; import io.nuls.base.data.CoinData; import io.nuls.base.data.CoinFrom; import io.nuls.base.data.CoinTo; import io.nuls.base.data.Transaction; import io.nuls.core.crypto.HexUtil; import io.nuls.core.model.StringUtils; import io.nuls.core.parse.JSONUtils; import io.nuls.crosschain.base.model.bo.txdata.CrossTransferData; import org.junit.Test; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author: PierreLuo * @date: 2022/4/18 */ public class CrossTxHashTest { static int nulsChainId = 5; static int nerveChainId = 5; static String rpcAddress = ""; private void setTest() { nulsChainId = 2; nerveChainId = 5; rpcAddress = "http://beta.api.nerve.network/jsonrpc"; } private void setMain() { nulsChainId = 1; nerveChainId = 9; rpcAddress = "https://api.nerve.network/jsonrpc"; } @Test public void test() throws Exception { setTest(); String hash = "ae2aec0316f0e7ad497eb9b1a768de1cb1a8f3fe1cf9a9e51a920883044210a3"; Map resultMap = this.request(rpcAddress, "getTx", List.of(nerveChainId, hash)); Long timestamp = Long.valueOf(resultMap.get("timestamp").toString()); String remark = (String) resultMap.get("remark"); List<Map> froms = (List<Map>) resultMap.get("from"); List<Map> tos = (List<Map>) resultMap.get("to"); if (tos.size() > 1) { throw new RuntimeException("不支持的交易! 原因:CoinTo有多个."); } Transaction tx = new Transaction(); // 组装NULS网络跨链交易的基本信息 tx.setType(10); tx.setTime(timestamp); if (StringUtils.isNotBlank(remark)) { tx.setRemark(remark.getBytes(StandardCharsets.UTF_8)); } // 组装NULS网络跨链交易的txData CrossTransferData txData = new CrossTransferData(); txData.setSourceType(10); txData.setSourceHash(HexUtil.decode(hash)); byte[] txDataBytes = txData.serialize(); tx.setTxData(txDataBytes); // 组装NULS网络跨链交易的CoinData CoinData coinData = new CoinData(); boolean isTransferNVT = false; BigInteger transferAmount = BigInteger.ZERO; for (Map to : tos) { int assetsChainId = Integer.parseInt(to.get("assetsChainId").toString()); int assetsId = Integer.parseInt(to.get("assetsId").toString()); if (assetsChainId == nerveChainId && assetsId == 1) { isTransferNVT = true; } String address = to.get("address").toString(); transferAmount = new BigInteger(to.get("amount").toString()); long lockTime = Long.parseLong(to.get("lockTime").toString()); CoinTo _to = new CoinTo(); _to.setAddress(AddressTool.getAddress(address)); _to.setAssetsChainId(assetsChainId); _to.setAssetsId(assetsId); _to.setAmount(transferAmount); _to.setLockTime(lockTime); coinData.getTo().add(_to); } for (Map from : froms) { int assetsChainId = Integer.parseInt(from.get("assetsChainId").toString()); int assetsId = Integer.parseInt(from.get("assetsId").toString()); BigInteger amount = new BigInteger(from.get("amount").toString()); // 排除 NERVE链的NVT手续费 if (assetsChainId == nerveChainId && assetsId == 1) { if (!isTransferNVT) { continue; } else { amount = transferAmount; } } String address = from.get("address").toString(); String nonce = from.get("nonce").toString(); int locked = Integer.parseInt(from.get("locked").toString()); CoinFrom _from = new CoinFrom(); _from.setAddress(AddressTool.getAddress(address)); _from.setAssetsChainId(assetsChainId); _from.setAssetsId(assetsId); _from.setAmount(amount); _from.setNonce(HexUtil.decode(nonce)); _from.setLocked((byte) locked); coinData.getFrom().add(_from); } tx.setCoinData(coinData.serialize()); System.out.println(String.format("NULS网络的交易hash: %s", tx.getHash().toString())); } private Map request(String requestURL, String method, List<Object> params) throws Exception { Map<String, Object> paramMap = new HashMap<>(); paramMap.put("jsonrpc", "2.0"); paramMap.put("method", method); paramMap.put("params", params); paramMap.put("id", "1234"); String response = HttpClientUtil.post(requestURL, paramMap); if (StringUtils.isBlank(response)) { System.err.println("未能得到返回数据"); return null; } Map<String, Object> map = JSONUtils.json2map(response); Map<String, Object> resultMap = (Map<String, Object>) map.get("result"); if (null == resultMap) { System.err.println(map.get("error")); return null; } return resultMap; } }
package com.unisports.bl; import com.unisports.dao.TeamDAO; import com.unisports.entities.Team; import java.util.List; import java.util.UUID; import javafx.util.Pair; public class TeamBL { TeamDAO _teamDao; public TeamBL() { _teamDao = new TeamDAO(); } public Team GetTeamById(UUID id) { Team team = new Team(); return _teamDao.getTeamById(team.getId()); } public Pair<Boolean, String> SaveTeam(Team team) { if (team.getName().isEmpty()) { return new Pair<>(false, "El nombre es requerido"); } else if (team.getSportId() == null) { return new Pair<>(false, "El deporte es requerido"); } if (_teamDao.createTeam(team)) { return new Pair<>(true, ""); } return new Pair<>(false, "Error guardando el equipo"); } public boolean UpdateTeam(Team team) { return true; } public List<Team> GetAllTeamsByUserId(UUID id) { return _teamDao.getAllTeam(); } public boolean GetTeamsByName(String word) { return true; } public boolean UploadTeamPhoto(String photo) { return true; } public boolean DeleteTeam(UUID teamId) { return true; } public boolean GetAllUserInscriptionByUserId(UUID id) { return true; } private boolean SendConfirmationEmail(UUID userId) { return true; } public List<Team> GetAllTeams() { return _teamDao.getAllTeam(); } }
package com.eomcs.basic.ex05; //# 증감 연산자 : 후위(post-fix) 증가 연산자 // public class Exam0610 { public static void main(String[] args) { int i = 2; //증갑연산자가 없다면 //기존 변수의 값을 1증가시키기 위해 다음과 같이 코딩해야 한다. // i = i + 1; //증감연산자를 사용하면 다음과 같이 간단하게 작성할 수 있다. i++; // 3 // 현재 위치에 i 메모리에 들어 있는 값을 꺼내 놓는다. // i 메모리의 값을 1 증가시킨다. i++; // 4 System.out.println(i); // 4 System.out.println(i++); // 4 지만 다음 i는 5 // System.out.println(4); // i = i + 1; System.out.println(++i); //(전위 연산자) i는 5에다 전위연산자라 1을 더해 6 System.out.println(i); //i 는 6 } }
package com.example.imgurimagesearch.data.localdatabase; import androidx.room.Database; import androidx.room.RoomDatabase; import com.example.imgurimagesearch.data.localdatabase.Dao.ICommentsDao; import com.example.imgurimagesearch.data.localdatabase.Entity.CommentsEntity; @Database(entities = {CommentsEntity.class},version = 1,exportSchema = false) public abstract class CommentsDatabase extends RoomDatabase { public abstract ICommentsDao getCommentsDao(); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.airportservice; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import com.mycompany.airportservice.exceptions.WebException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; /** * * @author User */ @RestController @RequestMapping("/api") public class WeatherController { @Autowired ScheduleRepository scheduleRepository; private RestTemplate restTemplate = new RestTemplate(); @GetMapping(value = "/weathers") public ResponseEntity<Weather[]> getAllWeathers(){ try{ return restTemplate.getForEntity("http://app2:5000/locations", Weather[].class); } catch(Exception e){ return null; } } @GetMapping(value = "/weathers/{id}") public Weather getWeatherById(@PathVariable(value = "id") Long weatherId){ Weather result = null; try{ result = restTemplate.getForObject("http://app2:5000/locations/" + weatherId, Weather.class); } catch(Exception e){ if(!e.getMessage().contains("I/O error")){ throw new WebException("GET api/weathers", "- no weather found"); } } return result; } @DeleteMapping(value = "/weathers/{id}") public ResponseEntity<?> deleteWeather(@PathVariable(value = "id") Long weatherId){ try{ restTemplate.delete("http://app2:5000/locations/" + weatherId); List<Schedule> schedules = scheduleRepository.findAll(); Schedule schedule; for (int i = 0; i < schedules.size(); i++){ schedule = schedules.get(i); if(schedule.getWeatherId() == weatherId){ schedule.setWeatherId(null); schedule.setWeather(null); scheduleRepository.save(schedule); } } return ResponseEntity.noContent().build(); } catch(Exception e){ if(!e.getMessage().contains("I/O error")){ throw new WebException("DELETE api/weathers/id", "- no weather found"); } } return ResponseEntity.noContent().build(); } }
package org.fmedlin.camper; import android.app.Application; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import com.fmedlin.intentbuilder.BuildConfig; import org.fmedlin.camper.IntentBuilder.ExplicitIntentBuilder; import org.fmedlin.camper.IntentBuilder.ImplicitIntentBuilder; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.res.builder.RobolectricPackageManager; import org.robolectric.shadows.ShadowApplication; import java.io.Serializable; import java.util.Arrays; import static org.assertj.android.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.robolectric.Shadows.shadowOf; @RunWith(RobolectricTestRunner.class) @Config(sdk = 23, constants = BuildConfig.class, manifest=Config.NONE) public class IntentBuilderTest { TestActivity activity; @Before public void setUp() { activity = Robolectric.buildActivity(TestActivity.class).create().get(); } @Test public void testStartActivityWithExplicitIntent() { Intent intent = IntentBuilder.start(TargetActivity.class) .from(RuntimeEnvironment.application) .assertType(ExplicitIntentBuilder.class) .execute(); assertThat(ShadowApplication.getInstance().getNextStartedActivity()).isEqualTo(intent); } @Test public void testExtraSetters() { CharSequence cs = "charsequence"; CharSequence[] csa = new CharSequence[] { "cs1", "cs2", "cs3"}; Intent intent = IntentBuilder.with(RuntimeEnvironment.application) .action("intent action") .type("text/plain") .extra("byte extra", (byte) 0x21) .extra("byte array extra", new byte[] {(byte) 0xaa, (byte) 0xbb}) .extra("char extra", 'c') .extra("char array extra", new char[] {'a', 'b', 'c'}) .extra("string extra", "string") .extra("string array extra", new String[] {"first", "second", "third"}) .extra("cs extra", cs) .extra("cs array extra", csa) .extra("short extra", (short) 8) .extra("short array extra", new short[] {82, 83, 84}) .extra("int extra", 1) .extra("int array extra", new int[] {42, 43, 44}) .extra("long extra", 2L) .extra("long array extra", new long[] {2L, 3L}) .extra("float extra", 3f) .extra("float array extra", new float[] {4f, 5f, 6f}) .extra("double extra", 0.5) .extra("double array extra", new double[] {0.1, 0.2, 0.3}) .extra("boolean extra", true) .extra("boolean array extra", new boolean[] {true, true, false, true}) .extra("serializable extra", (Serializable) "serialized") .extra("parcelable extra", Uri.parse("http://google.com")) .extra("parcelable array extra", new Parcelable[]{ Uri.parse("http://google.com"), Uri.parse("http://apple.com")}) .extraListOfString("string list extra", Arrays.asList("first", "second", "third")) .extraListOfCharSequence("cs list extra", Arrays.asList(csa)) .extraListOfInteger("integer list extra", Arrays.asList(51, 52, 53)) .extraListOfParcelable("parcelable list extra", Arrays.asList((Parcelable) Uri.parse("http://google.com"), Uri.parse("http://apple.com"))) .build(); assertThat(intent).hasAction("intent action") .hasType("text/plain") .hasExtra("byte extra", (byte) 0x21) .hasExtra("byte array extra", new byte[] {(byte) 0xaa, (byte) 0xbb}) .hasExtra("char extra", 'c') .hasExtra("char array extra", new char[] {'a', 'b', 'c'}) .hasExtra("string extra", "string") .hasExtra("string array extra", new String[] {"first", "second", "third"}) .hasExtra("cs extra", "charsequence") .hasExtra("cs array extra", new CharSequence[] { "cs1", "cs2", "cs3"}) .hasExtra("short extra", (short) 8) .hasExtra("short array extra", new short[] {82, 83, 84}) .hasExtra("int extra", 1) .hasExtra("int array extra", new int[] {42,43, 44}) .hasExtra("long extra", 2L) .hasExtra("long array extra", new long[] {2L, 3L}) .hasExtra("float extra", 3f) .hasExtra("float array extra", new float[] {4f, 5f, 6f}) .hasExtra("double extra", 0.5) .hasExtra("double array extra", new double[] {0.1, 0.2, 0.3}) .hasExtra("boolean extra", true) .hasExtra("boolean array extra", new boolean[] {true, true, false, true}) .hasExtra("serializable extra", "serialized") .hasExtra("parcelable extra", Uri.parse("http://google.com")) .hasExtra("parcelable array extra", new Parcelable[]{ Uri.parse("http://google.com"), Uri.parse("http://apple.com")}) .hasExtra("string list extra", Arrays.asList("first", "second", "third")) .hasExtra("cs list extra", Arrays.asList(csa)) .hasExtra("integer list extra", Arrays.asList(51, 52, 53)) .hasExtra("parcelable list extra", Arrays.asList(Uri.parse("http://google.com"), Uri.parse("http://apple.com"))); } @Test public void testBundleExtra() { Bundle b = new Bundle(); b.putString("string extra", "bundle value"); Intent intent = IntentBuilder.with(RuntimeEnvironment.application) .action("intent action") .extra("bundle extra", b) .build(); assertThat(intent).hasAction("intent action") .hasExtra("bundle extra", b); } @Test public void testExtras() { Intent extraIntent = IntentBuilder.with(RuntimeEnvironment.application) .action("intent action") .extra("first", 1) .extra("second", 2) .build(); Bundle extraBundle = new Bundle(); extraBundle.putInt("one", 1); extraBundle.putInt("two", 2); Intent intent = IntentBuilder.with(RuntimeEnvironment.application) .action("intent action") .extras(extraIntent) .extras(extraBundle) .build(); assertThat(intent).hasAction("intent action") .hasExtra("first", 1) .hasExtra("second", 2) .hasExtra("one", 1) .hasExtra("two", 2); } @Test public void testWhenDataShouldOverrideExistingType() { // Type is applied after data, so it will not be lost. Order doesn't matter. Intent intent = IntentBuilder.with(Uri.parse("http://theworld.org")) .action(Intent.ACTION_VIEW) .type("text/plain") .data(Uri.parse("http://google.com")) .build(); assertThat(intent).hasType("text/plain"); // DataAndType trumps individual data and type setters. Order doesn't matter. intent = IntentBuilder.with(Uri.parse("http://theworld.org")) .action(Intent.ACTION_VIEW) .type("text/plain") .dataAndType(Uri.parse("http://google.com"), "audio/*") .build(); assertThat(intent).hasType("audio/*"); } @Test public void testImplicitIntent() { Intent intent = IntentBuilder.with(Intent.ACTION_VIEW, Uri.parse("http://google.com")) .extra("string extra", "string") .assertType(ImplicitIntentBuilder.class) .build(); RuntimeEnvironment.application.startActivity(intent); assertThat(ShadowApplication.getInstance().getNextStartedActivity()).isEqualTo(intent); } @Test public void testImplicitActionIntent() { Intent intent = IntentBuilder.with(Intent.ACTION_VIEW) .extra("string extra", "string") .assertType(ImplicitIntentBuilder.class) .build(); RuntimeEnvironment.application.startActivity(intent); assertThat(ShadowApplication.getInstance().getNextStartedActivity()).isEqualTo(intent); } @Test(expected = IllegalArgumentException.class) public void testImplicitIntentRequiresAction() { IntentBuilder.with(Uri.parse("http://google.com")).build(); } @Test public void testCopyConstructor() { Intent original = new Intent(); Intent copy = IntentBuilder.copy(original).build(); assertThat(original).isNotEqualTo(copy); } @Ignore public void testChooserExecution() { setupResolver(Intent.ACTION_SEND); Application app = RuntimeEnvironment.application; IntentBuilder.with(Intent.ACTION_SEND) .chooser("Pick me") .execute(app.getApplicationContext(), app.getPackageManager()) .onResolveFailure(new ResolveFailure() { @Override public void onFail() { fail("Should not have failed activity resolution"); } }); Intent intent = shadowOf(RuntimeEnvironment.application).getNextStartedActivity(); assertThat(intent).hasAction(Intent.ACTION_CHOOSER); } @Test public void testChooserBuilding() { Intent chooser = IntentBuilder.with(Intent.ACTION_SEND) .chooser("Pick me") .build(); assertThat(chooser).hasAction(Intent.ACTION_CHOOSER); } private void setupResolver(String action) { Intent intent = new Intent(action); RobolectricPackageManager pm = RuntimeEnvironment.getRobolectricPackageManager(); ResolveInfo resolveInfo = new ResolveInfo(); try { resolveInfo.activityInfo = pm.getActivityInfo(activity.getComponentName(), 0); } catch (NameNotFoundException e) { fail(e.getMessage()); } pm.addResolveInfoForIntent(intent, resolveInfo); } }
package hu.mentlerd.hybrid.asm; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) /* * A method is considered special if it returns multiple values, or requires * direct access to the call frame and argument count. In this case the @LuaMethod * annotation is placed to alert the compiler about this behavior. * * Apart from the annotation, the following rules apply: * - The only parameter is CallFrame * - The method returns an integer value * * If any of these rules don't apply, the compiler will ignore the special * behavior request, and will warn the developer */ public @interface LuaMethod { }
package com.contract.system.controller; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.contract.system.model.Booking; import com.contract.system.model.Contract; import com.contract.system.model.Customer; import com.contract.system.model.Performance; import com.contract.system.model.Service; import com.contract.system.model.Slot; import com.contract.system.model.Tax; import com.contract.system.model.User; import com.contract.system.model.Venue; import com.contract.system.service.BookingService; import com.contract.system.service.ContractService; import com.contract.system.service.CustomerService; import com.contract.system.service.PerformanceService; import com.contract.system.service.SecurityService; import com.contract.system.service.ServiceService; import com.contract.system.service.SlotService; import com.contract.system.service.TaxService; import com.contract.system.service.UserService; import com.contract.system.service.VenueService; import com.contract.system.validator.UserValidator; @Controller public class MainController{ @Autowired private UserService userService; @Autowired private ServiceService serviceService; @Autowired private SlotService slotService; @Autowired private VenueService venueService; @Autowired private TaxService taxService; @Autowired private CustomerService customerService; @Autowired private ContractService contractService; @Autowired private SecurityService securityService; @Autowired private UserValidator userValidator; @Autowired private PerformanceService performanceService; @Autowired private BookingService bookingService; @RequestMapping(value = "/registration", method = RequestMethod.GET) public String registration(Model model){ model.addAttribute("userForm", new User()); return "registration"; } @RequestMapping(value = "/registration", method = RequestMethod.POST) public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) { userValidator.validate(userForm, bindingResult); if (bindingResult.hasErrors()) { return "registration"; } userService.save(userForm); securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm()); return "redirect:/welcome"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(Model model, String error, String logout) { if (error != null) model.addAttribute("error", "Your username and password is invalid."); if (logout != null) model.addAttribute("message", "You have been logged out successfully."); return "login"; } @RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET) public String welcome(Model model) { Date date= new Date(); model.addAttribute("day", new SimpleDateFormat("EEEE").format(date)); model.addAttribute("date", new SimpleDateFormat("dd-MM-yyyy '|' hh:mm:ss a '|' zzz").format(date)); model.addAttribute("location", "Delhi, India"); model.addAttribute("noofCustomer", customerService.getTotal()); model.addAttribute("noofContract", contractService.getTotal()); model.addAttribute("revenue", contractService.getSumAmount()); model.addAttribute("invoicecount", null); return "welcome"; } /* Contract Controller */ @RequestMapping("/contract") public String contract(HttpServletRequest request) { request.setAttribute("allcustomer", customerService.findName()); request.setAttribute("allservices", serviceService.findName()); return "contract"; } @RequestMapping(value = "/save-contract", method = RequestMethod.GET) public String saveContract( Model model, @ModelAttribute Contract contract, @ModelAttribute Performance performance, @ModelAttribute Booking booking, @RequestParam String cname) { System.out.println(cname); Customer customer = customerService.findCustomer(cname); System.out.println("Customer : " +customer); System.out.println("Performance : "+performance); contract.setCustomer(customer); performance.setContract(contract); performanceService.save(performance); booking.setContract(contract); bookingService.save(booking); // contract.setBookings(bookings); // contract.setPerformances(performances); contractService.save(contract); return "contract"; } @RequestMapping("/booking") public String booking(HttpServletRequest request) { request.setAttribute("allcustomer", customerService.getCustomer()); return "booking"; } @RequestMapping(value = "/searchService", method = RequestMethod.POST) public @ResponseBody String searchService(HttpServletRequest request, @RequestParam("service") String service) { System.out.print("Service layer : "+service); String s = "abcdef"; return s; } /* Employee controller */ @RequestMapping(value = "/employee", method = RequestMethod.POST) public String employee(BindingResult bindingResult, Model model) { return "redirect:/welcome"; } /* Receipt Controller*/ @RequestMapping(value = "/receipt", method = RequestMethod.GET) public String receipt(BindingResult bindingResult, Model model) { return "receipt"; } /* Invoice Controller */ @RequestMapping(value = "/invoice", method = RequestMethod.GET) public String invoice( Model model, HttpServletResponse response) { List l = new ArrayList(); Slot c = new Slot(); c.setSlotid(1); c.setStarttime("2015-11-28"); c.setEndtime("2015-11-29"); c.setSlotname("Task in Progress"); Slot d = new Slot(); d.setSlotid(2); d.setStarttime("2013-07-26"); d.setEndtime("2013-08-28"); d.setSlotname("Task in Progress"); l.add(c); l.add(d); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); // PrintWriter out = response.getWriter(); // out.write(new Gson().toJson(l)); return "invoice"; } /* Service Controller */ @RequestMapping(value = "/service", method = RequestMethod.GET) public String service( Model model, HttpServletRequest request){ request.setAttribute("allservice", serviceService.getService()); request.setAttribute("allvenue", venueService.findVenue()); request.setAttribute("allslot", slotService.findSlot()); request.setAttribute("allsaccode", taxService.getAllSaccode()); return "service"; } @RequestMapping(value = "/saveService", method = RequestMethod.GET) public String saveService( Model model, @ModelAttribute("serviceForm") Service service) { serviceService.save(service); return "service"; } /* Invoice Controller */ @RequestMapping(value = "/venue", method = RequestMethod.GET) public String venue( Model model, HttpServletRequest request) { request.setAttribute("allvenue", venueService.getAllVenue()); return "venue"; } @RequestMapping(value = "/saveVenue", method = RequestMethod.GET) public String saveVenue( Model model, @ModelAttribute("venueForm") Venue venue) { venueService.save(venue); return "venue"; } /* Invoice Controller */ @RequestMapping("/slot") public String slot(HttpServletRequest request) { request.setAttribute("allslot", slotService.getSlot()); return "slot"; } @RequestMapping(value = "/saveSlot", method = RequestMethod.GET) public String saveSlot( Model model, @ModelAttribute("slotForm") Slot slot) { slotService.save(slot); return "slot"; } /* Tax Controller */ @RequestMapping("/tax") public String tax(HttpServletRequest request) { request.setAttribute("alltax", taxService.getTax()); return "tax"; } @RequestMapping(value = "/saveTax", method = RequestMethod.GET) public String saveTax( Model model, @ModelAttribute("taxForm") Tax tax) { taxService.save(tax); return "tax"; } /* Customer Controller */ @RequestMapping("/customer") public String customer(HttpServletRequest request) { request.setAttribute("allcustomer", customerService.getCustomer()); return "customer"; } @RequestMapping(value = "/saveCustomer", method = RequestMethod.POST) public String saveCustomer( Model model, @ModelAttribute("customerForm") Customer customer) { customerService.save(customer); return "customer"; } }
package com.ypeksen.mvc.dao; import com.ypeksen.mvc.model.User; public interface UserDao { User findAuthenticatedUserByEmail(String email); User findByEmail(String email); void save(User user); }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.03.27 at 10:31:23 AM EDT // package org.geosamples.samples; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for MineralDetails1. <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="MineralDetails1"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="Abelsonite"/&gt; * &lt;enumeration value="Abenakiite-(Ce)"/&gt; * &lt;enumeration value="Abernathyite"/&gt; * &lt;enumeration value="Abhurite"/&gt; * &lt;enumeration value="Abswurmbachite"/&gt; * &lt;enumeration value="Acanthite"/&gt; * &lt;enumeration value="Acetamide"/&gt; * &lt;enumeration value="Actinolite"/&gt; * &lt;enumeration value="Acuminite"/&gt; * &lt;enumeration value="Adamite"/&gt; * &lt;enumeration value="Adamsite-(Y)"/&gt; * &lt;enumeration value="Adelite"/&gt; * &lt;enumeration value="Admontite"/&gt; * &lt;enumeration value="Aegirine"/&gt; * &lt;enumeration value="Aenigmatite"/&gt; * &lt;enumeration value="Aerinite"/&gt; * &lt;enumeration value="Aerugite"/&gt; * &lt;enumeration value="Aeschynite"/&gt; * &lt;enumeration value="Aeschynite-(Ce)"/&gt; * &lt;enumeration value="Aeschynite-(Nd)"/&gt; * &lt;enumeration value="Aeschynite-(Y)"/&gt; * &lt;enumeration value="Afghanite"/&gt; * &lt;enumeration value="Afwillite"/&gt; * &lt;enumeration value="Agardite"/&gt; * &lt;enumeration value="Agardite-(La)"/&gt; * &lt;enumeration value="Agardite-(Y)"/&gt; * &lt;enumeration value="Agrellite"/&gt; * &lt;enumeration value="Agrinierite"/&gt; * &lt;enumeration value="Aguilarite"/&gt; * &lt;enumeration value="Aheylite"/&gt; * &lt;enumeration value="Ahlfeldite"/&gt; * &lt;enumeration value="Aikinite"/&gt; * &lt;enumeration value="Ajoite"/&gt; * &lt;enumeration value="Akaganeite"/&gt; * &lt;enumeration value="Akatoreite"/&gt; * &lt;enumeration value="Akdalaite"/&gt; * &lt;enumeration value="Akermanite"/&gt; * &lt;enumeration value="Akhtenskite"/&gt; * &lt;enumeration value="Akimotoite"/&gt; * &lt;enumeration value="Akrochordite"/&gt; * &lt;enumeration value="Aksaite"/&gt; * &lt;enumeration value="Aktashite"/&gt; * &lt;enumeration value="Alabandite"/&gt; * &lt;enumeration value="Alacranite"/&gt; * &lt;enumeration value="Alamosite"/&gt; * &lt;enumeration value="Alarsite"/&gt; * &lt;enumeration value="Albite"/&gt; * &lt;enumeration value="Albrechtschraufite"/&gt; * &lt;enumeration value="Aldermanite"/&gt; * &lt;enumeration value="Aldzhanite"/&gt; * &lt;enumeration value="Aleksite"/&gt; * &lt;enumeration value="Alforsite"/&gt; * &lt;enumeration value="Algodonite"/&gt; * &lt;enumeration value="Aliettite"/&gt; * &lt;enumeration value="AllMinerals"/&gt; * &lt;enumeration value="Allactite"/&gt; * &lt;enumeration value="Allanite"/&gt; * &lt;enumeration value="Allanite-(Ce)"/&gt; * &lt;enumeration value="Allanite-(La)"/&gt; * &lt;enumeration value="Allanite-(Y)"/&gt; * &lt;enumeration value="Allargentum"/&gt; * &lt;enumeration value="Alleghanyite"/&gt; * &lt;enumeration value="Alloclasite"/&gt; * &lt;enumeration value="Allophane"/&gt; * &lt;enumeration value="Alluaivite"/&gt; * &lt;enumeration value="Alluaudite"/&gt; * &lt;enumeration value="Almandine"/&gt; * &lt;enumeration value="Alstonite"/&gt; * &lt;enumeration value="Altaite"/&gt; * &lt;enumeration value="Althausite"/&gt; * &lt;enumeration value="Althupite"/&gt; * &lt;enumeration value="Altisite"/&gt; * &lt;enumeration value="Alum(GeneralTerm)"/&gt; * &lt;enumeration value="Aluminite"/&gt; * &lt;enumeration value="Aluminium"/&gt; * &lt;enumeration value="Aluminoceladonite"/&gt; * &lt;enumeration value="Aluminocopiapite"/&gt; * &lt;enumeration value="Aluminokatophorite"/&gt; * &lt;enumeration value="Aluminotschermakite"/&gt; * &lt;enumeration value="Aluminum"/&gt; * &lt;enumeration value="Alumohydrocalcite"/&gt; * &lt;enumeration value="Alumoklyuchevskite"/&gt; * &lt;enumeration value="Alumopharmacosiderite"/&gt; * &lt;enumeration value="Alumotantite"/&gt; * &lt;enumeration value="Alumotungstite"/&gt; * &lt;enumeration value="Alunite"/&gt; * &lt;enumeration value="Alunogen"/&gt; * &lt;enumeration value="Alvanite"/&gt; * &lt;enumeration value="Amakinite"/&gt; * &lt;enumeration value="Amalgam"/&gt; * &lt;enumeration value="Amarantite"/&gt; * &lt;enumeration value="Amarillite"/&gt; * &lt;enumeration value="Amber"/&gt; * &lt;enumeration value="Amblygonite"/&gt; * &lt;enumeration value="Ameghinite"/&gt; * &lt;enumeration value="Amesite"/&gt; * &lt;enumeration value="Amicite"/&gt; * &lt;enumeration value="Aminoffite"/&gt; * &lt;enumeration value="Ammonioalunite"/&gt; * &lt;enumeration value="Ammonioborite"/&gt; * &lt;enumeration value="Ammoniojarosite"/&gt; * &lt;enumeration value="Ammonioleucite"/&gt; * &lt;enumeration value="AmphiboleGroup"/&gt; * &lt;enumeration value="Amstallite"/&gt; * &lt;enumeration value="Analcime"/&gt; * &lt;enumeration value="Anandite"/&gt; * &lt;enumeration value="Anapaite"/&gt; * &lt;enumeration value="Anatase"/&gt; * &lt;enumeration value="Ancylite-(Ce)"/&gt; * &lt;enumeration value="Ancylite-(La)"/&gt; * &lt;enumeration value="Andalusite"/&gt; * &lt;enumeration value="Andersonite"/&gt; * &lt;enumeration value="Andesine"/&gt; * &lt;enumeration value="Andorite"/&gt; * &lt;enumeration value="Andradite"/&gt; * &lt;enumeration value="Andremeyerite"/&gt; * &lt;enumeration value="Androsite-(La)"/&gt; * &lt;enumeration value="Anduoite"/&gt; * &lt;enumeration value="Angelellite"/&gt; * &lt;enumeration value="Anglesite"/&gt; * &lt;enumeration value="Anhydrite"/&gt; * &lt;enumeration value="Anilite"/&gt; * &lt;enumeration value="Ankangite"/&gt; * &lt;enumeration value="Ankerite"/&gt; * &lt;enumeration value="Annabergite"/&gt; * &lt;enumeration value="Annite"/&gt; * &lt;enumeration value="Anorthite"/&gt; * &lt;enumeration value="Anorthoclase"/&gt; * &lt;enumeration value="Antarcticite"/&gt; * &lt;enumeration value="Anthoinite"/&gt; * &lt;enumeration value="Anthonyite"/&gt; * &lt;enumeration value="Anthophyllite"/&gt; * &lt;enumeration value="Antigorite"/&gt; * &lt;enumeration value="Antimonpearceite"/&gt; * &lt;enumeration value="Antimonselite"/&gt; * &lt;enumeration value="Antimony"/&gt; * &lt;enumeration value="Antlerite"/&gt; * &lt;enumeration value="Anyuiite"/&gt; * &lt;enumeration value="Apachite"/&gt; * &lt;enumeration value="ApatiteGroup"/&gt; * &lt;enumeration value="Aphthitalite"/&gt; * &lt;enumeration value="Apjohnite"/&gt; * &lt;enumeration value="Aplowite"/&gt; * &lt;enumeration value="Apophyllite"/&gt; * &lt;enumeration value="Apuanite"/&gt; * &lt;enumeration value="Aragonite"/&gt; * &lt;enumeration value="Arakiite"/&gt; * &lt;enumeration value="Aramayoite"/&gt; * &lt;enumeration value="Aravaipaite"/&gt; * &lt;enumeration value="Arcanite"/&gt; * &lt;enumeration value="Archerite"/&gt; * &lt;enumeration value="Arctite"/&gt; * &lt;enumeration value="Arcubisite"/&gt; * &lt;enumeration value="Ardaite"/&gt; * &lt;enumeration value="Ardealite"/&gt; * &lt;enumeration value="Ardennite"/&gt; * &lt;enumeration value="Arfvedsonite"/&gt; * &lt;enumeration value="Argentojarosite"/&gt; * &lt;enumeration value="Argentopentlandite"/&gt; * &lt;enumeration value="Argentopyrite"/&gt; * &lt;enumeration value="Argentotennantite"/&gt; * &lt;enumeration value="Argutite"/&gt; * &lt;enumeration value="Argyrodite"/&gt; * &lt;enumeration value="Arhbarite"/&gt; * &lt;enumeration value="Aristarainite"/&gt; * &lt;enumeration value="Armalcolite"/&gt; * &lt;enumeration value="Armangite"/&gt; * &lt;enumeration value="Armenite"/&gt; * &lt;enumeration value="Armstrongite"/&gt; * &lt;enumeration value="Arnhemite"/&gt; * &lt;enumeration value="Arrojadite"/&gt; * &lt;enumeration value="Arsenbrackebuschite"/&gt; * &lt;enumeration value="Arsendescloizite"/&gt; * &lt;enumeration value="Arsenic"/&gt; * &lt;enumeration value="Arseniopleite"/&gt; * &lt;enumeration value="Arseniosiderite"/&gt; * &lt;enumeration value="Arsenobismite"/&gt; * &lt;enumeration value="Arsenoclasite"/&gt; * &lt;enumeration value="Arsenocrandallite"/&gt; * &lt;enumeration value="Arsenoflorencite-(Ce)"/&gt; * &lt;enumeration value="Arsenogorceixite"/&gt; * &lt;enumeration value="Arsenogoyazite"/&gt; * &lt;enumeration value="Arsenohauchecornite"/&gt; * &lt;enumeration value="Arsenolamprite"/&gt; * &lt;enumeration value="Arsenolite"/&gt; * &lt;enumeration value="Arsenopalladinite"/&gt; * &lt;enumeration value="Arsenopyrite"/&gt; * &lt;enumeration value="Arsenosulvanite"/&gt; * &lt;enumeration value="Arsenpolybasite"/&gt; * &lt;enumeration value="Arsentsumebite"/&gt; * &lt;enumeration value="Arsenuranospathite"/&gt; * &lt;enumeration value="Arsenuranylite"/&gt; * &lt;enumeration value="Arthurite"/&gt; * &lt;enumeration value="Artinite"/&gt; * &lt;enumeration value="Artroeite"/&gt; * &lt;enumeration value="Arupite"/&gt; * &lt;enumeration value="Arzakite"/&gt; * &lt;enumeration value="Asbecasite"/&gt; * &lt;enumeration value="Asbestos"/&gt; * &lt;enumeration value="Asbolane"/&gt; * &lt;enumeration value="Aschamalmite"/&gt; * &lt;enumeration value="Ashanite"/&gt; * &lt;enumeration value="Ashburtonite"/&gt; * &lt;enumeration value="Ashcroftine-(Y)"/&gt; * &lt;enumeration value="Ashoverite"/&gt; * &lt;enumeration value="Asisite"/&gt; * &lt;enumeration value="Aspidolite"/&gt; * &lt;enumeration value="Asselbornite"/&gt; * &lt;enumeration value="Astrocyanite-(Ce)"/&gt; * &lt;enumeration value="Astrophyllite"/&gt; * &lt;enumeration value="Atacamite"/&gt; * &lt;enumeration value="Atelestite"/&gt; * &lt;enumeration value="Athabascaite"/&gt; * &lt;enumeration value="Atheneite"/&gt; * &lt;enumeration value="Atlasovite"/&gt; * &lt;enumeration value="Atokite"/&gt; * &lt;enumeration value="Attakolite"/&gt; * &lt;enumeration value="Aubertite"/&gt; * &lt;enumeration value="Augelite"/&gt; * &lt;enumeration value="Augite"/&gt; * &lt;enumeration value="Aurantimonate"/&gt; * &lt;enumeration value="Aurichalcite"/&gt; * &lt;enumeration value="Auricupride"/&gt; * &lt;enumeration value="Aurorite"/&gt; * &lt;enumeration value="Aurostibite"/&gt; * &lt;enumeration value="Austinite"/&gt; * &lt;enumeration value="Autunite"/&gt; * &lt;enumeration value="Averievite"/&gt; * &lt;enumeration value="Avicennite"/&gt; * &lt;enumeration value="Avogadrite"/&gt; * &lt;enumeration value="Awaruite"/&gt; * &lt;enumeration value="Azoproite"/&gt; * &lt;enumeration value="Azurite"/&gt; * &lt;enumeration value="Babefphite"/&gt; * &lt;enumeration value="Babingtonite"/&gt; * &lt;enumeration value="Babkinite"/&gt; * &lt;enumeration value="Baddeleyite"/&gt; * &lt;enumeration value="Bafertisite"/&gt; * &lt;enumeration value="Baghdadite"/&gt; * &lt;enumeration value="Bahianite"/&gt; * &lt;enumeration value="Baileychlore"/&gt; * &lt;enumeration value="Baiyuneboite"/&gt; * &lt;enumeration value="Baiyuneboite-(Ce)"/&gt; * &lt;enumeration value="Bakerite"/&gt; * &lt;enumeration value="Bakhchisaraitsevite"/&gt; * &lt;enumeration value="Baksanite"/&gt; * &lt;enumeration value="Balangeroite"/&gt; * &lt;enumeration value="Balavinskite"/&gt; * &lt;enumeration value="Balipholite"/&gt; * &lt;enumeration value="Balkanite"/&gt; * &lt;enumeration value="Balyakinite"/&gt; * &lt;enumeration value="Bambollaite"/&gt; * &lt;enumeration value="Bamfordite"/&gt; * &lt;enumeration value="Banalsite"/&gt; * &lt;enumeration value="Bandylite"/&gt; * &lt;enumeration value="Bannermanite"/&gt; * &lt;enumeration value="Bannisterite"/&gt; * &lt;enumeration value="Baotite"/&gt; * &lt;enumeration value="Bararite"/&gt; * &lt;enumeration value="Baratovite"/&gt; * &lt;enumeration value="Barberiite"/&gt; * &lt;enumeration value="Barbertonite"/&gt; * &lt;enumeration value="Barbosalite"/&gt; * &lt;enumeration value="Barentsite"/&gt; * &lt;enumeration value="Bariandite"/&gt; * &lt;enumeration value="Baricite"/&gt; * &lt;enumeration value="Bario-orthojoaquinite"/&gt; * &lt;enumeration value="Bariomicrolite"/&gt; * &lt;enumeration value="Bariopyrochlore"/&gt; * &lt;enumeration value="Bariosincosite"/&gt; * &lt;enumeration value="Barite"/&gt; * &lt;enumeration value="Barium-pharmacosiderite"/&gt; * &lt;enumeration value="Barnesite"/&gt; * &lt;enumeration value="Barquillite"/&gt; * &lt;enumeration value="Barrerite"/&gt; * &lt;enumeration value="Barringerite"/&gt; * &lt;enumeration value="Barringtonite"/&gt; * &lt;enumeration value="Barroisite"/&gt; * &lt;enumeration value="Barstowite"/&gt; * &lt;enumeration value="Bartelkeite"/&gt; * &lt;enumeration value="Bartonite"/&gt; * &lt;enumeration value="Barylite"/&gt; * &lt;enumeration value="Barysilite"/&gt; * &lt;enumeration value="Barytocalcite"/&gt; * &lt;enumeration value="Barytolamprophyllite"/&gt; * &lt;enumeration value="Basaluminite"/&gt; * &lt;enumeration value="Bassanite"/&gt; * &lt;enumeration value="Bassetite"/&gt; * &lt;enumeration value="Bastnasite"/&gt; * &lt;enumeration value="Bastnasite-(Ce)"/&gt; * &lt;enumeration value="Bastnasite-(La)"/&gt; * &lt;enumeration value="Bastnasite-(Y)"/&gt; * &lt;enumeration value="Batiferrite"/&gt; * &lt;enumeration value="Batisite"/&gt; * &lt;enumeration value="Baumhauerite"/&gt; * &lt;enumeration value="Baumhauerite-2a"/&gt; * &lt;enumeration value="Baumite"/&gt; * &lt;enumeration value="Baumstarkite"/&gt; * &lt;enumeration value="Bauranoite"/&gt; * &lt;enumeration value="Bauxite(GeneralTerm)"/&gt; * &lt;enumeration value="Bavenite"/&gt; * &lt;enumeration value="Bayankhanite"/&gt; * &lt;enumeration value="Bayerite"/&gt; * &lt;enumeration value="Bayldonite"/&gt; * &lt;enumeration value="Bayleyite"/&gt; * &lt;enumeration value="Baylissite"/&gt; * &lt;enumeration value="Bazhenovite"/&gt; * &lt;enumeration value="Bazirite"/&gt; * &lt;enumeration value="Bazzite"/&gt; * &lt;enumeration value="Bearsite"/&gt; * &lt;enumeration value="Bearthite"/&gt; * &lt;enumeration value="Beaverite"/&gt; * &lt;enumeration value="Bechererite"/&gt; * &lt;enumeration value="Becquerelite"/&gt; * &lt;enumeration value="Bederite"/&gt; * &lt;enumeration value="Behierite"/&gt; * &lt;enumeration value="Behoite"/&gt; * &lt;enumeration value="Beidellite"/&gt; * &lt;enumeration value="Belendorffite"/&gt; * &lt;enumeration value="Belkovite"/&gt; * &lt;enumeration value="Bellbergite"/&gt; * &lt;enumeration value="Bellidoite"/&gt; * &lt;enumeration value="Bellingerite"/&gt; * &lt;enumeration value="Belloite"/&gt; * &lt;enumeration value="Belovite-(Ce)"/&gt; * &lt;enumeration value="Belovite-(La)"/&gt; * &lt;enumeration value="Belyankinite"/&gt; * &lt;enumeration value="Bementite"/&gt; * &lt;enumeration value="Benauite"/&gt; * &lt;enumeration value="Benavidesite"/&gt; * &lt;enumeration value="Benitoite"/&gt; * &lt;enumeration value="Benjaminite"/&gt; * &lt;enumeration value="Benleonardite"/&gt; * &lt;enumeration value="Benstonite"/&gt; * &lt;enumeration value="Bentorite"/&gt; * &lt;enumeration value="Benyacarite"/&gt; * &lt;enumeration value="Beraunite"/&gt; * &lt;enumeration value="Berborite"/&gt; * &lt;enumeration value="Berborite-1t"/&gt; * &lt;enumeration value="Berdesinskiite"/&gt; * &lt;enumeration value="Berezanskite"/&gt; * &lt;enumeration value="Bergenite"/&gt; * &lt;enumeration value="Bergslagite"/&gt; * &lt;enumeration value="Berlinite"/&gt; * &lt;enumeration value="Bermanite"/&gt; * &lt;enumeration value="Bernalite"/&gt; * &lt;enumeration value="Bernardite"/&gt; * &lt;enumeration value="Berndtite"/&gt; * &lt;enumeration value="Berndtite-2t"/&gt; * &lt;enumeration value="Berndtite-4h"/&gt; * &lt;enumeration value="Berryite"/&gt; * &lt;enumeration value="Berthierine"/&gt; * &lt;enumeration value="Berthierite"/&gt; * &lt;enumeration value="Bertossaite"/&gt; * &lt;enumeration value="Bertrandite"/&gt; * &lt;enumeration value="Beryl"/&gt; * &lt;enumeration value="Beryllite"/&gt; * &lt;enumeration value="Beryllonite"/&gt; * &lt;enumeration value="Berzelianite"/&gt; * &lt;enumeration value="Berzeliite"/&gt; * &lt;enumeration value="Bessmertnovite"/&gt; * &lt;enumeration value="Beta-fergusonite-(Ce)"/&gt; * &lt;enumeration value="Beta-fergusonite-(Nd)"/&gt; * &lt;enumeration value="Beta-fergusonite-(Y)"/&gt; * &lt;enumeration value="Betafite"/&gt; * &lt;enumeration value="Betekhtinite"/&gt; * &lt;enumeration value="Betpakdalite"/&gt; * &lt;enumeration value="Beudantite"/&gt; * &lt;enumeration value="Beusite"/&gt; * &lt;enumeration value="Beyerite"/&gt; * &lt;enumeration value="Bezsmertnovite"/&gt; * &lt;enumeration value="Bianchite"/&gt; * &lt;enumeration value="Bicchulite"/&gt; * &lt;enumeration value="Bideauxite"/&gt; * &lt;enumeration value="Bieberite"/&gt; * &lt;enumeration value="Biehlite"/&gt; * &lt;enumeration value="Bigcreekite"/&gt; * &lt;enumeration value="Bijvoetite-(Y)"/&gt; * &lt;enumeration value="Bikitaite"/&gt; * &lt;enumeration value="Bilibinskite"/&gt; * &lt;enumeration value="Bilinite"/&gt; * &lt;enumeration value="Billietite"/&gt; * &lt;enumeration value="Billingsleyite"/&gt; * &lt;enumeration value="Bindheimite"/&gt; * &lt;enumeration value="Biotite"/&gt; * &lt;enumeration value="Biphosphammite"/&gt; * &lt;enumeration value="Biringuccite"/&gt; * &lt;enumeration value="Birnessite"/&gt; * &lt;enumeration value="Bischofite"/&gt; * &lt;enumeration value="Bismite"/&gt; * &lt;enumeration value="Bismoclite"/&gt; * &lt;enumeration value="Bismuth"/&gt; * &lt;enumeration value="Bismuthinite"/&gt; * &lt;enumeration value="Bismutite"/&gt; * &lt;enumeration value="Bismutocolumbite"/&gt; * &lt;enumeration value="Bismutoferrite"/&gt; * &lt;enumeration value="Bismutohauchecornite"/&gt; * &lt;enumeration value="Bismutomicrolite"/&gt; * &lt;enumeration value="Bismutopyrochlore"/&gt; * &lt;enumeration value="Bismutostibiconite"/&gt; * &lt;enumeration value="Bismutotantalite"/&gt; * &lt;enumeration value="Bityite"/&gt; * &lt;enumeration value="Bixbyite"/&gt; * &lt;enumeration value="Bjarebyite"/&gt; * &lt;enumeration value="Blakeite"/&gt; * &lt;enumeration value="Blatonite"/&gt; * &lt;enumeration value="Blatterite"/&gt; * &lt;enumeration value="Bleasdaleite"/&gt; * &lt;enumeration value="Blixite"/&gt; * &lt;enumeration value="Blodite"/&gt; * &lt;enumeration value="Blossite"/&gt; * &lt;enumeration value="Bobfergusonite"/&gt; * &lt;enumeration value="Bobierrite"/&gt; * &lt;enumeration value="Bogdanovite"/&gt; * &lt;enumeration value="Boggildite"/&gt; * &lt;enumeration value="Boggsite"/&gt; * &lt;enumeration value="Bogvadite"/&gt; * &lt;enumeration value="Bohdanowiczite"/&gt; * &lt;enumeration value="Bohmite"/&gt; * &lt;enumeration value="Bokite"/&gt; * &lt;enumeration value="Boleite"/&gt; * &lt;enumeration value="Bolivarite"/&gt; * &lt;enumeration value="Boltwoodite"/&gt; * &lt;enumeration value="Bonaccordite"/&gt; * &lt;enumeration value="Bonattite"/&gt; * &lt;enumeration value="Bonshtedtite"/&gt; * &lt;enumeration value="Boothite"/&gt; * &lt;enumeration value="Boracite"/&gt; * &lt;enumeration value="Boralsilite"/&gt; * &lt;enumeration value="Borax"/&gt; * &lt;enumeration value="Borcarite"/&gt; * &lt;enumeration value="Borishanskiite"/&gt; * &lt;enumeration value="Bornemanite"/&gt; * &lt;enumeration value="Bornhardtite"/&gt; * &lt;enumeration value="Bornite"/&gt; * &lt;enumeration value="Borodaevite"/&gt; * &lt;enumeration value="Boromuscovite"/&gt; * &lt;enumeration value="Borovskite"/&gt; * &lt;enumeration value="Bostwickite"/&gt; * &lt;enumeration value="Botallackite"/&gt; * &lt;enumeration value="Botryogen"/&gt; * &lt;enumeration value="Bottinoite"/&gt; * &lt;enumeration value="Boulangerite"/&gt; * &lt;enumeration value="Bournonite"/&gt; * &lt;enumeration value="Boussingaultite"/&gt; * &lt;enumeration value="Boussingualtite"/&gt; * &lt;enumeration value="Bowieite"/&gt; * &lt;enumeration value="Boyleite"/&gt; * &lt;enumeration value="Brabantite"/&gt; * &lt;enumeration value="Bracewellite"/&gt; * &lt;enumeration value="Brackebuschite"/&gt; * &lt;enumeration value="Bradleyite"/&gt; * &lt;enumeration value="Braggite"/&gt; * &lt;enumeration value="Braitschite-(Ce)"/&gt; * &lt;enumeration value="Brammallite"/&gt; * &lt;enumeration value="Brandholzite"/&gt; * &lt;enumeration value="Brandtite"/&gt; * &lt;enumeration value="Brannerite"/&gt; * &lt;enumeration value="Brannockite"/&gt; * &lt;enumeration value="Brassite"/&gt; * &lt;enumeration value="Braunite"/&gt; * &lt;enumeration value="Bravoite"/&gt; * &lt;enumeration value="Brazilianite"/&gt; * &lt;enumeration value="Bredigite"/&gt; * &lt;enumeration value="Breithauptite"/&gt; * &lt;enumeration value="Brenkite"/&gt; * &lt;enumeration value="Brewsterite"/&gt; * &lt;enumeration value="Brewsterite-Ba"/&gt; * &lt;enumeration value="Brewsterite-Sr"/&gt; * &lt;enumeration value="Brezinaite"/&gt; * &lt;enumeration value="Brianite"/&gt; * &lt;enumeration value="Brianroulstonite"/&gt; * &lt;enumeration value="Brianyoungite"/&gt; * &lt;enumeration value="Briartite"/&gt; * &lt;enumeration value="Brindleyite"/&gt; * &lt;enumeration value="Britholite"/&gt; * &lt;enumeration value="Britholite-(Ce)"/&gt; * &lt;enumeration value="Britholite-(Y)"/&gt; * &lt;enumeration value="Brizziite"/&gt; * &lt;enumeration value="Brochantite"/&gt; * &lt;enumeration value="Brockite"/&gt; * &lt;enumeration value="Brokenhillite"/&gt; * &lt;enumeration value="Bromargyrite"/&gt; * &lt;enumeration value="Bromellite"/&gt; * &lt;enumeration value="Brookite"/&gt; * &lt;enumeration value="Brownmillerite"/&gt; * &lt;enumeration value="Brucite"/&gt; * &lt;enumeration value="Bruggenite"/&gt; * &lt;enumeration value="Brugnatellite"/&gt; * &lt;enumeration value="Brunogeierite"/&gt; * &lt;enumeration value="Brushite"/&gt; * &lt;enumeration value="Buchwaldite"/&gt; * &lt;enumeration value="Buckhornite"/&gt; * &lt;enumeration value="Buddingtonite"/&gt; * &lt;enumeration value="Buergerite"/&gt; * &lt;enumeration value="Buetschliite"/&gt; * &lt;enumeration value="Bukovite"/&gt; * &lt;enumeration value="Bukovskyite"/&gt; * &lt;enumeration value="Bulachite"/&gt; * &lt;enumeration value="Bultfonteinite"/&gt; * &lt;enumeration value="Bunsenite"/&gt; * &lt;enumeration value="Burangaite"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "MineralDetails", namespace = "http://app.geosamples.org") @XmlEnum public enum MineralDetails1 { @XmlEnumValue("Abelsonite") ABELSONITE("Abelsonite"), @XmlEnumValue("Abenakiite-(Ce)") ABENAKIITE_CE("Abenakiite-(Ce)"), @XmlEnumValue("Abernathyite") ABERNATHYITE("Abernathyite"), @XmlEnumValue("Abhurite") ABHURITE("Abhurite"), @XmlEnumValue("Abswurmbachite") ABSWURMBACHITE("Abswurmbachite"), @XmlEnumValue("Acanthite") ACANTHITE("Acanthite"), @XmlEnumValue("Acetamide") ACETAMIDE("Acetamide"), @XmlEnumValue("Actinolite") ACTINOLITE("Actinolite"), @XmlEnumValue("Acuminite") ACUMINITE("Acuminite"), @XmlEnumValue("Adamite") ADAMITE("Adamite"), @XmlEnumValue("Adamsite-(Y)") ADAMSITE_Y("Adamsite-(Y)"), @XmlEnumValue("Adelite") ADELITE("Adelite"), @XmlEnumValue("Admontite") ADMONTITE("Admontite"), @XmlEnumValue("Aegirine") AEGIRINE("Aegirine"), @XmlEnumValue("Aenigmatite") AENIGMATITE("Aenigmatite"), @XmlEnumValue("Aerinite") AERINITE("Aerinite"), @XmlEnumValue("Aerugite") AERUGITE("Aerugite"), @XmlEnumValue("Aeschynite") AESCHYNITE("Aeschynite"), @XmlEnumValue("Aeschynite-(Ce)") AESCHYNITE_CE("Aeschynite-(Ce)"), @XmlEnumValue("Aeschynite-(Nd)") AESCHYNITE_ND("Aeschynite-(Nd)"), @XmlEnumValue("Aeschynite-(Y)") AESCHYNITE_Y("Aeschynite-(Y)"), @XmlEnumValue("Afghanite") AFGHANITE("Afghanite"), @XmlEnumValue("Afwillite") AFWILLITE("Afwillite"), @XmlEnumValue("Agardite") AGARDITE("Agardite"), @XmlEnumValue("Agardite-(La)") AGARDITE_LA("Agardite-(La)"), @XmlEnumValue("Agardite-(Y)") AGARDITE_Y("Agardite-(Y)"), @XmlEnumValue("Agrellite") AGRELLITE("Agrellite"), @XmlEnumValue("Agrinierite") AGRINIERITE("Agrinierite"), @XmlEnumValue("Aguilarite") AGUILARITE("Aguilarite"), @XmlEnumValue("Aheylite") AHEYLITE("Aheylite"), @XmlEnumValue("Ahlfeldite") AHLFELDITE("Ahlfeldite"), @XmlEnumValue("Aikinite") AIKINITE("Aikinite"), @XmlEnumValue("Ajoite") AJOITE("Ajoite"), @XmlEnumValue("Akaganeite") AKAGANEITE("Akaganeite"), @XmlEnumValue("Akatoreite") AKATOREITE("Akatoreite"), @XmlEnumValue("Akdalaite") AKDALAITE("Akdalaite"), @XmlEnumValue("Akermanite") AKERMANITE("Akermanite"), @XmlEnumValue("Akhtenskite") AKHTENSKITE("Akhtenskite"), @XmlEnumValue("Akimotoite") AKIMOTOITE("Akimotoite"), @XmlEnumValue("Akrochordite") AKROCHORDITE("Akrochordite"), @XmlEnumValue("Aksaite") AKSAITE("Aksaite"), @XmlEnumValue("Aktashite") AKTASHITE("Aktashite"), @XmlEnumValue("Alabandite") ALABANDITE("Alabandite"), @XmlEnumValue("Alacranite") ALACRANITE("Alacranite"), @XmlEnumValue("Alamosite") ALAMOSITE("Alamosite"), @XmlEnumValue("Alarsite") ALARSITE("Alarsite"), @XmlEnumValue("Albite") ALBITE("Albite"), @XmlEnumValue("Albrechtschraufite") ALBRECHTSCHRAUFITE("Albrechtschraufite"), @XmlEnumValue("Aldermanite") ALDERMANITE("Aldermanite"), @XmlEnumValue("Aldzhanite") ALDZHANITE("Aldzhanite"), @XmlEnumValue("Aleksite") ALEKSITE("Aleksite"), @XmlEnumValue("Alforsite") ALFORSITE("Alforsite"), @XmlEnumValue("Algodonite") ALGODONITE("Algodonite"), @XmlEnumValue("Aliettite") ALIETTITE("Aliettite"), @XmlEnumValue("AllMinerals") ALL_MINERALS("AllMinerals"), @XmlEnumValue("Allactite") ALLACTITE("Allactite"), @XmlEnumValue("Allanite") ALLANITE("Allanite"), @XmlEnumValue("Allanite-(Ce)") ALLANITE_CE("Allanite-(Ce)"), @XmlEnumValue("Allanite-(La)") ALLANITE_LA("Allanite-(La)"), @XmlEnumValue("Allanite-(Y)") ALLANITE_Y("Allanite-(Y)"), @XmlEnumValue("Allargentum") ALLARGENTUM("Allargentum"), @XmlEnumValue("Alleghanyite") ALLEGHANYITE("Alleghanyite"), @XmlEnumValue("Alloclasite") ALLOCLASITE("Alloclasite"), @XmlEnumValue("Allophane") ALLOPHANE("Allophane"), @XmlEnumValue("Alluaivite") ALLUAIVITE("Alluaivite"), @XmlEnumValue("Alluaudite") ALLUAUDITE("Alluaudite"), @XmlEnumValue("Almandine") ALMANDINE("Almandine"), @XmlEnumValue("Alstonite") ALSTONITE("Alstonite"), @XmlEnumValue("Altaite") ALTAITE("Altaite"), @XmlEnumValue("Althausite") ALTHAUSITE("Althausite"), @XmlEnumValue("Althupite") ALTHUPITE("Althupite"), @XmlEnumValue("Altisite") ALTISITE("Altisite"), @XmlEnumValue("Alum(GeneralTerm)") ALUM_GENERAL_TERM("Alum(GeneralTerm)"), @XmlEnumValue("Aluminite") ALUMINITE("Aluminite"), @XmlEnumValue("Aluminium") ALUMINIUM("Aluminium"), @XmlEnumValue("Aluminoceladonite") ALUMINOCELADONITE("Aluminoceladonite"), @XmlEnumValue("Aluminocopiapite") ALUMINOCOPIAPITE("Aluminocopiapite"), @XmlEnumValue("Aluminokatophorite") ALUMINOKATOPHORITE("Aluminokatophorite"), @XmlEnumValue("Aluminotschermakite") ALUMINOTSCHERMAKITE("Aluminotschermakite"), @XmlEnumValue("Aluminum") ALUMINUM("Aluminum"), @XmlEnumValue("Alumohydrocalcite") ALUMOHYDROCALCITE("Alumohydrocalcite"), @XmlEnumValue("Alumoklyuchevskite") ALUMOKLYUCHEVSKITE("Alumoklyuchevskite"), @XmlEnumValue("Alumopharmacosiderite") ALUMOPHARMACOSIDERITE("Alumopharmacosiderite"), @XmlEnumValue("Alumotantite") ALUMOTANTITE("Alumotantite"), @XmlEnumValue("Alumotungstite") ALUMOTUNGSTITE("Alumotungstite"), @XmlEnumValue("Alunite") ALUNITE("Alunite"), @XmlEnumValue("Alunogen") ALUNOGEN("Alunogen"), @XmlEnumValue("Alvanite") ALVANITE("Alvanite"), @XmlEnumValue("Amakinite") AMAKINITE("Amakinite"), @XmlEnumValue("Amalgam") AMALGAM("Amalgam"), @XmlEnumValue("Amarantite") AMARANTITE("Amarantite"), @XmlEnumValue("Amarillite") AMARILLITE("Amarillite"), @XmlEnumValue("Amber") AMBER("Amber"), @XmlEnumValue("Amblygonite") AMBLYGONITE("Amblygonite"), @XmlEnumValue("Ameghinite") AMEGHINITE("Ameghinite"), @XmlEnumValue("Amesite") AMESITE("Amesite"), @XmlEnumValue("Amicite") AMICITE("Amicite"), @XmlEnumValue("Aminoffite") AMINOFFITE("Aminoffite"), @XmlEnumValue("Ammonioalunite") AMMONIOALUNITE("Ammonioalunite"), @XmlEnumValue("Ammonioborite") AMMONIOBORITE("Ammonioborite"), @XmlEnumValue("Ammoniojarosite") AMMONIOJAROSITE("Ammoniojarosite"), @XmlEnumValue("Ammonioleucite") AMMONIOLEUCITE("Ammonioleucite"), @XmlEnumValue("AmphiboleGroup") AMPHIBOLE_GROUP("AmphiboleGroup"), @XmlEnumValue("Amstallite") AMSTALLITE("Amstallite"), @XmlEnumValue("Analcime") ANALCIME("Analcime"), @XmlEnumValue("Anandite") ANANDITE("Anandite"), @XmlEnumValue("Anapaite") ANAPAITE("Anapaite"), @XmlEnumValue("Anatase") ANATASE("Anatase"), @XmlEnumValue("Ancylite-(Ce)") ANCYLITE_CE("Ancylite-(Ce)"), @XmlEnumValue("Ancylite-(La)") ANCYLITE_LA("Ancylite-(La)"), @XmlEnumValue("Andalusite") ANDALUSITE("Andalusite"), @XmlEnumValue("Andersonite") ANDERSONITE("Andersonite"), @XmlEnumValue("Andesine") ANDESINE("Andesine"), @XmlEnumValue("Andorite") ANDORITE("Andorite"), @XmlEnumValue("Andradite") ANDRADITE("Andradite"), @XmlEnumValue("Andremeyerite") ANDREMEYERITE("Andremeyerite"), @XmlEnumValue("Androsite-(La)") ANDROSITE_LA("Androsite-(La)"), @XmlEnumValue("Anduoite") ANDUOITE("Anduoite"), @XmlEnumValue("Angelellite") ANGELELLITE("Angelellite"), @XmlEnumValue("Anglesite") ANGLESITE("Anglesite"), @XmlEnumValue("Anhydrite") ANHYDRITE("Anhydrite"), @XmlEnumValue("Anilite") ANILITE("Anilite"), @XmlEnumValue("Ankangite") ANKANGITE("Ankangite"), @XmlEnumValue("Ankerite") ANKERITE("Ankerite"), @XmlEnumValue("Annabergite") ANNABERGITE("Annabergite"), @XmlEnumValue("Annite") ANNITE("Annite"), @XmlEnumValue("Anorthite") ANORTHITE("Anorthite"), @XmlEnumValue("Anorthoclase") ANORTHOCLASE("Anorthoclase"), @XmlEnumValue("Antarcticite") ANTARCTICITE("Antarcticite"), @XmlEnumValue("Anthoinite") ANTHOINITE("Anthoinite"), @XmlEnumValue("Anthonyite") ANTHONYITE("Anthonyite"), @XmlEnumValue("Anthophyllite") ANTHOPHYLLITE("Anthophyllite"), @XmlEnumValue("Antigorite") ANTIGORITE("Antigorite"), @XmlEnumValue("Antimonpearceite") ANTIMONPEARCEITE("Antimonpearceite"), @XmlEnumValue("Antimonselite") ANTIMONSELITE("Antimonselite"), @XmlEnumValue("Antimony") ANTIMONY("Antimony"), @XmlEnumValue("Antlerite") ANTLERITE("Antlerite"), @XmlEnumValue("Anyuiite") ANYUIITE("Anyuiite"), @XmlEnumValue("Apachite") APACHITE("Apachite"), @XmlEnumValue("ApatiteGroup") APATITE_GROUP("ApatiteGroup"), @XmlEnumValue("Aphthitalite") APHTHITALITE("Aphthitalite"), @XmlEnumValue("Apjohnite") APJOHNITE("Apjohnite"), @XmlEnumValue("Aplowite") APLOWITE("Aplowite"), @XmlEnumValue("Apophyllite") APOPHYLLITE("Apophyllite"), @XmlEnumValue("Apuanite") APUANITE("Apuanite"), @XmlEnumValue("Aragonite") ARAGONITE("Aragonite"), @XmlEnumValue("Arakiite") ARAKIITE("Arakiite"), @XmlEnumValue("Aramayoite") ARAMAYOITE("Aramayoite"), @XmlEnumValue("Aravaipaite") ARAVAIPAITE("Aravaipaite"), @XmlEnumValue("Arcanite") ARCANITE("Arcanite"), @XmlEnumValue("Archerite") ARCHERITE("Archerite"), @XmlEnumValue("Arctite") ARCTITE("Arctite"), @XmlEnumValue("Arcubisite") ARCUBISITE("Arcubisite"), @XmlEnumValue("Ardaite") ARDAITE("Ardaite"), @XmlEnumValue("Ardealite") ARDEALITE("Ardealite"), @XmlEnumValue("Ardennite") ARDENNITE("Ardennite"), @XmlEnumValue("Arfvedsonite") ARFVEDSONITE("Arfvedsonite"), @XmlEnumValue("Argentojarosite") ARGENTOJAROSITE("Argentojarosite"), @XmlEnumValue("Argentopentlandite") ARGENTOPENTLANDITE("Argentopentlandite"), @XmlEnumValue("Argentopyrite") ARGENTOPYRITE("Argentopyrite"), @XmlEnumValue("Argentotennantite") ARGENTOTENNANTITE("Argentotennantite"), @XmlEnumValue("Argutite") ARGUTITE("Argutite"), @XmlEnumValue("Argyrodite") ARGYRODITE("Argyrodite"), @XmlEnumValue("Arhbarite") ARHBARITE("Arhbarite"), @XmlEnumValue("Aristarainite") ARISTARAINITE("Aristarainite"), @XmlEnumValue("Armalcolite") ARMALCOLITE("Armalcolite"), @XmlEnumValue("Armangite") ARMANGITE("Armangite"), @XmlEnumValue("Armenite") ARMENITE("Armenite"), @XmlEnumValue("Armstrongite") ARMSTRONGITE("Armstrongite"), @XmlEnumValue("Arnhemite") ARNHEMITE("Arnhemite"), @XmlEnumValue("Arrojadite") ARROJADITE("Arrojadite"), @XmlEnumValue("Arsenbrackebuschite") ARSENBRACKEBUSCHITE("Arsenbrackebuschite"), @XmlEnumValue("Arsendescloizite") ARSENDESCLOIZITE("Arsendescloizite"), @XmlEnumValue("Arsenic") ARSENIC("Arsenic"), @XmlEnumValue("Arseniopleite") ARSENIOPLEITE("Arseniopleite"), @XmlEnumValue("Arseniosiderite") ARSENIOSIDERITE("Arseniosiderite"), @XmlEnumValue("Arsenobismite") ARSENOBISMITE("Arsenobismite"), @XmlEnumValue("Arsenoclasite") ARSENOCLASITE("Arsenoclasite"), @XmlEnumValue("Arsenocrandallite") ARSENOCRANDALLITE("Arsenocrandallite"), @XmlEnumValue("Arsenoflorencite-(Ce)") ARSENOFLORENCITE_CE("Arsenoflorencite-(Ce)"), @XmlEnumValue("Arsenogorceixite") ARSENOGORCEIXITE("Arsenogorceixite"), @XmlEnumValue("Arsenogoyazite") ARSENOGOYAZITE("Arsenogoyazite"), @XmlEnumValue("Arsenohauchecornite") ARSENOHAUCHECORNITE("Arsenohauchecornite"), @XmlEnumValue("Arsenolamprite") ARSENOLAMPRITE("Arsenolamprite"), @XmlEnumValue("Arsenolite") ARSENOLITE("Arsenolite"), @XmlEnumValue("Arsenopalladinite") ARSENOPALLADINITE("Arsenopalladinite"), @XmlEnumValue("Arsenopyrite") ARSENOPYRITE("Arsenopyrite"), @XmlEnumValue("Arsenosulvanite") ARSENOSULVANITE("Arsenosulvanite"), @XmlEnumValue("Arsenpolybasite") ARSENPOLYBASITE("Arsenpolybasite"), @XmlEnumValue("Arsentsumebite") ARSENTSUMEBITE("Arsentsumebite"), @XmlEnumValue("Arsenuranospathite") ARSENURANOSPATHITE("Arsenuranospathite"), @XmlEnumValue("Arsenuranylite") ARSENURANYLITE("Arsenuranylite"), @XmlEnumValue("Arthurite") ARTHURITE("Arthurite"), @XmlEnumValue("Artinite") ARTINITE("Artinite"), @XmlEnumValue("Artroeite") ARTROEITE("Artroeite"), @XmlEnumValue("Arupite") ARUPITE("Arupite"), @XmlEnumValue("Arzakite") ARZAKITE("Arzakite"), @XmlEnumValue("Asbecasite") ASBECASITE("Asbecasite"), @XmlEnumValue("Asbestos") ASBESTOS("Asbestos"), @XmlEnumValue("Asbolane") ASBOLANE("Asbolane"), @XmlEnumValue("Aschamalmite") ASCHAMALMITE("Aschamalmite"), @XmlEnumValue("Ashanite") ASHANITE("Ashanite"), @XmlEnumValue("Ashburtonite") ASHBURTONITE("Ashburtonite"), @XmlEnumValue("Ashcroftine-(Y)") ASHCROFTINE_Y("Ashcroftine-(Y)"), @XmlEnumValue("Ashoverite") ASHOVERITE("Ashoverite"), @XmlEnumValue("Asisite") ASISITE("Asisite"), @XmlEnumValue("Aspidolite") ASPIDOLITE("Aspidolite"), @XmlEnumValue("Asselbornite") ASSELBORNITE("Asselbornite"), @XmlEnumValue("Astrocyanite-(Ce)") ASTROCYANITE_CE("Astrocyanite-(Ce)"), @XmlEnumValue("Astrophyllite") ASTROPHYLLITE("Astrophyllite"), @XmlEnumValue("Atacamite") ATACAMITE("Atacamite"), @XmlEnumValue("Atelestite") ATELESTITE("Atelestite"), @XmlEnumValue("Athabascaite") ATHABASCAITE("Athabascaite"), @XmlEnumValue("Atheneite") ATHENEITE("Atheneite"), @XmlEnumValue("Atlasovite") ATLASOVITE("Atlasovite"), @XmlEnumValue("Atokite") ATOKITE("Atokite"), @XmlEnumValue("Attakolite") ATTAKOLITE("Attakolite"), @XmlEnumValue("Aubertite") AUBERTITE("Aubertite"), @XmlEnumValue("Augelite") AUGELITE("Augelite"), @XmlEnumValue("Augite") AUGITE("Augite"), @XmlEnumValue("Aurantimonate") AURANTIMONATE("Aurantimonate"), @XmlEnumValue("Aurichalcite") AURICHALCITE("Aurichalcite"), @XmlEnumValue("Auricupride") AURICUPRIDE("Auricupride"), @XmlEnumValue("Aurorite") AURORITE("Aurorite"), @XmlEnumValue("Aurostibite") AUROSTIBITE("Aurostibite"), @XmlEnumValue("Austinite") AUSTINITE("Austinite"), @XmlEnumValue("Autunite") AUTUNITE("Autunite"), @XmlEnumValue("Averievite") AVERIEVITE("Averievite"), @XmlEnumValue("Avicennite") AVICENNITE("Avicennite"), @XmlEnumValue("Avogadrite") AVOGADRITE("Avogadrite"), @XmlEnumValue("Awaruite") AWARUITE("Awaruite"), @XmlEnumValue("Azoproite") AZOPROITE("Azoproite"), @XmlEnumValue("Azurite") AZURITE("Azurite"), @XmlEnumValue("Babefphite") BABEFPHITE("Babefphite"), @XmlEnumValue("Babingtonite") BABINGTONITE("Babingtonite"), @XmlEnumValue("Babkinite") BABKINITE("Babkinite"), @XmlEnumValue("Baddeleyite") BADDELEYITE("Baddeleyite"), @XmlEnumValue("Bafertisite") BAFERTISITE("Bafertisite"), @XmlEnumValue("Baghdadite") BAGHDADITE("Baghdadite"), @XmlEnumValue("Bahianite") BAHIANITE("Bahianite"), @XmlEnumValue("Baileychlore") BAILEYCHLORE("Baileychlore"), @XmlEnumValue("Baiyuneboite") BAIYUNEBOITE("Baiyuneboite"), @XmlEnumValue("Baiyuneboite-(Ce)") BAIYUNEBOITE_CE("Baiyuneboite-(Ce)"), @XmlEnumValue("Bakerite") BAKERITE("Bakerite"), @XmlEnumValue("Bakhchisaraitsevite") BAKHCHISARAITSEVITE("Bakhchisaraitsevite"), @XmlEnumValue("Baksanite") BAKSANITE("Baksanite"), @XmlEnumValue("Balangeroite") BALANGEROITE("Balangeroite"), @XmlEnumValue("Balavinskite") BALAVINSKITE("Balavinskite"), @XmlEnumValue("Balipholite") BALIPHOLITE("Balipholite"), @XmlEnumValue("Balkanite") BALKANITE("Balkanite"), @XmlEnumValue("Balyakinite") BALYAKINITE("Balyakinite"), @XmlEnumValue("Bambollaite") BAMBOLLAITE("Bambollaite"), @XmlEnumValue("Bamfordite") BAMFORDITE("Bamfordite"), @XmlEnumValue("Banalsite") BANALSITE("Banalsite"), @XmlEnumValue("Bandylite") BANDYLITE("Bandylite"), @XmlEnumValue("Bannermanite") BANNERMANITE("Bannermanite"), @XmlEnumValue("Bannisterite") BANNISTERITE("Bannisterite"), @XmlEnumValue("Baotite") BAOTITE("Baotite"), @XmlEnumValue("Bararite") BARARITE("Bararite"), @XmlEnumValue("Baratovite") BARATOVITE("Baratovite"), @XmlEnumValue("Barberiite") BARBERIITE("Barberiite"), @XmlEnumValue("Barbertonite") BARBERTONITE("Barbertonite"), @XmlEnumValue("Barbosalite") BARBOSALITE("Barbosalite"), @XmlEnumValue("Barentsite") BARENTSITE("Barentsite"), @XmlEnumValue("Bariandite") BARIANDITE("Bariandite"), @XmlEnumValue("Baricite") BARICITE("Baricite"), @XmlEnumValue("Bario-orthojoaquinite") BARIO_ORTHOJOAQUINITE("Bario-orthojoaquinite"), @XmlEnumValue("Bariomicrolite") BARIOMICROLITE("Bariomicrolite"), @XmlEnumValue("Bariopyrochlore") BARIOPYROCHLORE("Bariopyrochlore"), @XmlEnumValue("Bariosincosite") BARIOSINCOSITE("Bariosincosite"), @XmlEnumValue("Barite") BARITE("Barite"), @XmlEnumValue("Barium-pharmacosiderite") BARIUM_PHARMACOSIDERITE("Barium-pharmacosiderite"), @XmlEnumValue("Barnesite") BARNESITE("Barnesite"), @XmlEnumValue("Barquillite") BARQUILLITE("Barquillite"), @XmlEnumValue("Barrerite") BARRERITE("Barrerite"), @XmlEnumValue("Barringerite") BARRINGERITE("Barringerite"), @XmlEnumValue("Barringtonite") BARRINGTONITE("Barringtonite"), @XmlEnumValue("Barroisite") BARROISITE("Barroisite"), @XmlEnumValue("Barstowite") BARSTOWITE("Barstowite"), @XmlEnumValue("Bartelkeite") BARTELKEITE("Bartelkeite"), @XmlEnumValue("Bartonite") BARTONITE("Bartonite"), @XmlEnumValue("Barylite") BARYLITE("Barylite"), @XmlEnumValue("Barysilite") BARYSILITE("Barysilite"), @XmlEnumValue("Barytocalcite") BARYTOCALCITE("Barytocalcite"), @XmlEnumValue("Barytolamprophyllite") BARYTOLAMPROPHYLLITE("Barytolamprophyllite"), @XmlEnumValue("Basaluminite") BASALUMINITE("Basaluminite"), @XmlEnumValue("Bassanite") BASSANITE("Bassanite"), @XmlEnumValue("Bassetite") BASSETITE("Bassetite"), @XmlEnumValue("Bastnasite") BASTNASITE("Bastnasite"), @XmlEnumValue("Bastnasite-(Ce)") BASTNASITE_CE("Bastnasite-(Ce)"), @XmlEnumValue("Bastnasite-(La)") BASTNASITE_LA("Bastnasite-(La)"), @XmlEnumValue("Bastnasite-(Y)") BASTNASITE_Y("Bastnasite-(Y)"), @XmlEnumValue("Batiferrite") BATIFERRITE("Batiferrite"), @XmlEnumValue("Batisite") BATISITE("Batisite"), @XmlEnumValue("Baumhauerite") BAUMHAUERITE("Baumhauerite"), @XmlEnumValue("Baumhauerite-2a") BAUMHAUERITE_2_A("Baumhauerite-2a"), @XmlEnumValue("Baumite") BAUMITE("Baumite"), @XmlEnumValue("Baumstarkite") BAUMSTARKITE("Baumstarkite"), @XmlEnumValue("Bauranoite") BAURANOITE("Bauranoite"), @XmlEnumValue("Bauxite(GeneralTerm)") BAUXITE_GENERAL_TERM("Bauxite(GeneralTerm)"), @XmlEnumValue("Bavenite") BAVENITE("Bavenite"), @XmlEnumValue("Bayankhanite") BAYANKHANITE("Bayankhanite"), @XmlEnumValue("Bayerite") BAYERITE("Bayerite"), @XmlEnumValue("Bayldonite") BAYLDONITE("Bayldonite"), @XmlEnumValue("Bayleyite") BAYLEYITE("Bayleyite"), @XmlEnumValue("Baylissite") BAYLISSITE("Baylissite"), @XmlEnumValue("Bazhenovite") BAZHENOVITE("Bazhenovite"), @XmlEnumValue("Bazirite") BAZIRITE("Bazirite"), @XmlEnumValue("Bazzite") BAZZITE("Bazzite"), @XmlEnumValue("Bearsite") BEARSITE("Bearsite"), @XmlEnumValue("Bearthite") BEARTHITE("Bearthite"), @XmlEnumValue("Beaverite") BEAVERITE("Beaverite"), @XmlEnumValue("Bechererite") BECHERERITE("Bechererite"), @XmlEnumValue("Becquerelite") BECQUERELITE("Becquerelite"), @XmlEnumValue("Bederite") BEDERITE("Bederite"), @XmlEnumValue("Behierite") BEHIERITE("Behierite"), @XmlEnumValue("Behoite") BEHOITE("Behoite"), @XmlEnumValue("Beidellite") BEIDELLITE("Beidellite"), @XmlEnumValue("Belendorffite") BELENDORFFITE("Belendorffite"), @XmlEnumValue("Belkovite") BELKOVITE("Belkovite"), @XmlEnumValue("Bellbergite") BELLBERGITE("Bellbergite"), @XmlEnumValue("Bellidoite") BELLIDOITE("Bellidoite"), @XmlEnumValue("Bellingerite") BELLINGERITE("Bellingerite"), @XmlEnumValue("Belloite") BELLOITE("Belloite"), @XmlEnumValue("Belovite-(Ce)") BELOVITE_CE("Belovite-(Ce)"), @XmlEnumValue("Belovite-(La)") BELOVITE_LA("Belovite-(La)"), @XmlEnumValue("Belyankinite") BELYANKINITE("Belyankinite"), @XmlEnumValue("Bementite") BEMENTITE("Bementite"), @XmlEnumValue("Benauite") BENAUITE("Benauite"), @XmlEnumValue("Benavidesite") BENAVIDESITE("Benavidesite"), @XmlEnumValue("Benitoite") BENITOITE("Benitoite"), @XmlEnumValue("Benjaminite") BENJAMINITE("Benjaminite"), @XmlEnumValue("Benleonardite") BENLEONARDITE("Benleonardite"), @XmlEnumValue("Benstonite") BENSTONITE("Benstonite"), @XmlEnumValue("Bentorite") BENTORITE("Bentorite"), @XmlEnumValue("Benyacarite") BENYACARITE("Benyacarite"), @XmlEnumValue("Beraunite") BERAUNITE("Beraunite"), @XmlEnumValue("Berborite") BERBORITE("Berborite"), @XmlEnumValue("Berborite-1t") BERBORITE_1_T("Berborite-1t"), @XmlEnumValue("Berdesinskiite") BERDESINSKIITE("Berdesinskiite"), @XmlEnumValue("Berezanskite") BEREZANSKITE("Berezanskite"), @XmlEnumValue("Bergenite") BERGENITE("Bergenite"), @XmlEnumValue("Bergslagite") BERGSLAGITE("Bergslagite"), @XmlEnumValue("Berlinite") BERLINITE("Berlinite"), @XmlEnumValue("Bermanite") BERMANITE("Bermanite"), @XmlEnumValue("Bernalite") BERNALITE("Bernalite"), @XmlEnumValue("Bernardite") BERNARDITE("Bernardite"), @XmlEnumValue("Berndtite") BERNDTITE("Berndtite"), @XmlEnumValue("Berndtite-2t") BERNDTITE_2_T("Berndtite-2t"), @XmlEnumValue("Berndtite-4h") BERNDTITE_4_H("Berndtite-4h"), @XmlEnumValue("Berryite") BERRYITE("Berryite"), @XmlEnumValue("Berthierine") BERTHIERINE("Berthierine"), @XmlEnumValue("Berthierite") BERTHIERITE("Berthierite"), @XmlEnumValue("Bertossaite") BERTOSSAITE("Bertossaite"), @XmlEnumValue("Bertrandite") BERTRANDITE("Bertrandite"), @XmlEnumValue("Beryl") BERYL("Beryl"), @XmlEnumValue("Beryllite") BERYLLITE("Beryllite"), @XmlEnumValue("Beryllonite") BERYLLONITE("Beryllonite"), @XmlEnumValue("Berzelianite") BERZELIANITE("Berzelianite"), @XmlEnumValue("Berzeliite") BERZELIITE("Berzeliite"), @XmlEnumValue("Bessmertnovite") BESSMERTNOVITE("Bessmertnovite"), @XmlEnumValue("Beta-fergusonite-(Ce)") BETA_FERGUSONITE_CE("Beta-fergusonite-(Ce)"), @XmlEnumValue("Beta-fergusonite-(Nd)") BETA_FERGUSONITE_ND("Beta-fergusonite-(Nd)"), @XmlEnumValue("Beta-fergusonite-(Y)") BETA_FERGUSONITE_Y("Beta-fergusonite-(Y)"), @XmlEnumValue("Betafite") BETAFITE("Betafite"), @XmlEnumValue("Betekhtinite") BETEKHTINITE("Betekhtinite"), @XmlEnumValue("Betpakdalite") BETPAKDALITE("Betpakdalite"), @XmlEnumValue("Beudantite") BEUDANTITE("Beudantite"), @XmlEnumValue("Beusite") BEUSITE("Beusite"), @XmlEnumValue("Beyerite") BEYERITE("Beyerite"), @XmlEnumValue("Bezsmertnovite") BEZSMERTNOVITE("Bezsmertnovite"), @XmlEnumValue("Bianchite") BIANCHITE("Bianchite"), @XmlEnumValue("Bicchulite") BICCHULITE("Bicchulite"), @XmlEnumValue("Bideauxite") BIDEAUXITE("Bideauxite"), @XmlEnumValue("Bieberite") BIEBERITE("Bieberite"), @XmlEnumValue("Biehlite") BIEHLITE("Biehlite"), @XmlEnumValue("Bigcreekite") BIGCREEKITE("Bigcreekite"), @XmlEnumValue("Bijvoetite-(Y)") BIJVOETITE_Y("Bijvoetite-(Y)"), @XmlEnumValue("Bikitaite") BIKITAITE("Bikitaite"), @XmlEnumValue("Bilibinskite") BILIBINSKITE("Bilibinskite"), @XmlEnumValue("Bilinite") BILINITE("Bilinite"), @XmlEnumValue("Billietite") BILLIETITE("Billietite"), @XmlEnumValue("Billingsleyite") BILLINGSLEYITE("Billingsleyite"), @XmlEnumValue("Bindheimite") BINDHEIMITE("Bindheimite"), @XmlEnumValue("Biotite") BIOTITE("Biotite"), @XmlEnumValue("Biphosphammite") BIPHOSPHAMMITE("Biphosphammite"), @XmlEnumValue("Biringuccite") BIRINGUCCITE("Biringuccite"), @XmlEnumValue("Birnessite") BIRNESSITE("Birnessite"), @XmlEnumValue("Bischofite") BISCHOFITE("Bischofite"), @XmlEnumValue("Bismite") BISMITE("Bismite"), @XmlEnumValue("Bismoclite") BISMOCLITE("Bismoclite"), @XmlEnumValue("Bismuth") BISMUTH("Bismuth"), @XmlEnumValue("Bismuthinite") BISMUTHINITE("Bismuthinite"), @XmlEnumValue("Bismutite") BISMUTITE("Bismutite"), @XmlEnumValue("Bismutocolumbite") BISMUTOCOLUMBITE("Bismutocolumbite"), @XmlEnumValue("Bismutoferrite") BISMUTOFERRITE("Bismutoferrite"), @XmlEnumValue("Bismutohauchecornite") BISMUTOHAUCHECORNITE("Bismutohauchecornite"), @XmlEnumValue("Bismutomicrolite") BISMUTOMICROLITE("Bismutomicrolite"), @XmlEnumValue("Bismutopyrochlore") BISMUTOPYROCHLORE("Bismutopyrochlore"), @XmlEnumValue("Bismutostibiconite") BISMUTOSTIBICONITE("Bismutostibiconite"), @XmlEnumValue("Bismutotantalite") BISMUTOTANTALITE("Bismutotantalite"), @XmlEnumValue("Bityite") BITYITE("Bityite"), @XmlEnumValue("Bixbyite") BIXBYITE("Bixbyite"), @XmlEnumValue("Bjarebyite") BJAREBYITE("Bjarebyite"), @XmlEnumValue("Blakeite") BLAKEITE("Blakeite"), @XmlEnumValue("Blatonite") BLATONITE("Blatonite"), @XmlEnumValue("Blatterite") BLATTERITE("Blatterite"), @XmlEnumValue("Bleasdaleite") BLEASDALEITE("Bleasdaleite"), @XmlEnumValue("Blixite") BLIXITE("Blixite"), @XmlEnumValue("Blodite") BLODITE("Blodite"), @XmlEnumValue("Blossite") BLOSSITE("Blossite"), @XmlEnumValue("Bobfergusonite") BOBFERGUSONITE("Bobfergusonite"), @XmlEnumValue("Bobierrite") BOBIERRITE("Bobierrite"), @XmlEnumValue("Bogdanovite") BOGDANOVITE("Bogdanovite"), @XmlEnumValue("Boggildite") BOGGILDITE("Boggildite"), @XmlEnumValue("Boggsite") BOGGSITE("Boggsite"), @XmlEnumValue("Bogvadite") BOGVADITE("Bogvadite"), @XmlEnumValue("Bohdanowiczite") BOHDANOWICZITE("Bohdanowiczite"), @XmlEnumValue("Bohmite") BOHMITE("Bohmite"), @XmlEnumValue("Bokite") BOKITE("Bokite"), @XmlEnumValue("Boleite") BOLEITE("Boleite"), @XmlEnumValue("Bolivarite") BOLIVARITE("Bolivarite"), @XmlEnumValue("Boltwoodite") BOLTWOODITE("Boltwoodite"), @XmlEnumValue("Bonaccordite") BONACCORDITE("Bonaccordite"), @XmlEnumValue("Bonattite") BONATTITE("Bonattite"), @XmlEnumValue("Bonshtedtite") BONSHTEDTITE("Bonshtedtite"), @XmlEnumValue("Boothite") BOOTHITE("Boothite"), @XmlEnumValue("Boracite") BORACITE("Boracite"), @XmlEnumValue("Boralsilite") BORALSILITE("Boralsilite"), @XmlEnumValue("Borax") BORAX("Borax"), @XmlEnumValue("Borcarite") BORCARITE("Borcarite"), @XmlEnumValue("Borishanskiite") BORISHANSKIITE("Borishanskiite"), @XmlEnumValue("Bornemanite") BORNEMANITE("Bornemanite"), @XmlEnumValue("Bornhardtite") BORNHARDTITE("Bornhardtite"), @XmlEnumValue("Bornite") BORNITE("Bornite"), @XmlEnumValue("Borodaevite") BORODAEVITE("Borodaevite"), @XmlEnumValue("Boromuscovite") BOROMUSCOVITE("Boromuscovite"), @XmlEnumValue("Borovskite") BOROVSKITE("Borovskite"), @XmlEnumValue("Bostwickite") BOSTWICKITE("Bostwickite"), @XmlEnumValue("Botallackite") BOTALLACKITE("Botallackite"), @XmlEnumValue("Botryogen") BOTRYOGEN("Botryogen"), @XmlEnumValue("Bottinoite") BOTTINOITE("Bottinoite"), @XmlEnumValue("Boulangerite") BOULANGERITE("Boulangerite"), @XmlEnumValue("Bournonite") BOURNONITE("Bournonite"), @XmlEnumValue("Boussingaultite") BOUSSINGAULTITE("Boussingaultite"), @XmlEnumValue("Boussingualtite") BOUSSINGUALTITE("Boussingualtite"), @XmlEnumValue("Bowieite") BOWIEITE("Bowieite"), @XmlEnumValue("Boyleite") BOYLEITE("Boyleite"), @XmlEnumValue("Brabantite") BRABANTITE("Brabantite"), @XmlEnumValue("Bracewellite") BRACEWELLITE("Bracewellite"), @XmlEnumValue("Brackebuschite") BRACKEBUSCHITE("Brackebuschite"), @XmlEnumValue("Bradleyite") BRADLEYITE("Bradleyite"), @XmlEnumValue("Braggite") BRAGGITE("Braggite"), @XmlEnumValue("Braitschite-(Ce)") BRAITSCHITE_CE("Braitschite-(Ce)"), @XmlEnumValue("Brammallite") BRAMMALLITE("Brammallite"), @XmlEnumValue("Brandholzite") BRANDHOLZITE("Brandholzite"), @XmlEnumValue("Brandtite") BRANDTITE("Brandtite"), @XmlEnumValue("Brannerite") BRANNERITE("Brannerite"), @XmlEnumValue("Brannockite") BRANNOCKITE("Brannockite"), @XmlEnumValue("Brassite") BRASSITE("Brassite"), @XmlEnumValue("Braunite") BRAUNITE("Braunite"), @XmlEnumValue("Bravoite") BRAVOITE("Bravoite"), @XmlEnumValue("Brazilianite") BRAZILIANITE("Brazilianite"), @XmlEnumValue("Bredigite") BREDIGITE("Bredigite"), @XmlEnumValue("Breithauptite") BREITHAUPTITE("Breithauptite"), @XmlEnumValue("Brenkite") BRENKITE("Brenkite"), @XmlEnumValue("Brewsterite") BREWSTERITE("Brewsterite"), @XmlEnumValue("Brewsterite-Ba") BREWSTERITE_BA("Brewsterite-Ba"), @XmlEnumValue("Brewsterite-Sr") BREWSTERITE_SR("Brewsterite-Sr"), @XmlEnumValue("Brezinaite") BREZINAITE("Brezinaite"), @XmlEnumValue("Brianite") BRIANITE("Brianite"), @XmlEnumValue("Brianroulstonite") BRIANROULSTONITE("Brianroulstonite"), @XmlEnumValue("Brianyoungite") BRIANYOUNGITE("Brianyoungite"), @XmlEnumValue("Briartite") BRIARTITE("Briartite"), @XmlEnumValue("Brindleyite") BRINDLEYITE("Brindleyite"), @XmlEnumValue("Britholite") BRITHOLITE("Britholite"), @XmlEnumValue("Britholite-(Ce)") BRITHOLITE_CE("Britholite-(Ce)"), @XmlEnumValue("Britholite-(Y)") BRITHOLITE_Y("Britholite-(Y)"), @XmlEnumValue("Brizziite") BRIZZIITE("Brizziite"), @XmlEnumValue("Brochantite") BROCHANTITE("Brochantite"), @XmlEnumValue("Brockite") BROCKITE("Brockite"), @XmlEnumValue("Brokenhillite") BROKENHILLITE("Brokenhillite"), @XmlEnumValue("Bromargyrite") BROMARGYRITE("Bromargyrite"), @XmlEnumValue("Bromellite") BROMELLITE("Bromellite"), @XmlEnumValue("Brookite") BROOKITE("Brookite"), @XmlEnumValue("Brownmillerite") BROWNMILLERITE("Brownmillerite"), @XmlEnumValue("Brucite") BRUCITE("Brucite"), @XmlEnumValue("Bruggenite") BRUGGENITE("Bruggenite"), @XmlEnumValue("Brugnatellite") BRUGNATELLITE("Brugnatellite"), @XmlEnumValue("Brunogeierite") BRUNOGEIERITE("Brunogeierite"), @XmlEnumValue("Brushite") BRUSHITE("Brushite"), @XmlEnumValue("Buchwaldite") BUCHWALDITE("Buchwaldite"), @XmlEnumValue("Buckhornite") BUCKHORNITE("Buckhornite"), @XmlEnumValue("Buddingtonite") BUDDINGTONITE("Buddingtonite"), @XmlEnumValue("Buergerite") BUERGERITE("Buergerite"), @XmlEnumValue("Buetschliite") BUETSCHLIITE("Buetschliite"), @XmlEnumValue("Bukovite") BUKOVITE("Bukovite"), @XmlEnumValue("Bukovskyite") BUKOVSKYITE("Bukovskyite"), @XmlEnumValue("Bulachite") BULACHITE("Bulachite"), @XmlEnumValue("Bultfonteinite") BULTFONTEINITE("Bultfonteinite"), @XmlEnumValue("Bunsenite") BUNSENITE("Bunsenite"), @XmlEnumValue("Burangaite") BURANGAITE("Burangaite"); private final String value; MineralDetails1(String v) { value = v; } public String value() { return value; } public static MineralDetails1 fromValue(String v) { for (MineralDetails1 c: MineralDetails1.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
package gov.nih.mipav.model.scripting.actions; import gov.nih.mipav.model.scripting.ScriptableActionInterface; import gov.nih.mipav.model.scripting.parameters.ParameterTable; import gov.nih.mipav.view.Preferences; /** * A base class for all non-algorithmic (not JDialog*) script actions. */ public abstract class ActionBase implements ScriptableActionInterface { protected boolean isScript = true; /** * {@inheritDoc} */ public abstract void insertScriptLine(); /** * {@inheritDoc} */ public abstract void scriptRun(ParameterTable parameters); /** * Returns the script action command string for this action. * * @return The script command which should be used for this action (e.g., Clone for ActionClone). */ public String getActionName() { return ActionBase.getActionName(this.getClass()); } /** * Returns the script command string for an action. * * @param actionClass The class to find the script command string for. * * @return The script command which should be used for the given class (e.g., Clone for ActionClone). */ public static final String getActionName(Class actionClass) { String name = actionClass.getName(); int index = name.lastIndexOf("Action"); if (index == -1) { // TODO: may be an fatal error.. Preferences.debug("action base: No script Action prefix found. Returning " + name + "\n", Preferences.DEBUG_SCRIPTING); return name; } else { Preferences.debug("action base: Extracting script action command. Returning " + name.substring(index + 6) + "\n", Preferences.DEBUG_SCRIPTING); return name.substring(index + 6); } } public void setIsScript(boolean isScript) { this.isScript = isScript; } public boolean isScript() { return this.isScript; } }
class Solution { public boolean isValid(String s) { Stack<Character> charStack = new Stack<>(); for(char i: s.toCharArray()){ if(i == '(' || i == '{' || i == '['){ charStack.push(i); } else{ if(charStack.isEmpty()){ return false; } char popped = charStack.pop(); if((i == ')' && popped == '(') || (i == '}' && popped == '{') || (i == ']' && popped == '[')){ continue; } return false; } } if(!charStack.isEmpty()){ return false; } return true; } }
package team.groupproject.converters; import team.groupproject.dto.MyUserDto; import team.groupproject.entity.Myuser; public class MyUserConverter { public static MyUserDto convertMyUserToMyUserDto(Myuser myuser) { MyUserDto myUserDto = new MyUserDto(); myUserDto.setId(myuser.getId()); myUserDto.setEmail(myuser.getEmail()); myUserDto.setTitle(myuser.getTitle()); myUserDto.setFirstName(myuser.getFirstName()); myUserDto.setLastName(myuser.getLastName()); myUserDto.setUsername(myuser.getUsername()); myUserDto.setPhoneNumber(myuser.getPhoneNumber()); return myUserDto; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Paricular_view_our_social_work.java * * Created on May 18, 2012, 12:09:13 AM */ /** * * @author Amresh */ import java.sql.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Paricular_view_our_social_work extends javax.swing.JFrame { Connection con; Statement st; ResultSet rs; ResultSetMetaData rmeta; /** Creates new form Paricular_view_our_social_work */ public Paricular_view_our_social_work() { initComponents(); } public boolean setconn(String ds,String user,String pwd) { try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String url="jdbc:odbc:"+ds; con=DriverManager.getConnection(url,user,pwd); return(true); } catch(Exception e) { System.out.print(e.getMessage()); return(false); } }//close of conn() public void mySelect(String table) { try { st=con.createStatement(); String sql="SELECT * From "+table; rs=st.executeQuery(sql); //myDisplayResult(result); // rs.next(); //t1.setText(rs.getString(1)); //p1.setText(rs.getString(2)); } catch(Exception e) { System.out.println("Error:"+e.getMessage()); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); t1 = new javax.swing.JTextField(); t2 = new javax.swing.JTextField(); t3 = new javax.swing.JTextField(); t4 = new javax.swing.JTextField(); t5 = new javax.swing.JTextField(); t6 = new javax.swing.JTextField(); t7 = new javax.swing.JTextField(); t8 = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); t9 = new javax.swing.JTextArea(); ti1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Particular View of Our Social Work"); getContentPane().setLayout(null); jLabel1.setFont(new java.awt.Font("Arial", 1, 18)); jLabel1.setForeground(new java.awt.Color(255, 204, 204)); jLabel1.setText("Particular View of Our Social Work"); jLabel1.setName("jLabel1"); // NOI18N getContentPane().add(jLabel1); jLabel1.setBounds(370, 10, 310, 22); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/DSC02829.JPG"))); // NOI18N jLabel2.setText("jLabel2"); jLabel2.setName("jLabel2"); // NOI18N getContentPane().add(jLabel2); jLabel2.setBounds(0, 0, 690, 50); jPanel1.setBackground(new java.awt.Color(255, 204, 153)); jPanel1.setName("jPanel1"); // NOI18N jPanel1.setLayout(null); jLabel3.setFont(new java.awt.Font("Arial", 1, 14)); jLabel3.setText("Please enter Our Work Name"); jLabel3.setName("jLabel3"); // NOI18N jPanel1.add(jLabel3); jLabel3.setBounds(90, 30, 210, 17); jButton2.setText("Exit"); jButton2.setName("jButton2"); // NOI18N jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel1.add(jButton2); jButton2.setBounds(570, 410, 90, 40); jLabel5.setFont(new java.awt.Font("Arial", 1, 14)); jLabel5.setText("Work Name"); jLabel5.setName("jLabel5"); // NOI18N jPanel1.add(jLabel5); jLabel5.setBounds(80, 90, 79, 17); jLabel6.setFont(new java.awt.Font("Arial", 1, 14)); jLabel6.setText("Plase"); jLabel6.setName("jLabel6"); // NOI18N jPanel1.add(jLabel6); jLabel6.setBounds(80, 110, 40, 17); jLabel7.setFont(new java.awt.Font("Arial", 1, 14)); jLabel7.setText("Work Type"); jLabel7.setName("jLabel7"); // NOI18N jPanel1.add(jLabel7); jLabel7.setBounds(80, 150, 73, 17); jLabel8.setFont(new java.awt.Font("Arial", 1, 14)); jLabel8.setText("Total member in Work"); jLabel8.setName("jLabel8"); // NOI18N jPanel1.add(jLabel8); jLabel8.setBounds(80, 170, 152, 17); jLabel9.setFont(new java.awt.Font("Arial", 1, 14)); jLabel9.setText("Date"); jLabel9.setName("jLabel9"); // NOI18N jPanel1.add(jLabel9); jLabel9.setBounds(80, 127, 32, 20); jLabel10.setFont(new java.awt.Font("Arial", 1, 14)); jLabel10.setText("Year"); jLabel10.setName("jLabel10"); // NOI18N jPanel1.add(jLabel10); jLabel10.setBounds(80, 190, 33, 17); jLabel11.setFont(new java.awt.Font("Arial", 1, 14)); jLabel11.setText("Help get from you"); jLabel11.setName("jLabel11"); // NOI18N jPanel1.add(jLabel11); jLabel11.setBounds(80, 220, 124, 17); jLabel12.setFont(new java.awt.Font("Arial", 1, 14)); jLabel12.setText("Likes your work"); jLabel12.setName("jLabel12"); // NOI18N jPanel1.add(jLabel12); jLabel12.setBounds(80, 250, 110, 17); jLabel13.setFont(new java.awt.Font("Arial", 1, 14)); jLabel13.setText("About"); jLabel13.setName("jLabel13"); // NOI18N jPanel1.add(jLabel13); jLabel13.setBounds(70, 340, 41, 17); t1.setName("t1"); // NOI18N jPanel1.add(t1); t1.setBounds(170, 90, 240, 20); t2.setName("t2"); // NOI18N jPanel1.add(t2); t2.setBounds(170, 110, 240, 20); t3.setName("t3"); // NOI18N jPanel1.add(t3); t3.setBounds(170, 130, 240, 20); t4.setName("t4"); // NOI18N jPanel1.add(t4); t4.setBounds(170, 150, 240, 20); t5.setName("t5"); // NOI18N jPanel1.add(t5); t5.setBounds(240, 170, 170, 20); t6.setName("t6"); // NOI18N jPanel1.add(t6); t6.setBounds(180, 190, 230, 20); t7.setName("t7"); // NOI18N jPanel1.add(t7); t7.setBounds(210, 220, 200, 20); t8.setName("t8"); // NOI18N jPanel1.add(t8); t8.setBounds(210, 250, 200, 20); jScrollPane1.setName("jScrollPane1"); // NOI18N t9.setColumns(20); t9.setRows(5); t9.setName("t9"); // NOI18N jScrollPane1.setViewportView(t9); jPanel1.add(jScrollPane1); jScrollPane1.setBounds(140, 330, 410, 96); ti1.setName("ti1"); // NOI18N jPanel1.add(ti1); ti1.setBounds(320, 30, 220, 20); jButton1.setText("DISPLAY"); jButton1.setName("jButton1"); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel1.add(jButton1); jButton1.setBounds(560, 23, 100, 40); getContentPane().add(jPanel1); jPanel1.setBounds(0, 90, 690, 660); jLabel4.setFont(new java.awt.Font("Arial", 3, 18)); jLabel4.setText("Abhilasha pariwar SwyemSevi Sanstha marichaibari Katihar"); jLabel4.setName("jLabel4"); // NOI18N getContentPane().add(jLabel4); jLabel4.setBounds(80, 50, 520, 22); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-705)/2, (screenSize.height-590)/2, 705, 590); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: setVisible(false); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: int flag=1; try { st=con.createStatement(); String sql="SELECT * FROM socialwork;"; rs=st.executeQuery(sql); String mid=ti1.getText(); //String mid=JOptionPane.showInputDialog(this,"ENTER NAME OF POST"); while(rs.next()) { if (mid.equals(rs.getString(1))) { t1.setText(String.valueOf(mid)); //t1.setText(rs.getString(1)); t2.setText(rs.getString(2)); t3.setText(rs.getString(3)); t4.setText(rs.getString(4)); t5.setText(rs.getString(5)); t6.setText(rs.getString(6)); t7.setText(rs.getString(7)); t8.setText(rs.getString(8)); t9.setText(rs.getString(9)); //flag=2; break; } } if(flag==2) { JOptionPane.showMessageDialog(this,"Invalid Work Name Found"); } } catch(Exception e) { JOptionPane.showMessageDialog(this,e.getMessage()); } }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Paricular_view_our_social_work().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField t1; private javax.swing.JTextField t2; private javax.swing.JTextField t3; private javax.swing.JTextField t4; private javax.swing.JTextField t5; private javax.swing.JTextField t6; private javax.swing.JTextField t7; private javax.swing.JTextField t8; private javax.swing.JTextArea t9; private javax.swing.JTextField ti1; // End of variables declaration//GEN-END:variables }
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.resource; import java.io.IOException; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.HttpRequestHandler; import org.springframework.web.context.ServletContextAware; /** * An {@link HttpRequestHandler} for serving static files using the Servlet container's "default" Servlet. * * <p>This handler is intended to be used with a "/*" mapping when the * {@link org.springframework.web.servlet.DispatcherServlet DispatcherServlet} * is mapped to "/", thus overriding the Servlet container's default handling of static resources. * The mapping to this handler should generally be ordered as the last in the chain so that it will * only execute when no other more specific mappings (i.e., to controllers) can be matched. * * <p>Requests are handled by forwarding through the {@link RequestDispatcher} obtained via the * name specified through the {@link #setDefaultServletName "defaultServletName" property}. * In most cases, the {@code defaultServletName} does not need to be set explicitly, as the * handler checks at initialization time for the presence of the default Servlet of well-known * containers such as Tomcat, Jetty, Resin, WebLogic and WebSphere. However, when running in a * container where the default Servlet's name is not known, or where it has been customized * via server configuration, the {@code defaultServletName} will need to be set explicitly. * * @author Jeremy Grelle * @author Juergen Hoeller * @since 3.0.4 */ public class DefaultServletHttpRequestHandler implements HttpRequestHandler, ServletContextAware { /** Default Servlet name used by Tomcat, Jetty, JBoss, and GlassFish. */ private static final String COMMON_DEFAULT_SERVLET_NAME = "default"; /** Default Servlet name used by Google App Engine. */ private static final String GAE_DEFAULT_SERVLET_NAME = "_ah_default"; /** Default Servlet name used by Resin. */ private static final String RESIN_DEFAULT_SERVLET_NAME = "resin-file"; /** Default Servlet name used by WebLogic. */ private static final String WEBLOGIC_DEFAULT_SERVLET_NAME = "FileServlet"; /** Default Servlet name used by WebSphere. */ private static final String WEBSPHERE_DEFAULT_SERVLET_NAME = "SimpleFileServlet"; @Nullable private String defaultServletName; @Nullable private ServletContext servletContext; /** * Set the name of the default Servlet to be forwarded to for static resource requests. */ public void setDefaultServletName(String defaultServletName) { this.defaultServletName = defaultServletName; } /** * If the {@code defaultServletName} property has not been explicitly set, * attempts to locate the default Servlet using the known common * container-specific names. */ @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; if (!StringUtils.hasText(this.defaultServletName)) { if (this.servletContext.getNamedDispatcher(COMMON_DEFAULT_SERVLET_NAME) != null) { this.defaultServletName = COMMON_DEFAULT_SERVLET_NAME; } else if (this.servletContext.getNamedDispatcher(GAE_DEFAULT_SERVLET_NAME) != null) { this.defaultServletName = GAE_DEFAULT_SERVLET_NAME; } else if (this.servletContext.getNamedDispatcher(RESIN_DEFAULT_SERVLET_NAME) != null) { this.defaultServletName = RESIN_DEFAULT_SERVLET_NAME; } else if (this.servletContext.getNamedDispatcher(WEBLOGIC_DEFAULT_SERVLET_NAME) != null) { this.defaultServletName = WEBLOGIC_DEFAULT_SERVLET_NAME; } else if (this.servletContext.getNamedDispatcher(WEBSPHERE_DEFAULT_SERVLET_NAME) != null) { this.defaultServletName = WEBSPHERE_DEFAULT_SERVLET_NAME; } else { throw new IllegalStateException("Unable to locate the default servlet for serving static content. " + "Please set the 'defaultServletName' property explicitly."); } } } @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Assert.state(this.servletContext != null, "No ServletContext set"); RequestDispatcher rd = this.servletContext.getNamedDispatcher(this.defaultServletName); if (rd == null) { throw new IllegalStateException("A RequestDispatcher could not be located for the default servlet '" + this.defaultServletName + "'"); } rd.forward(request, response); } }
package com.yuneec.widget; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import android.widget.LinearLayout; import com.yuneec.flightmode15.R; import com.yuneec.flightmode15.Utilities; import com.yuneec.mission.MissionInterface.MissionType; import com.yuneec.mission.MissionPresentation; import com.yuneec.mission.MissionPresentation.MissionCallback; import com.yuneec.mission.MissionPresentation.MissionState; import com.yuneec.mission.SaveMissionData; import com.yuneec.uartcontroller.GPSUpLinkData; import com.yuneec.uartcontroller.RoiData; import com.yuneec.uartcontroller.UARTInfoMessage.MissionReply; import com.yuneec.uartcontroller.WaypointData; import com.yuneec.widget.MissionPromptView.MissionStep; import java.util.ArrayList; public class MissionView extends FrameLayout implements OnClickListener { private static /* synthetic */ int[] $SWITCH_TABLE$com$yuneec$mission$MissionPresentation$MissionState = null; private static final String LAST_POINTS_TABLE_NAME = "last_points_table"; private Button addPointButton; private Button backButton; private Button cccButton; private Button clearPointButton; private Button confirmButton; private MissionState currentMissionState = MissionState.NONE; private MissionType currentMissionType = MissionType.NONE; private Button cycleButton; private Button deletePointButton; private float droneAltitude; private float droneLatitude; private float droneLongitude; private Button exitButton; private int fMode = 0; private Button journeyButton; private Button loadRecordButton; private LinearLayout missionMenuView; private MissionPresentation missionPresentation; private MissionPromptView missionPromptView; private MissionViewCallback missionViewCallback; private Button pauseButton; private ArrayList<WaypointData> recordPoints = new ArrayList(); private Button resumeButton; private Button roiButton; private RoiData roiData = new RoiData(); private Button setCenterButton; public interface MissionViewCallback { GPSUpLinkData getControllerGps(); void updateError(int i); void updateStep(MissionState missionState); } static /* synthetic */ int[] $SWITCH_TABLE$com$yuneec$mission$MissionPresentation$MissionState() { int[] iArr = $SWITCH_TABLE$com$yuneec$mission$MissionPresentation$MissionState; if (iArr == null) { iArr = new int[MissionState.values().length]; try { iArr[MissionState.COMPLETE.ordinal()] = 5; } catch (NoSuchFieldError e) { } try { iArr[MissionState.NONE.ordinal()] = 1; } catch (NoSuchFieldError e2) { } try { iArr[MissionState.PAUSE.ordinal()] = 4; } catch (NoSuchFieldError e3) { } try { iArr[MissionState.PREPARE.ordinal()] = 2; } catch (NoSuchFieldError e4) { } try { iArr[MissionState.RESUME.ordinal()] = 3; } catch (NoSuchFieldError e5) { } $SWITCH_TABLE$com$yuneec$mission$MissionPresentation$MissionState = iArr; } return iArr; } public MissionView(Context context) { super(context); init(context); } public MissionView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public void updateFeedback(MissionReply feedbackData) { this.missionPresentation.updateFeedback(this.fMode, feedbackData); } public void setMissionViewCallback(MissionViewCallback missionViewCallback) { this.missionViewCallback = missionViewCallback; } public void updateDroneGps(int fMode, float latitude, float longitude, float altitude) { this.droneLatitude = latitude; this.droneLongitude = longitude; this.droneAltitude = altitude; this.fMode = fMode; } @SuppressLint({"ResourceAsColor"}) private void init(Context context) { LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService("layout_inflater"); this.missionPresentation = new MissionPresentation(new MissionCallback() { private static /* synthetic */ int[] $SWITCH_TABLE$com$yuneec$mission$MissionPresentation$MissionState; static /* synthetic */ int[] $SWITCH_TABLE$com$yuneec$mission$MissionPresentation$MissionState() { int[] iArr = $SWITCH_TABLE$com$yuneec$mission$MissionPresentation$MissionState; if (iArr == null) { iArr = new int[MissionState.values().length]; try { iArr[MissionState.COMPLETE.ordinal()] = 5; } catch (NoSuchFieldError e) { } try { iArr[MissionState.NONE.ordinal()] = 1; } catch (NoSuchFieldError e2) { } try { iArr[MissionState.PAUSE.ordinal()] = 4; } catch (NoSuchFieldError e3) { } try { iArr[MissionState.PREPARE.ordinal()] = 2; } catch (NoSuchFieldError e4) { } try { iArr[MissionState.RESUME.ordinal()] = 3; } catch (NoSuchFieldError e5) { } $SWITCH_TABLE$com$yuneec$mission$MissionPresentation$MissionState = iArr; } return iArr; } public void onUpdateState(MissionType type, MissionState state, int progress) { switch (AnonymousClass1.$SWITCH_TABLE$com$yuneec$mission$MissionPresentation$MissionState()[state.ordinal()]) { case 1: MissionView.this.missionPromptView.updatStep(MissionStep.PREPARE); break; case 2: MissionView.this.missionPromptView.updatStep(MissionStep.PREPARE); break; case 3: MissionView.this.missionPromptView.updateStepPrompt(MissionStep.RUNING, "Resume"); break; case 4: MissionView.this.missionPromptView.updateStepPrompt(MissionStep.RUNING, "Pause"); break; case 5: MissionView.this.missionPromptView.updatStep(MissionStep.PREPARE); break; } MissionView.this.missionViewCallback.updateStep(state); MissionView.this.currentMissionState = state; MissionView.this.updateControlButtonsEnable(state); } public void onTerminate(boolean result, int reasonResId) { if (result) { MissionView.this.currentMissionState = MissionState.COMPLETE; MissionView.this.missionPromptView.updatStep(MissionStep.PREPARE); MissionView.this.addMissionSelectMenu(); } else if (MissionView.this.missionViewCallback != null) { MissionView.this.missionViewCallback.updateError(reasonResId); } } public void onResume(MissionType type, boolean result, int reasonResId) { if (result) { MissionView.this.currentMissionState = MissionState.RESUME; MissionView.this.missionPromptView.updateStepPrompt(MissionStep.RUNING, "Resume"); } else if (MissionView.this.missionViewCallback != null) { MissionView.this.missionViewCallback.updateError(reasonResId); } } public void onQuery(MissionType type, boolean result, Object answer) { if (result) { if (type == MissionType.CRUVE_CABLE_CAM && (answer instanceof WaypointData)) { WaypointData waypointData = (WaypointData) answer; waypointData.pointerIndex = MissionView.this.recordPoints.size(); MissionView.this.recordPoints.add(waypointData); MissionView.this.missionPromptView.updateStepPrompt(MissionStep.PREPARE, "Point: " + MissionView.this.recordPoints.size()); } } else if (MissionView.this.missionViewCallback != null) { MissionView.this.missionViewCallback.updateError(R.string.mission_command_reason_query_null); } } public void onPrepare(MissionType type, boolean result, int reasonResId) { if (result) { MissionView.this.currentMissionState = MissionState.PREPARE; MissionView.this.missionPresentation.confirm(type); } else if (MissionView.this.missionViewCallback != null) { MissionView.this.missionViewCallback.updateError(reasonResId); } } public void onPause(MissionType type, boolean result, int reasonResId) { if (result) { MissionView.this.currentMissionState = MissionState.PAUSE; MissionView.this.missionPromptView.updateStepPrompt(MissionStep.RUNING, "Pause"); } else if (MissionView.this.missionViewCallback != null) { MissionView.this.missionViewCallback.updateError(reasonResId); } } public void onConfirm(MissionType type, boolean result, int reasonResId) { if (result) { MissionView.this.currentMissionState = MissionState.RESUME; MissionView.this.missionPromptView.updatStep(MissionStep.RUNING); MissionView.this.addMissionControlMenu(); } else if (MissionView.this.missionViewCallback != null) { MissionView.this.missionViewCallback.updateError(reasonResId); } } public void onCancel(MissionType type, boolean result, int reasonResId) { if (result) { MissionView.this.currentMissionState = MissionState.NONE; MissionView.this.missionPromptView.updatStep(MissionStep.PREPARE); MissionView.this.addMissionSelectMenu(); } else if (MissionView.this.missionViewCallback != null) { MissionView.this.missionViewCallback.updateError(reasonResId); } } }); initButton(context); LayoutParams params = new LayoutParams(-1, -1); View view = layoutInflater.inflate(R.layout.mission_frame, null); addView(view, params); setBackgroundColor(17170445); this.missionMenuView = (LinearLayout) view.findViewById(R.id.mission_menu_view); this.missionPromptView = (MissionPromptView) view.findViewById(R.id.mission_prompt_view); addMissionSelectMenu(); setVisibility(8); } private void updateControlButtonsEnable(MissionState missionState) { switch ($SWITCH_TABLE$com$yuneec$mission$MissionPresentation$MissionState()[missionState.ordinal()]) { case 1: this.resumeButton.setEnabled(true); this.pauseButton.setEnabled(true); return; case 2: this.resumeButton.setEnabled(false); this.pauseButton.setEnabled(false); return; case 3: this.resumeButton.setEnabled(false); this.pauseButton.setEnabled(true); return; case 4: this.resumeButton.setEnabled(true); this.pauseButton.setEnabled(false); return; case 5: this.resumeButton.setEnabled(true); this.pauseButton.setEnabled(true); return; default: return; } } private void initButton(Context context) { this.cccButton = new Button(context); this.cccButton.setText(R.string.mission_ccc_button); this.cccButton.setTextSize(8.0f); this.cccButton.setBackgroundResource(R.drawable.corners_round); this.cccButton.setOnClickListener(this); this.journeyButton = new Button(context); this.journeyButton.setText(R.string.mission_journey_button); this.journeyButton.setTextSize(8.0f); this.journeyButton.setBackgroundResource(R.drawable.corners_round); this.journeyButton.setOnClickListener(this); this.roiButton = new Button(context); this.roiButton.setText(R.string.mission_roi_button); this.roiButton.setTextSize(8.0f); this.roiButton.setBackgroundResource(R.drawable.corners_round); this.roiButton.setOnClickListener(this); this.cycleButton = new Button(context); this.cycleButton.setText(R.string.mission_cycle_button); this.cycleButton.setTextSize(8.0f); this.cycleButton.setBackgroundResource(R.drawable.corners_round); this.cycleButton.setOnClickListener(this); this.backButton = new Button(context); this.backButton.setText(R.string.mission_back_button); this.backButton.setTextSize(8.0f); this.backButton.setBackgroundResource(R.drawable.corners_round); this.backButton.setOnClickListener(this); this.addPointButton = new Button(context); this.addPointButton.setText(R.string.mission_add_point_button); this.addPointButton.setTextSize(8.0f); this.addPointButton.setBackgroundResource(R.drawable.corners_round); this.addPointButton.setOnClickListener(this); this.deletePointButton = new Button(context); this.deletePointButton.setText(R.string.mission_delete_point_button); this.deletePointButton.setTextSize(8.0f); this.deletePointButton.setBackgroundResource(R.drawable.corners_round); this.deletePointButton.setOnClickListener(this); this.clearPointButton = new Button(context); this.clearPointButton.setText(R.string.mission_clear_point_button); this.clearPointButton.setTextSize(8.0f); this.clearPointButton.setBackgroundResource(R.drawable.corners_round); this.clearPointButton.setOnClickListener(this); this.loadRecordButton = new Button(context); this.loadRecordButton.setText(R.string.mission_load_previous_button); this.loadRecordButton.setTextSize(8.0f); this.loadRecordButton.setBackgroundResource(R.drawable.corners_round); this.loadRecordButton.setOnClickListener(this); this.setCenterButton = new Button(context); this.setCenterButton.setText(R.string.mission_set_center_button); this.setCenterButton.setTextSize(8.0f); this.setCenterButton.setBackgroundResource(R.drawable.corners_round); this.setCenterButton.setOnClickListener(this); this.confirmButton = new Button(context); this.confirmButton.setText(R.string.mission_start_button); this.confirmButton.setTextSize(8.0f); this.confirmButton.setBackgroundResource(R.drawable.corners_round); this.confirmButton.setOnClickListener(this); this.resumeButton = new Button(context); this.resumeButton.setText(R.string.mission_resume_button); this.resumeButton.setTextSize(8.0f); this.resumeButton.setBackgroundResource(R.drawable.corners_round); this.resumeButton.setOnClickListener(this); this.pauseButton = new Button(context); this.pauseButton.setText(R.string.mission_pause_button); this.pauseButton.setTextSize(8.0f); this.pauseButton.setBackgroundResource(R.drawable.corners_round); this.pauseButton.setOnClickListener(this); this.exitButton = new Button(context); this.exitButton.setText(R.string.mission_exit_button); this.exitButton.setTextSize(8.0f); this.exitButton.setBackgroundResource(R.drawable.corners_round); this.exitButton.setOnClickListener(this); } private void addMissionSelectMenu() { this.missionMenuView.removeAllViews(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(75, 50); params.rightMargin = 6; this.missionMenuView.addView(this.cccButton, params); this.missionMenuView.addView(this.journeyButton, params); this.missionMenuView.addView(this.roiButton, params); LinearLayout.LayoutParams paramsNoMargin = new LinearLayout.LayoutParams(80, 50); paramsNoMargin.rightMargin = 0; this.missionMenuView.addView(this.cycleButton, paramsNoMargin); this.missionPromptView.setVisibility(8); } private void addCCCSettingMenu() { this.missionMenuView.removeAllViews(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(75, 50); params.rightMargin = 6; this.missionMenuView.addView(this.backButton, params); this.missionMenuView.addView(this.addPointButton, params); this.missionMenuView.addView(this.deletePointButton, params); this.missionMenuView.addView(this.clearPointButton, params); this.missionMenuView.addView(this.loadRecordButton, params); LinearLayout.LayoutParams paramsNoMargin = new LinearLayout.LayoutParams(75, 50); paramsNoMargin.rightMargin = 0; this.missionMenuView.addView(this.confirmButton, paramsNoMargin); this.missionPromptView.setVisibility(0); } private void addRoiSettingMenu() { this.missionMenuView.removeAllViews(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(75, 50); params.rightMargin = 6; this.missionMenuView.addView(this.backButton, params); this.missionMenuView.addView(this.setCenterButton, params); LinearLayout.LayoutParams paramsNoMargin = new LinearLayout.LayoutParams(75, 50); paramsNoMargin.rightMargin = 0; this.missionMenuView.addView(this.confirmButton, paramsNoMargin); this.missionPromptView.setVisibility(0); } private void addOtherSettingMenu() { this.missionMenuView.removeAllViews(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(75, 50); params.rightMargin = 6; this.missionMenuView.addView(this.backButton, params); LinearLayout.LayoutParams paramsNoMargin = new LinearLayout.LayoutParams(75, 50); paramsNoMargin.rightMargin = 0; this.missionMenuView.addView(this.confirmButton, paramsNoMargin); this.missionPromptView.setVisibility(0); } private void addMissionControlMenu() { this.missionMenuView.removeAllViews(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(80, 50); params.rightMargin = 6; this.missionMenuView.addView(this.resumeButton, params); this.missionMenuView.addView(this.pauseButton, params); LinearLayout.LayoutParams paramsNoMargin = new LinearLayout.LayoutParams(80, 50); paramsNoMargin.rightMargin = 0; this.missionMenuView.addView(this.exitButton, paramsNoMargin); this.missionPromptView.setVisibility(0); } public void onClick(View v) { if (v == this.cccButton) { this.currentMissionType = MissionType.CRUVE_CABLE_CAM; addCCCSettingMenu(); this.recordPoints.clear(); } else if (v == this.journeyButton) { this.currentMissionType = MissionType.JOURNEY; addOtherSettingMenu(); } else if (v == this.roiButton) { this.currentMissionType = MissionType.ROI; this.roiData.reset(); addRoiSettingMenu(); } else if (v == this.cycleButton) { this.currentMissionType = MissionType.CYCLE; addOtherSettingMenu(); } else if (v == this.backButton) { this.currentMissionType = MissionType.NONE; this.currentMissionState = MissionState.NONE; this.missionPresentation.terminate(); addMissionSelectMenu(); } else if (v == this.addPointButton) { this.missionPresentation.query(MissionType.CRUVE_CABLE_CAM); } else if (v == this.deletePointButton) { if (this.recordPoints.size() > 0) { this.recordPoints.remove(this.recordPoints.size() - 1); } this.missionPromptView.updateStepPrompt(MissionStep.PREPARE, "Point: " + this.recordPoints.size()); } else if (v == this.clearPointButton) { this.recordPoints.clear(); this.missionPromptView.updateStepPrompt(MissionStep.PREPARE, "Clear"); } else if (v == this.loadRecordButton) { this.recordPoints.clear(); SaveMissionData.loadCruveCableCam(LAST_POINTS_TABLE_NAME, this.recordPoints); this.missionPromptView.updateStepPrompt(MissionStep.PREPARE, "Point: " + this.recordPoints.size()); } else if (v == this.confirmButton) { if (this.currentMissionType == MissionType.CRUVE_CABLE_CAM) { SaveMissionData.saveCruveCableCam(LAST_POINTS_TABLE_NAME, this.recordPoints); this.missionPresentation.prepare(this.currentMissionType, this.recordPoints); } else if (this.currentMissionType == MissionType.ROI) { if (this.roiData.centerLatitude == 0.0f || this.roiData.centerLongitude == 0.0f) { if (this.missionViewCallback != null) { this.missionViewCallback.updateError(R.string.mission_command_reason_no_center); } } else if (this.missionViewCallback != null) { GPSUpLinkData controllerGps = this.missionViewCallback.getControllerGps(); float[] result = Utilities.calculateDistanceAndBearing(this.roiData.centerLatitude, this.roiData.centerLongitude, 0.0f, controllerGps.lat, controllerGps.lon, 0.0f); if (result[0] <= 1000.0f) { this.roiData.radius = Math.round(result[0]); this.roiData.speed = 5; this.missionPresentation.prepare(this.currentMissionType, this.roiData); } else if (this.missionViewCallback != null) { this.missionViewCallback.updateError(R.string.mission_command_reason_radius_over_range); } } } else if (this.currentMissionType == MissionType.JOURNEY) { this.missionPresentation.prepare(this.currentMissionType, new Integer(10)); } else if (this.currentMissionType == MissionType.CYCLE) { this.missionPresentation.prepare(this.currentMissionType, null); } } else if (v == this.setCenterButton) { this.roiData.centerLatitude = this.droneLatitude; this.roiData.centerLongitude = this.droneLongitude; this.roiData.centerAltitude = this.droneAltitude; this.missionPromptView.updateStepPrompt(MissionStep.PREPARE, "Set Center"); } else if (v == this.resumeButton) { this.missionPresentation.resume(this.currentMissionType); } else if (v == this.pauseButton) { this.missionPresentation.pause(this.currentMissionType); } else if (v == this.exitButton) { this.missionPresentation.terminate(); } } }
package com.gwc.bisv; import java.util.Date; public class Song { private String title; private String artistFirstName; private String artistLastName; // Constructors public Song(String title, String artistFirstName, String artistLastName) { this.title = title; this.artistFirstName = artistFirstName; this.artistLastName = artistLastName; } @Override public String toString() { return "Song {" + "title='" + title + '\'' + ", artistFirstName='" + artistFirstName + '\'' + ", artistLastName='" + artistLastName + '\'' + '}'; } // Getters & setters public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getArtistFirstName() { return artistFirstName; } public void setArtistFirstName(String artistFirstName) { this.artistFirstName = artistFirstName; } public String getArtistLastName() { return artistLastName; } public void setArtistLastName(String artistLastName) { this.artistLastName = artistLastName; } // private String lyrics; // private String duration; }
import dataServiceImpl.CreditDataServiceImpl; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import po.CreditInfoPO; import java.rmi.RemoteException; import java.util.ArrayList; /** * CreditDataServiceImpl Tester. * * @author <Authors name> * @since <pre>十二月 7, 2016</pre> * @version 1.0 */ public class CreditDataServiceImplTest { CreditDataServiceImpl creditDao= CreditDataServiceImpl.getCreditDataServiceInstance(); public CreditDataServiceImplTest() throws RemoteException { } @Before public void before() throws Exception { } @After public void after() throws Exception { } /** * * Method: getCustomerCredits() * */ @Test @Ignore public void testGetCustomerCredits() throws Exception { //TODO: Test goes here... ArrayList<CreditInfoPO> list=creditDao.getCustomerCredits("arloor"); for (CreditInfoPO cell:list ) { System.out.println(cell.getCreditChangeType()+" "+cell.getUserName()+" "+cell.getChange()+" "+cell.getTime()+" "+cell.getOrderID()+" "+cell.getNumCredit()); } } /** * * Method: insert(CreditInfoPO creditInfoPO) * */ @Test @Ignore public void testInsert() throws Exception { //TODO: Test goes here... ArrayList<CreditInfoPO> list=creditDao.getCustomerCredits("arloor"); CreditInfoPO creditInfoPO=list.get(0); creditInfoPO.setTime("1997-04-21 12:00:00"); creditDao.insert(creditInfoPO); } }
package WebShop.model; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Category { @Id @GeneratedValue private Integer id; private String categoryName; public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public String getCategoryName() { return categoryName; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } /*public void addProduct(Product product){ product.setCategory(this); this.products.add(product); }*/ }
package interfaces; import classes.Interpreter; /** * @author dylan * */ public interface Expression { /** * @param interpreter * @return */ public String interpret(Interpreter interpreter); }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.view.json; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.ser.FilterProvider; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.converter.json.MappingJacksonValue; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.web.servlet.view.AbstractView; /** * Abstract base class for Jackson based and content type independent * {@link AbstractView} implementations. * * @author Jeremy Grelle * @author Arjen Poutsma * @author Rossen Stoyanchev * @author Juergen Hoeller * @author Sebastien Deleuze * @since 4.1 */ public abstract class AbstractJackson2View extends AbstractView { private ObjectMapper objectMapper; private JsonEncoding encoding = JsonEncoding.UTF8; @Nullable private Boolean prettyPrint; private boolean disableCaching = true; protected boolean updateContentLength = false; protected AbstractJackson2View(ObjectMapper objectMapper, String contentType) { this.objectMapper = objectMapper; configurePrettyPrint(); setContentType(contentType); setExposePathVariables(false); } /** * Set the {@code ObjectMapper} for this view. * If not set, a default {@link ObjectMapper#ObjectMapper() ObjectMapper} will be used. * <p>Setting a custom-configured {@code ObjectMapper} is one way to take further control of * the JSON serialization process. The other option is to use Jackson's provided annotations * on the types to be serialized, in which case a custom-configured ObjectMapper is unnecessary. */ public void setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; configurePrettyPrint(); } /** * Return the {@code ObjectMapper} for this view. */ public final ObjectMapper getObjectMapper() { return this.objectMapper; } /** * Set the {@code JsonEncoding} for this view. * By default, {@linkplain JsonEncoding#UTF8 UTF-8} is used. */ public void setEncoding(JsonEncoding encoding) { Assert.notNull(encoding, "'encoding' must not be null"); this.encoding = encoding; } /** * Return the {@code JsonEncoding} for this view. */ public final JsonEncoding getEncoding() { return this.encoding; } /** * Whether to use the default pretty printer when writing the output. * This is a shortcut for setting up an {@code ObjectMapper} as follows: * <pre class="code"> * ObjectMapper mapper = new ObjectMapper(); * mapper.configure(SerializationFeature.INDENT_OUTPUT, true); * </pre> * <p>The default value is {@code false}. */ public void setPrettyPrint(boolean prettyPrint) { this.prettyPrint = prettyPrint; configurePrettyPrint(); } private void configurePrettyPrint() { if (this.prettyPrint != null) { this.objectMapper.configure(SerializationFeature.INDENT_OUTPUT, this.prettyPrint); } } /** * Disables caching of the generated JSON. * <p>Default is {@code true}, which will prevent the client from caching the generated JSON. */ public void setDisableCaching(boolean disableCaching) { this.disableCaching = disableCaching; } /** * Whether to update the 'Content-Length' header of the response. When set to * {@code true}, the response is buffered in order to determine the content * length and set the 'Content-Length' header of the response. * <p>The default setting is {@code false}. */ public void setUpdateContentLength(boolean updateContentLength) { this.updateContentLength = updateContentLength; } @Override protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) { setResponseContentType(request, response); response.setCharacterEncoding(this.encoding.getJavaName()); if (this.disableCaching) { response.addHeader("Cache-Control", "no-store"); } } @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { ByteArrayOutputStream temporaryStream = null; OutputStream stream; if (this.updateContentLength) { temporaryStream = createTemporaryOutputStream(); stream = temporaryStream; } else { stream = response.getOutputStream(); } Object value = filterAndWrapModel(model, request); writeContent(stream, value); if (temporaryStream != null) { writeToResponse(response, temporaryStream); } } /** * Filter and optionally wrap the model in {@link MappingJacksonValue} container. * @param model the model, as passed on to {@link #renderMergedOutputModel} * @param request current HTTP request * @return the wrapped or unwrapped value to be rendered */ protected Object filterAndWrapModel(Map<String, Object> model, HttpServletRequest request) { Object value = filterModel(model); Class<?> serializationView = (Class<?>) model.get(JsonView.class.getName()); FilterProvider filters = (FilterProvider) model.get(FilterProvider.class.getName()); if (serializationView != null || filters != null) { MappingJacksonValue container = new MappingJacksonValue(value); if (serializationView != null) { container.setSerializationView(serializationView); } if (filters != null) { container.setFilters(filters); } value = container; } return value; } /** * Write the actual JSON content to the stream. * @param stream the output stream to use * @param object the value to be rendered, as returned from {@link #filterModel} * @throws IOException if writing failed */ protected void writeContent(OutputStream stream, Object object) throws IOException { try (JsonGenerator generator = this.objectMapper.getFactory().createGenerator(stream, this.encoding)) { writePrefix(generator, object); Object value = object; Class<?> serializationView = null; FilterProvider filters = null; if (value instanceof MappingJacksonValue container) { value = container.getValue(); serializationView = container.getSerializationView(); filters = container.getFilters(); } ObjectWriter objectWriter = (serializationView != null ? this.objectMapper.writerWithView(serializationView) : this.objectMapper.writer()); if (filters != null) { objectWriter = objectWriter.with(filters); } objectWriter.writeValue(generator, value); writeSuffix(generator, object); generator.flush(); } } /** * Set the attribute in the model that should be rendered by this view. * When set, all other model attributes will be ignored. */ public abstract void setModelKey(String modelKey); /** * Filter out undesired attributes from the given model. * The return value can be either another {@link Map} or a single value object. * @param model the model, as passed on to {@link #renderMergedOutputModel} * @return the value to be rendered */ protected abstract Object filterModel(Map<String, Object> model); /** * Write a prefix before the main content. * @param generator the generator to use for writing content. * @param object the object to write to the output message. */ protected void writePrefix(JsonGenerator generator, Object object) throws IOException { } /** * Write a suffix after the main content. * @param generator the generator to use for writing content. * @param object the object to write to the output message. */ protected void writeSuffix(JsonGenerator generator, Object object) throws IOException { } }
package com.myvodafone.android.front.bundle; import android.graphics.Typeface; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.Html; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.ViewFlipper; import com.myvodafone.android.R; import com.myvodafone.android.business.managers.PostPayBundlePurchaseManager; import com.myvodafone.android.business.managers.PrePayBundlePurchaseManager; import com.myvodafone.android.business.managers.MemoryCacheManager; import com.myvodafone.android.front.VFGRFragment; import com.myvodafone.android.front.helpers.Dialogs; import com.myvodafone.android.front.home.FragmentHome; import com.myvodafone.android.front.soasta.OmnitureHelper; import com.myvodafone.android.model.business.VFAccount; import com.myvodafone.android.model.view.BundlePurchaseCategories; import com.myvodafone.android.model.view.PostPayBundlePurchaseCategories; import com.myvodafone.android.model.view.PrePayBundlePurchaseCategories; import com.myvodafone.android.model.view.VFModelBundleItemPurchase; import com.myvodafone.android.model.view.VFModelBundleItemsPurchase; import com.myvodafone.android.utils.StaticTools; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import uk.co.exus.circulargauge.GaugeLayout; import uk.co.exus.circulargauge.OnBumpClickListener; /** * Created by kakaso on 3/21/2016. */ public class FragmentBundlePurchaseList extends VFGRFragment implements PrePayBundlePurchaseManager.PrePayBundlePurchaseListener, PostPayBundlePurchaseManager.PostPayBundlePurchaseListener { ListView listViewBundles; ImageView btnPrev, btnNext, btnBack; List<String> categories; ViewFlipper flipperCategories; RelativeLayout bundlesContainer; Spinner spinnerHybridMethods; TextView txtHead; RelativeLayout layoutNoBundlesHeader, layoutCategories; HashMap<String, VFModelBundleItemsPurchase> mapCategoriesData; public static final String TAG_CATEGORY = "TAG_CAT" ; public static final String TAG_REFRESH = "TAG_REFRESH" ; public static final String TAG_SELECT = "TAG_SELECT" ; private float x1,x2,y1,y2; static final int MIN_DISTANCE = 200; private String currentCategory; public static int categoryIndex; private ArrayList<VFModelBundleItemPurchase> currentBundlesList, nextBillBundlesList,balanceBundlesList; private static int SPINNER_SELECTION_NEXT_BILL = 0; private static int SPINNER_SELECTION_BALANCE = 1; public static int navigatedFrom = FragmentBundlePurchaseCategories.NAV_FROM_CATEGORIES; public static int spinnerSelection = 0; public static int listSelection = 0; private Typeface tf; @Override public BackFragment getPreviousFragment() { if(navigatedFrom == FragmentBundlePurchaseCategories.NAV_FROM_USAGE) { if(!FragmentBundlePurchaseCategories.isPostPay(getBundlesAccount())) { return BackFragment.FragmentPrepayUsage; } else { return BackFragment.FragmentPostpayUsage; } } else if(navigatedFrom == FragmentBundlePurchaseCategories.NAV_FROM_HOME){ return BackFragment.FragmentHome; } else{ return BackFragment.FragmentPrePayBundlesPurchase; } } public static FragmentBundlePurchaseList newInstance(String category, boolean refreshData, int spinnerSelection){ Bundle args = new Bundle(); if(category!=null) args.putString(TAG_CATEGORY, category); args.putBoolean(TAG_REFRESH, refreshData); args.putInt(TAG_SELECT,spinnerSelection); FragmentBundlePurchaseList fragment = new FragmentBundlePurchaseList(); fragment.setArguments(args); return fragment; } @Override public String getFragmentTitle() { return null; } @Override public void onResume() { super.onResume(); mapCategoriesData = new HashMap<>(); if (getArguments().containsKey(TAG_REFRESH) && getArguments().getBoolean(TAG_REFRESH)) { if (getBundlesAccount()!= null) { if(!FragmentBundlePurchaseCategories.isPostPay()) { Dialogs.showProgress(activity); PrePayBundlePurchaseManager.getEligiblePrepayBundles(activity, getBundlesAccount(), new WeakReference<PrePayBundlePurchaseManager.PrePayBundlePurchaseListener>(this)); } else { Dialogs.showProgress(activity); PostPayBundlePurchaseManager.getPostPayBundles(activity, getBundlesAccount(), new WeakReference<PostPayBundlePurchaseManager.PostPayBundlePurchaseListener>(this)); } } } else { loadCategoriesData(); loadCategoryData(categoryIndex); } activity.sideMenuHelper.disableSwipe(); //BG StaticTools.setAppBackground(getContext(),StaticTools.BACKGROUND_TYPE_NORMAL,(ImageView) getView().findViewById(R.id.dynamicBG),null); } public static VFAccount getBundlesAccount(){ return MemoryCacheManager.getSelectedAccount(); } private void setFlipperCategories(){ try { for (String cat : categories) { flipperCategories.addView(createCategoryImage(cat)); } if(categories!=null && categories.size()==1){ btnPrev.setVisibility(View.INVISIBLE); btnNext.setVisibility(View.INVISIBLE); } } catch (Exception e){ StaticTools.Log(e); } } private ImageView createCategoryImage(String cat){ ImageView imageView = new ImageView(activity); ViewFlipper.LayoutParams lp = new ViewFlipper.LayoutParams(ViewFlipper.LayoutParams.WRAP_CONTENT, ViewFlipper.LayoutParams.WRAP_CONTENT); lp.gravity = Gravity.CENTER; imageView.setLayoutParams(lp); imageView.setImageResource(getCategoryIcon(cat)); imageView.setTag(cat); return imageView; } private String getLinkCategory(){ return getArguments()!=null && getArguments().containsKey(TAG_CATEGORY)? getArguments().getString(TAG_CATEGORY):""; } private boolean flipperContainsCategory(String cat) { for (int i = 0; i < flipperCategories.getChildCount(); i++){ if (((ImageView) flipperCategories.getChildAt(i)).getTag().equals(cat)) { return true; } } return false; } private int getCategoryIcon(String category){ switch (category){ case BundlePurchaseCategories.DEFAULT: return R.drawable.bundle_top_inter; case BundlePurchaseCategories.VOICE: return R.drawable.bundle_top_voice; case BundlePurchaseCategories.COMBO: return R.drawable.bundle_top_combo; case BundlePurchaseCategories.INTERNATIONAL: return R.drawable.bundle_top_inter; case PrePayBundlePurchaseCategories.DATA: return R.drawable.bundle_top_net; case PostPayBundlePurchaseCategories.DATA: return R.drawable.bundle_top_net; case BundlePurchaseCategories.SMS: return R.drawable.bundle_top_sms; case BundlePurchaseCategories.STUDENT: return R.drawable.bundle_top_student; case BundlePurchaseCategories.UNDER24: return R.drawable.bundle_top_under24; case BundlePurchaseCategories.STUDENT24: return R.drawable.bundle_top_student; default: return R.drawable.bundle_top_inter; } } private void loadCategoryData(int index){ if(!FragmentBundlePurchaseCategories.isPostPay(getBundlesAccount())) { if (getBundlesAccount().isHybrid()) { loadHybridCategoryData(index); } else { loadPrePayCategoryData(index); } } else { loadPostPayCategoryData(index); } } private void loadPostPayCategoryData(int index) { if(categories!=null && index >=0 && index < categories.size() && categories.get(index)!=null) { try { if (getBundlesAccount() != null && getBundlesAccount().getAccountSegment() == VFAccount.TYPE_MOBILE_BIZ) { //Omniture String extra = categories.get(index); if (extra.equalsIgnoreCase("internet")) { extra = "data"; } String userType = "Business bundles "; String tag = userType + extra; OmnitureHelper.trackView(tag); //Send } else { //Omniture String extra = categories.get(index); if (extra.equalsIgnoreCase("internet")) { extra = "data"; } String userType = "Postpay bundles "; String tag = userType + extra; OmnitureHelper.trackView(tag); //Send } } catch (Exception e){ StaticTools.Log(e); } VFModelBundleItemsPurchase model = mapCategoriesData.get(categories.get(index)); if(model!=null) { List<VFModelBundleItemPurchase> list = model.getBundleItemsList(); if (list != null && list.size()>0) { showBundlesHeader(); BundleAdapter adapter = new BundleAdapter(); currentBundlesList = (ArrayList<VFModelBundleItemPurchase>) list; adapter.setItems(currentBundlesList); listViewBundles.setAdapter(adapter); MemoryCacheManager.setSelectedBundleCategory(categories.get(index)); selectFlipperCategory(currentBundlesList, categoryIndex); trySetSelection(); } else { txtHead.setText(getString(R.string.msg_no_bundles)); listViewBundles.setAdapter(new BundleAdapter()); selectFlipperCategory(currentBundlesList, index); } } } else { showNoBundlesHeader(); } } private void loadPrePayCategoryData(int index){ if(categories!=null && index >=0 && index <categories.size() && categories.get(index)!=null) { //Omniture String extra = categories.get(index); if (extra.equalsIgnoreCase("internet")) { extra = "data"; } String userType = "Prepay bundles "; String tag = userType + extra; OmnitureHelper.trackView(tag); //Send VFModelBundleItemsPurchase model = PrePayBundlePurchaseManager.getBundleListModel(categories.get(index)); if (model!=null && model.getBundleItemsList()!=null && model.getBundleItemsList().size()>0) { showBundlesHeader(); BundleAdapter adapter = new BundleAdapter(); currentBundlesList = (ArrayList<VFModelBundleItemPurchase>) model.getBundleItemsList(); adapter.setItems(sortBundles(currentBundlesList)); listViewBundles.setAdapter(adapter); MemoryCacheManager.setSelectedBundleCategory(categories.get(index)); selectFlipperCategory(currentBundlesList, categoryIndex); trySetSelection(); } else { txtHead.setText(getString(R.string.msg_no_bundles)); listViewBundles.setAdapter(new BundleAdapter()); selectFlipperCategory(currentBundlesList, index); } } else { showNoBundlesHeader(); } } private ArrayList<VFModelBundleItemPurchase> sortBundles(ArrayList<VFModelBundleItemPurchase> initList){ ArrayList<VFModelBundleItemPurchase> active = new ArrayList<>(),inactive = new ArrayList<>(), expireList = new ArrayList<>(); for(VFModelBundleItemPurchase item: initList){ if(item.isActive() || (item.getRecurringBundle()!=null && item.getRecurringBundle().isActive())){ if(item.getExpireDate()!=null){ expireList.add(item); } else { active.add(item); } } else{ inactive.add(item); } } Collections.sort(expireList, new BundleComparatorExpireDate()); Collections.sort(active, new BundleComparatorModDate()); Collections.sort(inactive, new BundleComparatorModDate()); expireList.addAll(active); expireList.addAll(inactive); return expireList; } private void selectFlipperCategory(ArrayList<VFModelBundleItemPurchase> list, int index){ flipperCategories.setVisibility(View.VISIBLE); flipperCategories.setDisplayedChild(index); } private void loadHybridCategoryData(int index) { if (categories!=null && index >=0 && index <categories.size() && categories.get(index) != null) { //Omniture String userType = "Hybrid bundles "; if (!categories.get(index).contains("combo")) { String extraNote = ""; if (spinnerHybridMethods != null) { if (spinnerHybridMethods.getSelectedItemPosition() == 0) { extraNote = " next bill"; } else { extraNote = " instant"; } } String tag = userType + categories.get(index) + extraNote; OmnitureHelper.trackView(tag); } //Send VFModelBundleItemsPurchase model = PrePayBundlePurchaseManager.getBundleListModel(categories.get(index)); if (model!=null && model.getBundleItemsList()!=null && model.getBundleItemsList().size()>0) { showBundlesHeader(); balanceBundlesList = new ArrayList<>(); nextBillBundlesList = new ArrayList<>(); currentBundlesList = (ArrayList<VFModelBundleItemPurchase>) model.getBundleItemsList(); for (VFModelBundleItemPurchase bItem : currentBundlesList) { if (bItem.isNextBill()) { nextBillBundlesList.add(bItem); } else { balanceBundlesList.add(bItem); } } nextBillBundlesList = sortBundles(nextBillBundlesList); balanceBundlesList = sortBundles(balanceBundlesList); MemoryCacheManager.setSelectedBundleCategory(categories.get(index)); if(nextBillBundlesList.size() >0 && balanceBundlesList.size()>0) { spinnerHybridMethods.setEnabled(true); spinnerHybridMethods.setSelection(spinnerSelection); loadAdapterData(spinnerHybridMethods.getSelectedItemPosition()); } else if(nextBillBundlesList.size() == 0){ spinnerHybridMethods.setEnabled(false); spinnerHybridMethods.setSelection(SPINNER_SELECTION_BALANCE); loadAdapterData(spinnerHybridMethods.getSelectedItemPosition()); } else if(balanceBundlesList.size() == 0){ spinnerHybridMethods.setEnabled(false); spinnerHybridMethods.setSelection(SPINNER_SELECTION_NEXT_BILL); loadAdapterData(spinnerHybridMethods.getSelectedItemPosition()); } } else { txtHead.setText(getString(R.string.msg_no_bundles)); listViewBundles.setAdapter(new BundleAdapter()); selectFlipperCategory(currentBundlesList, index); } } else { showNoBundlesHeader(); } } private void trySetSelection(){ try{ listViewBundles.setSelection(listSelection); } catch (Exception e){ StaticTools.Log(e); } } private void showNoBundlesHeader(){ layoutCategories.setVisibility(View.INVISIBLE); layoutNoBundlesHeader.setVisibility(View.VISIBLE); ((TextView)layoutNoBundlesHeader.findViewById(R.id.textScreenTitle)).setText(getString(R.string.bundles_2nd_level_header)); txtHead.setText(getString(R.string.msg_no_bundles)); btnBack.setVisibility(View.VISIBLE); ImageView logo = (ImageView) (getView()!=null ? getView().findViewById(R.id.logo) : null); if (logo != null) { logo.setVisibility(View.INVISIBLE); } } private void showBundlesHeader(){ if(MemoryCacheManager.getSelectedAccount() != null && MemoryCacheManager.getSelectedAccount().isHybrid()){ String text = getString(R.string.bunldes_text_msisdn_hybrid).replace("__X", FragmentBundlePurchaseList.getBundlesAccount().getSelectedAccountNumber()); txtHead.setText(Html.fromHtml(text)); } else { String text = getString(R.string.bundles_text_msisdn).replace("__X", FragmentBundlePurchaseList.getBundlesAccount().getSelectedAccountNumber()); txtHead.setText(Html.fromHtml(text)); } } private void loadAdapterData(int spinnerMethodIndex){ BundleAdapter adapter = new BundleAdapter(); if(spinnerMethodIndex== SPINNER_SELECTION_NEXT_BILL){ if(nextBillBundlesList!=null) { adapter.setItems(nextBillBundlesList); listViewBundles.setAdapter(adapter); selectFlipperCategory(nextBillBundlesList, categoryIndex); } } else if(spinnerMethodIndex== SPINNER_SELECTION_BALANCE){ if(balanceBundlesList!=null) { adapter.setItems(balanceBundlesList); listViewBundles.setAdapter(adapter); selectFlipperCategory(balanceBundlesList, categoryIndex); } } trySetSelection(); } @Override public void onSuccessBundleList() { Dialogs.closeProgress(); loadCategoriesData(); loadCategoryData(categoryIndex); } private void loadCategoriesData() { if(!FragmentBundlePurchaseCategories.isPostPay(getBundlesAccount())) { buildPrePaySortedCategories(); } else { buildPostPaySortedCategories(); } setFlipperCategories(); if (categories.size() > 0) { if (getArguments().containsKey(TAG_CATEGORY) && !getArguments().getString(TAG_CATEGORY).equals("")) { currentCategory = getArguments().getString(TAG_CATEGORY); categoryIndex = categories.indexOf(currentCategory); getArguments().putString(TAG_CATEGORY, ""); } if(getArguments().containsKey(TAG_SELECT)){ spinnerSelection = getArguments().getInt(TAG_SELECT); } } } @Override public void onErrorBundleList(String message) { Dialogs.closeProgress(); if(message!=null && message.equals(PrePayBundlePurchaseManager.ERROR_EMPTY)){ showNoBundlesHeader(); } else { Dialogs.showErrorDialog(activity, message); } } @Override public void onGenericErrorBundleList() { Dialogs.closeProgress(); Dialogs.showErrorDialog(activity, getStringSafe(R.string.vf_generic_error)); } @Override public void onSuccessPostPayBundleList() { Dialogs.closeProgress(); loadCategoriesData(); loadCategoryData(categoryIndex); } @Override public void onErrorPostPayBundleList(String message) { Dialogs.closeProgress(); if(message!=null && message.equals(PrePayBundlePurchaseManager.ERROR_EMPTY)){ showNoBundlesHeader(); } else { Dialogs.showErrorDialog(activity, message); } } @Override public void onGenericErrorPostPayBundleList() { Dialogs.closeProgress(); Dialogs.showErrorDialog(activity, getStringSafe(R.string.vf_generic_error)); } public class BundleComparatorModDate implements Comparator<VFModelBundleItemPurchase> { @Override public int compare(VFModelBundleItemPurchase left, VFModelBundleItemPurchase right) { if (left.getModDate() == null || right.getModDate() == null) return 0; return right.getModDate().compareTo(left.getModDate()); } } public class BundleComparatorExpireDate implements Comparator<VFModelBundleItemPurchase> { @Override public int compare(VFModelBundleItemPurchase left, VFModelBundleItemPurchase right) { if (left.getExpireDate() == null) return -1; if(right.getExpireDate() == null) return 1; return left.getExpireDate().compareTo(right.getExpireDate()); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_bundle_purchase_list, container, false); initViews(view); StaticTools.setLogo(view, activity); return view; } private void initViews(View v){ listViewBundles = (ListView) v.findViewById(R.id.listBundles); btnPrev = (ImageView) v.findViewById(R.id.btnArrowLeft); btnNext = (ImageView) v.findViewById(R.id.btnArrowRight); btnPrev.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadPrevCategory(); } }); btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadNextCategory(); } }); btnPrev.setVisibility(View.VISIBLE); btnNext.setVisibility(View.VISIBLE); flipperCategories = (ViewFlipper) v.findViewById(R.id.flipperCategories); bundlesContainer = (RelativeLayout) v.findViewById(R.id.bundlesContainer); // listViewBundles.setOnTouchListener(onTouchBundlesContainer); spinnerHybridMethods = (Spinner) v.findViewById(R.id.spinnerHybridMethods); txtHead = (TextView) v.findViewById(R.id.txtHead); tf = Typeface.createFromAsset(activity.getAssets(),"fonts/VodafoneRg.ttf"); if(MemoryCacheManager.getSelectedAccount() != null && MemoryCacheManager.getSelectedAccount().isHybrid()){ spinnerHybridMethods.setVisibility(View.VISIBLE); setUpSpinnerHybrid(); } else { spinnerHybridMethods.setVisibility(View.GONE); } layoutCategories = (RelativeLayout)v.findViewById(R.id.layoutCategories); layoutNoBundlesHeader = (RelativeLayout) v.findViewById(R.id.layoutNoBundlesHeader); ImageView close = (ImageView) v.findViewById(R.id.btnHeaderClose); ImageView closeCat = (ImageView) v.findViewById(R.id.btnHeaderCloseCateg); close.setVisibility(View.VISIBLE); close.setOnClickListener(listener); closeCat.setOnClickListener(listener); ImageView goBack = (ImageView) v.findViewById(R.id.backButton); btnBack = (ImageView) v.findViewById(R.id.back); goBack.setVisibility(View.VISIBLE); View.OnClickListener backBtnListener = new View.OnClickListener() { @Override public void onClick(View v) { activity.onBackPressed(); } }; goBack.setOnClickListener(backBtnListener); btnBack.setOnClickListener(backBtnListener); } View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { activity.replaceFragment(FragmentHome.newInstance()); } }; @Override public void onPause() { super.onPause(); activity.sideMenuHelper.enableSwipe(); } private void setUpSpinnerHybrid(){ String[] array = { getString(R.string.balance_next_bill_selection), getString(R.string.bundles_current_balance_selection)}; ArrayAdapter adapter = new ArrayAdapter(activity, R.layout.item_spinner_simple, array); adapter.setDropDownViewResource(R.layout.item_spinner_simple); spinnerHybridMethods.setAdapter(adapter); spinnerHybridMethods.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position != 2) { loadAdapterData(position); if (view.isEnabled()) { spinnerSelection = position; } } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } View.OnTouchListener onTouchBundlesContainer = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: x1 = event.getX(); y1 = event.getY(); break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: x2 = event.getX(); y2 = event.getY(); float deltaX = x2 - x1; float deltaY = y2 - y1; if(Math.abs(deltaY)<100) { if (deltaX > MIN_DISTANCE) { loadPrevCategory(); } else if (deltaX < -MIN_DISTANCE) { loadNextCategory(); } } break; } return false; } }; private void buildPrePaySortedCategories(){ String[] items = new PrePayBundlePurchaseCategories().getValues(); Map<Integer, String> contentItems = new HashMap<>(); for(String cat:items){ if(PrePayBundlePurchaseManager.getBundleItemsOfCategory(cat).size()>0) { contentItems.put(getCategoryIndex(cat),cat); } else if(!StaticTools.isNullOrEmpty(getLinkCategory()) && getLinkCategory().equals(cat)){ contentItems.put(getCategoryIndex(cat),cat); } } List<Integer> sorted = new ArrayList<>(contentItems.keySet()); Collections.sort(sorted); categories = new ArrayList<>(); for(Integer i:sorted){ categories.add(contentItems.get(i)); } } private void buildPostPaySortedCategories(){ String[] items = new PostPayBundlePurchaseCategories().getValues(); Map<Integer, String> contentItems = new HashMap<>(); for(String cat:items){ VFModelBundleItemsPurchase categoryModel = PostPayBundlePurchaseManager.filterPostPayServicesByCategory(cat); if(categoryModel!=null && categoryModel.getBundleItemsList()!=null && categoryModel.getBundleItemsList().size()>0) { mapCategoriesData.put(cat, categoryModel); contentItems.put(getCategoryIndex(cat), cat); }// Added to support empty bundle categories from link else if(!StaticTools.isNullOrEmpty(getLinkCategory()) && getLinkCategory().equals(cat)){ mapCategoriesData.put(cat, new VFModelBundleItemsPurchase()); contentItems.put(getCategoryIndex(cat), cat); } } List<Integer> sorted = new ArrayList<>(contentItems.keySet()); Collections.sort(sorted); categories = new ArrayList<>(); for(Integer i:sorted){ categories.add(contentItems.get(i)); } } private int getCategoryIndex(String cat) { switch (cat){ case BundlePurchaseCategories.UNDER24: return 0; case BundlePurchaseCategories.STUDENT24: return 1; case BundlePurchaseCategories.STUDENT: return 2; case PrePayBundlePurchaseCategories.DATA: return 3; case PostPayBundlePurchaseCategories.DATA: return 4; case BundlePurchaseCategories.VOICE: return 5; case BundlePurchaseCategories.SMS: return 6; case BundlePurchaseCategories.COMBO: return 7; case BundlePurchaseCategories.INTERNATIONAL: return 8; case BundlePurchaseCategories.DEFAULT: return 9; default: return 10; } } private void loadNextCategory(){ if(categories!=null) { listSelection = 0; flipperCategories.setInAnimation(activity, R.anim.enter_from_left); flipperCategories.setOutAnimation(activity, R.anim.exit_to_right_fade); if (categoryIndex < categories.size() - 1) { categoryIndex++; } else { categoryIndex = 0; } loadCategoryData(categoryIndex); } } private void loadPrevCategory(){ if(categories!=null) { listSelection = 0; flipperCategories.setInAnimation(activity, R.anim.enter_from_right); flipperCategories.setOutAnimation(activity, R.anim.exit_to_left_fade); if (categoryIndex > 0) { categoryIndex--; } else { categoryIndex = categories.size() - 1; } loadCategoryData(categoryIndex); } } class ViewHolder{ TextView txtActive, txtRecurring, txtAdHoc; GaugeLayout gauge; } class BundleAdapter extends BaseAdapter{ ArrayList<VFModelBundleItemPurchase> list; public BundleAdapter(){ list = new ArrayList<>(); } public void setItems(ArrayList<VFModelBundleItemPurchase> list){ this.list = list; } @Override public int getCount() { return list.size(); } @Override public VFModelBundleItemPurchase getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { VFModelBundleItemPurchase model = getItem(position); if(convertView==null){ ViewHolder viewHolder = new ViewHolder(); convertView = activity.getLayoutInflater().inflate(R.layout.item_bundle_list, parent, false); viewHolder.gauge = (GaugeLayout) convertView.findViewById(R.id.gaugeBundle); viewHolder.gauge.getTextView().setTypeface(tf); viewHolder.txtActive = (TextView) convertView.findViewById(R.id.txtActive); viewHolder.txtRecurring = (TextView) convertView.findViewById(R.id.txtType); viewHolder.txtAdHoc = (TextView) convertView.findViewById(R.id.txtType2); convertView.setTag(viewHolder); } final ViewHolder vh = (ViewHolder) convertView.getTag(); vh.gauge.showBump(false); vh.txtRecurring.setVisibility(View.GONE); vh.txtAdHoc.setVisibility(View.GONE); if(model.isActive() || (model.getRecurringBundle()!=null && model.getRecurringBundle().isActive())){ vh.gauge.setActivated(true); vh.txtActive.setVisibility(View.VISIBLE); vh.txtActive.setText(getString(R.string.bundles_active_text)); if (model.getRecurringBundle()!=null && model.getRecurringBundle().isActive()) { vh.txtRecurring.setVisibility(View.VISIBLE); if (model.isActive()) { vh.txtAdHoc.setVisibility(View.VISIBLE); } } else { if (model.isActive()) { if (model.getBundleType() == VFModelBundleItemPurchase.BundleType.Recurring) { vh.txtRecurring.setVisibility(View.VISIBLE); } else { vh.txtAdHoc.setVisibility(View.VISIBLE); } } } //single item if(model.getRecurringBundle()==null){ if(showBundleBump(model)){ vh.gauge.showBump(false); } else { vh.gauge.hideBump(false); } }//group of 2 bundles else{ if(showBundleBump(model) || showBundleBump(model.getRecurringBundle())){ vh.gauge.showBump(false); } else { vh.gauge.hideBump(false); } } } else { vh.gauge.setActivated(false); vh.txtActive.setVisibility(View.GONE); } vh.gauge.setGaugeBumpListener(new OnBumpClickListener() { @Override public void onClick() { onClickGauge(position); } }); vh.gauge.setTextValue(PrePayBundlePurchaseManager.getBundleHeader(activity,model.getBundleHeader(), model.getPrice())); vh.gauge.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickGauge(position); } }); return convertView; } private boolean showBundleBump(VFModelBundleItemPurchase model){ if(model.isActive() && model.getBundleType()!= VFModelBundleItemPurchase.BundleType.OnceOff){ return false; } return true; } private void onClickGauge(int position){ MemoryCacheManager.setSelectedBundle(getItem(position)); listSelection = position; replaceFragment(FragmentBundlePurchaseDetails.newInstance()); } } }
package a50; import java.util.Arrays; /** * @author 方康华 * @title ThreeSumClosest * @projectName leetcode * @description No.16 Medium * @date 2019/7/29 21:34 */ public class ThreeSumClosest { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int close = 0, dif = Integer.MAX_VALUE; for(int i = 0; i < nums.length - 2; i++) { int sum = twoSum(i + 1, nums.length - 1, nums[i], target, nums); if(Math.abs(sum - target) < dif) { dif = Math.abs(sum - target); close = sum; } } return close; } public int twoSum(int id1, int id2, int n, int target, int[] nums) { int close = 0, dif = Integer.MAX_VALUE; while(id1 < id2) { int sum = nums[id1] + nums[id2] + n; System.out.println(n + " " + nums[id1] + " " + nums[id2]); if(Math.abs(sum - target) < dif) { dif = Math.abs(sum - target); close = sum; } if(sum < target) { id1++; } else if(sum > target) { id2--; } else { break; } } return close; } public static void main(String[] args) { int[] nums = new int[] {0,1,2}; System.out.println(new ThreeSumClosest().threeSumClosest(nums, 3)); } }
package com.tyrant.equalshashcode; /** * @author:profiteur * @create 2020-07-02 15:57 **/ public class User implements Cloneable{ private String name; private String age; public User() {} public User(String name, String age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
package Actions; import Articles.*; import Attributes.ADate; import Utils.Data; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; public class Create extends Action { final int createMenuWidth=400; final int createMenuHeight=250; public Create(){} public Create(Article a){ itemToCreate=a; } Article itemToCreate; @Override public String action() { Stage stage = new Stage(); stage.setTitle("Create Menu"); if(itemToCreate instanceof Lecture){ TextField course = new TextField(); TextField time = new TextField(); TextField date = new TextField(); TextField extraText = new TextField(); Label lCourse = new Label("Course"); Label lTime = new Label("Time"); Label lDate = new Label("Date (dd/MM/yy)"); Label lET = new Label("Extra Text"); GridPane root = new GridPane(); root.add(course,1,0); root.add(lCourse,0,0); root.add(time,1,1); root.add(lTime,0,1); root.add(date,1,2); root.add(lDate,0,2); root.add(extraText,1,3); root.add(lET,0,3); Label error = new Label("Incomplete entry"); error.setVisible(false); Button add = new Button("Add"); EventHandler<ActionEvent> addE = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if(course.getText().length()>0&&time.getText().length()>0&&date.getText().length()>0) { try { FileWriter writer = new FileWriter("src/CSVFiles/Lectures.csv", true); String day = new ADate(date.getText()).getDay(); if (newLineExists(new File("src/CSVFiles/Lectures.csv"))) { writer.write(course.getText() + "," + time.getText() + "," + date.getText() + "," + day + "," + extraText.getText()); } else { writer.write('\n' + course.getText() + "," + time.getText() + "," + date.getText() + "," + day + "," + extraText.getText()); } writer.close(); } catch (IOException e) { e.printStackTrace(); } try { Data.fillData(); } catch (IOException e) { e.printStackTrace(); } }else{ error.setVisible(true); } } }; add.setOnAction(addE); root.add(add,0,4); root.add(error,0,5); stage.setScene(new Scene(root, createMenuWidth, createMenuHeight)); stage.show(); } if(itemToCreate instanceof Event){ TextField title = new TextField(); TextField time = new TextField(); TextField date = new TextField(); TextField notes = new TextField(); Label lCourse = new Label("Title"); Label lTime = new Label("Time"); Label lDate = new Label("Date (dd/MM/yy)"); Label lET = new Label("Notes"); GridPane root = new GridPane(); root.add(title,1,0); root.add(lCourse,0,0); root.add(time,1,1); root.add(lTime,0,1); root.add(date,1,2); root.add(lDate,0,2); root.add(notes,1,3); root.add(lET,0,3); Label error = new Label("Incomplete entry"); error.setVisible(false); Button add = new Button("Add"); EventHandler<ActionEvent> addE = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if(time.getText().length()>0&&date.getText().length()>0) { try { FileWriter writer = new FileWriter("src/CSVFiles/Events.csv", true); if (newLineExists(new File("src/CSVFiles/Lectures.csv"))) { writer.write(title.getText() + "," + time.getText() + "," + date.getText() + "," + notes.getText()); } writer.write('\n' + title.getText() + "," + time.getText() + "," + date.getText() + "," + notes.getText()); writer.close(); } catch (IOException e) { e.printStackTrace(); } }else{ error.setVisible(true); } } }; add.setOnAction(addE); root.add(add,0,4); root.add(error,0,5); stage.setScene(new Scene(root, createMenuWidth, createMenuHeight)); stage.show(); } if(itemToCreate instanceof Notification){ TextField course = new TextField(); TextField time = new TextField(); TextField date = new TextField(); TextField extraText = new TextField(); Label lCourse = new Label("Course"); Label lTime = new Label("Time"); Label lDate = new Label("Date (dd/MM/yy)"); Label lET = new Label("Details"); GridPane root = new GridPane(); root.add(course,1,0); root.add(lCourse,0,0); root.add(time,1,1); root.add(lTime,0,1); root.add(date,1,2); root.add(lDate,0,2); root.add(extraText,1,3); root.add(lET,0,3); Label error = new Label("Incomplete entry"); error.setVisible(false); Button add = new Button("Add"); EventHandler<ActionEvent> addE = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if(course.getText().length()>0&&time.getText().length()>0&&date.getText().length()>0&&extraText.getText().length()>0) { try { FileWriter writer = new FileWriter("src/CSVFiles/Notifications.csv", true); String day = new ADate(date.getText()).getDay(); if (newLineExists(new File("src/CSVFiles/Notifications.csv"))) { writer.write(course.getText() + "," + time.getText() + "," + date.getText() + "," + day + "," + extraText.getText()); } else { writer.write('\n' + course.getText() + "," + time.getText() + "," + date.getText() + "," + day + "," + extraText.getText()); } writer.close(); } catch (IOException e) { e.printStackTrace(); } try { Data.fillData(); } catch (IOException e) { e.printStackTrace(); } }else{ error.setVisible(true); } } }; add.setOnAction(addE); root.add(add,0,4); root.add(error,0,5); stage.setScene(new Scene(root, createMenuWidth, createMenuHeight)); stage.show(); } if(itemToCreate instanceof Webpage || itemToCreate instanceof FolderLocation){ TextField tag= new TextField(); TextField rul= new TextField(); Label ltag= new Label("Tag"); Label lurl= new Label("URL"); if(itemToCreate instanceof FolderLocation) lurl.setText("Path"); GridPane root = new GridPane(); root.add(ltag,0,0); root.add(tag,1,0); root.add(lurl,0,1); root.add(rul,1,1); String filePath="src/CSVFiles/Links.csv"; if(itemToCreate instanceof FolderLocation) filePath="src/CSVFiles/Paths.csv"; Button add = new Button("Add"); String finalFilePath = filePath; Label error = new Label("Incomplete entry"); error.setVisible(false); EventHandler<ActionEvent> addE = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if(tag.getText().length()>0&&rul.getText().length()>0) { try { FileWriter writer = new FileWriter(finalFilePath, true); if (newLineExists(new File(finalFilePath))) { writer.write(tag.getText() + "," + rul.getText()); } else { writer.write('\n' + tag.getText() + "," + rul.getText()); } writer.close(); } catch (IOException e) { e.printStackTrace(); } try { Data.fillData(); } catch (IOException e) { e.printStackTrace(); } }else{ error.setVisible(true); } } }; add.setOnAction(addE); root.add(add,0,4); root.add(error,0,5); stage.setScene(new Scene(root, createMenuWidth, createMenuHeight)); stage.show(); } if(itemToCreate instanceof Medication){ TextField medication = new TextField(); TextField illness = new TextField(); Label lMed = new Label("Medication"); Label lIll = new Label("Illness"); GridPane root = new GridPane(); root.add(medication,1,0); root.add(lMed,0,0); root.add(illness,1,1); root.add(lIll,0,1); Label error = new Label("Incomplete entry"); error.setVisible(false); Button add = new Button("Add"); EventHandler<ActionEvent> addE = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if(medication.getText().length()>0&&illness.getText().length()>0) { try { FileWriter writer = new FileWriter("src/CSVFiles/Meds.csv", true); if (newLineExists(new File("src/CSVFiles/Meds.csv"))) { writer.write(medication.getText() + "," + illness.getText()); } else { writer.write('\n' +medication.getText() + "," + illness.getText()); } writer.close(); } catch (IOException e) { e.printStackTrace(); } try { Data.fillData(); } catch (IOException e) { e.printStackTrace(); } }else{ error.setVisible(true); } } }; add.setOnAction(addE); root.add(add,0,4); root.add(error,0,5); stage.setScene(new Scene(root, createMenuWidth, createMenuHeight)); stage.show(); } return "Opening create menu"; } @Override public String toString(){ return "Create"; } public static boolean newLineExists(File file) throws IOException { RandomAccessFile fileHandler = new RandomAccessFile(file, "r"); long fileLength = fileHandler.length() - 1; if (fileLength < 0) { fileHandler.close(); return true; } fileHandler.seek(fileLength); byte readByte = fileHandler.readByte(); fileHandler.close(); if (readByte == 0xA || readByte == 0xD) { return true; } return false; } }
/** * Sencha GXT 3.0.1 - Sencha for GWT * Copyright(c) 2007-2012, Sencha, Inc. * licensing@sencha.com * * http://www.sencha.com/products/gxt/license/ */ package com.sencha.gxt.explorer.shared; import com.google.web.bindery.requestfactory.shared.RequestFactory; public interface ExplorerRequestFactory extends RequestFactory { }
package Locadora; import java.util.InputMismatchException; import java.util.Scanner; public class Locacao { public static void main(String[] args) { Acervo acervo = new Acervo(); Cadastro cadastro = new Cadastro(); boolean verifica = true; while (verifica) { System.out.println("Infome a opção desejada"); System.out.println("1- Cadastrar Midia"); System.out.println("2- Cadastrar Usuario"); System.out.println("3- Locacao"); Scanner sc = new Scanner(System.in); int opcao = sc.nextInt(); if (opcao == 1) { System.out.println("Informe o nome"); String nome = sc.next(); System.out.println("Infome data de lancamento"); int data = sc.nextInt(); System.out.println("Informe a quantidade de midias"); int quant = sc.nextInt(); acervo.cadastrarFilme(nome, data, quant); } else if (opcao == 2) { System.out.println("Informe o nome"); String nome = sc.next(); Usuario usuario = new Usuario(nome); cadastro.cadastrarUsuario(usuario); System.out.println("Seu numero de usuário é: " + cadastro.getNumCadastro()); } else if (opcao == 3) { System.out.println("Informe o numero do cadastro"); int num = sc.nextInt(); if (cadastro.verificarCadastro(num)) { System.out.println("Informe o nome da midia"); String nome = sc.next(); Midia midia = acervo.buscarAcervo(nome); if (midia != null) { if (acervo.retirarAcervo(nome, midia)) { System.out.println("Midia alugada"); } else { System.out.println("Não há mais midia no estoque"); } }else System.out.println("Midia não encontrada"); }else System.out.println("Cadastro não encontrado"); } else { System.out.println("Esta não é uma opção válida"); } System.out.println("Digite 0 para finalizar, ou qualquer outra tecla para continuar"); try { int num = sc.nextInt(); if (num == 0) { verifica = false; } } catch (InputMismatchException e) { System.out.println(""); } } } }
package com.wdl.query.hql.pojo; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; public class ConditionOperator { private final String operator; private static final Map cachedOperators = new HashMap(); private ConditionOperator(String operator) { this.operator = operator; } public String getString() { return operator; } public static ConditionOperator getOperator(String operator) throws RuntimeException { operator = operator.toUpperCase(); ConditionOperator op = (ConditionOperator) cachedOperators .get(operator); if (op == null) try { Field field = ConditionOperator.class.getField(operator); op = (ConditionOperator) field.get(null); cachedOperators.put(operator, op); } catch (Exception e){ throw new RuntimeException((new StringBuilder()).append("Unknown operator: ").append(operator).toString(), e); } return op; } public static final ConditionOperator LIKE = new ConditionOperator("%0 LIKE %1") ; public static final ConditionOperator EQ = new ConditionOperator("%0 = %1"); public static final ConditionOperator NOT_EQ = new ConditionOperator("%0 <> %1"); public static final ConditionOperator GT = new ConditionOperator("%0 > %1"); public static final ConditionOperator LT = new ConditionOperator("%0 < %1"); public static final ConditionOperator GE = new ConditionOperator("%0 >= %1"); public static final ConditionOperator LE = new ConditionOperator("%0 <= %1"); public static final ConditionOperator BETWEEN = new ConditionOperator("%0 BETWEEN %1"); }
package com.gtambit.gt.app.setting; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ToggleButton; import com.hyxen.analytics.AnalyticsTracker; import com.ambit.city_guide.R; public class SettingActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gt_setting); initLayout(); setIsAutoDelete(); } private void initLayout() { findViewById(R.id.ImageButtonBack).setOnClickListener(this); findViewById(R.id.LayoutAbout).setOnClickListener(this); } private void setIsAutoDelete() { ToggleButton switchIsAutoDelete = (ToggleButton)findViewById(R.id.ToggleButtonIsAutoDeleteCoupon); switchIsAutoDelete.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); } @Override public void onClick(View v) { switch(v.getId()) { case R.id.ImageButtonBack: finish(); break; case R.id.LayoutAbout: startActivity(new Intent(SettingActivity.this, SettingAboutActivity.class)); break; } } @Override public void onStart() { super.onStart(); AnalyticsTracker.getInstance().startTrackPage(this, getClass().getName()); } @Override public void onStop() { super.onStop(); AnalyticsTracker.getInstance().stopTrackPage(this, getClass().getName()); } }
package com.proyecto.server.service.impl; import org.springframework.stereotype.Service; import com.proyecto.dom.Perfil; import com.proyecto.kernel.service.ServiceBase; import com.proyecto.server.dao.IPerfilAplicacionDAO; import com.proyecto.server.service.IPerfilService; @Service public class PerfilService extends ServiceBase<Perfil, Long, IPerfilAplicacionDAO> implements IPerfilService { public Perfil findByIdInteger(Long idPerfil){ return this.getDao().findByIdInteger(idPerfil); } public boolean existsProfilByMenu(Long menuId,Long idPerfil){ return this.getDao().existsProfilByMenu(menuId,idPerfil); } }
package br.com.estore.web.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import br.com.estore.web.factory.ConnectionFactory; import br.com.estore.web.model.CustomerBean; public class CustomerDAO implements GenericDAO<CustomerBean> { @Override public List<CustomerBean> getAll() throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub return null; } @Override public CustomerBean save(CustomerBean pCustomer) throws ClassNotFoundException, SQLException { Connection dbConnection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String sql = "INSERT INTO mydb.customer" + "( " + "IS_ADMIN," + "LOGIN," + "PASSWORD," + "NAME," + "EMAIL," + "GENDER," + "PHONE," + "ADDRESS)" + "VALUES" + "(" + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?" + ");"; try { dbConnection = ConnectionFactory.getConnection(); preparedStatement = dbConnection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); preparedStatement.setInt(1, 0); preparedStatement.setString(2, pCustomer.getLogin()); preparedStatement.setString(3, pCustomer.getPassword()); preparedStatement.setString(4, pCustomer.getName()); preparedStatement.setString(5, pCustomer.getEmail()); preparedStatement.setString(6, pCustomer.getGender()); preparedStatement.setString(7, pCustomer.getPhone()); preparedStatement.setString(8, pCustomer.getAddress()); if (preparedStatement.executeUpdate() == 1) { // execute insert SQL stetement resultSet = preparedStatement.getGeneratedKeys(); if(resultSet.next()) { pCustomer.setId(resultSet.getInt(1)); } return pCustomer; } } finally { if (preparedStatement != null) { preparedStatement.close(); } if (dbConnection != null) { dbConnection.close(); } } return null; } @Override public CustomerBean get(Integer id) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub return null; } public CustomerBean get(CustomerBean pCustomer) throws ClassNotFoundException, SQLException { Connection dbConnection = null; PreparedStatement preparedStatement = null; String selectTableSQL = " SELECT " + " customer.ID," + " customer.IS_ADMIN," + " customer.LOGIN," + " customer.PASSWORD," + " customer.NAME," + " customer.EMAIL," + " customer.GENDER," + " customer.PHONE," + " customer.ADDRESS" + " FROM " + " mydb.customer" + " WHERE " + " customer.LOGIN = ? " + " AND " + " customer.PASSWORD = ?;"; try { dbConnection = ConnectionFactory.getConnection(); preparedStatement = dbConnection.prepareStatement(selectTableSQL); preparedStatement.setString(1, pCustomer.getLogin()); preparedStatement.setString(2, pCustomer.getPassword()); // execute select SQL stetement ResultSet rs = preparedStatement.executeQuery(); CustomerBean customer = null; if (rs.next()) { customer = new CustomerBean(); customer.setId(rs.getInt("ID")); customer.setIs_admin(rs.getInt("IS_ADMIN")); customer.setLogin(rs.getString("LOGIN")); customer.setPassword(rs.getString("PASSWORD")); customer.setName(rs.getString("NAME")); customer.setEmail(rs.getString("EMAIL")); customer.setGender(rs.getString("GENDER")); customer.setPhone(rs.getString("PHONE")); customer.setAddress(rs.getString("ADDRESS")); } return customer; } finally { if (preparedStatement != null) { preparedStatement.close(); } if (dbConnection != null) { dbConnection.close(); } } } @Override public boolean update(CustomerBean object) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub return false; } @Override public boolean delete(CustomerBean object) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub return false; } @Override public boolean deleteAll() throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub return false; } }
package com.ua.dekhtiarenko.webapp.services; import com.ua.dekhtiarenko.webapp.db.dao.classes.BookDAOImpl; import com.ua.dekhtiarenko.webapp.db.entity.Book; import org.apache.log4j.Logger; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by Dekhtiarenko-Daniil on 25.02.2021. */ public class MainPageService { private static final Logger log = Logger.getLogger(MainPageService.class); public void mainPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { log.info("Start MainPageService"); ServletContext servletContext = req.getServletContext(); BookDAOImpl bookDAOImpl = (BookDAOImpl) servletContext.getAttribute("bookDAO"); List<Book> bookListAvailabilityLess = new ArrayList<>(); List<Book> bookList = bookDAOImpl.getListBook(); List<Book> bookListAvailabilityMore = new ArrayList<>(); for (Book book : bookList) { if (book.getAvailability() > 0) { if (book.getAvailability() < 3) { bookListAvailabilityLess.add(book); } if (book.getAvailability() >= 3) { bookListAvailabilityMore.add(book); } } } log.info("Availability of book has been changed"); req.setAttribute("bookListAvailabilityMore", bookListAvailabilityMore); req.setAttribute("bookListAvailabilityLess", bookListAvailabilityLess); req.setAttribute("language", req.getAttribute("language")); req.getRequestDispatcher("/index.jsp").forward(req, resp); log.info("Finished MainPageService"); } }
package com.example.demo.controller; import com.example.demo.model.Course; import com.example.demo.model.User; import com.example.demo.model.UserCourse; import org.springframework.stereotype.Controller; import java.util.ArrayList; import java.util.List; @Controller public class CourseController { public static List<Course> getUserCourses(User user) { List<Course> courses = new ArrayList<>(); for (UserCourse userCourse : user.getUserCourses()) { courses.add(userCourse.getCourse()); } return courses; } public static List<User> getCourseTeachers(Course course) { List<User> teachers = new ArrayList<>(); for (UserCourse userCourse : course.getUserCourses()) { if (userCourse.getUser().getRole().equals("ROLE_TEACHER")) { teachers.add(userCourse.getUser()); } } return teachers; } public static List<User> getCourseStudents(Course course) { List<User> students = new ArrayList<>(); for (UserCourse userCourse : course.getUserCourses()) { if (userCourse.getUser().getRole().equals("ROLE_STUDENT") && userCourse.getAccepted()) { students.add(userCourse.getUser()); } } return students; } }
package com.tech.interview.siply.redbus.repository.contract.users; import com.tech.interview.siply.redbus.entity.dao.users.Admin; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; import java.util.UUID; @Repository public interface AdminRepository extends JpaRepository<Admin, UUID> { Optional<Admin> findByUserName(String userName); @Override void deleteById(UUID uuid); }
package sop.filegen; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @Author: LCF * @Date: 2020/1/9 9:37 * @Package: sop.filegen */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface GenFile { String value(); }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.mvc.method.annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.core.DefaultParameterNameDiscoverer; import org.springframework.core.KotlinDetector; import org.springframework.core.MethodIntrospector; import org.springframework.core.MethodParameter; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.log.LogFormatUtils; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.lang.Nullable; import org.springframework.ui.ModelMap; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; import org.springframework.util.ReflectionUtils.MethodFilter; import org.springframework.validation.method.MethodValidator; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.support.DefaultDataBinderFactory; import org.springframework.web.bind.support.DefaultSessionAttributeStore; import org.springframework.web.bind.support.SessionAttributeStore; import org.springframework.web.bind.support.WebBindingInitializer; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.WebRequest; import org.springframework.web.context.request.async.AsyncWebRequest; import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncTask; import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.method.ControllerAdviceBean; import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.annotation.ErrorsMethodArgumentResolver; import org.springframework.web.method.annotation.ExpressionValueMethodArgumentResolver; import org.springframework.web.method.annotation.HandlerMethodValidator; import org.springframework.web.method.annotation.InitBinderDataBinderFactory; import org.springframework.web.method.annotation.MapMethodProcessor; import org.springframework.web.method.annotation.ModelAttributeMethodProcessor; import org.springframework.web.method.annotation.ModelFactory; import org.springframework.web.method.annotation.ModelMethodProcessor; import org.springframework.web.method.annotation.RequestHeaderMapMethodArgumentResolver; import org.springframework.web.method.annotation.RequestHeaderMethodArgumentResolver; import org.springframework.web.method.annotation.RequestParamMapMethodArgumentResolver; import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver; import org.springframework.web.method.annotation.SessionAttributesHandler; import org.springframework.web.method.annotation.SessionStatusMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite; import org.springframework.web.method.support.InvocableHandlerMethod; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.service.invoker.RequestParamArgumentResolver; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver; import org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.support.RequestContextUtils; import org.springframework.web.util.WebUtils; /** * Extension of {@link AbstractHandlerMethodAdapter} that supports * {@link RequestMapping @RequestMapping} annotated {@link HandlerMethod HandlerMethods}. * * <p>Support for custom argument and return value types can be added via * {@link #setCustomArgumentResolvers} and {@link #setCustomReturnValueHandlers}, * or alternatively, to re-configure all argument and return value types, * use {@link #setArgumentResolvers} and {@link #setReturnValueHandlers}. * * @author Rossen Stoyanchev * @author Juergen Hoeller * @author Sebastien Deleuze * @since 3.1 * @see HandlerMethodArgumentResolver * @see HandlerMethodReturnValueHandler */ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter implements BeanFactoryAware, InitializingBean { /** * MethodFilter that matches {@link InitBinder @InitBinder} methods. */ public static final MethodFilter INIT_BINDER_METHODS = method -> AnnotatedElementUtils.hasAnnotation(method, InitBinder.class); /** * MethodFilter that matches {@link ModelAttribute @ModelAttribute} methods. */ public static final MethodFilter MODEL_ATTRIBUTE_METHODS = method -> (!AnnotatedElementUtils.hasAnnotation(method, RequestMapping.class) && AnnotatedElementUtils.hasAnnotation(method, ModelAttribute.class)); private final static boolean BEAN_VALIDATION_PRESENT = ClassUtils.isPresent("jakarta.validation.Validator", HandlerMethod.class.getClassLoader()); @Nullable private List<HandlerMethodArgumentResolver> customArgumentResolvers; @Nullable private HandlerMethodArgumentResolverComposite argumentResolvers; @Nullable private HandlerMethodArgumentResolverComposite initBinderArgumentResolvers; @Nullable private List<HandlerMethodReturnValueHandler> customReturnValueHandlers; @Nullable private HandlerMethodReturnValueHandlerComposite returnValueHandlers; @Nullable private List<ModelAndViewResolver> modelAndViewResolvers; private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager(); private final List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); private final List<Object> requestResponseBodyAdvice = new ArrayList<>(); @Nullable private WebBindingInitializer webBindingInitializer; @Nullable private MethodValidator methodValidator; private AsyncTaskExecutor taskExecutor = new MvcSimpleAsyncTaskExecutor(); @Nullable private Long asyncRequestTimeout; private CallableProcessingInterceptor[] callableInterceptors = new CallableProcessingInterceptor[0]; private DeferredResultProcessingInterceptor[] deferredResultInterceptors = new DeferredResultProcessingInterceptor[0]; private ReactiveAdapterRegistry reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance(); private boolean ignoreDefaultModelOnRedirect = true; private int cacheSecondsForSessionAttributeHandlers = 0; private boolean synchronizeOnSession = false; private SessionAttributeStore sessionAttributeStore = new DefaultSessionAttributeStore(); private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); @Nullable private ConfigurableBeanFactory beanFactory; private final Map<Class<?>, SessionAttributesHandler> sessionAttributesHandlerCache = new ConcurrentHashMap<>(64); private final Map<Class<?>, Set<Method>> initBinderCache = new ConcurrentHashMap<>(64); private final Map<ControllerAdviceBean, Set<Method>> initBinderAdviceCache = new LinkedHashMap<>(); private final Map<Class<?>, Set<Method>> modelAttributeCache = new ConcurrentHashMap<>(64); private final Map<ControllerAdviceBean, Set<Method>> modelAttributeAdviceCache = new LinkedHashMap<>(); /** * Provide resolvers for custom argument types. Custom resolvers are ordered * after built-in ones. To override the built-in support for argument * resolution use {@link #setArgumentResolvers} instead. */ public void setCustomArgumentResolvers(@Nullable List<HandlerMethodArgumentResolver> argumentResolvers) { this.customArgumentResolvers = argumentResolvers; } /** * Return the custom argument resolvers, or {@code null}. */ @Nullable public List<HandlerMethodArgumentResolver> getCustomArgumentResolvers() { return this.customArgumentResolvers; } /** * Configure the complete list of supported argument types thus overriding * the resolvers that would otherwise be configured by default. */ public void setArgumentResolvers(@Nullable List<HandlerMethodArgumentResolver> argumentResolvers) { if (argumentResolvers == null) { this.argumentResolvers = null; } else { this.argumentResolvers = new HandlerMethodArgumentResolverComposite(); this.argumentResolvers.addResolvers(argumentResolvers); } } /** * Return the configured argument resolvers, or possibly {@code null} if * not initialized yet via {@link #afterPropertiesSet()}. */ @Nullable public List<HandlerMethodArgumentResolver> getArgumentResolvers() { return (this.argumentResolvers != null ? this.argumentResolvers.getResolvers() : null); } /** * Configure the supported argument types in {@code @InitBinder} methods. */ public void setInitBinderArgumentResolvers(@Nullable List<HandlerMethodArgumentResolver> argumentResolvers) { if (argumentResolvers == null) { this.initBinderArgumentResolvers = null; } else { this.initBinderArgumentResolvers = new HandlerMethodArgumentResolverComposite(); this.initBinderArgumentResolvers.addResolvers(argumentResolvers); } } /** * Return the argument resolvers for {@code @InitBinder} methods, or possibly * {@code null} if not initialized yet via {@link #afterPropertiesSet()}. */ @Nullable public List<HandlerMethodArgumentResolver> getInitBinderArgumentResolvers() { return (this.initBinderArgumentResolvers != null ? this.initBinderArgumentResolvers.getResolvers() : null); } /** * Provide handlers for custom return value types. Custom handlers are * ordered after built-in ones. To override the built-in support for * return value handling use {@link #setReturnValueHandlers}. */ public void setCustomReturnValueHandlers(@Nullable List<HandlerMethodReturnValueHandler> returnValueHandlers) { this.customReturnValueHandlers = returnValueHandlers; } /** * Return the custom return value handlers, or {@code null}. */ @Nullable public List<HandlerMethodReturnValueHandler> getCustomReturnValueHandlers() { return this.customReturnValueHandlers; } /** * Configure the complete list of supported return value types thus * overriding handlers that would otherwise be configured by default. */ public void setReturnValueHandlers(@Nullable List<HandlerMethodReturnValueHandler> returnValueHandlers) { if (returnValueHandlers == null) { this.returnValueHandlers = null; } else { this.returnValueHandlers = new HandlerMethodReturnValueHandlerComposite(); this.returnValueHandlers.addHandlers(returnValueHandlers); } } /** * Return the configured handlers, or possibly {@code null} if not * initialized yet via {@link #afterPropertiesSet()}. */ @Nullable public List<HandlerMethodReturnValueHandler> getReturnValueHandlers() { return (this.returnValueHandlers != null ? this.returnValueHandlers.getHandlers() : null); } /** * Provide custom {@link ModelAndViewResolver ModelAndViewResolvers}. * <p><strong>Note:</strong> This method is available for backwards * compatibility only. However, it is recommended to re-write a * {@code ModelAndViewResolver} as {@link HandlerMethodReturnValueHandler}. * An adapter between the two interfaces is not possible since the * {@link HandlerMethodReturnValueHandler#supportsReturnType} method * cannot be implemented. Hence {@code ModelAndViewResolver}s are limited * to always being invoked at the end after all other return value * handlers have been given a chance. * <p>A {@code HandlerMethodReturnValueHandler} provides better access to * the return type and controller method information and can be ordered * freely relative to other return value handlers. */ public void setModelAndViewResolvers(@Nullable List<ModelAndViewResolver> modelAndViewResolvers) { this.modelAndViewResolvers = modelAndViewResolvers; } /** * Return the configured {@link ModelAndViewResolver ModelAndViewResolvers}, or {@code null}. */ @Nullable public List<ModelAndViewResolver> getModelAndViewResolvers() { return this.modelAndViewResolvers; } /** * Set the {@link ContentNegotiationManager} to use to determine requested media types. * If not set, the default constructor is used. */ public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) { this.contentNegotiationManager = contentNegotiationManager; } /** * Provide the converters to use in argument resolvers and return value * handlers that support reading and/or writing to the body of the * request and response. */ public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) { this.messageConverters.clear(); this.messageConverters.addAll(messageConverters); } /** * Return the configured message body converters. */ public List<HttpMessageConverter<?>> getMessageConverters() { return this.messageConverters; } /** * Add one or more {@code RequestBodyAdvice} instances to intercept the * request before it is read and converted for {@code @RequestBody} and * {@code HttpEntity} method arguments. */ public void setRequestBodyAdvice(@Nullable List<RequestBodyAdvice> requestBodyAdvice) { if (requestBodyAdvice != null) { this.requestResponseBodyAdvice.addAll(requestBodyAdvice); } } /** * Add one or more {@code ResponseBodyAdvice} instances to intercept the * response before {@code @ResponseBody} or {@code ResponseEntity} return * values are written to the response body. */ public void setResponseBodyAdvice(@Nullable List<ResponseBodyAdvice<?>> responseBodyAdvice) { if (responseBodyAdvice != null) { this.requestResponseBodyAdvice.addAll(responseBodyAdvice); } } /** * Provide a WebBindingInitializer with "global" initialization to apply * to every DataBinder instance. */ public void setWebBindingInitializer(@Nullable WebBindingInitializer webBindingInitializer) { this.webBindingInitializer = webBindingInitializer; } /** * Return the configured WebBindingInitializer, or {@code null} if none. */ @Nullable public WebBindingInitializer getWebBindingInitializer() { return this.webBindingInitializer; } /** * Set the default {@link AsyncTaskExecutor} to use when a controller method * return a {@link Callable}. Controller methods can override this default on * a per-request basis by returning an {@link WebAsyncTask}. * <p>If your application has controllers with such return types, please * configure an {@link AsyncTaskExecutor} as the one used by default is not * suitable for production under load. */ public void setTaskExecutor(AsyncTaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } /** * Specify the amount of time, in milliseconds, before concurrent handling * should time out. In Servlet 3, the timeout begins after the main request * processing thread has exited and ends when the request is dispatched again * for further processing of the concurrently produced result. * <p>If this value is not set, the default timeout of the underlying * implementation is used. * @param timeout the timeout value in milliseconds */ public void setAsyncRequestTimeout(long timeout) { this.asyncRequestTimeout = timeout; } /** * Configure {@code CallableProcessingInterceptor}'s to register on async requests. * @param interceptors the interceptors to register */ public void setCallableInterceptors(List<CallableProcessingInterceptor> interceptors) { this.callableInterceptors = interceptors.toArray(new CallableProcessingInterceptor[0]); } /** * Configure {@code DeferredResultProcessingInterceptor}'s to register on async requests. * @param interceptors the interceptors to register */ public void setDeferredResultInterceptors(List<DeferredResultProcessingInterceptor> interceptors) { this.deferredResultInterceptors = interceptors.toArray(new DeferredResultProcessingInterceptor[0]); } /** * Configure the registry for reactive library types to be supported as * return values from controller methods. * @since 5.0.5 */ public void setReactiveAdapterRegistry(ReactiveAdapterRegistry reactiveAdapterRegistry) { this.reactiveAdapterRegistry = reactiveAdapterRegistry; } /** * Return the configured reactive type registry of adapters. * @since 5.0 */ public ReactiveAdapterRegistry getReactiveAdapterRegistry() { return this.reactiveAdapterRegistry; } /** * By default, the content of the "default" model is used both during * rendering and redirect scenarios. Alternatively a controller method * can declare a {@link RedirectAttributes} argument and use it to provide * attributes for a redirect. * <p>Setting this flag to {@code true} guarantees the "default" model is * never used in a redirect scenario even if a RedirectAttributes argument * is not declared. Setting it to {@code false} means the "default" model * may be used in a redirect if the controller method doesn't declare a * RedirectAttributes argument. * <p>As of 6.0, this property is set to {@code true} by default. * @see RedirectAttributes * @deprecated as of 6.0 without a replacement; once removed, the default * model will always be ignored on redirect */ @Deprecated(since = "6.0") public void setIgnoreDefaultModelOnRedirect(boolean ignoreDefaultModelOnRedirect) { this.ignoreDefaultModelOnRedirect = ignoreDefaultModelOnRedirect; } /** * Specify the strategy to store session attributes with. The default is * {@link org.springframework.web.bind.support.DefaultSessionAttributeStore}, * storing session attributes in the HttpSession with the same attribute * name as in the model. */ public void setSessionAttributeStore(SessionAttributeStore sessionAttributeStore) { this.sessionAttributeStore = sessionAttributeStore; } /** * Cache content produced by {@code @SessionAttributes} annotated handlers * for the given number of seconds. * <p>Possible values are: * <ul> * <li>-1: no generation of cache-related headers</li> * <li>0 (default value): "Cache-Control: no-store" will prevent caching</li> * <li>1 or higher: "Cache-Control: max-age=seconds" will ask to cache content; * not advised when dealing with session attributes</li> * </ul> * <p>In contrast to the "cacheSeconds" property which will apply to all general * handlers (but not to {@code @SessionAttributes} annotated handlers), * this setting will apply to {@code @SessionAttributes} handlers only. * @see #setCacheSeconds * @see org.springframework.web.bind.annotation.SessionAttributes */ public void setCacheSecondsForSessionAttributeHandlers(int cacheSecondsForSessionAttributeHandlers) { this.cacheSecondsForSessionAttributeHandlers = cacheSecondsForSessionAttributeHandlers; } /** * Set if controller execution should be synchronized on the session, * to serialize parallel invocations from the same client. * <p>More specifically, the execution of the {@code handleRequestInternal} * method will get synchronized if this flag is "true". The best available * session mutex will be used for the synchronization; ideally, this will * be a mutex exposed by HttpSessionMutexListener. * <p>The session mutex is guaranteed to be the same object during * the entire lifetime of the session, available under the key defined * by the {@code SESSION_MUTEX_ATTRIBUTE} constant. It serves as a * safe reference to synchronize on for locking on the current session. * <p>In many cases, the HttpSession reference itself is a safe mutex * as well, since it will always be the same object reference for the * same active logical session. However, this is not guaranteed across * different servlet containers; the only 100% safe way is a session mutex. * @see org.springframework.web.util.HttpSessionMutexListener * @see org.springframework.web.util.WebUtils#getSessionMutex(jakarta.servlet.http.HttpSession) */ public void setSynchronizeOnSession(boolean synchronizeOnSession) { this.synchronizeOnSession = synchronizeOnSession; } /** * Set the ParameterNameDiscoverer to use for resolving method parameter names if needed * (e.g. for default attribute names). * <p>Default is a {@link org.springframework.core.DefaultParameterNameDiscoverer}. */ public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer) { this.parameterNameDiscoverer = parameterNameDiscoverer; } /** * A {@link ConfigurableBeanFactory} is expected for resolving expressions * in method argument default values. */ @Override public void setBeanFactory(BeanFactory beanFactory) { if (beanFactory instanceof ConfigurableBeanFactory cbf) { this.beanFactory = cbf; } } /** * Return the owning factory of this bean instance, or {@code null} if none. */ @Nullable protected ConfigurableBeanFactory getBeanFactory() { return this.beanFactory; } @Override public void afterPropertiesSet() { // Do this first, it may add ResponseBody advice beans initControllerAdviceCache(); initMessageConverters(); if (this.argumentResolvers == null) { List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers(); this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers); } if (this.initBinderArgumentResolvers == null) { List<HandlerMethodArgumentResolver> resolvers = getDefaultInitBinderArgumentResolvers(); this.initBinderArgumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers); } if (this.returnValueHandlers == null) { List<HandlerMethodReturnValueHandler> handlers = getDefaultReturnValueHandlers(); this.returnValueHandlers = new HandlerMethodReturnValueHandlerComposite().addHandlers(handlers); } if (BEAN_VALIDATION_PRESENT) { List<HandlerMethodArgumentResolver> resolvers = this.argumentResolvers.getResolvers(); this.methodValidator = HandlerMethodValidator.from( this.webBindingInitializer, this.parameterNameDiscoverer, methodParamPredicate(resolvers, ModelAttributeMethodProcessor.class), methodParamPredicate(resolvers, RequestParamArgumentResolver.class)); } } private void initMessageConverters() { if (!this.messageConverters.isEmpty()) { return; } this.messageConverters.add(new ByteArrayHttpMessageConverter()); this.messageConverters.add(new StringHttpMessageConverter()); this.messageConverters.add(new AllEncompassingFormHttpMessageConverter()); } private void initControllerAdviceCache() { if (getApplicationContext() == null) { return; } List<ControllerAdviceBean> adviceBeans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext()); List<Object> requestResponseBodyAdviceBeans = new ArrayList<>(); for (ControllerAdviceBean adviceBean : adviceBeans) { Class<?> beanType = adviceBean.getBeanType(); if (beanType == null) { throw new IllegalStateException("Unresolvable type for ControllerAdviceBean: " + adviceBean); } Set<Method> attrMethods = MethodIntrospector.selectMethods(beanType, MODEL_ATTRIBUTE_METHODS); if (!attrMethods.isEmpty()) { this.modelAttributeAdviceCache.put(adviceBean, attrMethods); } Set<Method> binderMethods = MethodIntrospector.selectMethods(beanType, INIT_BINDER_METHODS); if (!binderMethods.isEmpty()) { this.initBinderAdviceCache.put(adviceBean, binderMethods); } if (RequestBodyAdvice.class.isAssignableFrom(beanType) || ResponseBodyAdvice.class.isAssignableFrom(beanType)) { requestResponseBodyAdviceBeans.add(adviceBean); } } if (!requestResponseBodyAdviceBeans.isEmpty()) { this.requestResponseBodyAdvice.addAll(0, requestResponseBodyAdviceBeans); } if (logger.isDebugEnabled()) { int modelSize = this.modelAttributeAdviceCache.size(); int binderSize = this.initBinderAdviceCache.size(); int reqCount = getBodyAdviceCount(RequestBodyAdvice.class); int resCount = getBodyAdviceCount(ResponseBodyAdvice.class); if (modelSize == 0 && binderSize == 0 && reqCount == 0 && resCount == 0) { logger.debug("ControllerAdvice beans: none"); } else { logger.debug("ControllerAdvice beans: " + modelSize + " @ModelAttribute, " + binderSize + " @InitBinder, " + reqCount + " RequestBodyAdvice, " + resCount + " ResponseBodyAdvice"); } } } // Count all advice, including explicit registrations.. private int getBodyAdviceCount(Class<?> adviceType) { List<Object> advice = this.requestResponseBodyAdvice; return RequestBodyAdvice.class.isAssignableFrom(adviceType) ? RequestResponseBodyAdviceChain.getAdviceByType(advice, RequestBodyAdvice.class).size() : RequestResponseBodyAdviceChain.getAdviceByType(advice, ResponseBodyAdvice.class).size(); } /** * Return the list of argument resolvers to use including built-in resolvers * and custom resolvers provided via {@link #setCustomArgumentResolvers}. */ private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() { List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>(30); // Annotation-based argument resolution resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false)); resolvers.add(new RequestParamMapMethodArgumentResolver()); resolvers.add(new PathVariableMethodArgumentResolver()); resolvers.add(new PathVariableMapMethodArgumentResolver()); resolvers.add(new MatrixVariableMethodArgumentResolver()); resolvers.add(new MatrixVariableMapMethodArgumentResolver()); resolvers.add(new ServletModelAttributeMethodProcessor(false)); resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice)); resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters(), this.requestResponseBodyAdvice)); resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory())); resolvers.add(new RequestHeaderMapMethodArgumentResolver()); resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory())); resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory())); resolvers.add(new SessionAttributeMethodArgumentResolver()); resolvers.add(new RequestAttributeMethodArgumentResolver()); // Type-based argument resolution resolvers.add(new ServletRequestMethodArgumentResolver()); resolvers.add(new ServletResponseMethodArgumentResolver()); resolvers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice)); resolvers.add(new RedirectAttributesMethodArgumentResolver()); resolvers.add(new ModelMethodProcessor()); resolvers.add(new MapMethodProcessor()); resolvers.add(new ErrorsMethodArgumentResolver()); resolvers.add(new SessionStatusMethodArgumentResolver()); resolvers.add(new UriComponentsBuilderMethodArgumentResolver()); if (KotlinDetector.isKotlinPresent()) { resolvers.add(new ContinuationHandlerMethodArgumentResolver()); } // Custom arguments if (getCustomArgumentResolvers() != null) { resolvers.addAll(getCustomArgumentResolvers()); } // Catch-all resolvers.add(new PrincipalMethodArgumentResolver()); resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), true)); resolvers.add(new ServletModelAttributeMethodProcessor(true)); return resolvers; } /** * Return the list of argument resolvers to use for {@code @InitBinder} * methods including built-in and custom resolvers. */ private List<HandlerMethodArgumentResolver> getDefaultInitBinderArgumentResolvers() { List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>(20); // Annotation-based argument resolution resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false)); resolvers.add(new RequestParamMapMethodArgumentResolver()); resolvers.add(new PathVariableMethodArgumentResolver()); resolvers.add(new PathVariableMapMethodArgumentResolver()); resolvers.add(new MatrixVariableMethodArgumentResolver()); resolvers.add(new MatrixVariableMapMethodArgumentResolver()); resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory())); resolvers.add(new SessionAttributeMethodArgumentResolver()); resolvers.add(new RequestAttributeMethodArgumentResolver()); // Type-based argument resolution resolvers.add(new ServletRequestMethodArgumentResolver()); resolvers.add(new ServletResponseMethodArgumentResolver()); // Custom arguments if (getCustomArgumentResolvers() != null) { resolvers.addAll(getCustomArgumentResolvers()); } // Catch-all resolvers.add(new PrincipalMethodArgumentResolver()); resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), true)); return resolvers; } /** * Return the list of return value handlers to use including built-in and * custom handlers provided via {@link #setReturnValueHandlers}. */ private List<HandlerMethodReturnValueHandler> getDefaultReturnValueHandlers() { List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(20); // Single-purpose return value types handlers.add(new ModelAndViewMethodReturnValueHandler()); handlers.add(new ModelMethodProcessor()); handlers.add(new ViewMethodReturnValueHandler()); handlers.add(new ResponseBodyEmitterReturnValueHandler(getMessageConverters(), this.reactiveAdapterRegistry, this.taskExecutor, this.contentNegotiationManager)); handlers.add(new StreamingResponseBodyReturnValueHandler()); handlers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.contentNegotiationManager, this.requestResponseBodyAdvice)); handlers.add(new HttpHeadersReturnValueHandler()); handlers.add(new CallableMethodReturnValueHandler()); handlers.add(new DeferredResultMethodReturnValueHandler()); handlers.add(new AsyncTaskMethodReturnValueHandler(this.beanFactory)); // Annotation-based return value types handlers.add(new ServletModelAttributeMethodProcessor(false)); handlers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.contentNegotiationManager, this.requestResponseBodyAdvice)); // Multi-purpose return value types handlers.add(new ViewNameMethodReturnValueHandler()); handlers.add(new MapMethodProcessor()); // Custom return value types if (getCustomReturnValueHandlers() != null) { handlers.addAll(getCustomReturnValueHandlers()); } // Catch-all if (!CollectionUtils.isEmpty(getModelAndViewResolvers())) { handlers.add(new ModelAndViewResolverMethodReturnValueHandler(getModelAndViewResolvers())); } else { handlers.add(new ServletModelAttributeMethodProcessor(true)); } return handlers; } private static Predicate<MethodParameter> methodParamPredicate( List<HandlerMethodArgumentResolver> resolvers, Class<?> resolverType) { return parameter -> { for (HandlerMethodArgumentResolver resolver : resolvers) { if (resolver.supportsParameter(parameter)) { return resolverType.isInstance(resolver); } } return false; }; } /** * Always return {@code true} since any method argument and return value * type will be processed in some way. A method argument not recognized * by any HandlerMethodArgumentResolver is interpreted as a request parameter * if it is a simple type, or as a model attribute otherwise. A return value * not recognized by any HandlerMethodReturnValueHandler will be interpreted * as a model attribute. */ @Override protected boolean supportsInternal(HandlerMethod handlerMethod) { return true; } @Override protected ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception { ModelAndView mav; checkRequest(request); // Execute invokeHandlerMethod in synchronized block if required. if (this.synchronizeOnSession) { HttpSession session = request.getSession(false); if (session != null) { Object mutex = WebUtils.getSessionMutex(session); synchronized (mutex) { mav = invokeHandlerMethod(request, response, handlerMethod); } } else { // No HttpSession available -> no mutex necessary mav = invokeHandlerMethod(request, response, handlerMethod); } } else { // No synchronization on session demanded at all... mav = invokeHandlerMethod(request, response, handlerMethod); } if (!response.containsHeader(HEADER_CACHE_CONTROL)) { if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) { applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers); } else { prepareResponse(response); } } return mav; } /** * This implementation always returns -1. An {@code @RequestMapping} method can * calculate the lastModified value, call {@link WebRequest#checkNotModified(long)}, * and return {@code null} if the result of that call is {@code true}. */ @Override @SuppressWarnings("deprecation") protected long getLastModifiedInternal(HttpServletRequest request, HandlerMethod handlerMethod) { return -1; } /** * Return the {@link SessionAttributesHandler} instance for the given handler type * (never {@code null}). */ private SessionAttributesHandler getSessionAttributesHandler(HandlerMethod handlerMethod) { return this.sessionAttributesHandlerCache.computeIfAbsent( handlerMethod.getBeanType(), type -> new SessionAttributesHandler(type, this.sessionAttributeStore)); } /** * Invoke the {@link RequestMapping} handler method preparing a {@link ModelAndView} * if view resolution is required. * @since 4.2 * @see #createInvocableHandlerMethod(HandlerMethod) */ @SuppressWarnings("deprecation") @Nullable protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception { ServletWebRequest webRequest = new ServletWebRequest(request, response); WebDataBinderFactory binderFactory = getDataBinderFactory(handlerMethod); ModelFactory modelFactory = getModelFactory(handlerMethod, binderFactory); ServletInvocableHandlerMethod invocableMethod = createInvocableHandlerMethod(handlerMethod); if (this.argumentResolvers != null) { invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers); } if (this.returnValueHandlers != null) { invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers); } invocableMethod.setDataBinderFactory(binderFactory); invocableMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer); invocableMethod.setMethodValidator(this.methodValidator); ModelAndViewContainer mavContainer = new ModelAndViewContainer(); mavContainer.addAllAttributes(RequestContextUtils.getInputFlashMap(request)); modelFactory.initModel(webRequest, mavContainer, invocableMethod); mavContainer.setIgnoreDefaultModelOnRedirect(this.ignoreDefaultModelOnRedirect); AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response); asyncWebRequest.setTimeout(this.asyncRequestTimeout); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); asyncManager.setTaskExecutor(this.taskExecutor); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.registerCallableInterceptors(this.callableInterceptors); asyncManager.registerDeferredResultInterceptors(this.deferredResultInterceptors); if (asyncManager.hasConcurrentResult()) { Object result = asyncManager.getConcurrentResult(); mavContainer = (ModelAndViewContainer) asyncManager.getConcurrentResultContext()[0]; asyncManager.clearConcurrentResult(); LogFormatUtils.traceDebug(logger, traceOn -> { String formatted = LogFormatUtils.formatValue(result, !traceOn); return "Resume with async result [" + formatted + "]"; }); invocableMethod = invocableMethod.wrapConcurrentResult(result); } invocableMethod.invokeAndHandle(webRequest, mavContainer); if (asyncManager.isConcurrentHandlingStarted()) { return null; } return getModelAndView(mavContainer, modelFactory, webRequest); } /** * Create a {@link ServletInvocableHandlerMethod} from the given {@link HandlerMethod} definition. * @param handlerMethod the {@link HandlerMethod} definition * @return the corresponding {@link ServletInvocableHandlerMethod} (or custom subclass thereof) * @since 4.2 */ protected ServletInvocableHandlerMethod createInvocableHandlerMethod(HandlerMethod handlerMethod) { return new ServletInvocableHandlerMethod(handlerMethod); } private ModelFactory getModelFactory(HandlerMethod handlerMethod, WebDataBinderFactory binderFactory) { SessionAttributesHandler sessionAttrHandler = getSessionAttributesHandler(handlerMethod); Class<?> handlerType = handlerMethod.getBeanType(); Set<Method> methods = this.modelAttributeCache.get(handlerType); if (methods == null) { methods = MethodIntrospector.selectMethods(handlerType, MODEL_ATTRIBUTE_METHODS); this.modelAttributeCache.put(handlerType, methods); } List<InvocableHandlerMethod> attrMethods = new ArrayList<>(); // Global methods first this.modelAttributeAdviceCache.forEach((controllerAdviceBean, methodSet) -> { if (controllerAdviceBean.isApplicableToBeanType(handlerType)) { Object bean = controllerAdviceBean.resolveBean(); for (Method method : methodSet) { attrMethods.add(createModelAttributeMethod(binderFactory, bean, method)); } } }); for (Method method : methods) { Object bean = handlerMethod.getBean(); attrMethods.add(createModelAttributeMethod(binderFactory, bean, method)); } return new ModelFactory(attrMethods, binderFactory, sessionAttrHandler); } private InvocableHandlerMethod createModelAttributeMethod(WebDataBinderFactory factory, Object bean, Method method) { InvocableHandlerMethod attrMethod = new InvocableHandlerMethod(bean, method); if (this.argumentResolvers != null) { attrMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers); } attrMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer); attrMethod.setDataBinderFactory(factory); return attrMethod; } private WebDataBinderFactory getDataBinderFactory(HandlerMethod handlerMethod) throws Exception { Class<?> handlerType = handlerMethod.getBeanType(); Set<Method> methods = this.initBinderCache.get(handlerType); if (methods == null) { methods = MethodIntrospector.selectMethods(handlerType, INIT_BINDER_METHODS); this.initBinderCache.put(handlerType, methods); } List<InvocableHandlerMethod> initBinderMethods = new ArrayList<>(); // Global methods first this.initBinderAdviceCache.forEach((controllerAdviceBean, methodSet) -> { if (controllerAdviceBean.isApplicableToBeanType(handlerType)) { Object bean = controllerAdviceBean.resolveBean(); for (Method method : methodSet) { initBinderMethods.add(createInitBinderMethod(bean, method)); } } }); for (Method method : methods) { Object bean = handlerMethod.getBean(); initBinderMethods.add(createInitBinderMethod(bean, method)); } DefaultDataBinderFactory factory = createDataBinderFactory(initBinderMethods); factory.setMethodValidationApplicable(this.methodValidator != null && handlerMethod.shouldValidateArguments()); return factory; } private InvocableHandlerMethod createInitBinderMethod(Object bean, Method method) { InvocableHandlerMethod binderMethod = new InvocableHandlerMethod(bean, method); if (this.initBinderArgumentResolvers != null) { binderMethod.setHandlerMethodArgumentResolvers(this.initBinderArgumentResolvers); } binderMethod.setDataBinderFactory(new DefaultDataBinderFactory(this.webBindingInitializer)); binderMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer); return binderMethod; } /** * Template method to create a new InitBinderDataBinderFactory instance. * <p>The default implementation creates a ServletRequestDataBinderFactory. * This can be overridden for custom ServletRequestDataBinder subclasses. * @param binderMethods {@code @InitBinder} methods * @return the InitBinderDataBinderFactory instance to use * @throws Exception in case of invalid state or arguments */ protected InitBinderDataBinderFactory createDataBinderFactory(List<InvocableHandlerMethod> binderMethods) throws Exception { return new ServletRequestDataBinderFactory(binderMethods, getWebBindingInitializer()); } @Nullable private ModelAndView getModelAndView(ModelAndViewContainer mavContainer, ModelFactory modelFactory, NativeWebRequest webRequest) throws Exception { modelFactory.updateModel(webRequest, mavContainer); if (mavContainer.isRequestHandled()) { return null; } ModelMap model = mavContainer.getModel(); ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, mavContainer.getStatus()); if (!mavContainer.isViewReference()) { mav.setView((View) mavContainer.getView()); } if (model instanceof RedirectAttributes redirectAttributes) { Map<String, ?> flashAttributes = redirectAttributes.getFlashAttributes(); HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); if (request != null) { RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes); } } return mav; } /** * A default Spring MVC AsyncTaskExecutor that warns if used. */ @SuppressWarnings("serial") private class MvcSimpleAsyncTaskExecutor extends SimpleAsyncTaskExecutor { private static boolean taskExecutorWarning = true; public MvcSimpleAsyncTaskExecutor() { super("MvcAsync"); } @Override public void execute(Runnable task) { if (taskExecutorWarning && logger.isWarnEnabled()) { synchronized (this) { if (taskExecutorWarning) { logger.warn(""" !!! Performing asynchronous handling through the default Spring MVC SimpleAsyncTaskExecutor. This executor is not suitable for production use under load. Please, configure an AsyncTaskExecutor through the WebMvc config. ------------------------------- !!!"""); taskExecutorWarning = false; } } } super.execute(task); } } }
package com.esum.framework.core.event.message; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import com.esum.framework.common.util.SysConstants; public class RoutingInfo implements Serializable { private static final long serialVersionUID = 1L; /** * Asynchronous Routing Type. */ public static final String ASYNC_ROUTING = "A"; /** * Synchronous Routing Type */ public static final String SYNC_ROUTING = "S"; /** * Normal Request Message. */ public static final String NORMAL_MESSAGE = "N"; /** * Acknowledge Response Message. */ public static final String ACK_MESSAGE = "A"; /** * Routing Flow. */ private String pathFlow=""; private List<String> path = new ArrayList<String>(); /** * Current path index. */ private int pathIndex = 1; private String targetInterfaceId; /** * routing type : A(async), S(sync) */ private String routeType = ASYNC_ROUTING; private int timeToLive = 10000; // default : 10sec private boolean skipRouting; /** * Inbound Ack. */ private boolean useInboundAck; private String acknowledgeClass; private String messageType = NORMAL_MESSAGE; private String parsingRule = ""; public String nextPath() { if(path.size()==0) return null; return (String) path.get(pathIndex++); } public String currentPath() { if(path.size()==0) return null; return (String) path.get(pathIndex - 1); } public boolean hasMorePath() { return pathIndex < path.size(); } public String getStartComponent() { if(path.size()==0) return null; return (String) path.get(0); } public boolean isEndPath() { return !hasMorePath(); } public int getPathSize() { return path.size(); } public String getPath(int index) { return (String) path.get(index); } public int getPathIndex() { return pathIndex; } public void addPath(String path) { this.path.add(path); } public void setPathIndex(int pathIndex) { this.pathIndex = pathIndex; } public void clearPath() { this.path.clear(); this.pathIndex = 1; } public void setPath(String[] paths) { if (paths == null) return; this.clearPath(); for (int i = 0; i < paths.length; i++) this.addPath(paths[i]); } public String getPathFlow() { return pathFlow; } public void setPathFlow(String flow) { this.pathFlow = flow; path.clear(); StringTokenizer tokens = new StringTokenizer(flow, "|"); while (tokens.hasMoreTokens()) { path.add(tokens.nextToken()); } this.pathIndex = 1; } public boolean isContainsPath(String path) { return this.path.contains(path); } public int getPathIndex(String path) { if (isContainsPath(path)) { return this.path.indexOf(path); } return -1; } public String getTargetInterfaceId() { return targetInterfaceId; } public void setTargetInterfaceId(String targetInterfaceId) { this.targetInterfaceId = targetInterfaceId; } public String getRouteType() { return routeType; } public void setRouteType(String routeType) { this.routeType = routeType; } public int getTimeToLive() { return timeToLive; } public void setTimeToLive(int timeToLive) { this.timeToLive = timeToLive; } public boolean isUseInboundAck() { return useInboundAck; } public void setUseInboundAck(boolean useInboundAck) { this.useInboundAck = useInboundAck; } public String getMessageType() { return messageType; } public void setMessageType(String messageType) { this.messageType = messageType; } public String getAcknowledgeClass() { return acknowledgeClass; } public void setAcknowledgeClass(String acknowledgeClass) { this.acknowledgeClass = acknowledgeClass; } public String getParsingRule() { return parsingRule; } public void setParsingRule(String parsingRule) { this.parsingRule = parsingRule; } public boolean isSkipRouting() { return skipRouting; } public void setSkipRouting(boolean skipRouting) { this.skipRouting = skipRouting; } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("PathFlow : " + pathFlow + SysConstants.LINE_SEPARATOR); buffer.append("CurrentPathIndex : " + pathIndex + SysConstants.LINE_SEPARATOR); buffer.append("RouteType : "+routeType + SysConstants.LINE_SEPARATOR); buffer.append("TimeToLive : "+timeToLive + SysConstants.LINE_SEPARATOR); buffer.append("MessageType : "+messageType + SysConstants.LINE_SEPARATOR); buffer.append("SkipRouting : "+skipRouting + SysConstants.LINE_SEPARATOR); buffer.append("useInboundAck : "+useInboundAck + SysConstants.LINE_SEPARATOR); buffer.append("parsingRule : "+parsingRule); return buffer.toString(); } }
package com.bbg.test; import java.util.concurrent.atomic.AtomicInteger; public class PrintThread implements Runnable { /* volatile int count=0; */ final AtomicInteger count = new AtomicInteger(0);//final for pointer not value, better for being used as lock /* static final AtomicInteger count = new AtomicInteger(0); private final int threadPosition; public PrintThread(int threadPosition) { this.threadPosition = threadPosition; } */ @Override public void run() { //no guarantee how many each thread print /* while (count < 101) { synchronized (this) { //double check because count may be incremented by other thread btw 20 and 21, otherwise may output 101 102 if(count < 101) System.out.println(Thread.currentThread().getId() + ":" + count++); } } */ int cur; while ((cur=count.get()) < 101) { synchronized (count) {//no need to sync atomic count, but need to sync on print //CAS: make last get to this set atomic, count.getAndIncrement() only current get and set atomic, need double check as volatile if (count.compareAndSet(cur, cur+1)) System.out.println(Thread.currentThread().getId() + ":" + cur); } } //9:0 10:1 11:2 9:3 10:4 11:5 9:6 10:7 11:8 9:9 10:10 /* int cur=0; while ((cur=count.get()) < 101) { if (cur % 3 == this.threadPosition) { //synchronize on static object because each thread has a separate instance synchronized (count) { if (count.compareAndSet(cur, cur+1))//CAS System.out.println(Thread.currentThread().getId() + ":" + cur); } } } */ } public static void main(String[] args) throws InterruptedException { PrintThread pr = new PrintThread(); Thread T1 = new Thread(pr); Thread T2 = new Thread(pr); Thread T3 = new Thread(pr); /* Thread T1 = new Thread(new PrintThread(0)); Thread T2 = new Thread(new PrintThread(1)); Thread T3 = new Thread(new PrintThread(2)); */ T1.start(); T2.start(); T3.start(); T1.join(); T2.join(); T3.join(); } }
package service; import java.io.UnsupportedEncodingException; /** * Rest Service Class provides all Rest API for Travel Experts \n * @version 1.0 - Date: 04/13/2019 * @author Quynh Nguyen (Queenie) * **/ import java.lang.reflect.Type; import java.net.URLDecoder; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import database.DBAgency; import database.DBAgent; import database.DBCustomer; import database.DBProvinceState; import database.DBReport; import model.Agency; import model.Agent; import model.Customer; import model.OrderDetail; import model.ProvincesState; import utilities.Utils; @Path(value = "/api") public class RestService { private static final Logger LOGGER = Logger.getLogger(RestService.class.getName()); public RestService() { // TODO Auto-generated constructor stub } /** * Customer Authentication - API: * http://domain-name/TravelExperts/service/api/customer/authenticate * * @param username Customer's username to login * @param password password to login * @return json String including result of authentication and error code if * there is */ @POST @Path("customer/authenticate") @Produces(MediaType.APPLICATION_JSON) public String customerAuthenticate(@FormParam("username") String username, @FormParam("password") String password) { try { if(!DBCustomer.customerAuthenticate(username, password)) return Utils.FAILURE; } catch (Exception e) { LOGGER.log(Level.SEVERE, "RestService.customerAuthenticate: " + e.getMessage()); return Utils.INTERNAL_ERROR; } return Utils.SUCCESS; } /** * Agent Authentication - API: * http://domain-name/TravelExperts/service/api/agent/authenticate * * @param username Agent's username to login * @param password password to login * @return json String including result of authentication and error code if * there is */ @POST @Path("agent/authenticate") @Produces(MediaType.APPLICATION_JSON) public String agentAuthenticate(@FormParam("username") String username, @FormParam("password") String password) { try { if(!DBAgent.agentAuthenticate(username, password)) return Utils.FAILURE; } catch (Exception e) { LOGGER.log(Level.SEVERE, "RestService.agentAuthenticate: " + e.getMessage()); return Utils.INTERNAL_ERROR; } return Utils.SUCCESS; } /** * Customer registration - Login Account to Travel Experts system - * * API: http://domain-name/TravelExperts/service/api/customer/register * * @param agent Agent object * @return json String including result of registration and error code if there * is */ @POST @Path("/agent/update") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String updateAgent(String agent) { try { agent = URLDecoder.decode(agent, "UTF-8"); agent = agent.substring(6, agent.length()-1); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("updateAgent: " + agent); Gson gson = new Gson(); Type type = new TypeToken<Agent>() {}.getType(); Agent agentObj = gson.fromJson(agent, type); try { if(!DBAgent.updateAgent(agentObj)) return "false"; } catch (Exception e) { LOGGER.log(Level.SEVERE, "RestService.updateAgent: " + e.getMessage()); return "false";//Utils.INTERNAL_ERROR; } return "true"; } /** * Customer registration - Login Account to Travel Experts system - * * API: http://domain-name/TravelExperts/service/api/customer/register * * @param customer Customer object (all registered data) * @return json String including result of registration and error code if there * is */ @POST @Path("/customer/register") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String registerCustomer(String customer) { Gson gson = new Gson(); Type type = new TypeToken<Customer>() {}.getType(); Customer customerObj = gson.fromJson(customer, type); try { if(!DBCustomer.addCustomer(customerObj)) return Utils.FAILURE; } catch (Exception e) { LOGGER.log(Level.SEVERE, "RestService.registerCustomer: " + e.getMessage()); return Utils.INTERNAL_ERROR; } return Utils.SUCCESS; } /** * Get List of Agents - * * API: http://domain-name/TravelExperts/service/api/agent/listAll * * @return json of All Agents and error code if there is */ @GET @Path("/agent/listAll") @Produces(MediaType.APPLICATION_JSON) public String getAllAgents() { System.out.println("in aganets"); List<Agent> list = DBAgent.getAgents(); if(list == null) return Utils.INTERNAL_ERROR; Gson gson = new Gson(); Type type = new TypeToken<List<Agent>>() { }.getType(); String stringJSON = gson.toJson(list, type); System.out.println(stringJSON); return stringJSON; } /** * Get list of Customers - API: * http://domain-name/TravelExperts/service/api/customer/listAll * * @return json of All Customers and error code if there is */ @GET @Path("/customer/listAll") @Produces(MediaType.APPLICATION_JSON) public String getAllCustomers() { List<Customer> list = DBCustomer.getCustomers(); if(list == null) return Utils.INTERNAL_ERROR; Gson gson = new Gson(); Type type = new TypeToken<List<Customer>>() { }.getType(); String stringJSON = gson.toJson(list, type); return stringJSON; } /** * Get list of Agencies - API: * http://domain-name/TravelExperts/service/api/agency/listAll * * @return json of All agencies and error code if there is */ @GET @Path("/agency/listAll") @Produces(MediaType.APPLICATION_JSON) public String getAllAgencies() { List<Agency> list = DBAgency.getAgencies(); if(list == null) return Utils.INTERNAL_ERROR; Gson gson = new Gson(); Type type = new TypeToken<List<Agency>>() { }.getType(); String stringJSON = gson.toJson(list, type); return stringJSON; } /** * Get Booking History - API: * http://domain-name/TravelExperts/service/api/booking/getReport/{customerId} * * @param customerId Customer Id * @return json of Booking History and error code if there is */ @GET @Path("/booking/getReport/{customerId}") @Produces(MediaType.APPLICATION_JSON) public String getReport(@PathParam("customerId") int customerId) { List<OrderDetail> list = DBReport.getOrderDetailsByCustId(customerId, null); if(list == null) return Utils.INTERNAL_ERROR; Gson gson = new Gson(); Type type = new TypeToken<List<OrderDetail>>() { }.getType(); String stringJSON = gson.toJson(list, type); return stringJSON; } /** * Get Invoice - API: * http://domain-name/TravelExperts/service/api/invoice/generate/{customerId}/{bookingNo} * * @param customerId Customer Id * @param bookingNo Booking Number * @return json of Invoice (sending invoice to customer's email) and error code * if there is */ @GET @Path("/invoice/generate/{customerId}/{bookingNo}") @Produces(MediaType.APPLICATION_JSON) public String generateInvoice(@PathParam("customerId") int customerId, @PathParam("bookingNo") String bookingNo) { List<OrderDetail> list = DBReport.getOrderDetailsByCustId(customerId, bookingNo); if(list == null) return Utils.INTERNAL_ERROR; if(!Utils.generatePDF(list)) return Utils.FAILURE; return Utils.SUCCESS; } /** * List of Provinces or States based on countryId - API: * http://domain-name/TravelExperts/service/api/getgetProvStates/{countryId} * * @param countryId Country Id * @return json of Provinces or States and error code if there is */ @GET @Path("/getProvStates/{countryId}") @Produces(MediaType.APPLICATION_JSON) public String getProvStates(@PathParam("countryId") String countryId) { List<ProvincesState> list = DBProvinceState.getProvStates(Integer.valueOf(countryId)); Gson gson = new Gson(); Type type = new TypeToken<List<ProvincesState>>() { }.getType(); String stringJSON = gson.toJson(list, type); return stringJSON; } }
// https://leetcode.com/problems/construct-string-from-binary-tree/solution/ class Solution { public String tree2str(TreeNode t) { if (t == null) return ""; if (t.left==null && t.right==null) return t.val + ""; if (t.right == null) return t.val + "(" + tree2str(t.left) + ")"; return t.val + "(" + tree2str(t.left) + ")(" + tree2str(t.right) + ")"; } }
package charactor; public class Hero { protected String name; //姓名 public float hp; //血量 public float armor; //护甲 public int moveSpeed; //移动速度 Hero(){ } Hero(String heroName){ name = heroName; } Hero(String heroName, float heroHP, float heroArmor, int heroMoveSpeed){ this(heroName); // this(); //调用当前类,其他构造方法。 必须放在当前方法的第一行 且只能调用一个构造方法 hp = heroHP; armor = heroArmor; moveSpeed = heroMoveSpeed; } //类方法 public static void battleWin(){ System.out.println("hero battle win"); } public String getName() { return name; } public void kill(Mortal m) { System.out.print(this.name + " kill "); m.die(); } //jvm 对象回收时调用该函数 public void finalize(){ System.out.println("这个英雄正在被回收"); } @Override public boolean equals(Object obj) { if( obj instanceof Hero ){ Hero h = (Hero) obj; return this.hp == h.hp; } return false; } public static void main(String[] args){ Hero ez = new Hero("ez", 100.0f, 22.0f, 200); ADHero ad = new ADHero(); ez = ad; // ADHero 是 Hero的子类,可以转换成功 AD adi = ad; //ADHero向上转型为 AD 一定成功 adi.physicAttack(); //是否为 Hero的子类 System.out.println(adi instanceof Hero); //是否为 ADHero的子类 System.out.println(adi instanceof ADHero); //是否为 AD的子类 System.out.println(adi instanceof AD); //是否为 APHero的子类 System.out.println(adi instanceof APHero); ADHero gailun = new ADHero(); Hero h = gailun; adi = (AD)h; // APHero ap = (APHero)adi; //这里会出错, adi 本质是一个ADHero /** * 通过override重写/覆写 子类覆盖父类的对象方法, 达到多态 */ Hero garen = new Hero("garen"); ADHero jianSheng = new ADHero("jianSheng"); APHero teemo = new APHero("teemo"); ADAPHero ez2 = new ADAPHero("Ez"); garen.kill(jianSheng); garen.kill(teemo); garen.kill(ez2); /** * 隐藏 子类覆写 父类的 类方法 static */ garen.battleWin(); jianSheng.battleWin(); garen = jianSheng; garen.battleWin(); //调用的是父类,类方法s //object 都继承自超类 System.out.println(garen.toString()); System.out.println(garen.equals(ez)); System.out.println(garen == ez); garen = teemo; System.out.println(garen == teemo); garen.getClass();//反射,之后再了解 } }
package com.springapp.mvc.service; import com.springapp.mvc.dao.UserDao; import com.springapp.mvc.domain.User; import com.springapp.mvc.web.request.RegisterForm; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; import java.util.Date; /** * Created by lv on 2016/1/5. */ @Service public class RegisterService { @Inject private UserDao userDao; @Transactional("hibernateTransaction") public void register(RegisterForm registerForm) { User user = new User(); user.setCreatedDate(new Date()); user.setGender(registerForm.getGender()); user.setGrade(registerForm.getGrade()); user.setName(registerForm.getName()); user.setNickName(registerForm.getNiceName()); user.setPassword(registerForm.getPassword()); user.setPhoneNumber(registerForm.getPhoneNumber()); user.setQqNumber(registerForm.getQqNumber()); user.setWeChatNumber(registerForm.getWeChatNumber()); user.setOtherInfo(registerForm.getOtherInfo()); user.setWishCount(0); userDao.save(user); } }
package lesson2; /** * Created by Admin on 09.02.2015. */ public class test5 { public test5() { } public static void main(String[] args) { int x = 223; switch (x % 100) { case 11: System.out.println(x + " рублей "); break; case 12: System.out.println(x + " рублей "); break; case 13: System.out.println(x + " рублей "); break; case 14: System.out.println(x + " рублей "); break; case 15: System.out.println(x + " рублей "); break; default: switch (x % 10) { case 0: System.out.println(x + " рублей "); break; case 1: System.out.println(x + " рубль "); break; case 2: System.out.println(x + " рубля "); break; case 3: System.out.println(x + " рубля "); break; case 4: System.out.println(x + " рубля "); break; case 5: System.out.println(x + " рублей "); break; case 6: System.out.println(x + " рублей "); break; case 7: System.out.println(x + " рублей "); break; case 8: System.out.println(x + " рублей "); break; case 9: System.out.println(x + " рублей "); } } } }
package org.basex.query.func.array; import org.basex.query.*; import org.basex.query.iter.*; import org.basex.query.util.list.*; import org.basex.query.value.*; import org.basex.query.value.item.*; import org.basex.util.*; /** * Function implementation. * * @author BaseX Team 2005-15, BSD License * @author Christian Gruen */ public final class ArrayJoin extends ArrayFn { @Override public Item item(final QueryContext qc, final InputInfo ii) throws QueryException { final ValueList vl = new ValueList(); final Iter ir = qc.iter(exprs[0]); for(Item it; (it = ir.next()) != null;) { for(final Value v : toArray(it).members()) vl.add(v); } return vl.array(); } }
package org.endeavourhealth.im.models.mapping; import com.fasterxml.jackson.annotation.JsonProperty; public class MapDependentColumn { private String column; private MapValueRequest value; @JsonProperty("Column") public String getColumn() { return column; } public MapDependentColumn setColumn(String column) { this.column = column; return this; } @JsonProperty("Value") public MapValueRequest getValue() { return value; } public MapDependentColumn setValue(MapValueRequest value) { this.value = value; return this; } }
package pkgclass.firstprg; public class ClassFirstPrg { public static void main(String[] args) { System.out.println("Hello Word"); } } class FirstPrg { public static void main(String args[]) { System.out.println("Dhananjani"); System.out.println("19.1 MIS"); } }
package jesk.configuration; import java.io.File; public class JeskConfiguration extends Configuration { public JeskConfiguration(File file) { super(file); addDefault("desktop.general.background-image", "included://res/background-sample.png"); save(); } public String getBackgroundImage() { return getString("desktop.general.background-image"); } }
/** * Copyright (C) 2008 Atlassian * * 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.atlassian.theplugin.idea.action.issues.activetoolbar; import com.atlassian.connector.commons.jira.rss.JIRAException; import com.atlassian.theplugin.commons.util.StringUtil; import com.atlassian.theplugin.idea.IdeaHelper; import com.atlassian.theplugin.idea.jira.ActiveIssueResultHandler; import com.atlassian.theplugin.idea.jira.IssueListToolWindowPanel; import com.atlassian.theplugin.jira.model.ActiveJiraIssue; import com.intellij.openapi.actionSystem.AnActionEvent; import javax.swing.*; /** * User: pmaruszak */ public class ActiveIssueLogWorkAction extends AbstractActiveJiraIssueAction { public void actionPerformed(final AnActionEvent event) { SwingUtilities.invokeLater(new Runnable() { public void run() { final IssueListToolWindowPanel panel = IdeaHelper.getIssueListToolWindowPanel(event); final ActiveJiraIssue activeIssue = ActiveIssueUtils.getActiveJiraIssue(event); if (activeIssue != null && panel != null) { boolean isOk = false; try { panel.logWorkOrDeactivateIssue(ActiveIssueUtils.getJIRAIssue(event), getActiveJiraServerData(event), StringUtil.generateJiraLogTimeString(activeIssue.recalculateTimeSpent()), false, new ActiveIssueResultHandler() { public void success() { activeIssue.resetTimeSpent(); } public void failure(Throwable problem) { } public void cancel(String problem) { } }); } catch (JIRAException e) { panel.setStatusErrorMessage("Error logging work: " + e.getMessage(), e); } } } }); } public void onUpdate(final AnActionEvent event) { } public void onUpdate(final AnActionEvent event, final boolean enabled) { event.getPresentation().setEnabled(enabled); } }
/* * 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 FileIO; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author YNZ */ public class OutFileStream { public static String copyRight = "// Copyright 2016\n" + "// All rights reserved\n" + "// ********************\n"; public static void main(String[] args) throws FileNotFoundException { File dir = new File("./src/tmp"); dir.mkdirs(); try { File file = new File(dir, "hello.txt"); System.out.println("" + file.getAbsolutePath()); try (FileOutputStream fileOutputStream = new FileOutputStream(file)) { fileOutputStream.write(copyRight.getBytes()); } } catch (IOException ex) { Logger.getLogger(OutFileStream.class.getName()).log(Level.SEVERE, null, ex); } } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.function.server; import java.net.InetSocketAddress; import java.net.URI; import java.nio.charset.Charset; import java.security.Principal; import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.OptionalLong; import java.util.function.Consumer; import java.util.function.Function; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.ResolvableType; import org.springframework.core.codec.DecodingException; import org.springframework.core.codec.Hints; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.HttpCookie; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpRange; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.MediaType; import org.springframework.http.codec.HttpMessageReader; import org.springframework.http.codec.multipart.Part; import org.springframework.http.server.RequestPath; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.MultiValueMap; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.support.WebExchangeDataBinder; import org.springframework.web.reactive.function.BodyExtractor; import org.springframework.web.reactive.function.BodyExtractors; import org.springframework.web.reactive.function.UnsupportedMediaTypeException; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; import org.springframework.web.server.UnsupportedMediaTypeStatusException; import org.springframework.web.server.WebSession; import org.springframework.web.util.UriBuilder; import org.springframework.web.util.UriComponentsBuilder; /** * {@code ServerRequest} implementation based on a {@link ServerWebExchange}. * * @author Arjen Poutsma * @since 5.0 */ class DefaultServerRequest implements ServerRequest { private static final Function<UnsupportedMediaTypeException, UnsupportedMediaTypeStatusException> ERROR_MAPPER = ex -> (ex.getContentType() != null ? new UnsupportedMediaTypeStatusException( ex.getContentType(), ex.getSupportedMediaTypes(), ex.getBodyType()) : new UnsupportedMediaTypeStatusException( ex.getMessage(), ex.getSupportedMediaTypes())); private static final Function<DecodingException, ServerWebInputException> DECODING_MAPPER = ex -> new ServerWebInputException("Failed to read HTTP message", null, ex); private final ServerWebExchange exchange; private final Headers headers; private final List<HttpMessageReader<?>> messageReaders; DefaultServerRequest(ServerWebExchange exchange, List<HttpMessageReader<?>> messageReaders) { this.exchange = exchange; this.messageReaders = List.copyOf(messageReaders); this.headers = new DefaultHeaders(); } static Mono<ServerResponse> checkNotModified(ServerWebExchange exchange, @Nullable Instant lastModified, @Nullable String etag) { if (lastModified == null) { lastModified = Instant.MIN; } if (exchange.checkNotModified(etag, lastModified)) { HttpStatusCode statusCode = exchange.getResponse().getStatusCode(); return ServerResponse.status(statusCode != null ? statusCode : HttpStatus.OK) .headers(headers -> headers.addAll(exchange.getResponse().getHeaders())) .build(); } else { return Mono.empty(); } } @Override public HttpMethod method() { return request().getMethod(); } @Override @Deprecated public String methodName() { return request().getMethod().name(); } @Override public URI uri() { return request().getURI(); } @Override public UriBuilder uriBuilder() { return UriComponentsBuilder.fromUri(uri()); } @Override public RequestPath requestPath() { return request().getPath(); } @Override public Headers headers() { return this.headers; } @Override public MultiValueMap<String, HttpCookie> cookies() { return request().getCookies(); } @Override public Optional<InetSocketAddress> remoteAddress() { return Optional.ofNullable(request().getRemoteAddress()); } @Override public Optional<InetSocketAddress> localAddress() { return Optional.ofNullable(request().getLocalAddress()); } @Override public List<HttpMessageReader<?>> messageReaders() { return this.messageReaders; } @Override public <T> T body(BodyExtractor<T, ? super ServerHttpRequest> extractor) { return bodyInternal(extractor, Hints.from(Hints.LOG_PREFIX_HINT, exchange().getLogPrefix())); } @Override public <T> T body(BodyExtractor<T, ? super ServerHttpRequest> extractor, Map<String, Object> hints) { hints = Hints.merge(hints, Hints.LOG_PREFIX_HINT, exchange().getLogPrefix()); return bodyInternal(extractor, hints); } private <T> T bodyInternal(BodyExtractor<T, ? super ServerHttpRequest> extractor, Map<String, Object> hints) { return extractor.extract(request(), new BodyExtractor.Context() { @Override public List<HttpMessageReader<?>> messageReaders() { return messageReaders; } @Override public Optional<ServerHttpResponse> serverResponse() { return Optional.of(exchange().getResponse()); } @Override public Map<String, Object> hints() { return hints; } }); } @Override public <T> Mono<T> bodyToMono(Class<? extends T> elementClass) { Mono<T> mono = body(BodyExtractors.toMono(elementClass)); return mono.onErrorMap(UnsupportedMediaTypeException.class, ERROR_MAPPER) .onErrorMap(DecodingException.class, DECODING_MAPPER); } @Override public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> typeReference) { Mono<T> mono = body(BodyExtractors.toMono(typeReference)); return mono.onErrorMap(UnsupportedMediaTypeException.class, ERROR_MAPPER) .onErrorMap(DecodingException.class, DECODING_MAPPER); } @Override @SuppressWarnings("unchecked") public <T> Flux<T> bodyToFlux(Class<? extends T> elementClass) { Flux<T> flux = (elementClass.equals(DataBuffer.class) ? (Flux<T>) request().getBody() : body(BodyExtractors.toFlux(elementClass))); return flux.onErrorMap(UnsupportedMediaTypeException.class, ERROR_MAPPER) .onErrorMap(DecodingException.class, DECODING_MAPPER); } @Override public <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> typeReference) { Flux<T> flux = body(BodyExtractors.toFlux(typeReference)); return flux.onErrorMap(UnsupportedMediaTypeException.class, ERROR_MAPPER) .onErrorMap(DecodingException.class, DECODING_MAPPER); } @Override @SuppressWarnings("unchecked") public <T> Mono<T> bind(Class<T> bindType, Consumer<WebDataBinder> dataBinderCustomizer) { Assert.notNull(bindType, "BindType must not be null"); Assert.notNull(dataBinderCustomizer, "DataBinderCustomizer must not be null"); return Mono.defer(() -> { WebExchangeDataBinder dataBinder = new WebExchangeDataBinder(null); dataBinder.setTargetType(ResolvableType.forClass(bindType)); dataBinderCustomizer.accept(dataBinder); ServerWebExchange exchange = exchange(); return dataBinder.construct(exchange) .then(dataBinder.bind(exchange)) .then(Mono.defer(() -> { BindingResult bindingResult = dataBinder.getBindingResult(); if (bindingResult.hasErrors()) { return Mono.error(new BindException(bindingResult)); } else { T result = (T) bindingResult.getTarget(); return Mono.justOrEmpty(result); } })); }); } @Override public Map<String, Object> attributes() { return this.exchange.getAttributes(); } @Override public MultiValueMap<String, String> queryParams() { return request().getQueryParams(); } @Override public Map<String, String> pathVariables() { return this.exchange.getAttributeOrDefault( RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE, Collections.emptyMap()); } @Override public Mono<WebSession> session() { return this.exchange.getSession(); } @Override public Mono<? extends Principal> principal() { return this.exchange.getPrincipal(); } @Override public Mono<MultiValueMap<String, String>> formData() { return this.exchange.getFormData(); } @Override public Mono<MultiValueMap<String, Part>> multipartData() { return this.exchange.getMultipartData(); } private ServerHttpRequest request() { return this.exchange.getRequest(); } @Override public ServerWebExchange exchange() { return this.exchange; } @Override public String toString() { return String.format("HTTP %s %s", method(), path()); } private class DefaultHeaders implements Headers { private final HttpHeaders httpHeaders = HttpHeaders.readOnlyHttpHeaders(request().getHeaders()); @Override public List<MediaType> accept() { return this.httpHeaders.getAccept(); } @Override public List<Charset> acceptCharset() { return this.httpHeaders.getAcceptCharset(); } @Override public List<Locale.LanguageRange> acceptLanguage() { return this.httpHeaders.getAcceptLanguage(); } @Override public OptionalLong contentLength() { long value = this.httpHeaders.getContentLength(); return (value != -1 ? OptionalLong.of(value) : OptionalLong.empty()); } @Override public Optional<MediaType> contentType() { return Optional.ofNullable(this.httpHeaders.getContentType()); } @Override public InetSocketAddress host() { return this.httpHeaders.getHost(); } @Override public List<HttpRange> range() { return this.httpHeaders.getRange(); } @Override public List<String> header(String headerName) { List<String> headerValues = this.httpHeaders.get(headerName); return (headerValues != null ? headerValues : Collections.emptyList()); } @Override public HttpHeaders asHttpHeaders() { return this.httpHeaders; } @Override public String toString() { return this.httpHeaders.toString(); } } }
package ru.dm_ushakov.mycalculator.lang.func; import java.math.BigDecimal; import ru.dm_ushakov.mycalculator.lang.OperationContext; public class TanFunc extends AbstractFunction { @Override public BigDecimal evalute(BigDecimal[] args, OperationContext context) { if(args.length!=1)throw new IllegalArgumentException("tan function expects 1 argument!"); return new BigDecimal(Math.tan(args[0].doubleValue())); } }
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.r2dbc.core; import java.util.function.Consumer; import io.r2dbc.spi.ConnectionFactory; import io.r2dbc.spi.Statement; import org.springframework.lang.Nullable; import org.springframework.r2dbc.core.binding.BindMarkersFactory; import org.springframework.r2dbc.core.binding.BindMarkersFactoryResolver; import org.springframework.util.Assert; /** * Default implementation of {@link DatabaseClient.Builder}. * * @author Mark Paluch * @since 5.3 */ class DefaultDatabaseClientBuilder implements DatabaseClient.Builder { @Nullable private BindMarkersFactory bindMarkers; @Nullable private ConnectionFactory connectionFactory; private ExecuteFunction executeFunction = Statement::execute; private boolean namedParameters = true; DefaultDatabaseClientBuilder() { } @Override public DatabaseClient.Builder bindMarkers(BindMarkersFactory bindMarkers) { Assert.notNull(bindMarkers, "BindMarkersFactory must not be null"); this.bindMarkers = bindMarkers; return this; } @Override public DatabaseClient.Builder connectionFactory(ConnectionFactory factory) { Assert.notNull(factory, "ConnectionFactory must not be null"); this.connectionFactory = factory; return this; } @Override public DatabaseClient.Builder executeFunction(ExecuteFunction executeFunction) { Assert.notNull(executeFunction, "ExecuteFunction must not be null"); this.executeFunction = executeFunction; return this; } @Override public DatabaseClient.Builder namedParameters(boolean enabled) { this.namedParameters = enabled; return this; } @Override public DatabaseClient build() { Assert.notNull(this.connectionFactory, "ConnectionFactory must not be null"); BindMarkersFactory bindMarkers = this.bindMarkers; if (bindMarkers == null) { if (this.namedParameters) { bindMarkers = BindMarkersFactoryResolver.resolve(this.connectionFactory); } else { bindMarkers = BindMarkersFactory.anonymous("?"); } } return new DefaultDatabaseClient( bindMarkers, this.connectionFactory, this.executeFunction, this.namedParameters); } @Override public DatabaseClient.Builder apply(Consumer<DatabaseClient.Builder> builderConsumer) { Assert.notNull(builderConsumer, "BuilderConsumer must not be null"); builderConsumer.accept(this); return this; } }
package com.beike.dao.background.landmarks; import java.util.List; import com.beike.dao.GenericDao; import com.beike.entity.background.landmarks.LandMarks; import com.beike.form.background.landmarks.LandMarksForm; /** * * Title : LandMarksDao * <p/> * Description : 地标信息访问数据接口 * <p/> * CopyRight : CopyRight (c) 2011 * </P> * Company : Sinobo * </P> * JDK Version Used : JDK 5.0 + * <p/> * Modification History : * <p/> * <pre>NO. Date Modified By Why & What is modified</pre> * <pre>1 2011-06-08 lvjx Created<pre> * <p/> * * @author lvjx * @version 1.0.0.2011-06-08 */ public interface LandMarksDao extends GenericDao<LandMarks,Long> { /** * Description : 查询地标 * @return * @throws Exception */ public List<LandMarks> queryLandMarks(LandMarksForm landMarksForm) throws Exception; }
package com.cinema.sys.service; import com.cinema.sys.model.Site; import com.cinema.sys.model.base.TSite; public interface SiteService { Site getDetail(); /**添加或更新*/ int save(TSite t); }
package com.overlo4ded.fol.reader.gui; import java.awt.EventQueue; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import javax.swing.BoxLayout; import java.awt.GridBagLayout; import javax.swing.JLabel; import java.awt.GridBagConstraints; import javax.swing.JTextField; import java.awt.Insets; import javax.swing.JButton; import javax.swing.JProgressBar; import org.apache.commons.io.IOUtils; import com.overlo4ded.fol.reader.ParserListener; import com.overlo4ded.fol.reader.Reader; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class SwingUI implements ParserListener{ private JFrame frame; private JTextField txtFolUrl; private JTextField txtLastPage; private JLabel lblProgress; private Reader reader = new Reader(); private int start=0; private int end=0; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { SwingUI window = new SwingUI(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public SwingUI() { initialize(); reader.addParserListener(this); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); frame.getContentPane().add(panel, BorderLayout.NORTH); GridBagLayout gbl_panel = new GridBagLayout(); gbl_panel.columnWidths = new int[]{0, 0, 0}; gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0}; gbl_panel.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE}; gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; panel.setLayout(gbl_panel); JLabel lblFolUrl = new JLabel("FOL URL"); GridBagConstraints gbc_lblFolUrl = new GridBagConstraints(); gbc_lblFolUrl.insets = new Insets(0, 0, 5, 5); gbc_lblFolUrl.anchor = GridBagConstraints.EAST; gbc_lblFolUrl.gridx = 0; gbc_lblFolUrl.gridy = 2; panel.add(lblFolUrl, gbc_lblFolUrl); txtFolUrl = new JTextField(); GridBagConstraints gbc_txtFolUrl = new GridBagConstraints(); gbc_txtFolUrl.insets = new Insets(0, 0, 5, 0); gbc_txtFolUrl.fill = GridBagConstraints.HORIZONTAL; gbc_txtFolUrl.gridx = 1; gbc_txtFolUrl.gridy = 2; panel.add(txtFolUrl, gbc_txtFolUrl); txtFolUrl.setColumns(10); JLabel lblLastPage = new JLabel("Last Page"); GridBagConstraints gbc_lblLastPage = new GridBagConstraints(); gbc_lblLastPage.anchor = GridBagConstraints.EAST; gbc_lblLastPage.insets = new Insets(0, 0, 5, 5); gbc_lblLastPage.gridx = 0; gbc_lblLastPage.gridy = 3; panel.add(lblLastPage, gbc_lblLastPage); txtLastPage = new JTextField(); GridBagConstraints gbc_txtLastPage = new GridBagConstraints(); gbc_txtLastPage.insets = new Insets(0, 0, 5, 0); gbc_txtLastPage.fill = GridBagConstraints.HORIZONTAL; gbc_txtLastPage.gridx = 1; gbc_txtLastPage.gridy = 3; panel.add(txtLastPage, gbc_txtLastPage); txtLastPage.setColumns(10); JButton btnRun = new JButton("Run"); btnRun.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { String data = reader.read(txtFolUrl.getText(),txtLastPage.getText()); final JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); try { IOUtils.write(data,new FileOutputStream(file)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } else { } } }); GridBagConstraints gbc_btnRun = new GridBagConstraints(); gbc_btnRun.insets = new Insets(0, 0, 5, 0); gbc_btnRun.gridx = 1; gbc_btnRun.gridy = 4; panel.add(btnRun, gbc_btnRun); lblProgress = new JLabel(""); GridBagConstraints gbc_lblProgress = new GridBagConstraints(); gbc_lblProgress.insets = new Insets(0, 0, 5, 0); gbc_lblProgress.gridx = 1; gbc_lblProgress.gridy = 5; panel.add(lblProgress, gbc_lblProgress); } @Override public void completed(String page) { end++; lblProgress.setText("processing "+start+" of "+end); } @Override public void computedIterations(int min, int max) { start=min; end=max; lblProgress.setText("processing "+start+" of "+end); } }
package CoreVkApiParse.Wall; import org.json.simple.JSONObject; public class Photo { private Object id, album_id, owner_id, user_id, photo_75, photo_130, photo_604, width, height, text, date, post_id, access_key; public Photo(JSONObject jo){ try { this.id = jo.get("id"); this.album_id = jo.get("album_id"); this.owner_id = jo.get("owner_id"); this.user_id = jo.get("user_id"); this.photo_75 = jo.get("photo_75"); this.photo_130 = jo.get("photo_130"); this.photo_604 = jo.get("photo_604"); this.width = jo.get("width"); this.height = jo.get("height"); this.text = jo.get("text"); this.date = jo.get("date"); this.post_id = jo.get("post_id"); this.access_key = jo.get("access_key"); } catch(Exception ex) { System.out.println("Error: class Like = " + ex.toString()); } } public void info() { System.out.println("\n\nid = " + this.id); System.out.println("album_id = " + this.album_id); System.out.println("owner_id = " + this.owner_id); System.out.println("user_id = " + this.user_id); System.out.println("photo_75 = " + this.photo_75); System.out.println("photo_130 = " + this.photo_130); System.out.println("photo_604 = " + this.photo_604); System.out.println("width = " + this.width); System.out.println("height = " + this.height); System.out.println("text = " + this.text); System.out.println("date = " + this.date); System.out.println("post_id = " + this.post_id); System.out.println("access_key = " + this.access_key); } }
package com.fpl.web; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.repository.query.Param; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.fpl.dao.UserRepository; import com.fpl.entities.User; @RestController @CrossOrigin("http://localhost:4200") public class UserRestService { @Autowired private UserRepository userRepository; @RequestMapping(value="/users", method=RequestMethod.GET) public List<User> getAllUsers(){ return userRepository.findAll(); } @RequestMapping(value="/OtherUsers/{userId}", method=RequestMethod.GET) public List<User> getOtherUsers(@PathVariable Long userId){ List<User> other=new ArrayList<>(); List<User> allUser=userRepository.findAll(); for(User us:allUser) { if(us.getId()!=userId) { other.add(us); } } return other; } @RequestMapping(value="/addUser", method=RequestMethod.POST) public User saveUser(@RequestBody User u) { return userRepository.save(u); } @RequestMapping(value="/getUser/{idUser}", method=RequestMethod.GET) public Optional<User> getUserById(@PathVariable Long idUser){ return userRepository.findById(idUser); } }
/** */ package mmodela.impl; import mmodela.*; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EFactory; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class MmodelaFactoryImpl extends EFactoryImpl implements MmodelaFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static MmodelaFactory init() { try { EFactory eFactory = EPackage.Registry.INSTANCE.getEFactory(MmodelaPackage.eNS_URI); if(eFactory instanceof MmodelaFactory) { return (MmodelaFactory)eFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new MmodelaFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MmodelaFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case MmodelaPackage.ITEM: return createItem(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Item createItem() { ItemImpl item = new ItemImpl(); return item; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MmodelaPackage getMmodelaPackage() { return (MmodelaPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static MmodelaPackage getPackage() { return MmodelaPackage.eINSTANCE; } } //MmodelaFactoryImpl
package common.util; import static org.junit.Assert.*; import java.util.Locale; import org.junit.Test; public class MessageUtilTests { @Test public void getMessageTest() { Locale locale = new Locale("vi", "VN"); assertEquals("Dữ liệu phải bắt đầu từ dòng 999", MessageUtil.getMessage("import.importError1", locale, 999)); assertEquals("Thông tin trên file Import rỗng", MessageUtil.getMessage("import.importError2", locale)); assertEquals("Dữ liệu có lỗi", MessageUtil.getMessage("import.importError3", locale)); assertEquals("File không có định dạng không chuẩn (hãy bỏ qua các format đặc biệt)", MessageUtil.getMessage("import.importError4", locale)); assertEquals("Không đủ bộ nhớ (hãy loại bỏ các định dạng trong file import)", MessageUtil.getMessage("import.importError5", locale)); assertEquals("Bạn chỉ được import tối đa 100 dòng (thực tế 200 dòng)", MessageUtil.getMessage("import.importError8", locale, 100, 200)); } }
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class jdbcUtil { private static String url="jdbc:mysql://localhost:3306/db_project"; private static String user="root"; private static String password="123456"; static{ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() { Connection conn; try { conn = DriverManager.getConnection(url, user, password); return conn; } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } public static void close(ResultSet rs,Statement stmt,Connection conn) { if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } }
package com.gmail.filoghost.holographicdisplays.object; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import com.gmail.filoghost.holographicdisplays.HolographicDisplays; import com.gmail.filoghost.holographicdisplays.api.VisibilityManager; import com.gmail.filoghost.holographicdisplays.util.Validator; import com.gmail.filoghost.holographicdisplays.util.VersionUtils; public class CraftVisibilityManager implements VisibilityManager { private final CraftHologram hologram; private Map<String, Boolean> playersVisibilityMap; private boolean visibleByDefault; private static final int VISIBILITY_DISTANCE_SQUARED = 64 * 64; public CraftVisibilityManager(CraftHologram hologram) { Validator.notNull(hologram, "hologram"); this.hologram = hologram; this.visibleByDefault = true; } @Override public boolean isVisibleByDefault() { return visibleByDefault; } @Override public void setVisibleByDefault(boolean visibleByDefault) { if (this.visibleByDefault != visibleByDefault) { boolean oldVisibleByDefault = this.visibleByDefault; this.visibleByDefault = visibleByDefault; for (Player player : VersionUtils.getOnlinePlayers()) { if (playersVisibilityMap != null && playersVisibilityMap.containsKey(player.getName().toLowerCase())) { // Has a specific value set continue; } if (oldVisibleByDefault) { // If previously was visible, now is NOT visible by default, because the value has changed sendDestroyPacketIfNear(player, hologram); } else { // Opposite case sendCreatePacketIfNear(player, hologram); } } } } @Override public void showTo(Player player) { Validator.notNull(player, "player"); boolean wasVisible = isVisibleTo(player); if (playersVisibilityMap == null) { // Lazy initialization playersVisibilityMap = new ConcurrentHashMap<String, Boolean>(); } playersVisibilityMap.put(player.getName().toLowerCase(), true); if (!wasVisible) { sendCreatePacketIfNear(player, hologram); } } @Override public void hideTo(Player player) { Validator.notNull(player, "player"); boolean wasVisible = isVisibleTo(player); if (playersVisibilityMap == null) { // Lazy initialization playersVisibilityMap = new ConcurrentHashMap<String, Boolean>(); } playersVisibilityMap.put(player.getName().toLowerCase(), false); if (wasVisible) { sendDestroyPacketIfNear(player, hologram); } } @Override public boolean isVisibleTo(Player player) { Validator.notNull(player, "player"); if (playersVisibilityMap != null) { Boolean value = playersVisibilityMap.get(player.getName().toLowerCase()); if (value != null) { return value; } } return visibleByDefault; } @Override public void resetVisibility(Player player) { Validator.notNull(player, "player"); if (playersVisibilityMap == null) { return; } boolean wasVisible = isVisibleTo(player); playersVisibilityMap.remove(player.getName().toLowerCase()); if (visibleByDefault && !wasVisible) { sendCreatePacketIfNear(player, hologram); } else if (!visibleByDefault && wasVisible) { sendDestroyPacketIfNear(player, hologram); } } @Override public void resetVisibilityAll() { if (playersVisibilityMap != null) { // We need to refresh all the players Set<String> playerNames = new HashSet<String>(playersVisibilityMap.keySet()); for (String playerName : playerNames) { Player onlinePlayer = Bukkit.getPlayerExact(playerName); if (onlinePlayer != null) { resetVisibility(onlinePlayer); } } playersVisibilityMap.clear(); playersVisibilityMap = null; } } private static void sendCreatePacketIfNear(Player player, CraftHologram hologram) { if (HolographicDisplays.hasProtocolLibHook() && isNear(player, hologram)) { HolographicDisplays.getProtocolLibHook().sendCreateEntitiesPacket(player, hologram); } } private static void sendDestroyPacketIfNear(Player player, CraftHologram hologram) { if (HolographicDisplays.hasProtocolLibHook() && isNear(player, hologram)) { HolographicDisplays.getProtocolLibHook().sendDestroyEntitiesPacket(player, hologram); } } private static boolean isNear(Player player, CraftHologram hologram) { return player.isOnline() && player.getWorld().equals(hologram.getWorld()) && player.getLocation().distanceSquared(hologram.getLocation()) < VISIBILITY_DISTANCE_SQUARED; } @Override public String toString() { return "CraftVisibilityManager [playersMap=" + playersVisibilityMap + ", visibleByDefault=" + visibleByDefault + "]"; } }
package com.proyectogrado.alternativahorario.alternativahorario.negocio; import com.proyectogrado.alternativahorario.entidades.Carrera; import com.proyectogrado.alternativahorario.persistencia.FachadaPersistenciaCarreraLocal; import java.util.List; import javax.ejb.EJB; import javax.ejb.Stateless; /** * * @author Steven */ @Stateless public class AdministracionCarrera implements AdministracionCarreraLocal { @EJB private FachadaPersistenciaCarreraLocal fachadaPersistenciaCarrera; @Override public List<Carrera> getCarreras() { return fachadaPersistenciaCarrera.findAll(); } @Override public boolean eliminarCarrera(Carrera carrera) { try { Carrera carreraEliminar = fachadaPersistenciaCarrera.findByNombre(carrera.getNombre()); fachadaPersistenciaCarrera.remove(carreraEliminar); } catch (Exception e) { System.out.println("Ocurrio un error eliminando la carrera " + carrera.getNombre()); return false; } return true; } @Override public List<Carrera> eliminarCarreras(List<Carrera> carreras) { for (Carrera carrera : carreras) { eliminarCarrera(carrera); } return null; } @Override public boolean agregarCarrera(Carrera carrera) { try { fachadaPersistenciaCarrera.create(carrera); } catch (Exception e) { System.out.println("Ocurrio un error creacion la carrera " + carrera.getNombre()); return false; } return true; } @Override public boolean modificarCarrera(Carrera carrera) { try { fachadaPersistenciaCarrera.edit(carrera); } catch (Exception e) { System.out.println("Ocurrio un error modificacion la carrera " + carrera.getNombre()); return false; } return true; } @Override public Carrera getCarreraPorNombre(String nombre) { return fachadaPersistenciaCarrera.findByNombre(nombre); } }
package com.springtraining.model; import java.io.Serializable; import javax.persistence.*; import java.sql.Timestamp; import java.util.List; /** * The persistent class for the M_SECTION database table. * */ @Entity @Table(name="M_SECTION") @NamedQuery(name="MSection.findAll", query="SELECT m FROM MSection m") public class MSection implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="SECTION_ID") private String sectionId; @Column(name="CREATE_DATE") private Timestamp createDate; @Column(name="CREATE_USER") private String createUser; @Column(name="INVALID_FLG") private String invalidFlg; @Column(name="SECTION_NAME") private String sectionName; @Column(name="UPDATE_DATE") private Timestamp updateDate; @Column(name="UPDATE_USER") private String updateUser; //bi-directional many-to-one association to MUser @OneToMany(mappedBy="MSection") private List<MUser> MUsers; public MSection() { } public String getSectionId() { return this.sectionId; } public void setSectionId(String sectionId) { this.sectionId = sectionId; } public Timestamp getCreateDate() { return this.createDate; } public void setCreateDate(Timestamp createDate) { this.createDate = createDate; } public String getCreateUser() { return this.createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } public String getInvalidFlg() { return this.invalidFlg; } public void setInvalidFlg(String invalidFlg) { this.invalidFlg = invalidFlg; } public String getSectionName() { return this.sectionName; } public void setSectionName(String sectionName) { this.sectionName = sectionName; } public Timestamp getUpdateDate() { return this.updateDate; } public void setUpdateDate(Timestamp updateDate) { this.updateDate = updateDate; } public String getUpdateUser() { return this.updateUser; } public void setUpdateUser(String updateUser) { this.updateUser = updateUser; } public List<MUser> getMUsers() { return this.MUsers; } public void setMUsers(List<MUser> MUsers) { this.MUsers = MUsers; } public MUser addMUser(MUser MUser) { getMUsers().add(MUser); MUser.setMSection(this); return MUser; } public MUser removeMUser(MUser MUser) { getMUsers().remove(MUser); MUser.setMSection(null); return MUser; } }
package com.zimu.ao.board; import java.awt.Point; import org.newdawn.slick.Graphics; import com.zimu.ao.enums.Direction; public abstract class RenderebleBoard { protected int cursor; protected int topCursor; public abstract void moveCursor(Direction direction); public abstract void tabSwitch(); public abstract void render(Graphics g, Point point); }
package com.infoworks.ml.domain.detectors; import com.infoworks.ml.services.FileResources; import org.tensorflow.Graph; import org.tensorflow.Operation; import java.awt.*; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import java.util.*; /** * Wrapper for frozen detection models trained using the Tensorflow Object Detection API: * github.com/tensorflow/models/tree/master/research/object_detection */ public class TFObjectDetector implements Classifier { private TFGraphInference inference; // Only return this many results. private static final int MAX_RESULTS = 1001; // Config values. private String inputName; // Pre-allocated buffers. private Vector<String> labels = new Vector<>(); private float[] outputLocations; private float[] outputScores; private float[] outputClasses; private float[] outputNumDetections; private String[] outputNames; private final float CUT_OFF = 0.6f; // 0.5f public TFObjectDetector(String savedModelName, String objDetectionName) throws IOException { // FileResources fileResources = new FileResources(); InputStream objInputLabel = fileResources.getFileFromResourceAsStream(objDetectionName); try (BufferedReader br = new BufferedReader(new InputStreamReader(objInputLabel))) { String line; StringBuilder builder = null; addNoneAt(0, labels); while ((line = br.readLine()) != null) { if(builder == null) builder = new StringBuilder(); if (line.trim().startsWith("item {")){ builder.append(line.trim()); }else{ if (line.trim().startsWith("id:")) builder.append(line.trim() + ", "); else builder.append(line.trim() + " "); } if (line.trim().startsWith("}")){ this.labels.add(builder.toString()); builder = null; } } } // byte[] graphDef = fileResources.readAllBytesOrExit(savedModelName); // try (Graph g = new Graph()) { g.importGraphDef(graphDef); this.inputName = "image_tensor"; // The inputName node has a shape of [N, H, W, C], where // N is the batch size // H = W are the height and width // C is the number of channels (3 for our purposes - RGB) final Operation inputOp = g.operation(this.inputName); if (inputOp == null) { throw new RuntimeException("Failed to find input Node '" + this.inputName + "'"); } // The outputScoresName node has a shape of [N, NumLocations], where N // is the batch size. final Operation outputOp1 = g.operation("detection_scores"); if (outputOp1 == null) { throw new RuntimeException("Failed to find output Node 'detection_scores'"); } final Operation outputOp2 = g.operation("detection_boxes"); if (outputOp2 == null) { throw new RuntimeException("Failed to find output Node 'detection_boxes'"); } final Operation outputOp3 = g.operation("detection_classes"); if (outputOp3 == null) { throw new RuntimeException("Failed to find output Node 'detection_classes'"); } // Pre-allocate buffers. this.outputNames = new String[]{"detection_boxes", "detection_scores", "detection_classes", "num_detections"}; this.outputScores = new float[MAX_RESULTS]; this.outputLocations = new float[MAX_RESULTS * 4]; this.outputClasses = new float[MAX_RESULTS]; this.outputNumDetections = new float[1]; this.inference = new TFGraphInference(graphDef); } } private void addNoneAt(int index, Vector<String> labels) { labels.add(index, Recognition.NONE_ITEM); } @Override public List<Recognition> recognizeImage(final BufferedImage image) { // Preprocess the image data from 0-255 int to normalized float based // on the provided parameters. inference.feedImage(inputName, getPixelBytes(image)); inference.run(outputNames, false); // Copy the output Tensor back into the output array. outputLocations = new float[MAX_RESULTS * 4]; outputScores = new float[MAX_RESULTS]; outputClasses = new float[MAX_RESULTS]; outputNumDetections = new float[1]; inference.fetch(outputNames[0], outputLocations); inference.fetch(outputNames[1], outputScores); inference.fetch(outputNames[2], outputClasses); inference.fetch(outputNames[3], outputNumDetections); // Find the best detections. final PriorityQueue<Recognition> pq = new PriorityQueue<Recognition>( 1, (lhs, rhs) -> { // Intentionally reversed to put high confidence at the head of the queue. return Float.compare(rhs.getConfidence(), lhs.getConfidence()); }); // Scale them back to the input size. for (int i = 0; i < outputScores.length; ++i) { if (outputScores[i] > CUT_OFF) { float xmin = outputLocations[4 * i + 1] * image.getWidth(); float ymin = outputLocations[4 * i] * image.getHeight(); float xmax = outputLocations[4 * i + 3] * image.getWidth(); float ymax = outputLocations[4 * i + 2] * image.getHeight(); final Rectangle2D detection = new Rectangle(); detection.setRect(xmin, ymin, xmax - xmin, ymax - ymin); //pq.add(new Recognition("" + i, labels.get((int) outputClasses[i]), outputScores[i], detection)); pq.add(new Recognition(labels.get((int) outputClasses[i]), outputScores[i], detection)); } } final ArrayList<Recognition> recognitions = new ArrayList<Recognition>(); for (int i = 0; i < Math.min(pq.size(), MAX_RESULTS); ++i) { recognitions.add(pq.poll()); } return recognitions; } private byte[][][][] getPixelBytes(BufferedImage image) { int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); byte[][][][] featuresTensorData = new byte[1][imageHeight][imageWidth][3]; int[][] imageArray = new int[imageHeight][imageWidth]; for (int row = 0; row < imageHeight; row++) { for (int column = 0; column < imageWidth; column++) { imageArray[row][column] = image.getRGB(column, row); int pixel = image.getRGB(column, row); byte red = (byte)((pixel >> 16) & 0xff); byte green = (byte)((pixel >> 8) & 0xff); byte blue = (byte)(pixel & 0xff); featuresTensorData[0][row][column][0] = red; featuresTensorData[0][row][column][1] = green; featuresTensorData[0][row][column][2] = blue; } } return featuresTensorData; } }
package org.talend.components.i18n; import static java.util.stream.Collectors.toMap; import static org.eclipse.jgit.diff.DiffEntry.ChangeType.ADD; import static org.eclipse.jgit.diff.DiffEntry.ChangeType.DELETE; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.text.ParseException; import java.util.AbstractMap; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.eclipse.jgit.api.DiffCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.LogCommand; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.AbstractTreeIterator; import org.eclipse.jgit.treewalk.CanonicalTreeParser; import org.eclipse.jgit.treewalk.filter.PathSuffixFilter; import lombok.Data; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor public class ChangesService implements AutoCloseable { private final static String HEAD = "HEAD"; private final String repositoryPath; private final String outDirPath; private final Configuration config; private Git git; public void open() { try { git = Git.open(new File(repositoryPath)); } catch (IOException e) { throw new IllegalStateException("Can't open git repository", e); } } @Override public void close() { if (git != null) { git.close(); } } public void exportChanged(final String since) { final File outDir = new File(outDirPath); if (!outDir.exists()) { if (!outDir.mkdirs()) { throw new IllegalStateException("Can't create output directory in '" + outDirPath + "'"); } } final Map<String, Properties> changesByFile = effectiveChanges(since); final Properties mapping = new Properties(); final AtomicInteger counter = new AtomicInteger(1); final AtomicInteger keysCounter = new AtomicInteger(0); changesByFile.forEach((k, changes) -> { try { keysCounter.addAndGet(changes.size()); String name = counter.getAndIncrement() + "-" + k.substring(k.lastIndexOf("/") + 1); changes.store(new FileWriter(new File(outDir, name)), null); mapping.put(name, k); } catch (IOException e) { log.error("Can't extract file " + k, e); } }); try { mapping.put("metadata.git.repository.path", repositoryPath); mapping.put("metadata.extraction.since", since); mapping.put("metadata.total.file", String.valueOf(counter.get())); mapping.put("metadata.total.keys", String.valueOf(keysCounter.get())); mapping.store(new FileWriter(new File(outDir, "metadata")), null); } catch (IOException e) { throw new IllegalStateException("Can't create metadata file"); } } private Map<String, Properties> effectiveChanges(final String since) { final DiffOutputStream out = new DiffOutputStream(); try (DiffFormatter formatter = new DiffFormatter(out)) { formatter.setRepository(git.getRepository()); Map<String, Map<DiffEntry.ChangeType, Properties>> patch = new HashMap<>(); changes(since, ".properties").forEach(entry -> { try { formatter.format(entry); final List<String> changes; try (final BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(out.getDiff().toString().getBytes(StandardCharsets.UTF_8))))) { changes = br.lines().collect(Collectors.toList()); } switch (entry.getChangeType()) { case ADD: patch.putIfAbsent(entry.getNewPath(), new HashMap<>()); patch.get(entry.getNewPath()).putIfAbsent(ADD, new Properties()); patch.get(entry.getNewPath()).get(ADD).putAll(extractAdditions(entry, changes)); break; case DELETE: patch.putIfAbsent(entry.getNewPath(), new HashMap<>()); patch.get(entry.getNewPath()).putIfAbsent(DELETE, new Properties()); patch.get(entry.getNewPath()).get(DELETE).putAll(extractDeletions(entry, changes)); break; case MODIFY: patch.putIfAbsent(entry.getNewPath(), new HashMap<>()); patch.get(entry.getNewPath()).putIfAbsent(ADD, new Properties()); patch.get(entry.getNewPath()).get(ADD).putAll(extractAdditions(entry, changes)); patch.putIfAbsent(entry.getNewPath(), new HashMap<>()); patch.get(entry.getNewPath()).putIfAbsent(DELETE, new Properties()); patch.get(entry.getNewPath()).get(DELETE).putAll(extractDeletions(entry, changes)); break; case RENAME: break; case COPY: break; default: break; } } catch (IOException e) { throw new IllegalStateException(e); } finally { out.reset(); } }); Map<String, Properties> effectiveChanges = new HashMap<>(); patch.forEach((filePath, changes) -> { Properties properties = new Properties(); if (changes.containsKey(ADD) && !changes.get(ADD).isEmpty()) { changes.get(ADD).entrySet().stream() .filter(kv -> !changes.containsKey(DELETE) || !changes.get(DELETE).containsKey(kv.getKey()) || !changes.get(DELETE).get(kv.getKey()).equals(kv.getValue()) // not the same value between add/delete ) .filter(kv -> !String.valueOf(kv.getValue()).isEmpty()) .forEach(kv -> properties.put(kv.getKey(), kv.getValue())); if (!properties.isEmpty()) { effectiveChanges.put(filePath, properties); } } }); return effectiveChanges; } } private Map<String, String> extractAdditions(final DiffEntry entry, final List<String> changes) { return changes.stream().filter(l -> !l.isEmpty() && !l.substring(1).trim().isEmpty()) .filter(l -> !l.startsWith("+++")) .filter(this::notComment) .filter(l -> l.startsWith("+")) .map(this::toKeyValue) .map(kv -> new AbstractMap.SimpleEntry<>(kv[0], kv.length == 2 ? kv[1] : "")) .collect(toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue, (k, k2) -> { log.warn("duplicated key '" + k + "' found in " + entry.getNewPath()); return k2; })); } private Map<String, String> extractDeletions(final DiffEntry entry, final List<String> changes) { return changes.stream().filter(l -> !l.isEmpty() && !l.substring(1).trim().isEmpty()) .filter(l -> !l.startsWith("---")) .filter(this::notComment) .filter(l -> l.startsWith("-")) .map(this::toKeyValue) .map(kv -> new AbstractMap.SimpleEntry<>(kv[0], kv.length == 2 ? kv[1] : "")) .collect(toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue, (k, k2) -> { log.warn("duplicated key '" + k + "' found in " + entry.getNewPath()); return k2; })); } private String[] toKeyValue(final String line) { return line.substring(1).trim().split("="); } private boolean notComment(final String line) { return !line.substring(1).trim().startsWith("#"); } private List<DiffEntry> changes(String since, String fileSuffix) { try { final Repository repository = git.getRepository(); final DiffCommand cmd = git.diff(); final AbstractTreeIterator headTree = prepareTreeParser(repository, repository.resolve(HEAD)); final AbstractTreeIterator oldTree = prepareTreeParser(repository, commitSince(since)); cmd.setOldTree(oldTree).setNewTree(headTree).setShowNameAndStatusOnly(false); if (fileSuffix != null && !fileSuffix.isEmpty()) { cmd.setPathFilter(PathSuffixFilter.create(fileSuffix)); } try { return cmd.call().stream() .filter(diffEntry -> isTranslatable(diffEntry.getNewPath())) .collect(Collectors.toList()); } catch (GitAPIException e) { throw new IllegalStateException("Can't get the file diff", e); } } catch (IOException e) { throw new IllegalStateException(e); } } private static boolean isTranslatable(String file) { return file.endsWith(".properties") && file.contains("/src/main/resources/") && !file.contains("_fr.properties") && !file.contains("_ja.properties") && !file.contains("_en.properties") && !file.contains("jndi") && !file.contains("log4j") && !file.contains("pom"); } @Data private static class DiffOutputStream extends OutputStream { private StringBuilder diff = new StringBuilder(); @Override public void write(final int b) { int[] bytes = { b }; diff.append(new String(bytes, 0, bytes.length)); } void reset() { diff = new StringBuilder(); } } private ObjectId commitSince(String since) { final Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(config.getTimeZone()); calendar.setLenient(false); final Date sinceDate; try { calendar.setTime(config.getDateFormat().parse(since)); sinceDate = calendar.getTime(); } catch (ParseException e) { throw new IllegalArgumentException(e); } try { final LogCommand cmd = git.log(); ObjectId ref = null; final Iterable<RevCommit> all = cmd.call(); for (final RevCommit revCommit : all) { calendar.setTimeInMillis(revCommit.getCommitTime() * 1000L); if (sinceDate.after(calendar.getTime())) { break; } ref = revCommit; } if (ref == null) { throw new IllegalStateException("Can't find any commit since '" + since + "'"); } return ref; } catch (GitAPIException e) { throw new IllegalStateException(e); } } private static AbstractTreeIterator prepareTreeParser(final Repository repository, final ObjectId objectId) throws IOException { try (RevWalk walk = new RevWalk(repository)) { RevCommit commit = walk.parseCommit(objectId); RevTree tree = walk.parseTree(commit.getTree().getId()); CanonicalTreeParser treeParser = new CanonicalTreeParser(); try (ObjectReader reader = repository.newObjectReader()) { treeParser.reset(reader, tree.getId()); } walk.dispose(); return treeParser; } } }
package com.mall.backend.web; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.mall.domain.Prod; import com.mall.service.ProdService; import com.mall.util.BaseFactory; /** * Servlet implementation class DelProdServlet */ @WebServlet("/DelProdServlet") public class DelProdServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pidStr = request.getParameter("pid"); int pid = Integer.parseInt(pidStr); //根据service执行删除逻辑 ProdService service = BaseFactory.getFactory().getInstance(ProdService.class); //根据pid删除商品 boolean flag = service.deleteProdByPid(pid); if(flag==true){ //删除成功则重定向列出全部商品页面 response.getWriter().write("商品删除成功"); response.setHeader("refresh", "3;url="+request.getContextPath()+"/backend/ListProdServlet"); return ; } //不成功,则转发回原来的页面,并且携带原来的商品信息 List<Prod> list = service.listAllProd(); request.setAttribute("list", list); request.setAttribute("errMsg", "删除商品失败"); request.getRequestDispatcher("").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package me.wuxingxing.pay.alipay.exception; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; /** * @author xingxing.wu * @date 2018/3/29 */ public class AlipayException extends RuntimeException { private static final long serialVersionUID = 1L; private int status; private Integer code; public AlipayException(String message) { super(message); this.code = 0; this.status = 500; } public AlipayException(int status) { this.status = status; } public AlipayException(int errorCode, String message) { this(400, errorCode, message); } public AlipayException(int status, Integer code, String message) { this(status, code, message, null); } public AlipayException(int status, Integer code, String message, Throwable cause) { super(message, cause); this.status = status; this.code = code; } public int getStatus() { return this.status; } public Integer getCode() { return this.code; } public void logException(Logger logger) { if (this.status>=500) { logger.error(this.getMessage(), this); } else if (StringUtils.isNotEmpty(this.getMessage())) { logger.warn(this.getMessage()); } }}
package com.propertycross.mgwt.ui; import java.util.ArrayList; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.Label; import com.googlecode.mgwt.ui.client.widget.CellList; import com.googlecode.mgwt.ui.client.widget.celllist.CellSelectedEvent; import com.propertycross.mgwt.PropertyCrossTestCase; import com.propertycross.mgwt.locations.Location; public class LocationListGwtTest extends PropertyCrossTestCase { private List<Location> results = new ArrayList<Location>(); private HasValue<String> searchBox; private MockHasWidgets panel = new MockHasWidgets(); private LocationList list; private Mocks mocks; @Override protected void gwtSetUp() throws Exception { mocks = GWT.create(Mocks.class); searchBox = mocks.hasStringValue(); results.add(new Location("longA", "A")); results.add(new Location("longB", "B")); list = new LocationList(searchBox, results); } @SuppressWarnings("unchecked") public void testCellList() throws Throwable { list.addTo(panel); assertTrue("widget type", panel.widgets.get(1) instanceof CellList); CellList<Location> cl = (CellList<Location>)panel.widgets.get(1); searchBox.setValue("B", true); mocks.expectLastCall(); mocks.replay(); cl.fireEvent(new CellSelectedEvent(1, null)); } public void testLabel() throws Throwable { list.addTo(panel); assertTrue("widget type", panel.widgets.get(0) instanceof Label); Label l = (Label)panel.widgets.get(0); assertEquals("text", "Please select a location below:", l.getText()); assertTrue("word wrap", l.getWordWrap()); } public void testAddsComponents() throws Throwable { list.addTo(panel); assertEquals(2, panel.widgets.size()); } public void testNoAddLabelIfNoLocations() throws Throwable { LocationList list = new LocationList( searchBox, new ArrayList<Location>()); list.addTo(panel); assertTrue(panel.widgets.isEmpty()); } }
import java.awt.List; import java.math.BigDecimal; import org.junit.Assert; import cucumber.api.PendingException; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import cucumber.deps.com.thoughtworks.xstream.converters.basic.StringConverter; import org.junit.Assert; import net.baade.*; public class AtendimentoRotinaTeste { private Cliente cliente = new Cliente(); Animal animal = new Animal(null); Procedimento procedimento = new Procedimento(); //>>>>>>> branch 'HEAD' of https://github.com/rodgessilva/TDDC.git Recibo recibo = new Recibo(); private void Recibo() { recibo.setNomeCliente("Fofo"); recibo.setNomeCliente("Dave Atkins"); } @Given("^um cliente com nome \"([^\"]*)\" que tem um animal de nome \"([^\"]*)\"$") public void um_cliente_com_nome_que_tem_um_animal_de_nome(String cliente, String animal) throws Throwable { //<<<<<<< HEAD recibo.setNomeCliente( cliente); recibo.setNomeAnimal( animal ); //======= recibo.setNomeCliente( cliente ); recibo.setNomeAnimal( animal); //>>>>>>> branch 'HEAD' of https://github.com/rodgessilva/TDDC.git } @Given("^um servico de \"([^\"]*)\" que custa \"([^\"]*)\"$") public void um_servico_de_que_custa(String procedimento, String valorProcedimento) throws Throwable { // Write code here that turns the phrase above into concrete actions BigDecimal valorProcedimentos = new BigDecimal( valorProcedimento ); recibo.listaItemAdd(new Item(procedimento, valorProcedimentos)); } @Given("^um outro servico de \"([^\"]*)\" que custa \"([^\"]*)\"$") public void um_outro_servico_de_que_custa(String procedimento, String valorProcedimento) throws Throwable { // Write code here that turns the phrase above into concrete actions BigDecimal valorProcedimentos = new BigDecimal( valorProcedimento ); recibo.listaItemAdd(new Item(procedimento, valorProcedimentos)); } @When("^o cliente pagar em \"([^\"]*)\"$") public void o_cliente_pagar_em(String pagamento) throws Throwable { // Write code here that turns the phrase above into concrete actions Assert.assertTrue( pagamento.equals( "Dinheiro" ) ); } @Then("^o recibo deve ter (\\d+) servicos$") public void o_recibo_deve_ter_servicos(int servicos) throws Throwable { // Write code here that turns the phrase above into concrete actions int quantidadeServicosRecibo = recibo.getItens().size(); Assert.assertEquals(quantidadeServicosRecibo, servicos); } @Then("^o servico (\\d+) deve ser \"([^\"]*)\"$") //<<<<<<< HEAD public void o_servico_deve_ser1(int arg1, String arg2) throws Throwable { switch ( arg1 ) { case 1: Assert.assertEquals( arg2, "consulta de rotina" ); break; default: Assert.assertEquals( arg2, "vacinacao contra raiva" ); }} //======= public void o_servico_deve_ser(int procedimento1, String procedimento2) throws Throwable { switch ( procedimento1 ) { case 1: Assert.assertEquals( procedimento2, "consulta de rotina" ); break; default: Assert.assertEquals( procedimento2, "vacinacao contra raiva" ); //>>>>>>> branch 'HEAD' of https://github.com/rodgessilva/TDDC.git break; } } @Then("^o valor total do recibo deve ser \"([^\"]*)\"$") public void o_valor_total_do_recibo_deve_ser(String valorTotal) throws Throwable { // Write code here that turns the phrase above into concrete actions BigDecimal total = new BigDecimal( valorTotal ); System.out.println(total); Assert.assertEquals( recibo.getValorAtendimento(), total ); System.out.println(recibo.getValorAtendimento()); } }
package com.yc.education.model.account; import java.math.BigDecimal; import java.util.Date; import javax.persistence.*; @Table(name = "account_coast_purchase") public class AccountCoastPurchase { /** * 成本核算-采购成本 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * 成本核算id */ private Long otherid; /** * 产品编号 */ @Column(name = "product_no") private String productNo; /** * 产品名称 */ @Column(name = "product_name") private String productName; /** * 仓库库位 */ @Column(name = "warehouse_position") private String warehousePosition; /** * 入库数量 */ @Column(name = "warehouse_num") private Integer warehouseNum; /** * 单价 */ private BigDecimal price; /** * 美金 */ private BigDecimal dollar; /** * 订单编号 */ @Column(name = "order_no") private String orderNo; /** * 人民币总金额 */ @Column(name = "rmb_money") private BigDecimal rmbMoney; /** * 添加时间 */ private Date addtime; /** * 美金总金额 */ @Column(name = "usd_money") private BigDecimal usdMoney; public BigDecimal getUsdMoney() { return usdMoney; } public void setUsdMoney(BigDecimal usdMoney) { this.usdMoney = usdMoney; } public BigDecimal getRmbMoney() { return rmbMoney; } public void setRmbMoney(BigDecimal rmbMoney) { this.rmbMoney = rmbMoney; } public Date getAddtime() { return addtime; } public void setAddtime(Date addtime) { this.addtime = addtime; } /** * 获取成本核算-采购成本 * * @return id - 成本核算-采购成本 */ public Long getId() { return id; } /** * 设置成本核算-采购成本 * * @param id 成本核算-采购成本 */ public void setId(Long id) { this.id = id; } /** * 获取成本核算id * * @return otherid - 成本核算id */ public Long getOtherid() { return otherid; } /** * 设置成本核算id * * @param otherid 成本核算id */ public void setOtherid(Long otherid) { this.otherid = otherid; } /** * 获取产品编号 * * @return product_no - 产品编号 */ public String getProductNo() { return productNo; } /** * 设置产品编号 * * @param productNo 产品编号 */ public void setProductNo(String productNo) { this.productNo = productNo; } /** * 获取产品名称 * * @return product_name - 产品名称 */ public String getProductName() { return productName; } /** * 设置产品名称 * * @param productName 产品名称 */ public void setProductName(String productName) { this.productName = productName; } /** * 获取仓库库位 * * @return warehouse_position - 仓库库位 */ public String getWarehousePosition() { return warehousePosition; } /** * 设置仓库库位 * * @param warehousePosition 仓库库位 */ public void setWarehousePosition(String warehousePosition) { this.warehousePosition = warehousePosition; } /** * 获取入库数量 * * @return warehouse_num - 入库数量 */ public Integer getWarehouseNum() { return warehouseNum; } /** * 设置入库数量 * * @param warehouseNum 入库数量 */ public void setWarehouseNum(Integer warehouseNum) { this.warehouseNum = warehouseNum; } /** * 获取单价 * * @return price - 单价 */ public BigDecimal getPrice() { return price; } /** * 设置单价 * * @param price 单价 */ public void setPrice(BigDecimal price) { this.price = price; } /** * 获取美金 * * @return dollar - 美金 */ public BigDecimal getDollar() { return dollar; } /** * 设置美金 * * @param dollar 美金 */ public void setDollar(BigDecimal dollar) { this.dollar = dollar; } /** * 获取订单编号 * * @return order_no - 订单编号 */ public String getOrderNo() { return orderNo; } /** * 设置订单编号 * * @param orderNo 订单编号 */ public void setOrderNo(String orderNo) { this.orderNo = orderNo; } }
package com.example.uma.model; import java.util.Set; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "roles") public class Role { @Id private String roleId; @Indexed(unique=true) private String roleName; //@DBRef //private Collection<Privilege> privileges; private String roleStatus; public Role(String roleName,String roleStatus) { this.roleName = roleName; this.roleStatus=roleStatus; //this.privileges=null; } public String getRoleId() { return roleId; } public String getRoleName() { return roleName; } public String getRoleStatus() { return roleStatus; } public void setRoleStatus(String status) { this.roleStatus=status; } }
package com.eshop.model.entity; public enum ProductState { ON_SALE, HIDDEN; }
package com.example.jayclark.ideexplorer; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.util.Log; public class MainActivity extends AppCompatActivity { public final static String TAG = "TestLog"; private EditText username; private EditText password; private Button login; private TextView textV; private int counter = 5; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i(TAG,"onCreate"); username = (EditText) findViewById(R.id.userName); password = (EditText) findViewById(R.id.passWord); login = (Button) findViewById(R.id.button); textV = (TextView) findViewById(R.id.textView); textV.setText("Number of attempts remaining: 5" ); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v){ validation(username.getText().toString(), password.getText().toString()); } }); } private void validation (String user, String pass) { if(user.equals("jonathanClark") && pass.equals("password")) { Intent intent = new Intent(MainActivity.this, DisplayMessageActivity.class); startActivity(intent); } else{ counter--; AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this); dlgAlert.setMessage("Invalid username or password. Please try again. \n" + "\n"+"Number of attempts remaining: " + String.valueOf(counter)); dlgAlert.setTitle("Error"); dlgAlert.setPositiveButton("OK", null); dlgAlert.setCancelable(true); dlgAlert.create().show(); textV.setText("Number of attempts remaining: " + String.valueOf(counter)); if(counter == 0) { login.setEnabled(false); } } }
package com.mxninja.example.spring_micro_services.users.domain; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.UUID; @Setter @Getter @EqualsAndHashCode(of = "uid") @Entity @Table(name = "users") public class User { @Id @GeneratedValue(generator = "UUID") @GenericGenerator( name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") @Column(name = "uid", updatable = false, nullable = false, unique = true) private UUID uid; @Column(name = "name") private String name; @Column(name = "hashPassword") private String hashPassword; @Column(name = "email", unique = true) private String email; }
package com.uchain; public class GlobalConfig { public static String genesisBlockChainId = ""; }
package io.papermc.hangar.security.metadatasources; import io.papermc.hangar.security.PermissionAttribute; import io.papermc.hangar.security.annotations.ProjectPermission; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.annotation.AnnotationMetadataExtractor; import java.util.Collection; public class ProjectPermissionSource implements AnnotationMetadataExtractor<ProjectPermission> { @Override public Collection<? extends ConfigAttribute> extractAttributes(ProjectPermission securityAnnotation) { return PermissionAttribute.createList(securityAnnotation.value()); } }
package inheritance; public class Medic { }
package com.ma.pluginframework.domain.richmsg.section; import org.json.JSONException; import org.json.JSONObject; public class PluginTextSection extends PluginMsgSection { //region 需要存储的字段 private String text; //endregion public PluginTextSection(String text) { this.text = text; } public PluginTextSection() { } public String getText() { return text; } public void setText(String text) { this.text = text; } @Override public boolean available() { return text != null && text.length() > 0; } @Override public JSONObject toJSONObject() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("text", getText()); jsonObject.put("type", TYPE_TEXT); return jsonObject; } @Override public PluginMsgSection readFromJSONObject(JSONObject jsonObject) { PluginTextSection textLocalSection = new PluginTextSection(); textLocalSection.setText(jsonObject.optString("text", null)); return textLocalSection; } @Override public String toString() { return text; } }
package pers.lyr.demo.dao.impl; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import pers.lyr.demo.common.factory.JdbcTemplateFactory; import pers.lyr.demo.common.mapper.StudentTableMapper; import pers.lyr.demo.dao.BaseDAOImpl; import pers.lyr.demo.dao.StudentDAO; import pers.lyr.demo.pojo.po.Student; /** * @Author lyr * @create 2020/9/13 19:02 */ public class StudentDAOImpl extends BaseDAOImpl<Student> implements StudentDAO { JdbcTemplate jdbcTemplate = JdbcTemplateFactory.getJdbcTemplate(); /** * 获取 T 表的名字 * * @return 数据库表的名字 */ @Override public String getTableName() { return "t_student"; } /** * 返回映射 的实现 * * @return jdbcTemplate 定义的 映射接口 */ @Override public RowMapper<Student> getRowMapper() { return StudentTableMapper.INSTANCE; } @Override public String getTableIdField() { return "student_id"; } /** * 根据ID 查找 * * @param query query对象 * @return */ @Override public Student selectById(Student query) { return super.selectById(query.getStudentId()); } @Override public int insertOne(Student object) { String l = "insert into " + "t_student( student_name,student_password,student_id_card,sex,is_deleted,gmt_create,gmt_modified) values(?,?,?,?,?,?,?)"; int row = jdbcTemplate.update(l, object.getStudentName(), object.getStudentPassword(), object.getStudentIdCard(), object.getSex(), object.getDeleted(), object.getGmtCreate(), object.getGmtModified() ); if(row >0) { return super.getLastInsertId(); } return row; } }
package com.jl.extract; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.List; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.dictionary.CustomDictionary; import com.hankcs.hanlp.seg.common.Term; import com.jl.tools.common; public class IKAnalysisSplit { public static void dictionary() throws Exception{ File f= new File("setConfig/word_dictionary.txt"); InputStreamReader isr=new InputStreamReader(new FileInputStream(f),"utf-8"); //编码格式 BufferedReader bisr=new BufferedReader(isr); String str=""; while((str=bisr.readLine())!=null){ CustomDictionary.add(str); } bisr.close(); isr.close(); } public static String IKAnalysis(String str) { String content=""; try { List list=HanLP.segment(str); for(int i=0;i<list.size();i++){ Term ss=(Term) list.get(i); content=content+ss.word+" "; } }catch(Exception e){ e.printStackTrace(); } return content; } public static String IKAnalysis_stopwords(String str){ String content=""; try { List list=HanLP.segment(str); for(int i=0;i<list.size();i++){ Term ss=(Term) list.get(i); if(!(common.stopwords.contains(ss.word))){ content=content+ss.word+" "; } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(sb.toString()); // System.out.println(content); return content; } }
package com.tessoft.nearhere.activities; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import com.tessoft.common.Constants; import com.tessoft.domain.APIResponse; import com.tessoft.nearhere.R; import org.codehaus.jackson.type.TypeReference; import java.util.HashMap; public class TermsAgreementActivity extends BaseActivity { private static final int INSERT_USER_TERMS_AGREEMENT = 1; WebView webView1 = null; WebView webView2 = null; WebView webView3 = null; WebViewClient webViewClient = new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Toast.makeText( getApplicationContext(), description, Toast.LENGTH_SHORT).show(); } }; @Override protected void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setContentView(R.layout.activity_terms_agreement); webView1 = (WebView) findViewById(R.id.webView1); webView1.setWebViewClient( webViewClient ); webView2 = (WebView) findViewById(R.id.webView2); webView2.setWebViewClient( webViewClient ); webView3 = (WebView) findViewById(R.id.webView3); webView3.setWebViewClient( webViewClient ); webView1.loadUrl(Constants.getServerURL() + "/taxi/getUserTerms.do?type=nearhere&version=1.0"); webView2.loadUrl(Constants.getServerURL() + "/taxi/getUserTerms.do?type=personal&version=1.0"); webView3.loadUrl( Constants.getServerURL() + "/taxi/getUserTerms.do?type=location&version=1.0"); setTitle("이용약관"); findViewById(R.id.btnRefresh).setVisibility(ViewGroup.GONE); } catch( Exception ex ) { catchException(this, ex); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.terms_agreement, menu); return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void updateTermsAgreement( View v ) { try { setProgressBarIndeterminateVisibility(true); application.debug("profilePoint:" + application.getLoginUser().getProfilePoint()); HashMap hash = new HashMap(); hash.put("userID", application.getLoginUser().getUserID()); hash.put("nearhere_ver", "1.0"); hash.put("personal_ver", "1.0"); hash.put("location_ver", "1.0"); sendHttp("/taxi/insertTermsAgreement.do", mapper.writeValueAsString(hash), INSERT_USER_TERMS_AGREEMENT); } catch( Exception ex ) { catchException(this, ex); } } @Override public void doPostTransaction(int requestCode, Object result) { // TODO Auto-generated method stub try { if ( Constants.FAIL.equals(result) ) { setProgressBarIndeterminateVisibility(false); showOKDialog("통신중 오류가 발생했습니다.\r\n다시 시도해 주십시오.", null); return; } setProgressBarIndeterminateVisibility(false); APIResponse response = mapper.readValue(result.toString(), new TypeReference<APIResponse>(){}); if ( "0000".equals( response.getResCode() ) ) { if ( requestCode == INSERT_USER_TERMS_AGREEMENT ) { goMainActivity(); super.finish(); } } else { showOKDialog("경고", response.getResMsg(), null); return; } } catch( Exception ex ) { catchException(this, ex); } } @Override public void finish() { // TODO Auto-generated method stub super.finish(); } boolean doubleBackToExitPressedOnce = false; @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Toast.makeText(this, "이전 버튼을 한번 더 누르면 종료합니다.", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce=false; } }, 2000); } }
package vape.springmvc.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name ="procesadores") public class Procesadores { @Id @Column(name = "idproc") private String idproc; @Column(name = "modelo") private String modelo; @Column(name = "precio") private double precio; @Column(name = "img") private String img; @Column(name ="stock") private int stock; public Procesadores() { } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } public String getIdproc() { return idproc; } public void setIdproc(String idproc) { this.idproc = idproc; } public String getModelo() { return modelo; } public void setModelo(String modelo) { this.modelo = modelo; } public double getPrecio() { return precio; } public void setPrecio(double precio) { this.precio = precio; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } @Override public String toString() { return "Procesadores [idproc=" + idproc + ", modelo=" + modelo + ", precio=" + precio + ", img=" + img + "]"; } }
package com.gxtc.huchuan.ui.live.intro; import android.Manifest; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.bigkoo.pickerview.TimePickerView; import com.gxtc.commlibrary.base.BaseTitleActivity; import com.gxtc.commlibrary.helper.ImageHelper; import com.gxtc.commlibrary.utils.FileUtil; import com.gxtc.commlibrary.utils.GotoUtil; import com.gxtc.commlibrary.utils.ToastUtil; import com.gxtc.huchuan.MyApplication; import com.gxtc.huchuan.R; import com.gxtc.huchuan.bean.ChatInfosBean; import com.gxtc.huchuan.bean.ChooseClassifyBean; import com.gxtc.huchuan.bean.UploadResult; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.http.ApiCallBack; import com.gxtc.huchuan.http.ApiObserver; import com.gxtc.huchuan.http.ApiResponseBean; import com.gxtc.huchuan.http.LoadHelper; import com.gxtc.huchuan.http.service.LiveApi; import com.gxtc.huchuan.http.service.MineApi; import com.gxtc.huchuan.pop.PopPosition; import com.gxtc.huchuan.ui.live.intro.introresolve.IntroResolveActivity; import com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.seriesclassify.SeriesClassifyActivity; import com.gxtc.huchuan.utils.DateUtil; import com.gxtc.huchuan.utils.DialogUtil; import com.gxtc.huchuan.utils.JumpPermissionManagement; import com.gxtc.huchuan.utils.LoginErrorCodeUtil; import com.gxtc.huchuan.utils.RegexUtils; import com.luck.picture.lib.entity.LocalMedia; import com.luck.picture.lib.model.FunctionConfig; import com.luck.picture.lib.model.FunctionOptions; import com.luck.picture.lib.model.PictureConfig; import org.jsoup.Jsoup; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import butterknife.BindView; import butterknife.OnClick; import cn.carbswang.android.numberpickerview.library.NumberPickerView; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; import top.zibin.luban.Luban; import static com.gxtc.huchuan.ui.circle.dynamic.IssueDynamicActivity.maxLen_500k; /** * Created by Gubr on 2017/3/22. */ public class LiveIntroSettingActivity extends BaseTitleActivity implements View.OnClickListener, TimePickerView.OnTimeSelectListener, PictureConfig.OnSelectResultCallback { private static final String TAG = "LiveIntroSettingActivit"; private static final int SETTING_INTRO_REQUESTCODE = 1 << 5; private static int REQUEST_CODE_IMAGE = 10000; @BindView(R.id.iv_live_intro_setting_head) ImageView mIvLiveIntroSettingIcon; @BindView(R.id.tv_live_intro_setting_subtitle) TextView mTvLiveIntroSettingSubtitle; @BindView(R.id.tv_live_intro_setting_intro_starttime) TextView mTvLiveIntroSettingIntroStarttime; @BindView(R.id.tv_live_intro_setting_mainspeaker_name) TextView mTvLiveIntroSettingMainspeakerName; @BindView(R.id.tv_live_intro_setting_mainspeaker_intro) TextView mTvLiveIntroSettingMainspeakerIntro; @BindView(R.id.tv_live_intro_setting_live_intro) TextView mTvLiveIntroSettingLiveIntro; @BindView(R.id.cb_live_intro_setting_sharelist) CheckBox mCbLiveIntroSettingSharelist; @BindView(R.id.cb_live_intro_setting_singup) CheckBox mCbLiveIntroSettingSingup; @BindView(R.id.cb_live_intro_setting_intro) CheckBox mCbLiveIntroSettingIntro; @BindView(R.id.tv_live_intro_setting_intro_price) TextView mTvLiveIntroSettingIntroPrice; @BindView(R.id.rl_live_intro_setting_intro_price) RelativeLayout mRlLiveIntroSettingIntroPrice; @BindView(R.id.tv_live_intro_setting_intro_password) TextView mTvLiveIntroSettingIntroPassword; @BindView(R.id.rl_live_intro_setting_intro_password) RelativeLayout mRlLiveIntroSettingIntroPassword; @BindView(R.id.tv_live_intro_setting_series) TextView mTvLiveIntroSettingSeries; CompositeSubscription mCompositeSubscription = new CompositeSubscription(); @BindView(R.id.tv_divided_proportion) TextView mTvDividedProportion; //分成比例 @BindView(R.id.rl_divided_proportion) RelativeLayout mRlDividedProportion; private ChatInfosBean mBean; private String intro; private String newFacePricPath; private TimePickerView timePickerView; private Date mDate; private SimpleDateFormat sdf; private String time; private Subscription uploadSub; private String mNewFileUrl; private PopPosition mPopPosition; private List<ChooseClassifyBean> mSeriesTypes; private String[] series; private String seriesId; private long mStartTime; private AlertDialog mAlertDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_live_intro_setting); } @Override public void initView() { getBaseHeadView().showBackButton(this); getBaseHeadView().showTitle("设置信息"); getBaseHeadView().showHeadRightButton("确定", this); } @Override public void initData() { mBean = (ChatInfosBean) getIntent().getSerializableExtra("bean"); intro = mBean.getDesc(); seriesId = mBean.getChatSeries(); getTypeData(); setData(); } private void setData() { if (mBean != null) { ImageHelper.loadImage(this, mIvLiveIntroSettingIcon, mBean.getFacePic(), R.drawable.live_host_defaual_bg); mTvLiveIntroSettingMainspeakerIntro.setText(mBean.getSpeakerIntroduce()); mTvLiveIntroSettingMainspeakerName.setText(mBean.getMainSpeaker()); mTvLiveIntroSettingSubtitle.setText(mBean.getSubtitle()); mTvLiveIntroSettingIntroStarttime.setText(DateUtil.stampToDate(mBean.getStarttime())); try { if (!TextUtils.isEmpty(intro)) { String text = Jsoup.parse(intro).body().text(); mTvLiveIntroSettingLiveIntro.setText(text); } } catch (Exception e) { e.printStackTrace(); } mTvDividedProportion.setText(mBean.getPent()); switch (mBean.getChattype()) { case "0": mRlDividedProportion.setVisibility(View.GONE); break; case "1": mRlLiveIntroSettingIntroPassword.setVisibility(View.VISIBLE); mTvLiveIntroSettingIntroPassword.setText(mBean.getPassword()); break; case "2": mRlDividedProportion.setVisibility(View.VISIBLE); mRlLiveIntroSettingIntroPrice.setVisibility(View.VISIBLE); mTvLiveIntroSettingIntroPrice.setText(mBean.getFee()); break; } mCbLiveIntroSettingSingup.setChecked(mBean.isShowSignUp()); mCbLiveIntroSettingSharelist.setChecked(mBean.isShowShare()); if(!"0".equals(seriesId)){ mRlLiveIntroSettingIntroPrice.setVisibility(View.GONE); mRlDividedProportion.setVisibility(View.GONE); } } } @OnClick({R.id.rl_live_intro_setting_head, R.id.rl_live_intro_setting_subtitle, R.id.rl_live_intro_setting_intro_starttime, R.id.rl_live_intro_setting_mainspeaker_name, R.id.rl_live_intro_setting_mainspeaker_intro, R.id.rl_live_intro_setting_live_intro, R.id.rl_live_intro_setting_intro_price, R.id.rl_live_intro_setting_intro_password, R.id.rl_live_intro_setting_series, R.id.rl_divided_proportion}) public void onClick(View view) { switch (view.getId()) { case R.id.rl_live_intro_setting_head: //跳到去设置头像 chooseImg(); break; case R.id.rl_live_intro_setting_subtitle: showTheamDialog(); break; case R.id.rl_live_intro_setting_intro_starttime: showTimeDialog(); break; case R.id.rl_live_intro_setting_intro_price: //显示价格输入 showPriceDialog(); break; case R.id.rl_live_intro_setting_intro_password: //显示密码设置 showPasswordDialog(); break; case R.id.rl_live_intro_setting_mainspeaker_name: //输入主讲人名字 showNameDialog(); break; case R.id.rl_live_intro_setting_mainspeaker_intro: //输入主讲人的介绍 showSpeakerIntroDialog(); break; case R.id.rl_live_intro_setting_live_intro: //输入课堂的概要 showLiveIntroDialog(); break; case R.id.rl_live_intro_setting_series: showSeriesDialog(); break; case R.id.headBackButton: setResult(RESULT_CANCELED); finish(); break; case R.id.headRightButton: submit(); break; case R.id.rl_divided_proportion: showDividedProportion(); break; } } AlertDialog mDialog; private void showTheamDialog() { mDialog = DialogUtil.showInputDialog(this, false, "", "你只有一次修改主题,确定要修改吗", new View.OnClickListener() { @Override public void onClick(View v) { showSubtitleDialog(); mDialog.dismiss(); } }); } AlertDialog timeDialog; private void showTimeDialog() { timeDialog = DialogUtil.showInputDialog(this, false, "", "你只有一次修改开播的时间,确定要修改吗", new View.OnClickListener() { @Override public void onClick(View v) { showTimePop(); timeDialog.dismiss(); } }); } private void submit() { HashMap<String, String> map = new HashMap<>(); if (!UserManager.getInstance().isLogin()) { ToastUtil.showShort(this, "请先登录"); return; } map.put("token", UserManager.getInstance().getToken()); map.put("id", mBean.getId()); if (TextUtils.isEmpty(mTvLiveIntroSettingSubtitle.getText().toString())) { ToastUtil.showShort(this, "主题不能为空"); return; } mBean.setSubtitle(mTvLiveIntroSettingSubtitle.getText().toString()); map.put("subtitle", mTvLiveIntroSettingSubtitle.getText().toString()); if (!TextUtils.isEmpty(mTvLiveIntroSettingMainspeakerName.getText().toString())) { mBean.setMainSpeaker(mTvLiveIntroSettingMainspeakerName.getText().toString()); map.put("mainSpeaker", mTvLiveIntroSettingMainspeakerName.getText().toString()); } if (mStartTime != 0) { mBean.setStarttime(String.valueOf(mStartTime)); map.put("starttime", String.valueOf(mStartTime)); } if (!TextUtils.isEmpty(mTvDividedProportion.getText().toString())) { mBean.setPent(mTvDividedProportion.getText().toString()); map.put("pent", mTvDividedProportion.getText().toString()); } if (!TextUtils.isEmpty(mTvLiveIntroSettingMainspeakerIntro.getText().toString())) { mBean.setSpeakerIntroduce(mTvLiveIntroSettingMainspeakerIntro.getText().toString()); map.put("speakerIntroduce", mTvLiveIntroSettingMainspeakerIntro.getText().toString()); } if (!TextUtils.isEmpty(intro)) { mBean.setDesc(intro); map.put("desc", intro); } if (mNewFileUrl != null) { mBean.setFacePic(mNewFileUrl); map.put("facePic", mNewFileUrl); } if (TextUtils.isEmpty(seriesId) && !mBean.getChatSeries().equals(seriesId)) { mBean.setChatSeries(seriesId); map.put("chatSeries", seriesId); } switch (mBean.getChattype()) { case "1": if (TextUtils.isEmpty( mTvLiveIntroSettingIntroPassword.getText().toString()) || mTvLiveIntroSettingIntroPassword.getText().toString().length() < 6) { ToastUtil.showShort(this, "密码不能为空,最少需要6个字符"); return; } else if (!RegexUtils.isMathPsw(mTvLiveIntroSettingIntroPassword.getText())) { ToastUtil.showShort(this, "密码只能用字母或数字"); return; } else { mBean.setPassword(mTvLiveIntroSettingIntroPassword.getText().toString()); map.put("password", mTvLiveIntroSettingIntroPassword.getText().toString()); } break; case "2": if (!mBean.getFee().equals(mTvLiveIntroSettingIntroPrice.getText().toString())) { mBean.setFee(mTvLiveIntroSettingIntroPrice.getText().toString()); map.put("fee", mTvLiveIntroSettingIntroPrice.getText().toString()); } break; } if (mRlLiveIntroSettingIntroPrice.isShown() && !mBean.getFee().equals(mTvLiveIntroSettingIntroPrice.getText().toString())) { mBean.setFee(mTvLiveIntroSettingIntroPrice.getText().toString()); map.put("fee", mTvLiveIntroSettingIntroPrice.getText().toString()); } mBean.setShowShare(mCbLiveIntroSettingSharelist.isChecked() ? "0" : "1"); mBean.setShowSignup(mCbLiveIntroSettingSingup.isChecked() ? "0" : "1"); map.put("showSignup", mCbLiveIntroSettingSingup.isChecked() ? "0" : "1"); map.put("showShare", mCbLiveIntroSettingSharelist.isChecked() ? "0" : "1"); map.put("isPublish",mBean.getIsPublish()); /* 提交逻辑改成修改课程资料,课程不变成审核状态,审核修改的资料,审核后才更新 */ mCompositeSubscription.add(LiveApi.getInstance().saveChatInfoIntroduction(map).subscribeOn( Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe( new ApiObserver<ApiResponseBean<Void>>(new ApiCallBack() { @Override public void onSuccess(Object data) { //Intent intent = new Intent(); //intent.putExtra("bean", mBean); //setResult(RESULT_OK, intent); //finish(); showSaveDialog(); } @Override public void onError(String errorCode, String message) { ToastUtil.showShort(LiveIntroSettingActivity.this, message); } }))); } private AlertDialog saveDialog; private void showSaveDialog(){ saveDialog = DialogUtil.showInputDialog(this, false, "", "修改成功,内容审核后才能生效", new View.OnClickListener() { @Override public void onClick(View v) { saveDialog.dismiss(); finish(); } }); } private void showSeriesDialog() { if (mPopPosition == null) { if (series == null) { ToastUtil.showShort(this, "数据加载出错 请稍后再试"); getTypeData(); return; } //没有系列课 去选择系列课 if (series.length == 0) { GotoUtil.goToActivityForResult(this, SeriesClassifyActivity.class, 200); return; } mPopPosition = new PopPosition(this, R.layout.pop_ts_position); mPopPosition.setData(series); mPopPosition.setTitle("选择要移动到的系列课"); mPopPosition.setOnValueChangeListener(new NumberPickerView.OnValueChangeListener() { @Override public void onValueChange(NumberPickerView picker, int oldVal, int newVal) { mTvLiveIntroSettingSeries.setText(series[newVal]); seriesId = mSeriesTypes.get(newVal).getId(); } }); } mPopPosition.showPopOnRootView(this); } private void showPasswordDialog() { DialogUtil.showTopicInputDialog(this, "修改密码", "请设置密码", mTvLiveIntroSettingIntroPassword.getText().toString(), new View.OnClickListener() { @Override public void onClick(View v) { String str = (String) v.getTag(); if (TextUtils.isEmpty(str)) { } else { mTvLiveIntroSettingIntroPassword.setText(str); } } }); } private void showPriceDialog() { DialogUtil.showTopicInputDialog(this, "修改价格", "", mTvLiveIntroSettingIntroPrice.getText().toString(), 8194, 1, new View.OnClickListener() { @Override public void onClick(View v) { String str = (String) v.getTag(); try { double integer = Double.valueOf(str); if (integer < 1 || integer > 99999) { ToastUtil.showShort(LiveIntroSettingActivity.this, "价格范围是1-99999"); } else { mTvLiveIntroSettingIntroPrice.setText(String.valueOf(integer)); } } catch (NumberFormatException e) { e.printStackTrace(); ToastUtil.showShort(LiveIntroSettingActivity.this, "请输入正确的格式"); } } }); } private void showLiveIntroDialog() { Intent intent = new Intent(LiveIntroSettingActivity.this, IntroResolveActivity.class); intent.putExtra("intro", intro); startActivityForResult(intent, SETTING_INTRO_REQUESTCODE); } private void showSpeakerIntroDialog() { DialogUtil.showTopicInputDialog(this, "填写简介", "请填写主讲人简介", mTvLiveIntroSettingMainspeakerIntro.getText().toString(), -1, 5, new View.OnClickListener() { @Override public void onClick(View v) { String str = (String) v.getTag(); if (TextUtils.isEmpty(str)) { } else { mTvLiveIntroSettingMainspeakerIntro.setText(str); } } }); } private void showNameDialog() { DialogUtil.showTopicInputDialog(this, "填写主讲人", "请填写主讲人名称,多个主讲人请用空格隔开", mTvLiveIntroSettingMainspeakerName.getText().toString(), new View.OnClickListener() { @Override public void onClick(View v) { String str = (String) v.getTag(); if (TextUtils.isEmpty(str)) { } else { mTvLiveIntroSettingMainspeakerName.setText(str); } } }); } private void showDividedProportion() { DialogUtil.showTopicInputDialog(this, "修改分成比例", "请设置分成比例(5%~70%)", mTvDividedProportion.getText().toString(), EditorInfo.TYPE_CLASS_NUMBER, 0, new View.OnClickListener() { @Override public void onClick(View v) { String str = (String) v.getTag(); int num = 0; if (!TextUtils.isEmpty(str)) { try { num = Integer.valueOf(str); if (num < 5 || num > 70) { ToastUtil.showShort(LiveIntroSettingActivity.this, "请设置正确分成比例(5~70)"); } else { mTvDividedProportion.setText(num + ""); } } catch (Exception e) { ToastUtil.showShort(LiveIntroSettingActivity.this, "请输入正确数值"); } } } }); } private void showSubtitleDialog() { DialogUtil.showTopicInputDialog(this, "填写标题", "请输入课程标题", mTvLiveIntroSettingSubtitle.getText().toString(), new View.OnClickListener() { @Override public void onClick(View v) { String str = (String) v.getTag(); if (TextUtils.isEmpty(str)) { ToastUtil.showShort(LiveIntroSettingActivity.this, "标题不能为空"); } else { mTvLiveIntroSettingSubtitle.setText(str); } } }); } //选择日期 private void showTimePop() { try { long endTime = Long.valueOf(mBean.getStarttime()); if (endTime < System.currentTimeMillis()) { ToastUtil.showShort(this, "直播时间已结束,不能修改时间"); } else { if (timePickerView == null) { TimePickerView.Builder builder = new TimePickerView.Builder(this, this).setType( TimePickerView.Type.ALL).setOutSideCancelable(true); timePickerView = new TimePickerView(builder); } timePickerView.show(); } } catch (Exception e) { e.printStackTrace(); } } //选择照片 private void chooseImg() { String[] pers = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; performRequestPermissions("此应用需要读取相机和文件夹权限", pers, 1011, new PermissionsResultListener() { @Override public void onPermissionGranted() { int height = (int) getResources().getDimension(R.dimen.px500dp); FunctionOptions options = new FunctionOptions.Builder() .setType(FunctionConfig.TYPE_IMAGE) .setSelectMode(FunctionConfig.MODE_SINGLE) .setImageSpanCount(3) .setEnableQualityCompress(false) //是否启质量压缩 .setEnablePixelCompress(false) //是否启用像素压缩 .setEnablePreview(true) // 是否打开预览选项 .setShowCamera(true) .setPreviewVideo(true) .setIsCrop(true) .setAspectRatio(4, 3) .setMaxHeight(height) .create(); PictureConfig.getInstance().init(options).openPhoto(LiveIntroSettingActivity.this, LiveIntroSettingActivity.this); } @Override public void onPermissionDenied() { mAlertDialog = DialogUtil.showDeportDialog(LiveIntroSettingActivity.this, false, null, getString(R.string.pre_scan_notice_msg), new View.OnClickListener() { @Override public void onClick(View v) { if (v.getId() == R.id.tv_dialog_confirm) { JumpPermissionManagement.GoToSetting( LiveIntroSettingActivity.this); } mAlertDialog.dismiss(); } }); } }); } @Override public void onTimeSelect(Date date, View v) { mDate = date; sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm", Locale.CHINA);//yyyy.MM.dd.HH.mm.ss if (mDate.getTime() < System.currentTimeMillis()) { ToastUtil.showShort(LiveIntroSettingActivity.this, "设置的时间必须是未来时间"); return; } mStartTime = mDate.getTime(); time = sdf.format(date); mTvLiveIntroSettingIntroStarttime.setText(time); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SETTING_INTRO_REQUESTCODE && resultCode == RESULT_OK) { intro = data.getStringExtra("intro"); if (!TextUtils.isEmpty(intro)) { String text = Jsoup.parse(intro).body().text(); mTvLiveIntroSettingLiveIntro.setText(text); } } if (requestCode == 200 && resultCode == RESULT_OK) { getTypeData(); } } private void showLoad() { getBaseLoadingView().showLoading(); } private void showLoadFinish() { getBaseLoadingView().hideLoading(); } public void compressImg(String s) { showLoad(); //将图片进行压缩 final File file = new File(s); Luban.get(MyApplication.getInstance()).load(file).launch().asObservable().subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ApiObserver<File>(new ApiCallBack<File>() { @Override public void onSuccess(File compressFile) { if(FileUtil.getSize(file) > maxLen_500k ){ uploadingFile(compressFile); }else { uploadingFile(file); } } @Override public void onError(String errorCode, String message) { ToastUtil.showShort(MyApplication.getInstance(),message); } })); } public void uploadingFile(File file) { LoadHelper.uploadFile(LoadHelper.UP_TYPE_IMAGE, new LoadHelper.UploadCallback() { @Override public void onUploadSuccess(UploadResult result) { if (getBaseLoadingView() == null) return; showLoadFinish(); showUploadingSuccess(result.getUrl()); } @Override public void onUploadFailed(String errorCode, String msg) { showLoadFinish(); ToastUtil.showShort(LiveIntroSettingActivity.this, msg); } }, null, file); } private void showUploadingSuccess(String fileUrl) { mNewFileUrl = fileUrl; ImageHelper.loadImage(LiveIntroSettingActivity.this, mIvLiveIntroSettingIcon, fileUrl); } @Override protected void onDestroy() { mCompositeSubscription.unsubscribe(); if (uploadSub != null) { uploadSub.unsubscribe(); } mAlertDialog = null; super.onDestroy(); } private void getTypeData() { final HashMap<String, String> map = new HashMap<>(); map.put("chatRoomId", mBean.getChatRoom()); mCompositeSubscription.add(MineApi.getInstance().getChatSeriesTypeList(map).subscribeOn( Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe( new ApiObserver<ApiResponseBean<List<ChooseClassifyBean>>>( new ApiCallBack<List<ChooseClassifyBean>>() { @Override public void onSuccess(List<ChooseClassifyBean> data) { if (data != null && mTvLiveIntroSettingSeries != null) { mSeriesTypes = data; series = new String[mSeriesTypes.size()]; for (int i = 0; i < mSeriesTypes.size(); i++) { series[i] = mSeriesTypes.get(i).getTypeName(); } for (ChooseClassifyBean seriesType : mSeriesTypes) { if (seriesType.getId().equals(seriesId)) { mTvLiveIntroSettingSeries.setText( seriesType.getTypeName()); break; } } } } @Override public void onError(String errorCode, String message) { LoginErrorCodeUtil.showHaveTokenError(LiveIntroSettingActivity.this, errorCode, message); } }))); } @Override public void onSelectSuccess(List<LocalMedia> resultList) { } @Override public void onSelectSuccess(LocalMedia media) { compressImg(media.getPath()); } }
package com.alvin.demo.design.store; import java.util.Map; public interface ICommodity { void sendCommodity(String uId, String commdityId, String bizId, Map<String, String> extMap) throws Exception; }
package com.otala.codereveals.repository; import com.otala.codereveals.domain.Company; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; import java.util.List; /** * Spring Data repository for the Company entity. */ @SuppressWarnings("unused") @Repository public interface CompanyRepository extends JpaRepository<Company, Long> { @Query("select company from Company company where company.user.login = ?#{principal.preferredUsername}") List<Company> findByUserIsCurrentUser(); }
package com.gaoshin.onsalelocal.groupon.dao; import java.util.List; import com.gaoshin.onsalelocal.groupon.beans.Category; public interface CategoryDao { List<Category> getOrderedSubcategories(); }
package com.g2utools.whenmeet.activity.main; import android.content.DialogInterface; import android.content.Intent; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.g2utools.whenmeet.R; import com.g2utools.whenmeet.service.ReceiveNotification; import com.g2utools.whenmeet.adapter.ChatListAdapter; import com.g2utools.whenmeet.dialog.TextDialog; import com.g2utools.whenmeet.model.ChatItemData; import com.g2utools.whenmeet.model.PeopleItemData; import com.g2utools.whenmeet.model.TalkItemData; import com.g2utools.whenmeet.activity.sheet.SheetList; import com.g2utools.whenmeet.util.MessageSender; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.MutableData; import com.google.firebase.database.Transaction; import com.google.firebase.database.ValueEventListener; import java.util.HashMap; import java.util.Map; public class ChatRoomActivity extends AppCompatActivity { public static final String P_REF_CHAT_ROOM = "chat room"; public static final String P_REF_CHAT_ITEM = "chat item"; private EditText mMessage; private FloatingActionButton mSend; private RecyclerView mTalkListView; private LinearLayoutManager mTalkListLayoutMgr; private ChatListAdapter mChatListAdpater; private String uid; private String refChatRoom; private String refChatItem; private Map<String, PeopleItemData> mAttender = new HashMap<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat_room); //파라메터 설정 uid = FirebaseAuth.getInstance().getCurrentUser().getUid(); refChatRoom = getIntent().getStringExtra(P_REF_CHAT_ROOM); refChatItem = getIntent().getStringExtra(P_REF_CHAT_ITEM); //UI 연결 mMessage = findViewById(R.id.message); mSend = findViewById(R.id.send); mSend.setOnClickListener(onClickSendListener); //아래에 멤버 변수로 선언되어 있음 //리스트뷰 설정 mTalkListView = findViewById(R.id.talkes); mTalkListLayoutMgr = new LinearLayoutManager(this); mChatListAdpater = new ChatListAdapter(uid); mTalkListView.setLayoutManager(mTalkListLayoutMgr); mTalkListView.setAdapter(mChatListAdpater); } private View.OnClickListener onClickSendListener = new View.OnClickListener() { @Override public void onClick(View view) { //발송 준비 final String message = mMessage.getText().toString(); mMessage.setText(""); if (message.equals("")) { return; } //발송 MessageSender messageSender = new MessageSender(mChatRoomID, refChatRoom, mAttender); messageSender.SendMessage(message); } }; @Override protected void onStart() { super.onStart(); FirebaseDatabase.getInstance().getReference(refChatRoom).addValueEventListener(mChatRoomListener); FirebaseDatabase.getInstance().getReference(refChatItem).addValueEventListener(mChatItemListener); ReceiveNotification.refReadingChatItem = refChatItem; } @Override protected void onStop() { super.onStop(); FirebaseDatabase.getInstance().getReference(refChatRoom).removeEventListener(mChatRoomListener); FirebaseDatabase.getInstance().getReference(refChatItem).removeEventListener(mChatItemListener); ReceiveNotification.refReadingChatItem = null; } private ValueEventListener mChatRoomListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { mAttender.clear(); for(DataSnapshot o : dataSnapshot.child("attender").getChildren()){ PeopleItemData data = o.getValue(PeopleItemData.class); mAttender.put(data.uid, data); } mChatListAdpater.dataList.clear(); for(DataSnapshot o : dataSnapshot.child("talkes").getChildren()){ TalkItemData data = o.getValue(TalkItemData.class); mChatListAdpater.dataList.add(data); } mChatListAdpater.notifyDataSetChanged(); mTalkListView.scrollToPosition(mChatListAdpater.getItemCount() - 1); } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(ChatRoomActivity.this, "데이터를 불러올수 없습니다.", Toast.LENGTH_SHORT).show(); } }; private String mChatRoomID; private ValueEventListener mChatItemListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { ChatItemData data = dataSnapshot.getValue(ChatItemData.class); if (data == null) { return; } getSupportActionBar().setTitle(data.title); mChatRoomID = data.refChatRoom; if(data.noticeCount != 0){ data.noticeCount = 0l; FirebaseDatabase.getInstance().getReference(refChatItem).setValue(data); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(ChatRoomActivity.this, "데이터를 불러올수 없습니다.", Toast.LENGTH_SHORT).show(); } }; @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.chat_room_menu,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.sheet_list:{ Intent intent = new Intent(this, SheetList.class); intent.putExtra(SheetList.P_REF_SHEET_LIST,refChatRoom+"/sheets"); intent.putExtra(SheetList.P_MSG_SENDER, new MessageSender(mChatRoomID,refChatRoom,mAttender)); startActivity(intent); }break; case R.id.change_title:{ new TextDialog(this, "새로운 방 이름 입력", new TextDialog.OnConfirm() { @Override public void onConfirm(final String text) { FirebaseDatabase.getInstance().getReference(refChatItem).runTransaction(new Transaction.Handler() { @Override public Transaction.Result doTransaction(MutableData mutableData) { ChatItemData o = mutableData.getValue(ChatItemData.class); o.title = text; mutableData.setValue(o); return Transaction.success(mutableData); } @Override public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) { } }); } }).show(); }break; case R.id.out_room:{ new AlertDialog.Builder(this) .setTitle("방 나가기") .setMessage("정말로 방을 나가시겠습니까?") .setPositiveButton("나가기", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String nick = FirebaseAuth.getInstance().getCurrentUser().getDisplayName(); new MessageSender(mChatRoomID, refChatRoom, mAttender) .SendMessage(nick + "님이 방을 나가셨습니다."); finish(); FirebaseDatabase.getInstance().getReference(refChatItem).removeValue(); FirebaseDatabase.getInstance().getReference(refChatRoom+"/attender/" + uid).removeValue(); FirebaseDatabase.getInstance().getReference(refChatRoom).runTransaction(new Transaction.Handler() { @Override public Transaction.Result doTransaction(MutableData mutableData) { long count = mutableData.child("attender").getChildrenCount(); if(count == 0){ mutableData.setValue(null); } return Transaction.success(mutableData); } @Override public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) { } }); } }) .setNegativeButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .setCancelable(true) .create() .show(); }break; } return super.onOptionsItemSelected(item); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jms.support.converter; import javax.xml.transform.Result; import javax.xml.transform.Source; import jakarta.jms.BytesMessage; import jakarta.jms.Session; import jakarta.jms.TextMessage; import org.junit.jupiter.api.Test; import org.springframework.oxm.Marshaller; import org.springframework.oxm.Unmarshaller; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Arjen Poutsma */ public class MarshallingMessageConverterTests { private Marshaller marshallerMock = mock(); private Unmarshaller unmarshallerMock = mock(); private Session sessionMock = mock(); private MarshallingMessageConverter converter = new MarshallingMessageConverter(marshallerMock, unmarshallerMock); @Test public void toBytesMessage() throws Exception { BytesMessage bytesMessageMock = mock(); Object toBeMarshalled = new Object(); given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); verify(marshallerMock).marshal(eq(toBeMarshalled), isA(Result.class)); verify(bytesMessageMock).writeBytes(isA(byte[].class)); } @Test public void fromBytesMessage() throws Exception { BytesMessage bytesMessageMock = mock(); Object unmarshalled = new Object(); given(bytesMessageMock.getBodyLength()).willReturn(10L); given(bytesMessageMock.readBytes(isA(byte[].class))).willReturn(0); given(unmarshallerMock.unmarshal(isA(Source.class))).willReturn(unmarshalled); Object result = converter.fromMessage(bytesMessageMock); assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test public void toTextMessage() throws Exception { converter.setTargetType(MessageType.TEXT); TextMessage textMessageMock = mock(); Object toBeMarshalled = new Object(); given(sessionMock.createTextMessage(isA(String.class))).willReturn(textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); verify(marshallerMock).marshal(eq(toBeMarshalled), isA(Result.class)); } @Test public void fromTextMessage() throws Exception { TextMessage textMessageMock = mock(); Object unmarshalled = new Object(); String text = "foo"; given(textMessageMock.getText()).willReturn(text); given(unmarshallerMock.unmarshal(isA(Source.class))).willReturn(unmarshalled); Object result = converter.fromMessage(textMessageMock); assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } }
package com.trannguyentanthuan2903.yourfoods.history_order_user.model; import com.trannguyentanthuan2903.yourfoods.product.model.OrderProduct; import com.trannguyentanthuan2903.yourfoods.utility.Constain; import java.util.ArrayList; import java.util.HashMap; /** * Created by Administrator on 10/16/2017. */ public class HistoryOrderUser { private String idHistoryUser; private String idStore; private String storeName; private String linkPhotoStore; private String phoneNumber; private String address; private String timeOrder; private ArrayList<OrderProduct> arrProduct; private int statusOrder; // 0 : Đang chờ // 1: Đã giao //2 : Bị hủy //contructor public HistoryOrderUser() { } public HistoryOrderUser(String idHistoryUser, String idStore, String storeName, String linkPhotoStore, String phoneNumber, String address, String timeOrder, ArrayList<OrderProduct> arrProduct, int statusOrder) { this.idHistoryUser = idHistoryUser; this.idStore = idStore; this.storeName = storeName; this.linkPhotoStore = linkPhotoStore; this.phoneNumber = phoneNumber; this.address = address; this.timeOrder = timeOrder; this.arrProduct = arrProduct; this.statusOrder = statusOrder; } //put all to HashMap public HashMap<String, Object> putMap (){ HashMap<String, Object> myMap = new HashMap<>(); myMap.put(Constain.ID_HISTORY_ORDER_USER, idHistoryUser); myMap.put(Constain.ID_USER, idStore); myMap.put(Constain.USER_NAME, storeName); myMap.put(Constain.LINKPHOTOUSER, linkPhotoStore); myMap.put(Constain.PHONENUMBER, phoneNumber); myMap.put(Constain.ADDRESS, address); myMap.put(Constain.TIME_ORDER, timeOrder); myMap.put(Constain.PRODUCT_LIST, arrProduct); myMap.put(Constain.STATUS_PRODUCTS, statusOrder); return myMap; } //Getter and setter public String getIdHistoryUser() { return idHistoryUser; } public void setIdHistoryUser(String idHistoryUser) { this.idHistoryUser = idHistoryUser; } public String getIdStore() { return idStore; } public void setIdStore(String idStore) { this.idStore = idStore; } public String getStoreName() { return storeName; } public void setStoreName(String storeName) { this.storeName = storeName; } public String getLinkPhotoStore() { return linkPhotoStore; } public void setLinkPhotoStore(String linkPhotoStore) { this.linkPhotoStore = linkPhotoStore; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTimeOrder() { return timeOrder; } public void setTimeOrder(String timeOrder) { this.timeOrder = timeOrder; } public ArrayList<OrderProduct> getArrProduct() { return arrProduct; } public void setArrProduct(ArrayList<OrderProduct> arrProduct) { this.arrProduct = arrProduct; } public int getStatusOrder() { return statusOrder; } public void setStatusOrder(int statusOrder) { this.statusOrder = statusOrder; } }
package chribb.mactrac.data; import java.util.ArrayList; import java.util.List; public class FavoriteTrie { //TODO need method to remove a Favorite // as of now, I think the Trie will be stored in the AddViewModel. I'll initiallize the creation // of the Trie in mainactivity. ill use an executor. private TrieNode root; private int size; public FavoriteTrie() { root = new TrieNode('!'); size = 0; } public FavoriteTrie(List<Favorite> favorites) { this(); for (int i = 0; i < favorites.size(); i++) { Favorite f = favorites.get(i); add(f); } } public void clear() { root = new TrieNode('!'); size = 0; } public int size() { return size; } public boolean contains(String key) { TrieNode n = root; for(int i = 0; i <= key.length(); i++) { if(i == key.length()) { return n.isKey; } TrieNode nextN = n.next[key.charAt(i)]; if (nextN == null) { break; } n = nextN; } return false; } public void add(Favorite favorite) { String key = favorite.getName(); TrieNode n = root; int i = 0; //progress through Trie to the longest existing prefix of KEY while (i < key.length()) { TrieNode nextN = n.next[key.charAt(i)]; if (nextN == null) { break; } n = nextN; i++; } //If the whole word was already in here, set isKey to true and save the favorite. //This either overwrites an existing key, or adds a key to a prefix of an existing key, //i.e. if you had "hamburger" and then you added "ham." if (i == key.length()) { if (!n.isKey) { size++; n.isKey = true; } n.keyValue = favorite; return; } //if you've still got more of the Key left, keep adding each character to the Trie until //you get to the end, where you save it as a Key and save the Favorite. while (i < key.length()) { TrieNode nextN; if (i == key.length() - 1) { nextN = new TrieNode(key.charAt(i), favorite); size++; } else { nextN = new TrieNode(key.charAt(i)); } n.next[key.charAt(i)] = nextN; n = nextN; i++; } } public void delete(Favorite favorite) { String key = favorite.getName(); TrieNode n = root; int i = 0; while (i < key.length()) { TrieNode nextN = n.next[key.charAt(i)]; if (nextN == null) { break; } n = nextN; i++; } if (i == key.length() && n.isKey) { n.isKey = false; n.keyValue = null; size--; } } public List<Favorite> sortedFavoritesWithPrefix(String prefix) { List<Favorite> withPrefix = new ArrayList<>(); TrieNode n = root; for (int i = 0; i < prefix.length(); i++) { TrieNode nextN = n.next[prefix.charAt(i)]; if (nextN == null) { return withPrefix; } n = nextN; } addKeysWithPrefix(withPrefix, n); withPrefix.sort((f1, f2) -> f2.getCount() - f1.getCount()); //lambda for compare() return withPrefix; } private void addKeysWithPrefix(List<Favorite> l, TrieNode n) { if (n.isKey) { l.add(n.keyValue); } for (TrieNode nextN : n.next) { if (nextN == null) continue; addKeysWithPrefix(l, nextN); } } private static class TrieNode { char character; boolean isKey; TrieNode[] next; Favorite keyValue; TrieNode(Character character, Favorite keyValue) { this.character = character; this.isKey = true; next = new TrieNode[128]; this.keyValue = keyValue; } TrieNode(Character character) { this.character = character; this.isKey = false; next = new TrieNode[128]; } } }
package com.deepsingh44.ui; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.KeyStroke; import java.awt.event.KeyEvent; import java.awt.event.InputEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JDesktopPane; public class HomePage extends JFrame { private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { HomePage frame = new HomePage(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public HomePage() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 732, 451); setLocationRelativeTo(null); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnFile = new JMenu("File"); menuBar.add(mnFile); JMenuItem mntmNewFile = new JMenuItem("Add Book"); mntmNewFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK)); mnFile.add(mntmNewFile); JMenuItem mntmExit = new JMenuItem("Exit"); mntmExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK)); mnFile.add(mntmExit); JMenu mnView = new JMenu("View"); menuBar.add(mnView); JMenuItem mntmListOfB = new JMenuItem("List Of Books"); mnView.add(mntmListOfB); JMenu mnHelp = new JMenu("Help"); menuBar.add(mnHelp); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JDesktopPane desktopPane = new JDesktopPane(); contentPane.add(desktopPane, BorderLayout.CENTER); mntmNewFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AddBook account = new AddBook(); desktopPane.add(account); account.setVisible(true); } }); mntmListOfB.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { BookList bookList=new BookList(); desktopPane.add(bookList); bookList.setVisible(true); } }); } }
package seleniumBasicCode; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.ie.InternetExplorerDriver; public class seleniumRun { public static void main(String[] args) { // setting up the browser System.setProperty("webdriver.chrome.driver", "C:\\Users\\Agile1Tech\\Desktop\\Selenium Testing libraries\\chromedriver.exe"); // System.setProperty("webdriver.ie.driver", "C:\\Users\\Agile1Tech\\Desktop\\Selenium Testing libraries\\IEDriverServer.exe"); WebDriver driver = new ChromeDriver(); WebDriver driver1=new ChromeDriver(); //WebDriver driver2=new InternetExplorerDriver(); driver.get("https://www.facebook.com"); driver1.get("https://www.google.com"); //driver2.get("https://www.google.com"); //driver.quit(); } }
package fr.aresrpg.tofumanchou.domain.event.entity; import fr.aresrpg.commons.domain.event.Event; import fr.aresrpg.commons.domain.event.EventBus; import fr.aresrpg.dofus.structures.game.Effect; import fr.aresrpg.tofumanchou.domain.data.Account; import fr.aresrpg.tofumanchou.domain.data.entity.Entity; import java.util.Set; /** * * @since */ public class EntitiesReceiveSpellEffectEvent implements Event<EntitiesReceiveSpellEffectEvent> { private static final EventBus<EntitiesReceiveSpellEffectEvent> BUS = new EventBus<>(EntitiesReceiveSpellEffectEvent.class); private Account client; private Set<Entity> entities; private Effect effect; /** * @param client * @param entities * @param effect */ public EntitiesReceiveSpellEffectEvent(Account client, Set<Entity> entities, Effect effect) { this.client = client; this.entities = entities; this.effect = effect; } /** * @return the entities */ public Set<Entity> getEntities() { return entities; } /** * @param entities * the entities to set */ public void setEntities(Set<Entity> entities) { this.entities = entities; } /** * @return the effect */ public Effect getEffect() { return effect; } /** * @param effect * the effect to set */ public void setEffect(Effect effect) { this.effect = effect; } /** * @param client * the client to set */ public void setClient(Account client) { this.client = client; } /** * @return the client */ public Account getClient() { return client; } @Override public EventBus<EntitiesReceiveSpellEffectEvent> getBus() { return BUS; } @Override public boolean isAsynchronous() { return false; } @Override public String toString() { return "EntitiesReceiveSpellEffectEvent [client=" + client + ", entities=" + entities + ", effect=" + effect + "]"; } }
package com.smartsampa.busapi; /** * Created by ruan0408 on 5/07/2016. */ final class NullTrip extends Trip { private static final Trip ourInstance = new NullTrip(); private NullTrip() {} static Trip getInstance() { return ourInstance; } @Override public String getNumberSign() { return null; } @Override public Heading getHeading() { return null; } @Override public String getDestinationSign() { return null; } @Override public String getWorkingDays() { return null; } @Override public Double getFarePrice() { return null; } @Override public Boolean isCircular() { return null; } @Override public Shape getShape() { return null; } @Override public int getDepartureIntervalInSecondsAtTime(String hhmm) { return 0; } @Override public int getDepartureIntervalInSecondsNow() { return 0; } @Override public Integer getOlhovivoId() { return null; } @Override public String getGtfsId() { return null; } }
package com.vodafone.innogaragepb.geomapp; import android.Manifest; import android.animation.ValueAnimator; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.telephony.TelephonyManager; import android.telephony.gsm.GsmCellLocation; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationListener; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; public class MainActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{ public JSONObject jsonObj; private GoogleMap mMap; public Boolean ready; public LatLng myLatLng; public LatLng myLatLng2; public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; GoogleApiClient mGoogleApiClient; LocationRequest mLocationRequest; Marker mCurrentLocation; Location mLastLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission(); } //Obtain the cell ID TelephonyManager tm =(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); GsmCellLocation cellLocation = (GsmCellLocation)tm.getCellLocation(); int cellID = cellLocation.getCid() & 0xFFFF; // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); final Button accidentButton = (Button) findViewById(R.id.accidentButton); final Button trafficjamButton = (Button) findViewById(R.id.trafficjamButton); final Button speedlimitButton = (Button) findViewById(R.id.speedlimitButton); final String jsonString = loadJSONFromAsset(); try { jsonObj = new JSONObject(jsonString); } catch (Exception e) { e.printStackTrace(); } //Initializing the buttons accidentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Place a marker with location and time to live setSituation(5000, myLatLng, "accident"); } }); trafficjamButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Sendtraffic icon setSituation(10000, myLatLng2, "trafficjam"); } }); speedlimitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Sendtraffic icon //setLocation(5000, myLatLng2, myMarker, "pink"); try { setMarkers(jsonObj); } catch (JSONException e) { System.out.println("Could not set markers"); } } }); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; myLatLng = new LatLng(51.23610018, 6.73155069); myLatLng2 = new LatLng(51.23708092, 6.72972679); // Initialize Google Play Services if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){ buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } } else { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } mMap.getUiSettings().setZoomControlsEnabled(true); ready = true; } //SET USE CASES: Situation in the traffic or just location of the other cars public void setSituation(long duration, LatLng myLatLng, String myString) { Marker marker; final String code = myString; if (ready) { marker = mMap.addMarker(new MarkerOptions() .position(myLatLng) .icon(BitmapDescriptorFactory.fromBitmap(resizer(code, 70, 70)))); fadeTime(duration, marker); } } public void setLocation (long duration, LatLng myLatLng, String cellColor){ if (ready) { Marker marker; int id = getResources().getIdentifier(cellColor, "drawable", getPackageName()); marker = mMap.addMarker(new MarkerOptions() .position(myLatLng) .icon(BitmapDescriptorFactory.fromResource(id))); fadeTime(duration, marker); } } public void setMarkers(JSONObject myJson)throws JSONException { final JSONObject json = myJson; final JSONArray cans = myJson.getJSONArray("cans"); System.out.println("Inside setMarkers"); for (int i = 0; i < cans.length(); i++) { JSONObject c; final int number = i; try { c = cans.getJSONObject(i); final String MessageTypeID = c.getString("MessageTypeID"); final String Erzeugerzeitpunkt = c.getString("Erzeugerzeitpunkt"); final Long Lebensdauer = c.getLong("Lebensdauer"); //Float Lat = Float.valueOf(c.getString("Lat")); //Float Long = Float.valueOf(c.getString("Long")); final Double latitude = c.getDouble("Lat"); final Double longitude = c.getDouble("Long"); JSONArray CellID = c.getJSONArray("CellID"); final String Message = c.getString("Message"); int id = getResources().getIdentifier("pink", "drawable", getPackageName()); runOnUiThread(new Runnable(){ @Override public void run(){ setCoordinates(latitude,longitude, Lebensdauer, number, Erzeugerzeitpunkt, Message); } }); } catch (JSONException e) { e.printStackTrace(); } } } private void setCoordinates(Double lat, Double lon, Long dur, int number, String ezp, String msg){ int id = getResources().getIdentifier("pink", "drawable", getPackageName()); LatLng myPosition = new LatLng(lat, lon); mMap.addMarker(new MarkerOptions() .position(myPosition) .icon(BitmapDescriptorFactory.fromResource(id)) .title("Point "+number) .snippet("Message: " + msg ) ); //fadeTime(dur,mar); } //Customize characteristics of the markers: Size and time to fade public Bitmap resizer(String iconName, int width, int height) { Bitmap imgBitmap = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier(iconName, "drawable", getPackageName())); Bitmap resizedBitmap = Bitmap.createScaledBitmap(imgBitmap, width, height, false); return resizedBitmap; } public void fadeTime(long duration, Marker marker) { final Marker myMarker = marker; ValueAnimator myAnim = ValueAnimator.ofFloat(1, 0); myAnim.setDuration(duration); myAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { myMarker.setAlpha((float) animation.getAnimatedValue()); } }); myAnim.start(); } @Override public void onLocationChanged(Location location) { mLastLocation = location; if (mCurrentLocation != null){ mCurrentLocation.remove(); } //Place my location Marker LatLng latlong = new LatLng(location.getLatitude(), location.getLongitude()); //mCurrentLocation = mMap.addMarker(new MarkerOptions() // .position(latlong)); //.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))); //move map camera mMap.moveCamera(CameraUpdateFactory.newLatLng(latlong)); mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); //stop location updates if (mGoogleApiClient != null) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this); } } @Override public void onConnected(@Nullable Bundle bundle) { mLocationRequest = new LocationRequest(); mLocationRequest.setFastestInterval(1000); mLocationRequest.setInterval(1000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){ LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } protected synchronized void buildGoogleApiClient(){ mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } public boolean checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Asking user if explanation is needed if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an expanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } return false; } else { return true; } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission Granted if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (mGoogleApiClient == null) { buildGoogleApiClient(); } mMap.setMyLocationEnabled(true); } } else { // Permission denied, Disable the functionality that depends on this permission. Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); } return; } } } /*------------------Reading JSON Data------------------------*/ public String loadJSONFromAsset() { String json = null; try { InputStream is = getAssets().open("data1.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; } } //http://stackoverflow.com/questions/28109597/gradually-fade-out-a-custom-map-marker
package com.stk123.service.task; import com.stk123.util.ExceptionUtils; import lombok.Getter; import lombok.Setter; import lombok.extern.apachecommons.CommonsLog; import org.apache.commons.lang.StringUtils; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.time.ZoneId; import org.springframework.beans.factory.config.ConfigurableBeanFactory; @CommonsLog @Service @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public abstract class Task<R> { public enum EnumStatus { RUNNING, NOT_RUNNING } @Getter private String id; @Getter@Setter private boolean async; //if true, 就是异步 private EnumStatus status = EnumStatus.NOT_RUNNING; @Getter private LocalDateTime startTime; @Getter private LocalDateTime endTime; @Getter private TaskResult<?> taskResult; public Task(){ this(true); } public Task(boolean async){ this.async = async; this.id = String.valueOf(System.currentTimeMillis()); } public void run(String... args) { this.startTime = LocalDateTime.now(); log.info("["+this.getClass().getSimpleName()+"]..start, id:"+this.id+", param:"+ StringUtils.join(args,",")); try { status = EnumStatus.RUNNING; execute(args); taskResult = TaskResult.success(success(), this); } catch(Exception e){ log.error("task execute error:", e); taskResult = TaskResult.failure(ExceptionUtils.getExceptionAsString(e), this); } finally { this.endTime = LocalDateTime.now(); status = EnumStatus.NOT_RUNNING; log.info("["+this.getClass().getSimpleName()+"]....end, id:"+this.id+", cost time:"+ (getEndTimeToLong()-getStartTimeToLong())/1000.0 + "s"); } } public EnumStatus status() { return status; } public abstract void execute(String... args) throws Exception; public R success(){ return (R) ""; } public long getStartTimeToLong(){ return this.startTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } public long getEndTimeToLong(){ return this.endTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } }
package com.project.info; public class Operation { public static int removed = 0; public static int added = 1; }